From 4d5b8353529f12656f0acae8a3ffb99057188fc4 Mon Sep 17 00:00:00 2001 From: William Moberg Date: Wed, 20 Jan 2016 16:43:09 +0100 Subject: [PATCH 001/355] WIP triangles vs. AABB. --- .../Schema/Entities/ModelCollisionTest.xml | 49 +++++++++ src/Engine/Collision/Collision.cpp | 99 ++++++++++++++++--- src/Engine/Collision/CollisionSystem.cpp | 63 ++++++------ 3 files changed, 166 insertions(+), 45 deletions(-) create mode 100644 resources/Schema/Entities/ModelCollisionTest.xml diff --git a/resources/Schema/Entities/ModelCollisionTest.xml b/resources/Schema/Entities/ModelCollisionTest.xml new file mode 100644 index 00000000..46746264 --- /dev/null +++ b/resources/Schema/Entities/ModelCollisionTest.xml @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + ../assets/Models/Core/UnitCube.obj + + + + + + + + + + + + + + + ../assets/Models/Core/UnitCube.obj + + + + + + + + + + diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index b30ae927..c351d9fa 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -199,30 +199,93 @@ bool RayVsModel(const Ray& ray, return hit; } -bool AABBvsTriangles(const AABB& box, const std::vector& modelVertices, const std::vector& modelIndices, const glm::mat4& modelMatrix, glm::vec3& outResolutionVector) +bool AABBvsTriangle(const AABB& box, const glm::vec3& v0, const glm::vec3& v1, const glm::vec3& v2, glm::vec3& outResolutionVector) { - bool hit = false; - const glm::vec3& origin = box.Origin(); const glm::vec3& min = box.MinCorner(); const glm::vec3& max = box.MaxCorner(); + const glm::vec3& half = box.HalfSize(); - outResolutionVector.x = INFINITY; + const glm::vec3 triPos[] = { + v0, v1, v2 + }; - for (int i = 0; i < modelIndices.size(); ++i) { - glm::vec3 p = modelVertices[i].Position; + for (int ax = 0; ax < 3; ++ax) { + auto outsideMinPlane = glm::tvec3(false); + auto outsideMaxPlane = glm::tvec3(false); + for (int pos = 0; pos < 3; ++pos) { + outsideMinPlane[pos] = (min[ax] > triPos[pos][ax]); + outsideMaxPlane[pos] = (triPos[pos][ax] > max[ax]); + } + if (glm::all(outsideMinPlane) || glm::all(outsideMaxPlane)) { + return false; + } + } + return true; +} + +bool AABBvsTriangles(const AABB& box, const std::vector& modelVertices, const std::vector& modelIndices, const glm::mat4& modelMatrix, glm::vec3& outResolutionVector) +{ + bool hit = false; + for (int i = 0; i < modelIndices.size(); i += 3) { + glm::vec3 resVec; + hit = AABBvsTriangle( + box, + modelVertices[modelIndices[i]].Position, + modelVertices[modelIndices[i + 1]].Position, + modelVertices[modelIndices[i + 2]].Position, + resVec + ); + if (hit) { + break; + } + } + return hit; + //TODO: Remove old code. + + /* + auto hit = glm::tvec3(false); + const glm::vec3& origin = box.Origin(); + const glm::vec3& min = box.MinCorner(); + const glm::vec3& max = box.MaxCorner(); + const glm::vec3& half = box.HalfSize(); + + float minResolution = INFINITY; + outResolutionVector = glm::vec3(0.f); + //TODO: Don't need indices? Remove? + for (const auto& v : modelVertices) { + glm::vec3 p = v.Position; p = glm::vec3(modelMatrix * glm::vec4(p.x, p.y, p.z, 1)); - float distFromOrigin = glm::abs(origin.x - p.x); - float penetration = box.HalfSize().x - distFromOrigin; - if (penetration > 0 && penetration < glm::abs(outResolutionVector.x)) { - if (p.x > origin.x) { - outResolutionVector.x = -penetration; - } else { - outResolutionVector.x = penetration; + const glm::vec3 diffO = origin - p; + const glm::vec3 distO = glm::abs(diffO); + for (int axis = 0; axis < 3; ++axis) { + float penetration = half[axis] - distO[axis]; + if (penetration > 0){ + if (penetration < minResolution) { + minResolution = penetration; + outResolutionVector = glm::vec3(0.f); + if (p[axis] > origin[axis]) { + outResolutionVector[axis] = -penetration; + } else { + outResolutionVector[axis] = penetration; + } + } + hit[axis] = true; } - hit = true; } + + //float distFromOrigin = glm::abs(origin.x - p.x); + //float penetration = box.HalfSize().x - distFromOrigin; + //if (penetration > 0 && penetration < glm::abs(outResolutionVector.x)) { + // if (p.x > origin.x) { + // outResolutionVector.x = -penetration; + // } else { + // outResolutionVector.x = penetration; + // } + // hit = true; + //} + //glm::vec3 pLocal = origin - p; //for (int axis = 0; axis < 3; ++axis) { // if (p[axis] < min[axis] || p[axis] > max[axis]) { @@ -236,7 +299,13 @@ bool AABBvsTriangles(const AABB& box, const std::vector& model //} } - return hit; + //for (int axis = 0; axis < 3; ++axis) { + // if (glm::isinf(outResolutionVector[axis])) { + // outResolutionVector[axis] = 0.f; + // } + //} + + return glm::all(hit);*/ } bool IsSameBoxProbably(const AABB& first, const AABB& second, const float epsilon) diff --git a/src/Engine/Collision/CollisionSystem.cpp b/src/Engine/Collision/CollisionSystem.cpp index d841c75e..58e48357 100644 --- a/src/Engine/Collision/CollisionSystem.cpp +++ b/src/Engine/Collision/CollisionSystem.cpp @@ -1,6 +1,7 @@ #include "Collision/Collision.h" #include "Collision/CollisionSystem.h" #include "Core/AABB.h" +#include "Rendering/Model.h" void CollisionSystem::UpdateComponent(World* world, EntityWrapper& entity, ComponentWrapper& component, double dt) { @@ -22,40 +23,42 @@ void CollisionSystem::UpdateComponent(World* world, EntityWrapper& entity, Compo } // Collide against octree - std::vector octreeResult; - m_Octree->BoxesInSameRegion(*boundingBox, octreeResult); - for (auto& boxB : octreeResult) { - glm::vec3 resolutionVector; - if (Collision::IsSameBoxProbably(boxA, boxB)) { - continue; - } - if (Collision::AABBVsAABB(boxA, boxB, resolutionVector)) { - (glm::vec3&)cTransform["Position"] += resolutionVector; - cPhysics["Velocity"] = glm::vec3(0, 0, 0); - } - } - - // HACK: Temporarily collide against all collidable models since they're not in the octree yet - //auto otherCollidables = world->GetComponents("Model"); - //for (auto& cModel : *otherCollidables) { - // if (cModel.EntityID == entity) { - // continue; - // } - // if (!world->HasComponent(cModel.EntityID, "Collidable")) { - // continue; - // } - - // auto absPosition = RenderQueueFactory::AbsolutePosition(world, cModel.EntityID); - // auto absOrientation = RenderQueueFactory::AbsoluteOrientation(world, cModel.EntityID); - // auto absScale = RenderQueueFactory::AbsoluteScale(world, cModel.EntityID); - // glm::mat4 modelMatrix = glm::translate(absPosition); // *glm::toMat4(absOrientation) * glm::scale(absScale); - - // auto model = ResourceManager::Load(cModel["Resource"]); + //std::vector octreeResult; + //m_Octree->BoxesInSameRegion(*boundingBox, octreeResult); + //for (auto& boxB : octreeResult) { // glm::vec3 resolutionVector; - // if (Collision::AABBvsTriangles(boxA, model->m_Vertices, model->m_Indices, modelMatrix, resolutionVector)) { + // if (Collision::IsSameBoxProbably(boxA, boxB)) { + // continue; + // } + // if (Collision::AABBVsAABB(boxA, boxB, resolutionVector)) { // (glm::vec3&)cTransform["Position"] += resolutionVector; + // cPhysics["Velocity"] = glm::vec3(0, 0, 0); // } //} + + // HACK: Temporarily collide against all collidable models since they're not in the octree yet + auto otherCollidables = world->GetComponents("Model"); + for (auto& cModel : *otherCollidables) { + if (cModel.EntityID == EntityID(entity)) { + continue; + } + if (!world->HasComponent(cModel.EntityID, "Collidable")) { + continue; + } + + auto absPosition = Transform::AbsolutePosition(world, cModel.EntityID); + auto absOrientation = Transform::AbsoluteOrientation(world, cModel.EntityID); + auto absScale = Transform::AbsoluteScale(world, cModel.EntityID); + glm::mat4 modelMatrix = glm::translate(absPosition); // *glm::toMat4(absOrientation) * glm::scale(absScale); + + RawModel* model = ResourceManager::Load(cModel["Resource"]); + glm::vec3 resolutionVector; + if (Collision::AABBvsTriangles(boxA, model->m_Vertices, model->m_Indices, modelMatrix, resolutionVector)) { + //TODO: remove Temp. + (glm::vec3&)cTransform["Position"] = glm::vec3(2, 2, 2); + //(glm::vec3&)cTransform["Position"] += resolutionVector; + } + } } bool CollisionSystem::OnKeyUp(const Events::KeyUp & event) From de7c8e9234f89893265a6ce97a95b06268e6eb53 Mon Sep 17 00:00:00 2001 From: William Moberg Date: Thu, 21 Jan 2016 17:10:36 +0100 Subject: [PATCH 002/355] WIP, collision detects too much, no resolving for most cases. --- include/Engine/Collision/Collision.h | 9 + include/Engine/Core/Transform.h | 1 + .../Schema/Entities/ModelCollisionTest.xml | 10 +- src/Engine/Collision/Collision.cpp | 256 ++++++++++++++++-- src/Engine/Collision/CollisionSystem.cpp | 6 +- src/Engine/Core/Transform.cpp | 4 + 6 files changed, 248 insertions(+), 38 deletions(-) diff --git a/include/Engine/Collision/Collision.h b/include/Engine/Collision/Collision.h index 148f688d..b32d190a 100644 --- a/include/Engine/Collision/Collision.h +++ b/include/Engine/Collision/Collision.h @@ -26,6 +26,15 @@ bool RayVsAABB(const Ray& ray, const AABB& box); //Return true if the ray hits the box, also outputs distance from ray origin to intersection point in [outDistance]. bool RayVsAABB(const Ray& ray, const AABB& box, float& outDistance); +//Return true if the ray hits the triangle, and the distance is less than outDistance. +bool RayVsTriangle(const Ray& ray, + const glm::vec3& v0, + const glm::vec3& v1, + const glm::vec3& v2, + float& outDistance, + float& outUCoord, + float& outVCoord, + bool trueOnNegativeDistance = false); //Return true if the ray hits any of the triangles in the model. Stops checking when a hit is detected. bool RayVsModel(const Ray& ray, const std::vector& modelVertices, diff --git a/include/Engine/Core/Transform.h b/include/Engine/Core/Transform.h index 474a7bdb..b004f047 100644 --- a/include/Engine/Core/Transform.h +++ b/include/Engine/Core/Transform.h @@ -11,6 +11,7 @@ glm::vec3 AbsolutePosition(World* world, EntityID entity); glm::quat AbsoluteOrientation(World* world, EntityID entity); glm::vec3 AbsoluteScale(World* world, EntityID entity); glm::mat4 ModelMatrix(EntityID entity, World* world); +glm::vec3 TransformPoint(const glm::vec3& point, const glm::mat4& matrix); } diff --git a/resources/Schema/Entities/ModelCollisionTest.xml b/resources/Schema/Entities/ModelCollisionTest.xml index 46746264..fd26f0c5 100644 --- a/resources/Schema/Entities/ModelCollisionTest.xml +++ b/resources/Schema/Entities/ModelCollisionTest.xml @@ -11,8 +11,8 @@ - - + + @@ -22,10 +22,10 @@ ../assets/Models/Core/UnitCube.obj + - - + @@ -39,7 +39,7 @@ ../assets/Models/Core/UnitCube.obj - + diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index c351d9fa..6794f5b9 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -146,6 +146,38 @@ bool RayVsModel(const Ray& ray, return false; } +bool RayVsTriangle(const Ray& ray, + const glm::vec3& v0, + const glm::vec3& v1, + const glm::vec3& v2, + float& outDistance, + float& outUCoord, + float& outVCoord, + bool trueOnNegativeDistance) +{ + glm::vec3 e1 = v1 - v0; //v1 - v0 + glm::vec3 e2 = v2 - v0; //v2 - v0 + glm::vec3 m = ray.Origin() - v0; + glm::vec3 MxE1 = glm::cross(m, e1); + glm::vec3 DxE2 = glm::cross(ray.Direction(), e2);//pVec + float DetInv = glm::dot(e1, DxE2); + if (std::abs(DetInv) < FLT_EPSILON) { + return false; + } + DetInv = 1.0f / DetInv; + float dist = glm::dot(e2, MxE1) * DetInv; + if (dist >= outDistance) { + return false; + } + outDistance = dist; + outUCoord = glm::dot(m, DxE2) * DetInv; + outVCoord = glm::dot(ray.Direction(), MxE1) * DetInv; + + //u,v can be very close to 0 but still negative sometimes. added a deltafactor to compensate for that problem + //If u and v are positive, u+v <= 1, dist is positive, and less than closest. + return (0 <= (outUCoord + 0.001f) && 0 <= (outVCoord + 0.001f) && outUCoord + outVCoord <= 1 && (trueOnNegativeDistance || 0 <= dist)); +} + bool RayVsModel(const Ray& ray, const std::vector& modelVertices, const std::vector& modelIndices, @@ -157,26 +189,12 @@ bool RayVsModel(const Ray& ray, bool hit = false; for (int i = 0; i < modelIndices.size(); ++i) { glm::vec3 v0 = modelVertices[modelIndices[i]].Position; - glm::vec3 e1 = modelVertices[modelIndices[++i]].Position - v0; //v1 - v0 - glm::vec3 e2 = modelVertices[modelIndices[++i]].Position - v0; //v2 - v0 - glm::vec3 m = ray.Origin() - v0; - glm::vec3 MxE1 = glm::cross(m, e1); - glm::vec3 DxE2 = glm::cross(ray.Direction(), e2);//pVec - float DetInv = glm::dot(e1, DxE2); - if (std::abs(DetInv) < FLT_EPSILON) { - continue; - } - DetInv = 1.0f / DetInv; - float dist = glm::dot(e2, MxE1) * DetInv; - if (dist >= outDistance) { - continue; - } - float u = glm::dot(m, DxE2) * DetInv; - float v = glm::dot(ray.Direction(), MxE1) * DetInv; - - //u,v can be very close to 0 but still negative sometimes. added a deltafactor to compensate for that problem - //If u and v are positive, u+v <= 1, dist is positive, and less than closest. - if (0 <= (u + 0.001f) && 0 <= (v + 0.001f) && u + v <= 1 && 0 <= dist) { + glm::vec3 v1 = modelVertices[modelIndices[++i]].Position; + glm::vec3 v2 = modelVertices[modelIndices[++i]].Position; + float dist; + float u; + float v; + if (RayVsTriangle(ray, v0, v1, v2, dist, u, v)) { outDistance = dist; outUCoord = u; outVCoord = v; @@ -199,29 +217,205 @@ bool RayVsModel(const Ray& ray, return hit; } +constexpr inline int squareOf(float x) +{ + return x * x; +} + +constexpr inline int signNonZero(float x) +{ + return x < 0 ? -1 : 1; +} + +inline glm::vec3 signNonZero(const glm::vec3& x) +{ + glm::vec3 r; + for (int i = 0; i < 3; ++i) { + r[i] = signNonZero(x[i]); + } + return r; +} + +bool lineIntersectsBox(const AABB& box, const glm::vec3& v0, const glm::vec3& v1) +{ + const glm::vec3 edgevec = v1 - v0; + glm::vec3 edgevec_signs = signNonZero(edgevec); + + for (int i = 0; i < 3; ++i) + edgevec_signs[i] = signNonZero(edgevec[i]); + + /* + * Test the three cube faces on the v1-ward side of the cube-- + * if v0 is outside any of their planes then there is no intersection. + * Also test the three cube faces on the v0-ward side of the cube-- + * if v1 is outside any of their planes then there is no intersection. + */ + + for (int i = 0; i < 3; ++i) + { + if (v0[i] * edgevec_signs[i] > .5) return false; + if (v1[i] * edgevec_signs[i] < -.5) return false; + } + + /* + * Okay, that's the six easy faces of the rhombic dodecahedron + * out of the way. Six more to go. + * The remaining six planes bound an infinite hexagonal prism + * joining the petrie polygons (skew hexagons) of the two cubes + * centered at the endpoints. + */ + + for (int i = 0; i < 3; ++i) + { + float rhomb_normal_dot_v0, rhomb_normal_dot_cubedge; + + int iplus1 = (i + 1) % 3; + int iplus2 = (i + 2) % 3; + +#ifdef THE_EASY_TO_UNDERSTAND_WAY + + { + real rhomb_normal[3], cubedge_midpoint[3]; + + /* + * rhomb_normal = VXV3(edgevec, unit vector in direction i), + * being cavalier about which direction it's facing + */ + rhomb_normal[i] = 0; + rhomb_normal[iplus1] = edgevec[iplus2]; + rhomb_normal[iplus2] = -edgevec[iplus1]; + + /* + * We now are describing a plane parallel to + * both segment and the cube edge in question. + * if |DOT3(rhomb_normal, an arbitrary point on the segment)| > + * |DOT3(rhomb_normal, an arbitrary point on the cube edge in question| + * then the origin is outside this pair of opposite faces. + * (This is equivalent to saying that the line + * containing the segment is "outside" (i.e. further away from the + * origin than) the line containing the cube edge. + */ + + cubedge_midpoint[i] = 0; + cubedge_midpoint[iplus1] = edgevec_signs[iplus1] * .5; + cubedge_midpoint[iplus2] = -edgevec_signs[iplus2] * .5; + + rhomb_normal_dot_v0 = DOT3(rhomb_normal, v0); + rhomb_normal_dot_cubedge = DOT3(rhomb_normal, cubedge_midpoint); + } + +#else /* the efficient way */ + + rhomb_normal_dot_v0 = edgevec[iplus2] * v0[iplus1] + - edgevec[iplus1] * v0[iplus2]; + + rhomb_normal_dot_cubedge = .5 * + (edgevec[iplus2] * edgevec_signs[iplus1] + + edgevec[iplus1] * edgevec_signs[iplus2]); + +#endif /* the efficient way */ + + if (squareOf(rhomb_normal_dot_v0) > squareOf(rhomb_normal_dot_cubedge)) + return false; /* origin is outside this pair of opposite planes */ + } + return true; +} + +bool vectorHasLength(const glm::vec3& vec) +{ + return glm::all(glm::lessThan(glm::abs(vec), glm::vec3(0.0001f, 0.0001f, 0.0001f))); +} + bool AABBvsTriangle(const AABB& box, const glm::vec3& v0, const glm::vec3& v1, const glm::vec3& v2, glm::vec3& outResolutionVector) { + //Check so we don't have a zero area triangle when calculating the normal. + glm::vec3 triNormal = glm::cross(v1 - v0, v2 - v0); + if (vectorHasLength(triNormal)) { + return false; + } + const glm::vec3& origin = box.Origin(); + const glm::vec3& half = box.HalfSize(); const glm::vec3& min = box.MinCorner(); const glm::vec3& max = box.MaxCorner(); - const glm::vec3& half = box.HalfSize(); const glm::vec3 triPos[] = { v0, v1, v2 }; + auto insideAllPlanes = glm::tvec3(false); + //All triangle vertex points. + //Check if the triangle is completely outside or inside the box. for (int ax = 0; ax < 3; ++ax) { auto outsideMinPlane = glm::tvec3(false); auto outsideMaxPlane = glm::tvec3(false); + auto insidePlanes = glm::tvec3(false); for (int pos = 0; pos < 3; ++pos) { outsideMinPlane[pos] = (min[ax] > triPos[pos][ax]); outsideMaxPlane[pos] = (triPos[pos][ax] > max[ax]); + insidePlanes[pos] = !(outsideMinPlane[pos] || outsideMaxPlane[pos]); } if (glm::all(outsideMinPlane) || glm::all(outsideMaxPlane)) { return false; } + insideAllPlanes[ax] = glm::all(insidePlanes); } - return true; + if (glm::all(insideAllPlanes)) { + outResolutionVector = glm::vec3(0.f); + LOG_DEBUG("Triangle collision inside"); + return true; //TODO: Resolve. + } + + glm::vec3 triPosInBoxSpace[3]; + for (int i = 0; i < 3; ++i) { + triPosInBoxSpace[i] = (triPos[i] - origin) / (2.0f * half); + } + //All triangle lines. + //Check if each line on the triangle intersects any plane on the box. + for (int l = 0; l < 3; ++l) { + if (lineIntersectsBox(box, triPosInBoxSpace[l], triPosInBoxSpace[(l + 1) % 3])) { + outResolutionVector = glm::vec3(0.f); + LOG_DEBUG("Triangle collision lines"); + return true; //TODO: Resolve. + } + } + + //None of the polygon's edges intersects the cube, finally, check if any of the four + //cube diagonals intersect the interior of the polygon. + //If the polygon does intersect any of the cube diagonals, it will + //intersect the cube diagonal that comes + //closest to being perpendicular to the plane of the polygon. + + triNormal = glm::normalize(triNormal); + glm::vec3 diagonal = signNonZero(triNormal) * half; +#define EARLY_OUT_OR_MAYBE_JUST_EXTRA_WORK +#ifdef EARLY_OUT_OR_MAYBE_JUST_EXTRA_WORK + //The triangle plane contains all points P in dot(triNormal, P) == dot(triNormal, v0) + //The diagonal line contains all points P in P = origin + diagonal * t. + float t = glm::dot(triNormal, v0 - origin) / glm::dot(triNormal, diagonal); + + //If intersection point between plane and diagonal is not within the box. + if (glm::abs(t) > 1) { + return false; + } + //glm::vec3 intersection = origin + t * diagonal; +#endif + + //Check if intersection point is on the triangle. + Ray ray(origin, diagonal); + float dist = INFINITY, u, v; + if (RayVsTriangle(ray, v0, v1, v2, dist, u, v, true)) { +#ifndef EARLY_OUT_OR_MAYBE_JUST_EXTRA_WORK + if (glm::abs(dist) > glm::length(diagonal)) { + return false; + } +#endif + float dist = glm::dot(triNormal, origin + diagonal - v0); + outResolutionVector = dist * triNormal; + LOG_DEBUG("Triangle collision corner"); + return true; + } + return false; } bool AABBvsTriangles(const AABB& box, const std::vector& modelVertices, const std::vector& modelIndices, const glm::mat4& modelMatrix, glm::vec3& outResolutionVector) @@ -229,15 +423,19 @@ bool AABBvsTriangles(const AABB& box, const std::vector& model bool hit = false; for (int i = 0; i < modelIndices.size(); i += 3) { glm::vec3 resVec; - hit = AABBvsTriangle( + if (AABBvsTriangle( box, - modelVertices[modelIndices[i]].Position, - modelVertices[modelIndices[i + 1]].Position, - modelVertices[modelIndices[i + 2]].Position, + Transform::TransformPoint(modelVertices[modelIndices[i]].Position, modelMatrix), + Transform::TransformPoint(modelVertices[modelIndices[i + 1]].Position, modelMatrix), + Transform::TransformPoint(modelVertices[modelIndices[i + 2]].Position, modelMatrix), resVec - ); - if (hit) { - break; + )) + { + hit = true; + //If resolution distance is smaller than previous, and is non-zero. + if (glm::length(resVec) < glm::length(outResolutionVector) && vectorHasLength(resVec)) { + outResolutionVector = resVec; + } } } return hit; diff --git a/src/Engine/Collision/CollisionSystem.cpp b/src/Engine/Collision/CollisionSystem.cpp index 58e48357..abddce1f 100644 --- a/src/Engine/Collision/CollisionSystem.cpp +++ b/src/Engine/Collision/CollisionSystem.cpp @@ -49,14 +49,12 @@ void CollisionSystem::UpdateComponent(World* world, EntityWrapper& entity, Compo auto absPosition = Transform::AbsolutePosition(world, cModel.EntityID); auto absOrientation = Transform::AbsoluteOrientation(world, cModel.EntityID); auto absScale = Transform::AbsoluteScale(world, cModel.EntityID); - glm::mat4 modelMatrix = glm::translate(absPosition); // *glm::toMat4(absOrientation) * glm::scale(absScale); + glm::mat4 modelMatrix = glm::translate(absPosition) * glm::toMat4(absOrientation) * glm::scale(absScale); RawModel* model = ResourceManager::Load(cModel["Resource"]); glm::vec3 resolutionVector; if (Collision::AABBvsTriangles(boxA, model->m_Vertices, model->m_Indices, modelMatrix, resolutionVector)) { - //TODO: remove Temp. - (glm::vec3&)cTransform["Position"] = glm::vec3(2, 2, 2); - //(glm::vec3&)cTransform["Position"] += resolutionVector; + (glm::vec3&)cTransform["Position"] += resolutionVector; } } } diff --git a/src/Engine/Core/Transform.cpp b/src/Engine/Core/Transform.cpp index cbc405a3..054b1984 100644 --- a/src/Engine/Core/Transform.cpp +++ b/src/Engine/Core/Transform.cpp @@ -50,3 +50,7 @@ glm::mat4 Transform::ModelMatrix(EntityID entity, World* world) return modelMatrix; } +glm::vec3 Transform::TransformPoint(const glm::vec3& point, const glm::mat4& matrix) +{ + return glm::vec3(matrix * glm::vec4(point.x, point.y, point.z, 1)); +} \ No newline at end of file From 52765cc85bccfc3f4eaddefefcb404350fdc125f Mon Sep 17 00:00:00 2001 From: William Moberg Date: Fri, 22 Jan 2016 11:22:56 +0100 Subject: [PATCH 003/355] TriangleVsBox detection seems to work in all cases, but cannot resolve all cases yet. Also added default ctor for Ray and removed compilation errors in CollisionSystem. --- include/Engine/Core/Ray.h | 4 + src/Engine/Collision/Collision.cpp | 177 ++--------------------- src/Engine/Collision/CollisionSystem.cpp | 12 +- 3 files changed, 25 insertions(+), 168 deletions(-) diff --git a/include/Engine/Core/Ray.h b/include/Engine/Core/Ray.h index a234a488..03bfa391 100644 --- a/include/Engine/Core/Ray.h +++ b/include/Engine/Core/Ray.h @@ -7,6 +7,10 @@ class Ray { public: + Ray() + : m_Origin(glm::vec3(0.f)) + , m_Direction(glm::vec3(0, 0, 1)) + {} Ray(const glm::vec3& origin, const glm::vec3& dir) : m_Origin(origin) , m_Direction(glm::normalize(dir)) diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index 6794f5b9..d643e8cc 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -217,11 +217,6 @@ bool RayVsModel(const Ray& ray, return hit; } -constexpr inline int squareOf(float x) -{ - return x * x; -} - constexpr inline int signNonZero(float x) { return x < 0 ? -1 : 1; @@ -236,101 +231,17 @@ inline glm::vec3 signNonZero(const glm::vec3& x) return r; } -bool lineIntersectsBox(const AABB& box, const glm::vec3& v0, const glm::vec3& v1) -{ - const glm::vec3 edgevec = v1 - v0; - glm::vec3 edgevec_signs = signNonZero(edgevec); - - for (int i = 0; i < 3; ++i) - edgevec_signs[i] = signNonZero(edgevec[i]); - - /* - * Test the three cube faces on the v1-ward side of the cube-- - * if v0 is outside any of their planes then there is no intersection. - * Also test the three cube faces on the v0-ward side of the cube-- - * if v1 is outside any of their planes then there is no intersection. - */ - - for (int i = 0; i < 3; ++i) - { - if (v0[i] * edgevec_signs[i] > .5) return false; - if (v1[i] * edgevec_signs[i] < -.5) return false; - } - - /* - * Okay, that's the six easy faces of the rhombic dodecahedron - * out of the way. Six more to go. - * The remaining six planes bound an infinite hexagonal prism - * joining the petrie polygons (skew hexagons) of the two cubes - * centered at the endpoints. - */ - - for (int i = 0; i < 3; ++i) - { - float rhomb_normal_dot_v0, rhomb_normal_dot_cubedge; - - int iplus1 = (i + 1) % 3; - int iplus2 = (i + 2) % 3; - -#ifdef THE_EASY_TO_UNDERSTAND_WAY - - { - real rhomb_normal[3], cubedge_midpoint[3]; - - /* - * rhomb_normal = VXV3(edgevec, unit vector in direction i), - * being cavalier about which direction it's facing - */ - rhomb_normal[i] = 0; - rhomb_normal[iplus1] = edgevec[iplus2]; - rhomb_normal[iplus2] = -edgevec[iplus1]; - - /* - * We now are describing a plane parallel to - * both segment and the cube edge in question. - * if |DOT3(rhomb_normal, an arbitrary point on the segment)| > - * |DOT3(rhomb_normal, an arbitrary point on the cube edge in question| - * then the origin is outside this pair of opposite faces. - * (This is equivalent to saying that the line - * containing the segment is "outside" (i.e. further away from the - * origin than) the line containing the cube edge. - */ - - cubedge_midpoint[i] = 0; - cubedge_midpoint[iplus1] = edgevec_signs[iplus1] * .5; - cubedge_midpoint[iplus2] = -edgevec_signs[iplus2] * .5; - - rhomb_normal_dot_v0 = DOT3(rhomb_normal, v0); - rhomb_normal_dot_cubedge = DOT3(rhomb_normal, cubedge_midpoint); - } - -#else /* the efficient way */ - - rhomb_normal_dot_v0 = edgevec[iplus2] * v0[iplus1] - - edgevec[iplus1] * v0[iplus2]; - - rhomb_normal_dot_cubedge = .5 * - (edgevec[iplus2] * edgevec_signs[iplus1] + - edgevec[iplus1] * edgevec_signs[iplus2]); - -#endif /* the efficient way */ - - if (squareOf(rhomb_normal_dot_v0) > squareOf(rhomb_normal_dot_cubedge)) - return false; /* origin is outside this pair of opposite planes */ - } - return true; -} bool vectorHasLength(const glm::vec3& vec) { - return glm::all(glm::lessThan(glm::abs(vec), glm::vec3(0.0001f, 0.0001f, 0.0001f))); + return glm::any(glm::greaterThan(glm::abs(vec), glm::vec3(0.0001f, 0.0001f, 0.0001f))); } bool AABBvsTriangle(const AABB& box, const glm::vec3& v0, const glm::vec3& v1, const glm::vec3& v2, glm::vec3& outResolutionVector) { //Check so we don't have a zero area triangle when calculating the normal. glm::vec3 triNormal = glm::cross(v1 - v0, v2 - v0); - if (vectorHasLength(triNormal)) { + if (!vectorHasLength(triNormal)) { return false; } @@ -366,14 +277,15 @@ bool AABBvsTriangle(const AABB& box, const glm::vec3& v0, const glm::vec3& v1, c return true; //TODO: Resolve. } - glm::vec3 triPosInBoxSpace[3]; - for (int i = 0; i < 3; ++i) { - triPosInBoxSpace[i] = (triPos[i] - origin) / (2.0f * half); - } + Ray ray; //All triangle lines. //Check if each line on the triangle intersects any plane on the box. for (int l = 0; l < 3; ++l) { - if (lineIntersectsBox(box, triPosInBoxSpace[l], triPosInBoxSpace[(l + 1) % 3])) { + glm::vec3 edge = triPos[(l + 1) % 3] - triPos[l]; + ray.SetOrigin(triPos[l]); + ray.SetDirection(edge); + float dist; + if (RayVsAABB(ray, box, dist) && dist <= glm::length(edge)) { outResolutionVector = glm::vec3(0.f); LOG_DEBUG("Triangle collision lines"); return true; //TODO: Resolve. @@ -402,7 +314,8 @@ bool AABBvsTriangle(const AABB& box, const glm::vec3& v0, const glm::vec3& v1, c #endif //Check if intersection point is on the triangle. - Ray ray(origin, diagonal); + ray.SetOrigin(origin); + ray.SetDirection(diagonal); float dist = INFINITY, u, v; if (RayVsTriangle(ray, v0, v1, v2, dist, u, v, true)) { #ifndef EARLY_OUT_OR_MAYBE_JUST_EXTRA_WORK @@ -421,6 +334,7 @@ bool AABBvsTriangle(const AABB& box, const glm::vec3& v0, const glm::vec3& v1, c bool AABBvsTriangles(const AABB& box, const std::vector& modelVertices, const std::vector& modelIndices, const glm::mat4& modelMatrix, glm::vec3& outResolutionVector) { bool hit = false; + outResolutionVector = glm::vec3(INFINITY); for (int i = 0; i < modelIndices.size(); i += 3) { glm::vec3 resVec; if (AABBvsTriangle( @@ -438,72 +352,11 @@ bool AABBvsTriangles(const AABB& box, const std::vector& model } } } - return hit; - //TODO: Remove old code. - - /* - auto hit = glm::tvec3(false); - const glm::vec3& origin = box.Origin(); - const glm::vec3& min = box.MinCorner(); - const glm::vec3& max = box.MaxCorner(); - const glm::vec3& half = box.HalfSize(); - - float minResolution = INFINITY; - outResolutionVector = glm::vec3(0.f); - //TODO: Don't need indices? Remove? - for (const auto& v : modelVertices) { - glm::vec3 p = v.Position; - p = glm::vec3(modelMatrix * glm::vec4(p.x, p.y, p.z, 1)); - - const glm::vec3 diffO = origin - p; - const glm::vec3 distO = glm::abs(diffO); - for (int axis = 0; axis < 3; ++axis) { - float penetration = half[axis] - distO[axis]; - if (penetration > 0){ - if (penetration < minResolution) { - minResolution = penetration; - outResolutionVector = glm::vec3(0.f); - if (p[axis] > origin[axis]) { - outResolutionVector[axis] = -penetration; - } else { - outResolutionVector[axis] = penetration; - } - } - hit[axis] = true; - } - } - - //float distFromOrigin = glm::abs(origin.x - p.x); - //float penetration = box.HalfSize().x - distFromOrigin; - //if (penetration > 0 && penetration < glm::abs(outResolutionVector.x)) { - // if (p.x > origin.x) { - // outResolutionVector.x = -penetration; - // } else { - // outResolutionVector.x = penetration; - // } - // hit = true; - //} - - //glm::vec3 pLocal = origin - p; - //for (int axis = 0; axis < 3; ++axis) { - // if (p[axis] < min[axis] || p[axis] > max[axis]) { - // continue; - // } - - // if (glm::abs(pLocal[axis]) < box.HalfSize()[axis]) { - // outResolutionVector[axis] = (glm::sign(pLocal[axis]) * box.HalfSize()[axis]) - pLocal[axis]; - // hit = true; - // } - //} + //TODO: Unnecessary later, remove it. + if (glm::any(glm::isinf(outResolutionVector))) { + outResolutionVector = glm::vec3(0, 0, 0); } - - //for (int axis = 0; axis < 3; ++axis) { - // if (glm::isinf(outResolutionVector[axis])) { - // outResolutionVector[axis] = 0.f; - // } - //} - - return glm::all(hit);*/ + return hit; } bool IsSameBoxProbably(const AABB& first, const AABB& second, const float epsilon) diff --git a/src/Engine/Collision/CollisionSystem.cpp b/src/Engine/Collision/CollisionSystem.cpp index 84608fbd..657cc90b 100644 --- a/src/Engine/Collision/CollisionSystem.cpp +++ b/src/Engine/Collision/CollisionSystem.cpp @@ -37,18 +37,18 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c //} // HACK: Temporarily collide against all collidable models since they're not in the octree yet - auto otherCollidables = world->GetComponents("Model"); + auto otherCollidables = m_World->GetComponents("Model"); for (auto& cModel : *otherCollidables) { - if (cModel.EntityID == EntityID(entity)) { + if (cModel.EntityID == entity.ID) { continue; } - if (!world->HasComponent(cModel.EntityID, "Collidable")) { + if (!m_World->HasComponent(cModel.EntityID, "Collidable")) { continue; } - auto absPosition = Transform::AbsolutePosition(world, cModel.EntityID); - auto absOrientation = Transform::AbsoluteOrientation(world, cModel.EntityID); - auto absScale = Transform::AbsoluteScale(world, cModel.EntityID); + auto absPosition = Transform::AbsolutePosition(m_World, cModel.EntityID); + auto absOrientation = Transform::AbsoluteOrientation(m_World, cModel.EntityID); + auto absScale = Transform::AbsoluteScale(m_World, cModel.EntityID); glm::mat4 modelMatrix = glm::translate(absPosition) * glm::toMat4(absOrientation) * glm::scale(absScale); RawModel* model = ResourceManager::Load(cModel["Resource"]); From 3955e1d60c1d388b39599c5eaa3c343d064bac85 Mon Sep 17 00:00:00 2001 From: William Moberg Date: Fri, 22 Jan 2016 13:46:09 +0100 Subject: [PATCH 004/355] Can resolve collision when AABB corners cut through triangle. At least two more cases left to resolve. --- .../Schema/Entities/ModelCollisionTest.xml | 35 ++++++++++++++----- src/Engine/Collision/Collision.cpp | 8 ++--- src/Engine/Collision/CollisionSystem.cpp | 8 ++++- 3 files changed, 37 insertions(+), 14 deletions(-) diff --git a/resources/Schema/Entities/ModelCollisionTest.xml b/resources/Schema/Entities/ModelCollisionTest.xml index fd26f0c5..f7a547f5 100644 --- a/resources/Schema/Entities/ModelCollisionTest.xml +++ b/resources/Schema/Entities/ModelCollisionTest.xml @@ -2,7 +2,9 @@ - + + + @@ -11,8 +13,8 @@ - - + + @@ -21,25 +23,40 @@ - ../assets/Models/Core/UnitCube.obj - + ../assets/Models/Core/UnitQuad.obj + - + + + - + + + + + ../assets/Models/Core/UnitQuad.obj + + + + + + + + + - ../assets/Models/Core/UnitCube.obj + - + diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index d643e8cc..d174eb86 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -299,7 +299,7 @@ bool AABBvsTriangle(const AABB& box, const glm::vec3& v0, const glm::vec3& v1, c //closest to being perpendicular to the plane of the polygon. triNormal = glm::normalize(triNormal); - glm::vec3 diagonal = signNonZero(triNormal) * half; + glm::vec3 diagonal = -signNonZero(triNormal) * half; #define EARLY_OUT_OR_MAYBE_JUST_EXTRA_WORK #ifdef EARLY_OUT_OR_MAYBE_JUST_EXTRA_WORK //The triangle plane contains all points P in dot(triNormal, P) == dot(triNormal, v0) @@ -323,9 +323,9 @@ bool AABBvsTriangle(const AABB& box, const glm::vec3& v0, const glm::vec3& v1, c return false; } #endif - float dist = glm::dot(triNormal, origin + diagonal - v0); - outResolutionVector = dist * triNormal; - LOG_DEBUG("Triangle collision corner"); + //Distance between triangle plane, and the diagonal corner, multiplied by the normal. + //Signed distance, positive if on the same side as the normal. + outResolutionVector = -glm::dot(triNormal, origin + diagonal - v0) * triNormal; return true; } return false; diff --git a/src/Engine/Collision/CollisionSystem.cpp b/src/Engine/Collision/CollisionSystem.cpp index 657cc90b..11d2a836 100644 --- a/src/Engine/Collision/CollisionSystem.cpp +++ b/src/Engine/Collision/CollisionSystem.cpp @@ -51,7 +51,13 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c auto absScale = Transform::AbsoluteScale(m_World, cModel.EntityID); glm::mat4 modelMatrix = glm::translate(absPosition) * glm::toMat4(absOrientation) * glm::scale(absScale); - RawModel* model = ResourceManager::Load(cModel["Resource"]); + RawModel* model; + try { + model = ResourceManager::Load(cModel["Resource"]); + } catch (const std::exception&) { + continue; + } + glm::vec3 resolutionVector; if (Collision::AABBvsTriangles(boxA, model->m_Vertices, model->m_Indices, modelMatrix, resolutionVector)) { (glm::vec3&)cTransform["Position"] += resolutionVector; From 1670fb4e48f4e9aa215512a7238ec49898074ba3 Mon Sep 17 00:00:00 2001 From: William Moberg Date: Fri, 22 Jan 2016 14:45:50 +0100 Subject: [PATCH 005/355] Moved triangle vs ray code to method. --- include/Engine/Collision/Collision.h | 6 ++++ src/Engine/Collision/Collision.cpp | 54 +++++++++++++++++----------- 2 files changed, 39 insertions(+), 21 deletions(-) diff --git a/include/Engine/Collision/Collision.h b/include/Engine/Collision/Collision.h index b32d190a..4e764905 100644 --- a/include/Engine/Collision/Collision.h +++ b/include/Engine/Collision/Collision.h @@ -26,6 +26,12 @@ bool RayVsAABB(const Ray& ray, const AABB& box); //Return true if the ray hits the box, also outputs distance from ray origin to intersection point in [outDistance]. bool RayVsAABB(const Ray& ray, const AABB& box, float& outDistance); +//Return true if the ray hits the triangle. +bool RayVsTriangle(const Ray& ray, + const glm::vec3& v0, + const glm::vec3& v1, + const glm::vec3& v2, + bool trueOnNegativeDistance = false); //Return true if the ray hits the triangle, and the distance is less than outDistance. bool RayVsTriangle(const Ray& ray, const glm::vec3& v0, diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index d174eb86..d44c97be 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -116,30 +116,41 @@ bool AABBVsAABB(const AABB& a, const AABB& b, glm::vec3& minimumTranslation) return glm::all(axisesIntersecting); } +bool RayVsTriangle(const Ray& ray, + const glm::vec3& v0, + const glm::vec3& v1, + const glm::vec3& v2, + bool trueOnNegativeDistance) +{ + glm::vec3 e1 = v1 - v0; //v1 - v0 + glm::vec3 e2 = v2 - v0; //v2 - v0 + glm::vec3 m = ray.Origin() - v0; + glm::vec3 MxE1 = glm::cross(m, e1); + glm::vec3 DxE2 = glm::cross(ray.Direction(), e2); + float DetInv = glm::dot(e1, DxE2); + if (std::abs(DetInv) < FLT_EPSILON) { + return false; + } + DetInv = 1.0f / DetInv; + float u = glm::dot(m, DxE2) * DetInv; + float v = glm::dot(ray.Direction(), MxE1) * DetInv; + //u,v can be very close to 0 but still negative sometimes. added a deltafactor to compensate for that problem + if ((u + 0.001f) < 0 || (v + 0.001f) < 0 || 1 < u + v) { + return false; + } + //Here, u and v are positive, u+v <= 1, and if distance is positive - triangle is hit. + return trueOnNegativeDistance || 0 <= glm::dot(e2, MxE1) * DetInv; +} + bool RayVsModel(const Ray& ray, const std::vector& modelVertices, const std::vector& modelIndices) { for (int i = 0; i < modelIndices.size(); ++i) { glm::vec3 v0 = modelVertices[modelIndices[i]].Position; - glm::vec3 e1 = modelVertices[modelIndices[++i]].Position - v0; //v1 - v0 - glm::vec3 e2 = modelVertices[modelIndices[++i]].Position - v0; //v2 - v0 - glm::vec3 m = ray.Origin() - v0; - glm::vec3 MxE1 = glm::cross(m, e1); - glm::vec3 DxE2 = glm::cross(ray.Direction(), e2); - float DetInv = glm::dot(e1, DxE2); - if (std::abs(DetInv) < FLT_EPSILON) { - continue; - } - DetInv = 1.0f / DetInv; - float u = glm::dot(m, DxE2) * DetInv; - float v = glm::dot(ray.Direction(), MxE1) * DetInv; - //u,v can be very close to 0 but still negative sometimes. added a deltafactor to compensate for that problem - if ((u + 0.001f) < 0 || (v + 0.001f) < 0 || 1 < u + v) { - continue; - } - //Here, u and v are positive, u+v <= 1, and if distance is positive - triangle is hit. - if (0 <= glm::dot(e2, MxE1) * DetInv) { + glm::vec3 v1 = modelVertices[modelIndices[++i]].Position; + glm::vec3 v2 = modelVertices[modelIndices[++i]].Position; + if (RayVsTriangle(ray, v0, v1, v2)) { return true; } } @@ -300,7 +311,7 @@ bool AABBvsTriangle(const AABB& box, const glm::vec3& v0, const glm::vec3& v1, c triNormal = glm::normalize(triNormal); glm::vec3 diagonal = -signNonZero(triNormal) * half; -#define EARLY_OUT_OR_MAYBE_JUST_EXTRA_WORK +#define EARLY_OUT_OR_MAYBE_JUST_EXTRA_WORK //TODO: We should probably performance test with this on/off. #ifdef EARLY_OUT_OR_MAYBE_JUST_EXTRA_WORK //The triangle plane contains all points P in dot(triNormal, P) == dot(triNormal, v0) //The diagonal line contains all points P in P = origin + diagonal * t. @@ -310,15 +321,16 @@ bool AABBvsTriangle(const AABB& box, const glm::vec3& v0, const glm::vec3& v1, c if (glm::abs(t) > 1) { return false; } - //glm::vec3 intersection = origin + t * diagonal; #endif //Check if intersection point is on the triangle. ray.SetOrigin(origin); ray.SetDirection(diagonal); +#ifdef EARLY_OUT_OR_MAYBE_JUST_EXTRA_WORK + if (RayVsTriangle(ray, v0, v1, v2, true)) { +#else float dist = INFINITY, u, v; if (RayVsTriangle(ray, v0, v1, v2, dist, u, v, true)) { -#ifndef EARLY_OUT_OR_MAYBE_JUST_EXTRA_WORK if (glm::abs(dist) > glm::length(diagonal)) { return false; } From 3974c649ab8297a8dbf4750643f474f761fa9182 Mon Sep 17 00:00:00 2001 From: William Moberg Date: Sat, 23 Jan 2016 10:45:50 +0100 Subject: [PATCH 006/355] WIP on ModelBoxCollision. Octree works in Release mode. --- include/Engine/Collision/CollisionSystem.h | 7 -- include/Engine/Core/Octree.h | 2 +- .../Schema/Entities/ModelCollisionTest.xml | 6 +- src/Engine/Collision/Collision.cpp | 86 +++++++++++++------ src/Engine/Collision/CollisionSystem.cpp | 13 --- src/Engine/Core/Octree.cpp | 5 -- 6 files changed, 64 insertions(+), 55 deletions(-) diff --git a/include/Engine/Collision/CollisionSystem.h b/include/Engine/Collision/CollisionSystem.h index 5f15a3d5..93ec3d76 100644 --- a/include/Engine/Collision/CollisionSystem.h +++ b/include/Engine/Collision/CollisionSystem.h @@ -17,20 +17,13 @@ public: : System(world, eventBroker) , PureSystem("Collidable") , m_Octree(octree) - , zPress(false) { - //TODO: Debug stuff, remove later. - EVENT_SUBSCRIBE_MEMBER(m_EKeyUp, &CollisionSystem::OnKeyUp); } virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) override; private: Octree* m_Octree; - bool zPress; - - EventRelay m_EKeyUp; - bool OnKeyUp(const Events::KeyUp &event); }; #endif \ No newline at end of file diff --git a/include/Engine/Core/Octree.h b/include/Engine/Core/Octree.h index bbd27b3c..907d5736 100644 --- a/include/Engine/Core/Octree.h +++ b/include/Engine/Core/Octree.h @@ -111,7 +111,7 @@ struct Child std::vector& m_StaticObjectsRef; std::vector& m_DynamicObjectsRef; - inline bool hasChildren() const; + inline bool hasChildren() const { return m_Children[0] != nullptr; } int childIndexContainingPoint(const glm::vec3& point) const; std::vector childIndicesContainingBox(const AABB& box) const; }; diff --git a/resources/Schema/Entities/ModelCollisionTest.xml b/resources/Schema/Entities/ModelCollisionTest.xml index f7a547f5..f2a78549 100644 --- a/resources/Schema/Entities/ModelCollisionTest.xml +++ b/resources/Schema/Entities/ModelCollisionTest.xml @@ -23,7 +23,7 @@ - ../assets/Models/Core/UnitQuad.obj + ../assets/Models/Core/Tri.obj @@ -36,11 +36,11 @@ - ../assets/Models/Core/UnitQuad.obj + ../assets/Models/Core/Tri.obj - + diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index d44c97be..f040ccd5 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -248,7 +248,12 @@ bool vectorHasLength(const glm::vec3& vec) return glm::any(glm::greaterThan(glm::abs(vec), glm::vec3(0.0001f, 0.0001f, 0.0001f))); } -bool AABBvsTriangle(const AABB& box, const glm::vec3& v0, const glm::vec3& v1, const glm::vec3& v2, glm::vec3& outResolutionVector) +bool AABBvsTriangle(const AABB& box, + const glm::vec3& v0, + const glm::vec3& v1, + const glm::vec3& v2, + glm::vec3& outVector, + int& lineHit) { //Check so we don't have a zero area triangle when calculating the normal. glm::vec3 triNormal = glm::cross(v1 - v0, v2 - v0); @@ -283,23 +288,22 @@ bool AABBvsTriangle(const AABB& box, const glm::vec3& v0, const glm::vec3& v1, c insideAllPlanes[ax] = glm::all(insidePlanes); } if (glm::all(insideAllPlanes)) { - outResolutionVector = glm::vec3(0.f); - LOG_DEBUG("Triangle collision inside"); - return true; //TODO: Resolve. + return false; //If a triangle is completely inside the box, we call it a non-intersection. } + triNormal = glm::normalize(triNormal); Ray ray; - //All triangle lines. - //Check if each line on the triangle intersects any plane on the box. + //All triangle edges. + //Check if any edge on the triangle intersects the box. for (int l = 0; l < 3; ++l) { glm::vec3 edge = triPos[(l + 1) % 3] - triPos[l]; ray.SetOrigin(triPos[l]); ray.SetDirection(edge); float dist; if (RayVsAABB(ray, box, dist) && dist <= glm::length(edge)) { - outResolutionVector = glm::vec3(0.f); - LOG_DEBUG("Triangle collision lines"); - return true; //TODO: Resolve. + outVector = triNormal; + lineHit = l; + return true; } } @@ -309,7 +313,6 @@ bool AABBvsTriangle(const AABB& box, const glm::vec3& v0, const glm::vec3& v1, c //intersect the cube diagonal that comes //closest to being perpendicular to the plane of the polygon. - triNormal = glm::normalize(triNormal); glm::vec3 diagonal = -signNonZero(triNormal) * half; #define EARLY_OUT_OR_MAYBE_JUST_EXTRA_WORK //TODO: We should probably performance test with this on/off. #ifdef EARLY_OUT_OR_MAYBE_JUST_EXTRA_WORK @@ -337,7 +340,7 @@ bool AABBvsTriangle(const AABB& box, const glm::vec3& v0, const glm::vec3& v1, c #endif //Distance between triangle plane, and the diagonal corner, multiplied by the normal. //Signed distance, positive if on the same side as the normal. - outResolutionVector = -glm::dot(triNormal, origin + diagonal - v0) * triNormal; + outVector = -glm::dot(triNormal, origin + diagonal - v0) * triNormal; return true; } return false; @@ -345,28 +348,59 @@ bool AABBvsTriangle(const AABB& box, const glm::vec3& v0, const glm::vec3& v1, c bool AABBvsTriangles(const AABB& box, const std::vector& modelVertices, const std::vector& modelIndices, const glm::mat4& modelMatrix, glm::vec3& outResolutionVector) { + struct Triangle + { + glm::vec3 v0, v1, v2; + }; bool hit = false; - outResolutionVector = glm::vec3(INFINITY); + bool cornerHitTODO = false; + outResolutionVector = glm::vec3(0.f); + std::vector hitTriangles; + std::vector hitNormals; for (int i = 0; i < modelIndices.size(); i += 3) { - glm::vec3 resVec; - if (AABBvsTriangle( - box, - Transform::TransformPoint(modelVertices[modelIndices[i]].Position, modelMatrix), - Transform::TransformPoint(modelVertices[modelIndices[i + 1]].Position, modelMatrix), - Transform::TransformPoint(modelVertices[modelIndices[i + 2]].Position, modelMatrix), - resVec - )) + glm::vec3 outVec; + glm::vec3 v0 = Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix); + glm::vec3 v1 = Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix); + glm::vec3 v2 = Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix); + int lineHit = -1; + if (AABBvsTriangle(box, v0, v1, v2, outVec, lineHit)) { hit = true; - //If resolution distance is smaller than previous, and is non-zero. - if (glm::length(resVec) < glm::length(outResolutionVector) && vectorHasLength(resVec)) { - outResolutionVector = resVec; + if (lineHit == -1) { + outResolutionVector += outVec; + //TODO: We might be able to return here instead, having only convex geometry. + cornerHitTODO = true; + //return true; + } + else { + const glm::vec3 triPos[] = { + v0, v1, v2 + }; + glm::vec3 edge = triPos[(lineHit + 1) % 3] - triPos[lineHit]; + hitTriangles.push_back({v0, v1, v2}); + hitNormals.push_back(outVec); } } } - //TODO: Unnecessary later, remove it. - if (glm::any(glm::isinf(outResolutionVector))) { - outResolutionVector = glm::vec3(0, 0, 0); + if (hitTriangles.size() > 0) { + if (cornerHitTODO) { + LOG_DEBUG("Both edges and corners was hit on the same model."); + return true; + } + for (const glm::vec3& norm : hitNormals) { + outResolutionVector += norm; + } + //Normalize. + outResolutionVector /= hitNormals.size(); + const glm::vec3& origin = box.Origin(); + const glm::vec3& half = box.HalfSize(); + float maxDist = -10; + for (const Triangle& tri : hitTriangles) { + float d = glm::dot(outResolutionVector, 0.333f * (tri.v0 + tri.v1 + tri.v2) - origin); + maxDist = std::max(maxDist, d); + } + glm::vec3 tmp = glm::clamp(2.0f * outResolutionVector, glm::vec3(-1, -1, -1), glm::vec3(1, 1, 1)); + outResolutionVector *= maxDist + glm::length(tmp * half); } return hit; } diff --git a/src/Engine/Collision/CollisionSystem.cpp b/src/Engine/Collision/CollisionSystem.cpp index 11d2a836..452a73ef 100644 --- a/src/Engine/Collision/CollisionSystem.cpp +++ b/src/Engine/Collision/CollisionSystem.cpp @@ -17,11 +17,6 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c ComponentWrapper& cTransform = entity["Transform"]; AABB& boxA = *boundingBox; - //Press 'Z' to enable/disable collision. - if (zPress) { - return; - } - // Collide against octree //std::vector octreeResult; //m_Octree->ObjectsInSameRegion(*boundingBox, octreeResult); @@ -64,11 +59,3 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c } } } - -bool CollisionSystem::OnKeyUp(const Events::KeyUp & event) -{ - if (event.KeyCode == GLFW_KEY_Z) { - zPress = !zPress; - } - return false; -} diff --git a/src/Engine/Core/Octree.cpp b/src/Engine/Core/Octree.cpp index d7feba45..f6e358c8 100644 --- a/src/Engine/Core/Octree.cpp +++ b/src/Engine/Core/Octree.cpp @@ -276,9 +276,4 @@ std::vector Child::childIndicesContainingBox(const AABB& box) const } } -inline bool Child::hasChildren() const -{ - return m_Children[0] != nullptr; -} - } \ No newline at end of file From 71404c882819a10a4016cf95b032f67736911d11 Mon Sep 17 00:00:00 2001 From: William Moberg Date: Sat, 23 Jan 2016 14:01:54 +0100 Subject: [PATCH 007/355] Special case for collision vs ground (upward facing) triangles. --- .../Schema/Entities/CollisionTestLevel.xml | 186 ++++++------------ src/Engine/Collision/Collision.cpp | 92 ++++++--- src/Engine/Collision/CollisionSystem.cpp | 1 + 3 files changed, 134 insertions(+), 145 deletions(-) diff --git a/resources/Schema/Entities/CollisionTestLevel.xml b/resources/Schema/Entities/CollisionTestLevel.xml index d5e932c2..76a3b6e6 100644 --- a/resources/Schema/Entities/CollisionTestLevel.xml +++ b/resources/Schema/Entities/CollisionTestLevel.xml @@ -1,122 +1,66 @@ - + + - - - - - - - Models/DummyScene.obj - - - - - - - - - - - Models/Core/UnitSphere.obj - - - - - - - - - - - Models/RotationWidgetX.obj - - - - - - - - - - - - - - - Models/Core/UnitCube.obj - - - - - - - - - - - - - - - - - - - - - - Models/Core/UnitRaptor.obj - - - - - - - - - - - - 20 - - - - - - - - - - - - - Models/Core/UnitCube.obj - - - - - - - - - - - - - Models/Core/UnitCube.obj - - - - - - - - - - - - \ No newline at end of file + + + + + + + + + + + ../assets\Models\Test/ObstacleCourse.obj + + + + + + + + + + + 0.46000027656555176 + + + + + + + + + + + + + ../assets\Models\Core\UnitCube.obj + + + false + + + + + + + + + + + + + + ../assets\Models\Core\colorbox.obj + + + + + + + + + + + diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index f040ccd5..d134a5d8 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -4,6 +4,7 @@ #include "Engine/GLM.h" #include "Core/World.h" #include "Rendering/Model.h" +#include "imgui/imgui.h" namespace Collision { @@ -248,12 +249,21 @@ bool vectorHasLength(const glm::vec3& vec) return glm::any(glm::greaterThan(glm::abs(vec), glm::vec3(0.0001f, 0.0001f, 0.0001f))); } +enum BoxTriHit +{ + Line0 = 0, + Line1, + Line2, + Ground, + Corner +}; + bool AABBvsTriangle(const AABB& box, const glm::vec3& v0, const glm::vec3& v1, const glm::vec3& v2, glm::vec3& outVector, - int& lineHit) + BoxTriHit& outHit) { //Check so we don't have a zero area triangle when calculating the normal. glm::vec3 triNormal = glm::cross(v1 - v0, v2 - v0); @@ -266,6 +276,23 @@ bool AABBvsTriangle(const AABB& box, const glm::vec3& min = box.MinCorner(); const glm::vec3& max = box.MaxCorner(); + //Check if normal faces upwards, and if so, just push the box upwards on collision. + triNormal = glm::normalize(triNormal); + if (triNormal.y > 0.5f || true) { + //TODO: Optimize calculation since x, z is 0. + //Ray ray(glm::vec3(origin.x, origin.y + half.y, origin.z), glm::vec3(0, -1, 0)); + //float dist = INFINITY, u, v; + //if (RayVsTriangle(ray, v0, v1, v2, dist, u, v) && dist < 2.0f * half.y) { + Ray ray(origin, glm::vec3(0, -1, 0)); + float dist = INFINITY, u, v; + if (RayVsTriangle(ray, v0, v1, v2, dist, u, v) && dist < half.y) { + outVector = glm::vec3(0, half.y - dist, 0); + outHit = Ground; + return true; + } + //return false; //TODO: Uncomment? + } + const glm::vec3 triPos[] = { v0, v1, v2 }; @@ -291,7 +318,6 @@ bool AABBvsTriangle(const AABB& box, return false; //If a triangle is completely inside the box, we call it a non-intersection. } - triNormal = glm::normalize(triNormal); Ray ray; //All triangle edges. //Check if any edge on the triangle intersects the box. @@ -302,7 +328,7 @@ bool AABBvsTriangle(const AABB& box, float dist; if (RayVsAABB(ray, box, dist) && dist <= glm::length(edge)) { outVector = triNormal; - lineHit = l; + outHit = (BoxTriHit)l; return true; } } @@ -341,6 +367,7 @@ bool AABBvsTriangle(const AABB& box, //Distance between triangle plane, and the diagonal corner, multiplied by the normal. //Signed distance, positive if on the same side as the normal. outVector = -glm::dot(triNormal, origin + diagonal - v0) * triNormal; + outHit = Corner; return true; } return false; @@ -348,6 +375,7 @@ bool AABBvsTriangle(const AABB& box, bool AABBvsTriangles(const AABB& box, const std::vector& modelVertices, const std::vector& modelIndices, const glm::mat4& modelMatrix, glm::vec3& outResolutionVector) { + AABB newBox = box; struct Triangle { glm::vec3 v0, v1, v2; @@ -362,45 +390,61 @@ bool AABBvsTriangles(const AABB& box, const std::vector& model glm::vec3 v0 = Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix); glm::vec3 v1 = Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix); glm::vec3 v2 = Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix); - int lineHit = -1; - if (AABBvsTriangle(box, v0, v1, v2, outVec, lineHit)) + BoxTriHit hitCase; + if (AABBvsTriangle(newBox, v0, v1, v2, outVec, hitCase)) { hit = true; - if (lineHit == -1) { - outResolutionVector += outVec; - //TODO: We might be able to return here instead, having only convex geometry. - cornerHitTODO = true; - //return true; - } - else { - const glm::vec3 triPos[] = { - v0, v1, v2 - }; - glm::vec3 edge = triPos[(lineHit + 1) % 3] - triPos[lineHit]; + switch (hitCase) { + case Collision::Line0: + case Collision::Line1: + case Collision::Line2: + //TODO: Resolve. + //const glm::vec3 triPos[] = { + // v0, v1, v2 + //}; + //glm::vec3 edge = triPos[(hitCase + 1) % 3] - triPos[hitCase]; hitTriangles.push_back({v0, v1, v2}); hitNormals.push_back(outVec); + ImGui::Text("triangle edge collision."); + break; + case Collision::Corner: + //TODO: We might be able to return here instead, having only convex geometry. + cornerHitTODO = true; + //outResolutionVector += outVec; + //return true; + ImGui::Text("triangle corner collision."); + outResolutionVector += outVec; + newBox = AABB::FromOriginSize(newBox.Origin() + outVec, newBox.Size()); + break; + case Collision::Ground: + default: + outResolutionVector += outVec; + newBox = AABB::FromOriginSize(newBox.Origin() + outVec, newBox.Size()); + ImGui::Text("triangle ground collision."); + break; } } } if (hitTriangles.size() > 0) { if (cornerHitTODO) { - LOG_DEBUG("Both edges and corners was hit on the same model."); + ImGui::Text("Both edges and corners was hit on the same model."); return true; } + glm::vec3 lineResolve(0.f); for (const glm::vec3& norm : hitNormals) { - outResolutionVector += norm; + lineResolve += norm; } //Normalize. - outResolutionVector /= hitNormals.size(); - const glm::vec3& origin = box.Origin(); - const glm::vec3& half = box.HalfSize(); + lineResolve /= hitNormals.size(); + const glm::vec3& origin = newBox.Origin(); + const glm::vec3& half = newBox.HalfSize(); float maxDist = -10; for (const Triangle& tri : hitTriangles) { - float d = glm::dot(outResolutionVector, 0.333f * (tri.v0 + tri.v1 + tri.v2) - origin); + float d = glm::dot(lineResolve, 0.333f * (tri.v0 + tri.v1 + tri.v2) - origin); maxDist = std::max(maxDist, d); } - glm::vec3 tmp = glm::clamp(2.0f * outResolutionVector, glm::vec3(-1, -1, -1), glm::vec3(1, 1, 1)); - outResolutionVector *= maxDist + glm::length(tmp * half); + glm::vec3 tmp = glm::clamp(2.0f * lineResolve, glm::vec3(-1, -1, -1), glm::vec3(1, 1, 1)); + outResolutionVector += lineResolve * (maxDist + glm::length(tmp * half)); } return hit; } diff --git a/src/Engine/Collision/CollisionSystem.cpp b/src/Engine/Collision/CollisionSystem.cpp index 452a73ef..20854c12 100644 --- a/src/Engine/Collision/CollisionSystem.cpp +++ b/src/Engine/Collision/CollisionSystem.cpp @@ -56,6 +56,7 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c glm::vec3 resolutionVector; if (Collision::AABBvsTriangles(boxA, model->m_Vertices, model->m_Indices, modelMatrix, resolutionVector)) { (glm::vec3&)cTransform["Position"] += resolutionVector; + cPhysics["Velocity"] = glm::vec3(0, 0, 0); } } } From 6eeb3ea5248e2a0acfa72d81f65363deb24a7038 Mon Sep 17 00:00:00 2001 From: William Moberg Date: Sat, 23 Jan 2016 17:50:35 +0100 Subject: [PATCH 008/355] WIP, Bug fix + nitpicks + optimizations. --- resources/Schema/Entities/CollisionTestLevel.xml | 3 ++- src/Engine/Collision/Collision.cpp | 16 ++++++++-------- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/resources/Schema/Entities/CollisionTestLevel.xml b/resources/Schema/Entities/CollisionTestLevel.xml index 76a3b6e6..5c029cf3 100644 --- a/resources/Schema/Entities/CollisionTestLevel.xml +++ b/resources/Schema/Entities/CollisionTestLevel.xml @@ -42,7 +42,8 @@ - + + diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index d134a5d8..2b4b989e 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -278,8 +278,8 @@ bool AABBvsTriangle(const AABB& box, //Check if normal faces upwards, and if so, just push the box upwards on collision. triNormal = glm::normalize(triNormal); - if (triNormal.y > 0.5f || true) { - //TODO: Optimize calculation since x, z is 0. + if (triNormal.y > 0.5f) { + //TODO: Optimize calculation since x, z is 0, y is -1. //Ray ray(glm::vec3(origin.x, origin.y + half.y, origin.z), glm::vec3(0, -1, 0)); //float dist = INFINITY, u, v; //if (RayVsTriangle(ray, v0, v1, v2, dist, u, v) && dist < 2.0f * half.y) { @@ -290,7 +290,7 @@ bool AABBvsTriangle(const AABB& box, outHit = Ground; return true; } - //return false; //TODO: Uncomment? + return false; } const glm::vec3 triPos[] = { @@ -300,7 +300,8 @@ bool AABBvsTriangle(const AABB& box, auto insideAllPlanes = glm::tvec3(false); //All triangle vertex points. //Check if the triangle is completely outside or inside the box. - for (int ax = 0; ax < 3; ++ax) { + //First test x, then z, lastly y, since y is least likely to result in a early false. + for (int ax : { 0, 2, 1 }) { auto outsideMinPlane = glm::tvec3(false); auto outsideMaxPlane = glm::tvec3(false); auto insidePlanes = glm::tvec3(false); @@ -385,14 +386,13 @@ bool AABBvsTriangles(const AABB& box, const std::vector& model outResolutionVector = glm::vec3(0.f); std::vector hitTriangles; std::vector hitNormals; - for (int i = 0; i < modelIndices.size(); i += 3) { + for (int i = 0; i < modelIndices.size(); ) { glm::vec3 outVec; glm::vec3 v0 = Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix); glm::vec3 v1 = Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix); glm::vec3 v2 = Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix); BoxTriHit hitCase; - if (AABBvsTriangle(newBox, v0, v1, v2, outVec, hitCase)) - { + if (AABBvsTriangle(newBox, v0, v1, v2, outVec, hitCase)) { hit = true; switch (hitCase) { case Collision::Line0: @@ -403,7 +403,7 @@ bool AABBvsTriangles(const AABB& box, const std::vector& model // v0, v1, v2 //}; //glm::vec3 edge = triPos[(hitCase + 1) % 3] - triPos[hitCase]; - hitTriangles.push_back({v0, v1, v2}); + hitTriangles.push_back({ v0, v1, v2 }); hitNormals.push_back(outVec); ImGui::Text("triangle edge collision."); break; From e6224a4e96ab9d9d67c43810353098207927213d Mon Sep 17 00:00:00 2001 From: William Moberg Date: Sat, 23 Jan 2016 18:31:27 +0100 Subject: [PATCH 009/355] WIP (not working), attempt at separating axis theorem stuff. --- src/Engine/Collision/Collision.cpp | 96 +++++------------------------- 1 file changed, 15 insertions(+), 81 deletions(-) diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index 2b4b989e..911b87bc 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -275,103 +275,37 @@ bool AABBvsTriangle(const AABB& box, const glm::vec3& half = box.HalfSize(); const glm::vec3& min = box.MinCorner(); const glm::vec3& max = box.MaxCorner(); - - //Check if normal faces upwards, and if so, just push the box upwards on collision. - triNormal = glm::normalize(triNormal); - if (triNormal.y > 0.5f) { - //TODO: Optimize calculation since x, z is 0, y is -1. - //Ray ray(glm::vec3(origin.x, origin.y + half.y, origin.z), glm::vec3(0, -1, 0)); - //float dist = INFINITY, u, v; - //if (RayVsTriangle(ray, v0, v1, v2, dist, u, v) && dist < 2.0f * half.y) { - Ray ray(origin, glm::vec3(0, -1, 0)); - float dist = INFINITY, u, v; - if (RayVsTriangle(ray, v0, v1, v2, dist, u, v) && dist < half.y) { - outVector = glm::vec3(0, half.y - dist, 0); - outHit = Ground; - return true; - } - return false; - } - const glm::vec3 triPos[] = { v0, v1, v2 }; - auto insideAllPlanes = glm::tvec3(false); - //All triangle vertex points. - //Check if the triangle is completely outside or inside the box. - //First test x, then z, lastly y, since y is least likely to result in a early false. - for (int ax : { 0, 2, 1 }) { - auto outsideMinPlane = glm::tvec3(false); - auto outsideMaxPlane = glm::tvec3(false); - auto insidePlanes = glm::tvec3(false); - for (int pos = 0; pos < 3; ++pos) { - outsideMinPlane[pos] = (min[ax] > triPos[pos][ax]); - outsideMaxPlane[pos] = (triPos[pos][ax] > max[ax]); - insidePlanes[pos] = !(outsideMinPlane[pos] || outsideMaxPlane[pos]); - } - if (glm::all(outsideMinPlane) || glm::all(outsideMaxPlane)) { - return false; - } - insideAllPlanes[ax] = glm::all(insidePlanes); - } - if (glm::all(insideAllPlanes)) { - return false; //If a triangle is completely inside the box, we call it a non-intersection. + for (int axis : {1, 0, 2}) { + //2D Triangle. + //for axis=0,1,2: 2d point takes from xy,xz,yx. + int dim1 = axis == 2 ? 0 : 1; //0,0,1 + int dim2 = axis == 0 ? 1 : 2; //1,2,2 + glm::vec2 t0(triPos[0][dim1], triPos[0][dim2]); + glm::vec2 t1(triPos[1][dim1], triPos[1][dim2]); + glm::vec2 t2(triPos[2][dim1], triPos[2][dim2]); + //Project tri, + //Project box, + //if projections don't overlap, return false. } - Ray ray; - //All triangle edges. - //Check if any edge on the triangle intersects the box. - for (int l = 0; l < 3; ++l) { - glm::vec3 edge = triPos[(l + 1) % 3] - triPos[l]; - ray.SetOrigin(triPos[l]); - ray.SetDirection(edge); - float dist; - if (RayVsAABB(ray, box, dist) && dist <= glm::length(edge)) { - outVector = triNormal; - outHit = (BoxTriHit)l; - return true; - } - } - - //None of the polygon's edges intersects the cube, finally, check if any of the four - //cube diagonals intersect the interior of the polygon. //If the polygon does intersect any of the cube diagonals, it will //intersect the cube diagonal that comes //closest to being perpendicular to the plane of the polygon. - + triNormal = glm::normalize(triNormal); glm::vec3 diagonal = -signNonZero(triNormal) * half; -#define EARLY_OUT_OR_MAYBE_JUST_EXTRA_WORK //TODO: We should probably performance test with this on/off. -#ifdef EARLY_OUT_OR_MAYBE_JUST_EXTRA_WORK //The triangle plane contains all points P in dot(triNormal, P) == dot(triNormal, v0) //The diagonal line contains all points P in P = origin + diagonal * t. float t = glm::dot(triNormal, v0 - origin) / glm::dot(triNormal, diagonal); - - //If intersection point between plane and diagonal is not within the box. + //If intersection point between plane and diagonal is within the box. if (glm::abs(t) > 1) { return false; } -#endif - - //Check if intersection point is on the triangle. - ray.SetOrigin(origin); - ray.SetDirection(diagonal); -#ifdef EARLY_OUT_OR_MAYBE_JUST_EXTRA_WORK - if (RayVsTriangle(ray, v0, v1, v2, true)) { -#else - float dist = INFINITY, u, v; - if (RayVsTriangle(ray, v0, v1, v2, dist, u, v, true)) { - if (glm::abs(dist) > glm::length(diagonal)) { - return false; - } -#endif - //Distance between triangle plane, and the diagonal corner, multiplied by the normal. - //Signed distance, positive if on the same side as the normal. - outVector = -glm::dot(triNormal, origin + diagonal - v0) * triNormal; - outHit = Corner; - return true; - } - return false; + //TODO: Resolve it. + return true; } bool AABBvsTriangles(const AABB& box, const std::vector& modelVertices, const std::vector& modelIndices, const glm::mat4& modelMatrix, glm::vec3& outResolutionVector) From 910b3d10e4b18f20a1e1ed32430e077d3f351943 Mon Sep 17 00:00:00 2001 From: William Moberg Date: Sun, 24 Jan 2016 15:32:10 +0100 Subject: [PATCH 010/355] WIP (false collisions), collision method expanded, not working. --- .../Schema/Entities/ModelCollisionTest.xml | 7 +- src/Engine/Collision/Collision.cpp | 184 +++++++++--------- 2 files changed, 97 insertions(+), 94 deletions(-) diff --git a/resources/Schema/Entities/ModelCollisionTest.xml b/resources/Schema/Entities/ModelCollisionTest.xml index f2a78549..c4a3f81b 100644 --- a/resources/Schema/Entities/ModelCollisionTest.xml +++ b/resources/Schema/Entities/ModelCollisionTest.xml @@ -27,9 +27,8 @@ - - - + + @@ -56,7 +55,7 @@ - + diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index 911b87bc..48a6a1e3 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -249,24 +249,70 @@ bool vectorHasLength(const glm::vec3& vec) return glm::any(glm::greaterThan(glm::abs(vec), glm::vec3(0.0001f, 0.0001f, 0.0001f))); } -enum BoxTriHit +bool AARectangleVsTriangle(const glm::vec2& boxMin, + const glm::vec2& boxMax, + const std::array& triPos) { - Line0 = 0, - Line1, - Line2, - Ground, - Corner -}; + //Project along box normals (coordinate axes, since it's axis-aligned). + for (int ax = 0; ax < 2; ++ax) { + float minTri = INFINITY; + float maxTri = -INFINITY; + for (const glm::vec2& t : triPos) { + minTri = std::min(t[ax], minTri); + maxTri = std::max(t[ax], maxTri); + } + if (minTri > boxMax[ax] || maxTri < boxMin[ax]) { + return false; + } + } + //Project along triangle normals. + //Put edges into normal vector, make normals in the loop. + std::array triNormals = { + triPos[1] - triPos[0], + triPos[2] - triPos[1], + triPos[0] - triPos[2] + }; + std::array boxPos = { + boxMax, + glm::vec2(boxMax.x, boxMin.y), + glm::vec2(boxMin.x, boxMax.y), + boxMin + }; + for (auto& normal : triNormals) { + //Rotate edge to a normal. + normal = glm::vec2(-normal.y, normal.x); + //Project triangle onto the normal. + float minTri = INFINITY; + float maxTri = -INFINITY; + for (const glm::vec2& point : triPos) { + float dot = glm::dot(normal, point); + minTri = std::min(dot, minTri); + maxTri = std::max(dot, maxTri); + } + //Project box onto the normal. + float minBox = INFINITY; + float maxBox = -INFINITY; + for (const glm::vec2& point : boxPos) { + float dot = glm::dot(normal, point); + minBox = std::min(dot, minTri); + maxBox = std::max(dot, maxTri); + } + if (maxBox < minTri || minBox > maxTri) { + return false; + } + } + return true; +} + +//An array containing 3 int pairs { 0, 2 }, { 0, 1 }, { 1, 2 } +constexpr std::array, 3> DimensionPairs({ std::pair(0, 2), std::pair(0, 1), std::pair(1, 2) }); bool AABBvsTriangle(const AABB& box, - const glm::vec3& v0, - const glm::vec3& v1, - const glm::vec3& v2, - glm::vec3& outVector, - BoxTriHit& outHit) + const std::array& triPos, + glm::vec3& outVector) { //Check so we don't have a zero area triangle when calculating the normal. - glm::vec3 triNormal = glm::cross(v1 - v0, v2 - v0); + glm::vec3 triNormal = glm::cross(triPos[1] - triPos[0], triPos[2] - triPos[0]); if (!vectorHasLength(triNormal)) { return false; } @@ -275,111 +321,69 @@ bool AABBvsTriangle(const AABB& box, const glm::vec3& half = box.HalfSize(); const glm::vec3& min = box.MinCorner(); const glm::vec3& max = box.MaxCorner(); - const glm::vec3 triPos[] = { - v0, v1, v2 - }; - - for (int axis : {1, 0, 2}) { + glm::tvec3 axisHit(false, false, false); + int i = 0; + for (std::pair dim : DimensionPairs) { //2D Triangle. //for axis=0,1,2: 2d point takes from xy,xz,yx. - int dim1 = axis == 2 ? 0 : 1; //0,0,1 - int dim2 = axis == 0 ? 1 : 2; //1,2,2 - glm::vec2 t0(triPos[0][dim1], triPos[0][dim2]); - glm::vec2 t1(triPos[1][dim1], triPos[1][dim2]); - glm::vec2 t2(triPos[2][dim1], triPos[2][dim2]); - //Project tri, - //Project box, + //Project triangle. + std::array t2D = { + glm::vec2(triPos[0][dim.first], triPos[0][dim.second]), + glm::vec2(triPos[1][dim.first], triPos[1][dim.second]), + glm::vec2(triPos[2][dim.first], triPos[2][dim.second]) + }; + //Project box. + glm::vec2 boxMin(min[dim.first], min[dim.second]); + glm::vec2 boxMax(max[dim.first], max[dim.second]); //if projections don't overlap, return false. + if (!AARectangleVsTriangle(boxMin, boxMax, t2D)) { + //return false; + } else { + axisHit[i] = true; + ImGui::Text("Triangle collision: Box axis %s", i == 0 ? "y" : i == 1 ? "z" : "x"); + } + ++i; } - //If the polygon does intersect any of the cube diagonals, it will + //If the triangle does intersect any of the cube diagonals, it will //intersect the cube diagonal that comes - //closest to being perpendicular to the plane of the polygon. + //closest to being perpendicular to the plane of the triangle. triNormal = glm::normalize(triNormal); glm::vec3 diagonal = -signNonZero(triNormal) * half; //The triangle plane contains all points P in dot(triNormal, P) == dot(triNormal, v0) //The diagonal line contains all points P in P = origin + diagonal * t. - float t = glm::dot(triNormal, v0 - origin) / glm::dot(triNormal, diagonal); + 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; + } else { + ImGui::Text("Triangle collision: Triangle axis."); + return glm::all(axisHit); } //TODO: Resolve it. + outVector = glm::vec3(0.f); return true; } bool AABBvsTriangles(const AABB& box, const std::vector& modelVertices, const std::vector& modelIndices, const glm::mat4& modelMatrix, glm::vec3& outResolutionVector) { AABB newBox = box; - struct Triangle - { - glm::vec3 v0, v1, v2; - }; bool hit = false; - bool cornerHitTODO = false; outResolutionVector = glm::vec3(0.f); - std::vector hitTriangles; - std::vector hitNormals; for (int i = 0; i < modelIndices.size(); ) { + std::array triVertices = { + Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix), + Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix), + Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix) + }; glm::vec3 outVec; - glm::vec3 v0 = Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix); - glm::vec3 v1 = Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix); - glm::vec3 v2 = Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix); - BoxTriHit hitCase; - if (AABBvsTriangle(newBox, v0, v1, v2, outVec, hitCase)) { + if (AABBvsTriangle(newBox, triVertices, outVec)) { + ImGui::Text("Triangle collision: True."); hit = true; - switch (hitCase) { - case Collision::Line0: - case Collision::Line1: - case Collision::Line2: - //TODO: Resolve. - //const glm::vec3 triPos[] = { - // v0, v1, v2 - //}; - //glm::vec3 edge = triPos[(hitCase + 1) % 3] - triPos[hitCase]; - hitTriangles.push_back({ v0, v1, v2 }); - hitNormals.push_back(outVec); - ImGui::Text("triangle edge collision."); - break; - case Collision::Corner: - //TODO: We might be able to return here instead, having only convex geometry. - cornerHitTODO = true; - //outResolutionVector += outVec; - //return true; - ImGui::Text("triangle corner collision."); - outResolutionVector += outVec; - newBox = AABB::FromOriginSize(newBox.Origin() + outVec, newBox.Size()); - break; - case Collision::Ground: - default: - outResolutionVector += outVec; - newBox = AABB::FromOriginSize(newBox.Origin() + outVec, newBox.Size()); - ImGui::Text("triangle ground collision."); - break; - } + outResolutionVector += outVec; + newBox = AABB::FromOriginSize(newBox.Origin() + outVec, newBox.Size()); } } - if (hitTriangles.size() > 0) { - if (cornerHitTODO) { - ImGui::Text("Both edges and corners was hit on the same model."); - return true; - } - glm::vec3 lineResolve(0.f); - for (const glm::vec3& norm : hitNormals) { - lineResolve += norm; - } - //Normalize. - lineResolve /= hitNormals.size(); - const glm::vec3& origin = newBox.Origin(); - const glm::vec3& half = newBox.HalfSize(); - float maxDist = -10; - for (const Triangle& tri : hitTriangles) { - float d = glm::dot(lineResolve, 0.333f * (tri.v0 + tri.v1 + tri.v2) - origin); - maxDist = std::max(maxDist, d); - } - glm::vec3 tmp = glm::clamp(2.0f * lineResolve, glm::vec3(-1, -1, -1), glm::vec3(1, 1, 1)); - outResolutionVector += lineResolve * (maxDist + glm::length(tmp * half)); - } return hit; } From f1343e2f82b14a74710b8b01f5e1926851c9967d Mon Sep 17 00:00:00 2001 From: William Moberg Date: Sun, 24 Jan 2016 21:08:42 +0100 Subject: [PATCH 011/355] Collision may be working, kind of. --- src/Engine/Collision/Collision.cpp | 69 +++++++++++++++++++----------- 1 file changed, 44 insertions(+), 25 deletions(-) diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index 48a6a1e3..41ca2155 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -243,16 +243,19 @@ inline glm::vec3 signNonZero(const glm::vec3& x) return r; } - -bool vectorHasLength(const glm::vec3& vec) +template +bool vectorHasLength(const T& vec) { - return glm::any(glm::greaterThan(glm::abs(vec), glm::vec3(0.0001f, 0.0001f, 0.0001f))); + return glm::any(glm::greaterThan(glm::abs(vec), T(0.0001f))); } -bool AARectangleVsTriangle(const glm::vec2& boxMin, +bool rectangleVsTriangle(const glm::vec2& boxMin, const glm::vec2& boxMax, - const std::array& triPos) + const std::array& triPos, + glm::vec2& resolutionDirection, + float& resolutionDistance) { + resolutionDistance = INFINITY; //Project along box normals (coordinate axes, since it's axis-aligned). for (int ax = 0; ax < 2; ++ax) { float minTri = INFINITY; @@ -264,6 +267,12 @@ bool AARectangleVsTriangle(const glm::vec2& boxMin, if (minTri > boxMax[ax] || maxTri < boxMin[ax]) { return false; } + float push = std::min(maxTri - boxMin[ax], boxMax[ax] - minTri); + if (push < resolutionDistance) { + resolutionDistance = push; + resolutionDirection[1 - ax] = 0.f; + resolutionDirection[ax] = resolutionDistance; + } } //Project along triangle normals. //Put edges into normal vector, make normals in the loop. @@ -279,6 +288,9 @@ bool AARectangleVsTriangle(const glm::vec2& boxMin, boxMin }; for (auto& normal : triNormals) { + if (!vectorHasLength(normal)) { + continue; + } //Rotate edge to a normal. normal = glm::vec2(-normal.y, normal.x); //Project triangle onto the normal. @@ -294,18 +306,24 @@ bool AARectangleVsTriangle(const glm::vec2& boxMin, float maxBox = -INFINITY; for (const glm::vec2& point : boxPos) { float dot = glm::dot(normal, point); - minBox = std::min(dot, minTri); - maxBox = std::max(dot, maxTri); + minBox = std::min(dot, minBox); + maxBox = std::max(dot, maxBox); } if (maxBox < minTri || minBox > maxTri) { return false; } + //Here: maxBox > minTri && minBox < maxTri + float push = std::min(maxTri - minBox, maxBox - minTri); + if (push < resolutionDistance) { + resolutionDistance = push; + resolutionDirection = resolutionDistance * glm::normalize(normal); + } } return true; } //An array containing 3 int pairs { 0, 2 }, { 0, 1 }, { 1, 2 } -constexpr std::array, 3> DimensionPairs({ std::pair(0, 2), std::pair(0, 1), std::pair(1, 2) }); +constexpr std::array, 3> dimensionPairs({ std::pair(0, 2), std::pair(0, 1), std::pair(1, 2) }); bool AABBvsTriangle(const AABB& box, const std::array& triPos, @@ -321,11 +339,11 @@ bool AABBvsTriangle(const AABB& box, const glm::vec3& half = box.HalfSize(); const glm::vec3& min = box.MinCorner(); const glm::vec3& max = box.MaxCorner(); - glm::tvec3 axisHit(false, false, false); - int i = 0; - for (std::pair dim : DimensionPairs) { + float minimumTranslation = INFINITY; + + //For each projection in xy-, xz-, and yx-planes. + for (std::pair dim : dimensionPairs) { //2D Triangle. - //for axis=0,1,2: 2d point takes from xy,xz,yx. //Project triangle. std::array t2D = { glm::vec2(triPos[0][dim.first], triPos[0][dim.second]), @@ -335,33 +353,35 @@ bool AABBvsTriangle(const AABB& box, //Project box. glm::vec2 boxMin(min[dim.first], min[dim.second]); glm::vec2 boxMax(max[dim.first], max[dim.second]); + glm::vec2 resolutionVector; + float resolutionDist; //if projections don't overlap, return false. - if (!AARectangleVsTriangle(boxMin, boxMax, t2D)) { - //return false; - } else { - axisHit[i] = true; - ImGui::Text("Triangle collision: Box axis %s", i == 0 ? "y" : i == 1 ? "z" : "x"); + if (!rectangleVsTriangle(boxMin, boxMax, t2D, resolutionVector, resolutionDist)) { + return false; + } else if (resolutionDist < minimumTranslation) { + outVector = glm::vec3(0.f); + outVector[dim.first] = resolutionVector.x; + outVector[dim.second] = resolutionVector.y; + minimumTranslation = resolutionDist; } - ++i; } //If the triangle does intersect any of the cube diagonals, it will //intersect the cube diagonal that comes //closest to being perpendicular to the plane of the triangle. triNormal = glm::normalize(triNormal); - glm::vec3 diagonal = -signNonZero(triNormal) * half; + glm::vec3 diagonal = signNonZero(triNormal) * half; //The triangle plane contains all points P in dot(triNormal, P) == dot(triNormal, v0) //The diagonal line contains all points P in P = origin + diagonal * t. 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; - } else { - ImGui::Text("Triangle collision: Triangle axis."); - return glm::all(axisHit); } - //TODO: Resolve it. - outVector = glm::vec3(0.f); + glm::vec3 cornerResolution = (1+t) * diagonal; + if (glm::length(cornerResolution) < minimumTranslation) { + outVector = cornerResolution; + } return true; } @@ -378,7 +398,6 @@ bool AABBvsTriangles(const AABB& box, const std::vector& model }; glm::vec3 outVec; if (AABBvsTriangle(newBox, triVertices, outVec)) { - ImGui::Text("Triangle collision: True."); hit = true; outResolutionVector += outVec; newBox = AABB::FromOriginSize(newBox.Origin() + outVec, newBox.Size()); From 3389b965eb888a8a5c8ebe33a91da574568a3d09 Mon Sep 17 00:00:00 2001 From: William Moberg Date: Mon, 25 Jan 2016 10:55:05 +0100 Subject: [PATCH 012/355] Test on game level v1. --- .../Schema/Entities/LevelCollisionTest.xml | 43 ++++++++++++++++++ src/Engine/Collision/Collision.cpp | 44 +++++++++++++++++++ 2 files changed, 87 insertions(+) create mode 100644 resources/Schema/Entities/LevelCollisionTest.xml diff --git a/resources/Schema/Entities/LevelCollisionTest.xml b/resources/Schema/Entities/LevelCollisionTest.xml new file mode 100644 index 00000000..0feb9a11 --- /dev/null +++ b/resources/Schema/Entities/LevelCollisionTest.xml @@ -0,0 +1,43 @@ + + + + + + + ../assets\Models/MapVersion1.obj + + + + + + + + + + + + + ../assets/Models/Core/UnitCube.obj + + + false + + + + + + + + + + + + + + + + + + + + diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index 41ca2155..7e9edb31 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -403,6 +403,50 @@ bool AABBvsTriangles(const AABB& box, const std::vector& model newBox = AABB::FromOriginSize(newBox.Origin() + outVec, newBox.Size()); } } + + //outResolutionVector = glm::vec3(INFINITY); + //std::stack testBoxes; + //std::stack resolveIndices; + //std::stack resolveVectors; + //resolveVectors.push(glm::vec3(0.f)); + //resolveIndices.push(0); + //testBoxes.push(box); + //do { + // int i = resolveIndices.top(); + // resolveIndices.pop(); + // while (i < modelIndices.size()) { + // std::array triVertices = { + // Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix), + // Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix), + // Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix) + // }; + // glm::vec3 outVec; + // bool test = AABBvsTriangle(testBoxes.top(), triVertices, outVec); + // if (test) { + // hit = true; + // //emplace? + // resolveIndices.push(i); + // testBoxes.push(AABB::FromOriginSize(box.Origin() + outVec, box.Size())); + // resolveVectors.top() += outVec; + // } + // } + // testBoxes.pop(); + // resolveVectors.push(glm::vec3(0.f)); + //} while (!resolveIndices.empty()); + //if (hit) { + // if (!resolveVectors.empty()) { + // while (!resolveVectors.empty()) { + // if (glm::length2(resolveVectors.top()) < glm::length2(outResolutionVector)) { + // outResolutionVector = resolveVectors.top(); + // } + // resolveVectors.pop(); + // } + // } else { + // //TODO: This won't happen. + // ImGui::Text("Collision, but not resolved."); + // } + // return true; + //} return hit; } From c5b1afb0d493e14fdf7b4e22e8e7cf0514d8f642 Mon Sep 17 00:00:00 2001 From: antc13 Date: Wed, 27 Jan 2016 09:37:01 +0100 Subject: [PATCH 013/355] Exporter Fix --- assets | 2 +- tools/MayaExporter/MayaExporter/Export.cpp | 17 ++++++++++++++--- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/assets b/assets index 068fbb2d..75778193 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit 068fbb2d20682dd60f186c82172d7731e60ed7e9 +Subproject commit 757781933738bc4158c5c26750594b70acd537cd diff --git a/tools/MayaExporter/MayaExporter/Export.cpp b/tools/MayaExporter/MayaExporter/Export.cpp index d8f1abd4..2b2764b1 100644 --- a/tools/MayaExporter/MayaExporter/Export.cpp +++ b/tools/MayaExporter/MayaExporter/Export.cpp @@ -47,13 +47,24 @@ bool Export::Meshes(std::string pathName, bool selectedOnly) for (unsigned int i = 0; i < connections.length(); i++) { if (connections[i].node().apiType() == MFn::kSkinClusterFilter) { - MGlobal::select(shape.parent(i), MGlobal::kReplaceList); - MGlobal::displayInfo(MString() + "Moving " + thisNode.name() + " to bindPose."); + shape.parent(0, &status); + if (status != MS::kSuccess) { + MGlobal::displayError(MString() + "shape.parent(0, &status) failed with: " + status.errorString()); + } + status = MGlobal::select(shape.parent(0), MGlobal::kReplaceList); + if (status != MS::kSuccess) { + MGlobal::displayError(MString() + "Parent to " + thisNode.name() + " failed"); + } + + MFnDependencyNode tmp(shape.parent(0)); + MGlobal::displayInfo(MString() + "Moving " + tmp.name() + " to bindPose."); + status = MGlobal::executeCommand("GoToBindPose;"); if (status != MS::kSuccess) { MGlobal::displayError(MString() + "GoToBindPose: " + status.errorString()); } - MGlobal::displayInfo(MString() + "Has moved " + thisNode.name() + " to bindPose."); + + MGlobal::displayInfo(MString() + "Has moved " + tmp.name() + " to bindPose."); } } } From 6ea490e215775c1e11ae0b7bdee39396f83b543b Mon Sep 17 00:00:00 2001 From: William Moberg Date: Wed, 27 Jan 2016 10:34:26 +0100 Subject: [PATCH 014/355] Tried a horrible recursive method, extreme framedrop. --- include/Engine/Collision/Collision.h | 1 + .../Schema/Entities/LevelCollisionTest.xml | 6 +- src/Engine/Collision/Collision.cpp | 62 +++++++++++++++++-- src/Engine/Collision/CollisionSystem.cpp | 12 ++-- 4 files changed, 67 insertions(+), 14 deletions(-) diff --git a/include/Engine/Collision/Collision.h b/include/Engine/Collision/Collision.h index 4e764905..6e2d679e 100644 --- a/include/Engine/Collision/Collision.h +++ b/include/Engine/Collision/Collision.h @@ -65,6 +65,7 @@ bool AABBvsTriangles(const AABB& box, const std::vector& modelVertices, const std::vector& modelIndices, const glm::mat4& modelMatrix, + const glm::vec3& boxVelocity, glm::vec3& outResolutionVector); //Return true if the boxes are intersecting. diff --git a/resources/Schema/Entities/LevelCollisionTest.xml b/resources/Schema/Entities/LevelCollisionTest.xml index 0feb9a11..ce0fe405 100644 --- a/resources/Schema/Entities/LevelCollisionTest.xml +++ b/resources/Schema/Entities/LevelCollisionTest.xml @@ -6,9 +6,7 @@ ../assets\Models/MapVersion1.obj - - - + @@ -24,7 +22,7 @@ - + diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index 7e9edb31..96d908ff 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -327,11 +327,14 @@ constexpr std::array, 3> dimensionPairs({ std::pair& triPos, + const glm::vec3& boxVelocity, glm::vec3& outVector) { //Check so we don't have a zero area triangle when calculating the normal. + //Also, don't check a triangle facing away from the player. + //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)) { + if (!vectorHasLength(triNormal) || glm::dot(triNormal, boxVelocity) > 0) { return false; } @@ -385,10 +388,18 @@ bool AABBvsTriangle(const AABB& box, return true; } -bool AABBvsTriangles(const AABB& box, const std::vector& modelVertices, const std::vector& modelIndices, const glm::mat4& modelMatrix, glm::vec3& outResolutionVector) +bool AABBvsTriangles(const AABB& box, + const std::vector& modelVertices, + const std::vector& modelIndices, + const glm::mat4& modelMatrix, + const glm::vec3& boxVelocity, + glm::vec3& outResolutionVector, + int startIndex, + int recursiveDepth) { - AABB newBox = box; bool hit = false; + + AABB newBox = box; outResolutionVector = glm::vec3(0.f); for (int i = 0; i < modelIndices.size(); ) { std::array triVertices = { @@ -397,13 +408,38 @@ bool AABBvsTriangles(const AABB& box, const std::vector& model Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix) }; glm::vec3 outVec; - if (AABBvsTriangle(newBox, triVertices, outVec)) { + if (AABBvsTriangle(newBox, triVertices, boxVelocity, outVec)) { hit = true; outResolutionVector += outVec; newBox = AABB::FromOriginSize(newBox.Origin() + outVec, newBox.Size()); } } + //outResolutionVector = glm::vec3(INFINITY); + //if (recursiveDepth > 2) { + // return true; + //} + //for (int i = startIndex; i < modelIndices.size(); ) { + // std::array triVertices = { + // Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix), + // Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix), + // Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix) + // }; + // glm::vec3 outVec; + // if (AABBvsTriangle(box, triVertices, boxVelocity, outVec) && glm::length2(outVec) < glm::length2(outResolutionVector)) { + // hit = true; + // glm::vec3 potentialResolution = outVec; + // const AABB& resolvedBox = AABB::FromOriginSize(box.Origin() + potentialResolution, box.Size()); + // if (AABBvsTriangles(resolvedBox, modelVertices, modelIndices, modelMatrix, boxVelocity, outVec, i, recursiveDepth+1)) { + // potentialResolution += outVec; + // if (glm::length2(potentialResolution) > glm::length2(outResolutionVector)) { + // continue; + // } + // } + // outResolutionVector = potentialResolution; + // } + //} + //outResolutionVector = glm::vec3(INFINITY); //std::stack testBoxes; //std::stack resolveIndices; @@ -449,6 +485,24 @@ bool AABBvsTriangles(const AABB& box, const std::vector& model //} return hit; } +bool AABBvsTriangles(const AABB& box, + const std::vector& modelVertices, + const std::vector& modelIndices, + const glm::mat4& modelMatrix, + const glm::vec3& boxVelocity, + glm::vec3& outResolutionVector) +{ + return AABBvsTriangles( + box, + modelVertices, + modelIndices, + modelMatrix, + boxVelocity, + outResolutionVector, + 0, + 0 + ); +} bool IsSameBoxProbably(const AABB& first, const AABB& second, const float epsilon) { diff --git a/src/Engine/Collision/CollisionSystem.cpp b/src/Engine/Collision/CollisionSystem.cpp index 20854c12..612d0707 100644 --- a/src/Engine/Collision/CollisionSystem.cpp +++ b/src/Engine/Collision/CollisionSystem.cpp @@ -41,11 +41,6 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c continue; } - auto absPosition = Transform::AbsolutePosition(m_World, cModel.EntityID); - auto absOrientation = Transform::AbsoluteOrientation(m_World, cModel.EntityID); - auto absScale = Transform::AbsoluteScale(m_World, cModel.EntityID); - glm::mat4 modelMatrix = glm::translate(absPosition) * glm::toMat4(absOrientation) * glm::scale(absScale); - RawModel* model; try { model = ResourceManager::Load(cModel["Resource"]); @@ -53,8 +48,13 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c continue; } + auto absPosition = Transform::AbsolutePosition(m_World, cModel.EntityID); + auto absOrientation = Transform::AbsoluteOrientation(m_World, cModel.EntityID); + auto absScale = Transform::AbsoluteScale(m_World, cModel.EntityID); + glm::mat4 modelMatrix = glm::translate(absPosition) * glm::toMat4(absOrientation) * glm::scale(absScale); + glm::vec3 resolutionVector; - if (Collision::AABBvsTriangles(boxA, model->m_Vertices, model->m_Indices, modelMatrix, resolutionVector)) { + if (Collision::AABBvsTriangles(boxA, model->m_Vertices, model->m_Indices, modelMatrix, (glm::vec3&)cPhysics["Velocity"], resolutionVector)) { (glm::vec3&)cTransform["Position"] += resolutionVector; cPhysics["Velocity"] = glm::vec3(0, 0, 0); } From 5cdf6db3404904ca799bed8d65e880739d4a6d26 Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Wed, 27 Jan 2016 14:46:45 +0100 Subject: [PATCH 015/355] Modified HealthSystem so it actually publishes the DeathEvent. Modified EPlayerHealthPickup. Fixed 2 tests. Started work on PlayerDeathSystem --- include/Engine/Core/EPlayerDamage.h | 1 + include/Engine/Core/EPlayerHealthPickup.h | 4 +- include/Game/Systems/HealthSystem.h | 2 +- include/Game/Systems/PlayerDeathSystem.h | 39 ++++++++ resources/Schema/Entities/GameMap.xml | 4 +- src/Game/Game.cpp | 2 + src/Game/Systems/HealthSystem.cpp | 45 ++------- src/Game/Systems/PlayerDeathSystem.cpp | 116 ++++++++++++++++++++++ src/Tests/CollisionTest.cpp | 2 +- src/Tests/HealthSystemTest.cpp | 4 +- 10 files changed, 176 insertions(+), 43 deletions(-) create mode 100644 include/Game/Systems/PlayerDeathSystem.h create mode 100644 src/Game/Systems/PlayerDeathSystem.cpp diff --git a/include/Engine/Core/EPlayerDamage.h b/include/Engine/Core/EPlayerDamage.h index a7e135ce..8ba3907e 100644 --- a/include/Engine/Core/EPlayerDamage.h +++ b/include/Engine/Core/EPlayerDamage.h @@ -9,6 +9,7 @@ namespace Events struct PlayerDamage : Event { + //NOTE: this struct is missing information on what the damageSource is EntityWrapper Player; double Damage; }; diff --git a/include/Engine/Core/EPlayerHealthPickup.h b/include/Engine/Core/EPlayerHealthPickup.h index f3158f92..46ed76db 100644 --- a/include/Engine/Core/EPlayerHealthPickup.h +++ b/include/Engine/Core/EPlayerHealthPickup.h @@ -2,15 +2,15 @@ #define EPlayerHealthPickup_h__ #include "EventBroker.h" -#include "../Core/Entity.h" +#include "../Core/EntityWrapper.h" namespace Events { struct PlayerHealthPickup : Event { + EntityWrapper Player; double HealthAmount; - EntityID PlayerHealedID; }; } diff --git a/include/Game/Systems/HealthSystem.h b/include/Game/Systems/HealthSystem.h index 3b069349..46f24630 100644 --- a/include/Game/Systems/HealthSystem.h +++ b/include/Game/Systems/HealthSystem.h @@ -26,7 +26,7 @@ private: EventRelay m_EPlayerDamage; bool HealthSystem::OnPlayerDamaged(Events::PlayerDamage& e); EventRelay m_EPlayerHealthPickup; - bool HealthSystem::OnPlayerHealthPickup(const Events::PlayerHealthPickup& e); + bool HealthSystem::OnPlayerHealthPickup(Events::PlayerHealthPickup& e); //vector which will keep track of health changes std::vector> m_DeltaHealthVector; diff --git a/include/Game/Systems/PlayerDeathSystem.h b/include/Game/Systems/PlayerDeathSystem.h new file mode 100644 index 00000000..3f7268ca --- /dev/null +++ b/include/Game/Systems/PlayerDeathSystem.h @@ -0,0 +1,39 @@ +#ifndef PlayerDeathSystem_h__ +#define PlayerDeathSystem_h__ + +#include "Core/System.h" +#include "Input/EInputCommand.h" +#include "Systems/SpawnerSystem.h" +#include "Events/ESpawnerSpawn.h" +#include "Core/EPlayerSpawned.h" +#include "Rendering/ESetCamera.h" +#include "Core/ConfigFile.h" + +#include "Core/EPlayerDeath.h" +//tests +#include "Core/EPlayerDamage.h" + +class PlayerDeathSystem : public ImpureSystem +{ +public: + PlayerDeathSystem(World* world, EventBroker* eventBroker); + + virtual void Update(double dt) override; + +private: + struct SpawnRequest + { + int PlayerID; + ComponentInfo::EnumType Team; + }; + + bool m_NetworkEnabled = false; + std::vector m_SpawnRequests; + std::map m_PlayerEntities; + + EventRelay m_OnInputCommand; + bool OnInputCommand(const Events::InputCommand& e); + EventRelay m_OnPlayerDeath; + bool OnPlayerDeath(Events::PlayerDeath& e); +}; +#endif \ No newline at end of file diff --git a/resources/Schema/Entities/GameMap.xml b/resources/Schema/Entities/GameMap.xml index 97fd3f4d..b37f702d 100644 --- a/resources/Schema/Entities/GameMap.xml +++ b/resources/Schema/Entities/GameMap.xml @@ -139,7 +139,7 @@ - + @@ -201,7 +201,7 @@ - + diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index d13d62d4..b0c10a74 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -7,6 +7,7 @@ #include "Systems/PlayerMovementSystem.h" #include "Systems/SpawnerSystem.h" #include "Systems/PlayerSpawnSystem.h" +#include "Systems/PlayerDeathSystem.h" #include "Core/EntityFileWriter.h" #include "Game/Systems/CapturePointSystem.h" #include "Game/Systems/WeaponSystem.h" @@ -86,6 +87,7 @@ Game::Game(int argc, char* argv[]) m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); + m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer); m_SystemPipeline->AddSystem(updateOrderLevel); // Populate Octree with collidables diff --git a/src/Game/Systems/HealthSystem.cpp b/src/Game/Systems/HealthSystem.cpp index 9e118070..26d38c69 100644 --- a/src/Game/Systems/HealthSystem.cpp +++ b/src/Game/Systems/HealthSystem.cpp @@ -11,38 +11,6 @@ HealthSystem::HealthSystem(World* m_World, EventBroker* eventBroker) void HealthSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) { - //if entityID of health is 9 then the players ID is also 9 (player,health are connected to the same entity) - double maxHealth = (double)component["MaxHealth"]; - - //process the DeltaHealthVector and change the entitys health accordingly - for (size_t i = m_DeltaHealthVector.size(); i > 0; i--) - { - auto deltaHP = m_DeltaHealthVector[i - 1]; - //if we have a healthchange for the current player and health is greater than 0, then apply it - if (std::get<0>(deltaHP) == component.EntityID && (double)component["Health"] > 0.0f) { - //get the deltaHP value from the tuple and make sure you dont get more than maxHealth - double newHealth = std::min((double)component["Health"] + (double)std::get<1>(deltaHP), maxHealth); - component["Health"] = newHealth; - m_DeltaHealthVector.erase(m_DeltaHealthVector.begin() + i - 1); - //check if health is <= 0 - if ((double)component["Health"] <= 0.0f) { - component["Health"] = 0.0; - //publish death event - Events::PlayerDeath e; - e.PlayerID = component.EntityID; - m_EventBroker->Publish(e); - //clear the remaining hpDeltas for the dead player - for (size_t j = m_DeltaHealthVector.size(); j > 0; j--) - { - if (std::get<0>(m_DeltaHealthVector[j - 1]) == component.EntityID) - m_DeltaHealthVector.erase(m_DeltaHealthVector.begin() + j - 1); - } - //delete the player and break the loop - m_World->DeleteEntity(entity.ID); - break; - } - } - } } bool HealthSystem::OnPlayerDamaged(Events::PlayerDamage& e) @@ -52,16 +20,23 @@ bool HealthSystem::OnPlayerDamaged(Events::PlayerDamage& e) health -= e.Damage; if (health <= 0.0) { + Events::PlayerDeath ePlayerDeath; + ePlayerDeath.PlayerID = e.Player.ID; + m_EventBroker->Publish(ePlayerDeath); + m_World->DeleteEntity(e.Player.ID); } return true; } -bool HealthSystem::OnPlayerHealthPickup(const Events::PlayerHealthPickup& e) +bool HealthSystem::OnPlayerHealthPickup(Events::PlayerHealthPickup& e) { - //save the changed HP to a vector. it will be taken care of in UpdateComponent - m_DeltaHealthVector.push_back(std::make_tuple(e.PlayerHealedID, e.HealthAmount)); + ComponentWrapper cHealth = e.Player["Health"]; + double& health = cHealth["Health"]; + //NOTE: its possible to get more than MaxHealth health + health += e.HealthAmount; + return true; } diff --git a/src/Game/Systems/PlayerDeathSystem.cpp b/src/Game/Systems/PlayerDeathSystem.cpp new file mode 100644 index 00000000..dcee3a92 --- /dev/null +++ b/src/Game/Systems/PlayerDeathSystem.cpp @@ -0,0 +1,116 @@ +#include "Systems/PlayerDeathSystem.h" + +PlayerDeathSystem::PlayerDeathSystem(World* m_World, EventBroker* eventBroker) + : System(m_World, eventBroker) +{ + EVENT_SUBSCRIBE_MEMBER(m_OnInputCommand, &PlayerDeathSystem::OnInputCommand); + EVENT_SUBSCRIBE_MEMBER(m_OnPlayerDeath, &PlayerDeathSystem::OnPlayerDeath); + m_NetworkEnabled = ResourceManager::Load("Config.ini")->Get("Networking.StartNetwork", false); +} + +void PlayerDeathSystem::Update(double dt) +{ + auto playerSpawns = m_World->GetComponents("PlayerSpawn"); + if (playerSpawns == nullptr) { + return; + } + + for (auto& req : m_SpawnRequests) { + for (auto& cPlayerSpawn : *playerSpawns) { + EntityWrapper spawner(m_World, cPlayerSpawn.EntityID); + if (!spawner.HasComponent("Spawner")) { + continue; + } + + // If the spawner has a team affiliation, check it + if (spawner.HasComponent("Team")) { + if ((int)spawner["Team"]["Team"] != req.Team) { + continue; + } + } + + // Spawn the player! + EntityWrapper player = SpawnerSystem::Spawn(spawner); + // Set the player team affiliation + player["Team"]["Team"] = req.Team; + + // Publish a PlayerSpawned event + Events::PlayerSpawned e; + e.PlayerID = req.PlayerID; + e.Player = player; + e.Spawner = spawner; + m_EventBroker->Publish(e); + + } + } + m_SpawnRequests.clear(); +} + +bool PlayerDeathSystem::OnInputCommand(const Events::InputCommand& e) +{ + //testing: Jump -> playerdamage + if (e.Command != "Jump") { + return false; + } + + // 0 = released + if (e.Value != 0) { + return false; + } + + auto players = m_World->GetComponents("Player"); + + for (auto& cPlayer : *players) { + EntityWrapper player(m_World, cPlayer.EntityID); + Events::PlayerDamage e; + e.Player = player; + e.Damage = 50; + m_EventBroker->Publish(e); + } + + + + return true; +} + +bool PlayerDeathSystem::OnPlayerDeath(Events::PlayerDeath& e) +{ + //// When a player is actually spawned (since the actual spawning is handled on the server) + + //// Check if a player already exists + //if (m_PlayerEntities.count(e.PlayerID) != 0) { + // // TODO: Disallow infinite respawning here + // m_World->DeleteEntity(m_PlayerEntities[e.PlayerID].ID); + //} + + //// Store the player for future reference + //m_PlayerEntities[e.PlayerID] = e.Player; + + //// Set the camera to the correct entity + //EntityWrapper cameraEntity = e.Player.FirstChildByName("Camera"); + //if (cameraEntity.Valid()) { + // Events::SetCamera e; + // e.CameraEntity = cameraEntity; + // m_EventBroker->Publish(e); + //} + + //// HACK: Set the player model color to team color + //EntityWrapper playerModel = e.Player.FirstChildByName("PlayerModel"); + //if (playerModel.Valid() && e.Player.HasComponent("Team")) { + // ComponentWrapper cTeam = e.Player["Team"]; + // ComponentWrapper cModel = playerModel["Model"]; + // if ((ComponentInfo::EnumType)cTeam["Team"] == cTeam["Team"].Enum("Red")) { + // cModel["Color"] = glm::vec3(1.f, 0.f, 0.f); + // } else if ((ComponentInfo::EnumType)cTeam["Team"] == cTeam["Team"].Enum("Blue")) { + // cModel["Color"] = glm::vec3(0.f, 0.25f, 1.f); + // } + //} + + //// TODO: Set the player name to whatever + //EntityWrapper playerName = e.Player.FirstChildByName("PlayerName"); + //if (playerName.Valid()) { + // playerName["Text"]["Content"] = e.PlayerName; + //} + + return true; +} \ No newline at end of file diff --git a/src/Tests/CollisionTest.cpp b/src/Tests/CollisionTest.cpp index 67b6ce19..6cb6c88b 100644 --- a/src/Tests/CollisionTest.cpp +++ b/src/Tests/CollisionTest.cpp @@ -29,7 +29,7 @@ void RayTest(std::string fileName) { Ray ray(glm::vec3(-50, 0, 0), glm::vec3(1, 0, 0)); //using a - here, else we have to init the renderingsystem + //here, else we have to init the renderingsystem ResourceManager::RegisterType("RawModel"); auto unitBox = ResourceManager::Load(fileName); BOOST_REQUIRE(unitBox != nullptr); diff --git a/src/Tests/HealthSystemTest.cpp b/src/Tests/HealthSystemTest.cpp index bdd9ba4b..6a434a9a 100644 --- a/src/Tests/HealthSystemTest.cpp +++ b/src/Tests/HealthSystemTest.cpp @@ -69,8 +69,8 @@ GameHealthSystemTest::GameHealthSystemTest() m_EventBroker->Publish(e3); //damage player with 50 Events::PlayerDamage e; - e.DamageAmount = 50.0f; - e.PlayerDamagedID = healthsID; + e.Damage = 50.0f; +// e.PlayerDamagedID = healthsID; m_EventBroker->Publish(e); //heal some other player with 40 Events::PlayerHealthPickup e2; From 246f56c82363b455b9de82ad114eb921374a2759 Mon Sep 17 00:00:00 2001 From: stiffly Date: Wed, 27 Jan 2016 15:40:01 +0100 Subject: [PATCH 016/355] Removed brainless logic. --- src/Engine/Sound/SoundSystem.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Engine/Sound/SoundSystem.cpp b/src/Engine/Sound/SoundSystem.cpp index a55c1fee..ba46379e 100644 --- a/src/Engine/Sound/SoundSystem.cpp +++ b/src/Engine/Sound/SoundSystem.cpp @@ -71,7 +71,6 @@ void SoundSystem::deleteInactiveEmitters() alDeleteBuffers(1, &it->second->ALsource); alDeleteSources(1, &it->second->ALsource); m_World->DeleteEntity(it->first); - delete it->second; it = m_Sources.erase(it); } } else { From 950f3f3cf7a02a3950a74eb0445abca0af7e9568 Mon Sep 17 00:00:00 2001 From: stiffly Date: Wed, 27 Jan 2016 15:43:40 +0100 Subject: [PATCH 017/355] Fixed last commit. Removed the wrong thing. --- src/Engine/Sound/SoundSystem.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Engine/Sound/SoundSystem.cpp b/src/Engine/Sound/SoundSystem.cpp index ba46379e..d0887c05 100644 --- a/src/Engine/Sound/SoundSystem.cpp +++ b/src/Engine/Sound/SoundSystem.cpp @@ -70,7 +70,7 @@ void SoundSystem::deleteInactiveEmitters() // Sound has been stopped / finished playing. alDeleteBuffers(1, &it->second->ALsource); alDeleteSources(1, &it->second->ALsource); - m_World->DeleteEntity(it->first); + delete it->second; it = m_Sources.erase(it); } } else { From 8fc8d56ee10cd130030b911393287c7b18b29a37 Mon Sep 17 00:00:00 2001 From: viktorljung Date: Wed, 27 Jan 2016 17:14:16 +0100 Subject: [PATCH 018/355] Added BoneAttachment component --- .../Engine/Rendering/BoneAttachmentSystem.h | 29 +++++ include/Engine/Rendering/Skeleton.h | 12 +- resources/Schema/Components.xsd | 1 + .../Schema/Components/BoneAttachment.xml | 10 ++ .../Schema/Components/BoneAttachment.xsd | 19 +++ resources/Schema/Entities/AnimationTests.xml | 117 ++++++++++++++++++ resources/Schema/Entities/FastWorld.xml | 8 +- resources/Schema/Entities/awdawd | 23 ++++ src/Engine/Rendering/AnimationSystem.cpp | 2 - src/Engine/Rendering/BoneAttachmentSystem.cpp | 71 +++++++++++ src/Engine/Rendering/DrawFinalPass.cpp | 13 +- src/Engine/Rendering/Skeleton.cpp | 30 +++++ src/Game/Game.cpp | 4 +- 13 files changed, 322 insertions(+), 17 deletions(-) create mode 100644 include/Engine/Rendering/BoneAttachmentSystem.h create mode 100644 resources/Schema/Components/BoneAttachment.xml create mode 100644 resources/Schema/Components/BoneAttachment.xsd create mode 100644 resources/Schema/Entities/AnimationTests.xml create mode 100644 resources/Schema/Entities/awdawd create mode 100644 src/Engine/Rendering/BoneAttachmentSystem.cpp diff --git a/include/Engine/Rendering/BoneAttachmentSystem.h b/include/Engine/Rendering/BoneAttachmentSystem.h new file mode 100644 index 00000000..93ce5119 --- /dev/null +++ b/include/Engine/Rendering/BoneAttachmentSystem.h @@ -0,0 +1,29 @@ +#ifndef BoneAttachmentSystem_h__ +#define BoneAttachmentSystem_h__ + +#include "GLM.h" + +#include "Common.h" +#include "Core/System.h" +#include "Core/ResourceManager.h" +#include "Rendering/Model.h" +#include "Rendering/Skeleton.h" + +//Needs to be a higher orderlevel than AnimationSystem +class BoneAttachmentSystem : public PureSystem +{ +public: + BoneAttachmentSystem(World* world, EventBroker* eventBroker) + : System(world, eventBroker) + , PureSystem("BoneAttachment") + { + + } + ~BoneAttachmentSystem() { } + virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& BoneAttachmentComponent, double dt) override; +private: + + +}; + +#endif \ No newline at end of file diff --git a/include/Engine/Rendering/Skeleton.h b/include/Engine/Rendering/Skeleton.h index 3b89b89b..15749b85 100644 --- a/include/Engine/Rendering/Skeleton.h +++ b/include/Engine/Rendering/Skeleton.h @@ -82,17 +82,19 @@ public: int GetBoneID(std::string name); - const Animation* GetAnimation(std::string name); - std::vector GetFrameBones(const Animation& animation, double time, bool noRootMotion = false); - void AccumulateBoneTransforms(bool noRootMotion, const Animation::Keyframe& currentFrame, const Animation::Keyframe& nextFrame, float progress, std::map& boneMatrices, const Bone* bone, glm::mat4 parentMatrix); - void PrintSkeleton(); + const Animation* GetAnimation(std::string name); + std::vector GetFrameBones(const Animation& animation, double time, bool noRootMotion = false); + void AccumulateBoneTransforms(bool noRootMotion, const Animation::Keyframe& currentFrame, const Animation::Keyframe& nextFrame, float progress, std::map& boneMatrices, const Bone* bone, glm::mat4 parentMatrix); + void PrintSkeleton(); void PrintSkeleton(const Bone* parent, int depthCount); std::map Animations; + glm::mat4 GetBoneTransform(const Bone* bone, const Animation::Keyframe& currentFrame, const Animation::Keyframe& nextFrame, float progress, glm::mat4 parentMatrix); + int GetKeyframe(const Animation& animation, double time); + private: std::map m_BonesByName; - int GetKeyframe(const Animation& animation, double time); }; #endif diff --git a/resources/Schema/Components.xsd b/resources/Schema/Components.xsd index d663f695..eeeac344 100644 --- a/resources/Schema/Components.xsd +++ b/resources/Schema/Components.xsd @@ -24,4 +24,5 @@ + \ No newline at end of file diff --git a/resources/Schema/Components/BoneAttachment.xml b/resources/Schema/Components/BoneAttachment.xml new file mode 100644 index 00000000..c8a8971a --- /dev/null +++ b/resources/Schema/Components/BoneAttachment.xml @@ -0,0 +1,10 @@ + + + + + + + true + true + false + \ No newline at end of file diff --git a/resources/Schema/Components/BoneAttachment.xsd b/resources/Schema/Components/BoneAttachment.xsd new file mode 100644 index 00000000..bc1dc444 --- /dev/null +++ b/resources/Schema/Components/BoneAttachment.xsd @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/resources/Schema/Entities/AnimationTests.xml b/resources/Schema/Entities/AnimationTests.xml new file mode 100644 index 00000000..cdb80769 --- /dev/null +++ b/resources/Schema/Entities/AnimationTests.xml @@ -0,0 +1,117 @@ + + + + + + + + + + + + Models/Core/UnitPlane.mesh + + + + + + + + + + + + + Models/DirectionalLightWidget.mesh + + + + + + + + + + + + Run + + 0.5 + + + Models/AssaultAnimated.mesh + + + + + + + + + + + + 12 + 0.29999995231628418 + + + + + + + + + + + + 7 + + + + + + + + + + + + L_Foot + true + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + + R_Foot + true + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/FastWorld.xml b/resources/Schema/Entities/FastWorld.xml index 68d1dccb..4863f8f7 100644 --- a/resources/Schema/Entities/FastWorld.xml +++ b/resources/Schema/Entities/FastWorld.xml @@ -3,7 +3,7 @@ - + @@ -18,16 +18,14 @@ - + - Crouch Walk - - 32 + Walk Models/AssaultAnimated.mesh diff --git a/resources/Schema/Entities/awdawd b/resources/Schema/Entities/awdawd new file mode 100644 index 00000000..d8dacb54 --- /dev/null +++ b/resources/Schema/Entities/awdawd @@ -0,0 +1,23 @@ + + + + + + + L_Foot + true + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + diff --git a/src/Engine/Rendering/AnimationSystem.cpp b/src/Engine/Rendering/AnimationSystem.cpp index 2126362f..e164c7fb 100644 --- a/src/Engine/Rendering/AnimationSystem.cpp +++ b/src/Engine/Rendering/AnimationSystem.cpp @@ -41,7 +41,5 @@ void AnimationSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& a } } - - } diff --git a/src/Engine/Rendering/BoneAttachmentSystem.cpp b/src/Engine/Rendering/BoneAttachmentSystem.cpp new file mode 100644 index 00000000..82ef7764 --- /dev/null +++ b/src/Engine/Rendering/BoneAttachmentSystem.cpp @@ -0,0 +1,71 @@ +#include "Rendering/BoneAttachmentSystem.h" + +void BoneAttachmentSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& BoneAttachmentComponent, double dt) +{ + + if(!entity.HasComponent("Transform")) { + return; + } + + auto parent = entity.FirstParentWithComponent("Animation"); + if (!parent.HasComponent("Model")) { + return; + } + Model* model; + try { + model = ResourceManager::Load<::Model, true>(parent["Model"]["Resource"]); + } catch (const std::exception&) { + return; + } + + + Skeleton* skeleton = model->m_RawModel->m_Skeleton; + const Skeleton::Animation* animation = skeleton->GetAnimation(parent["Animation"]["Name"]); + + if (!animation) { + return; + } + + int id = skeleton->GetBoneID(entity["BoneAttachment"]["Name"]); + + if(id == -1) { + return; + } + + int currentKeyframeIndex = skeleton->GetKeyframe(*animation, parent["Animation"]["Time"]); + + const Skeleton::Animation::Keyframe& currentFrame = animation->Keyframes[currentKeyframeIndex]; + const Skeleton::Animation::Keyframe& nextFrame = animation->Keyframes[(currentKeyframeIndex + 1) % animation->Keyframes.size()]; + float alpha = ((double)parent["Animation"]["Time"] - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); + + glm::mat4 boneTransform = skeleton->GetBoneTransform(skeleton->Bones[id], currentFrame, nextFrame, alpha, glm::mat4(1)); + + + + glm::vec3 scale; + glm::quat rotation; + glm::vec3 translation; + glm::vec3 skew; + glm::vec4 perspective; + glm::decompose(boneTransform, scale, rotation, translation, skew, perspective); + + glm::vec3 angles; + angles.y = asin(-boneTransform[0][2]); + if (cos(angles.y) != 0) { + angles.x = atan2(boneTransform[1][2], boneTransform[2][2]); + angles.z = atan2(boneTransform[0][1], boneTransform[0][0]); + } else { + angles.x = atan2(-boneTransform[2][0], boneTransform[1][1]); + angles.z = 0; + } + + if ((bool)entity["BoneAttachment"]["InheritPosition"]) { + (glm::vec3&)entity["Transform"]["Position"] = translation + (glm::vec3)entity["BoneAttachment"]["PositionOffset"]; + } + if ((bool)entity["BoneAttachment"]["InheritOrientation"]) { + (glm::vec3&)entity["Transform"]["Orientation"] = angles + (glm::vec3)entity["BoneAttachment"]["OrientationOffset"]; + } + if ((bool)entity["BoneAttachment"]["InheritScale"]) { + (glm::vec3&)entity["Transform"]["Scale"] = scale * (glm::vec3)entity["BoneAttachment"]["ScaleOffset"]; + } +} diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index 52c9a4a9..9d36db2e 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -94,11 +94,16 @@ void DrawFinalPass::Draw(RenderScene& scene) glBindTexture(GL_TEXTURE_2D, m_BlackTexture->m_Texture); }*/ - //TODO: Fixa så att modelsJobs kan spela upp olika animationer och så att den kan få in en tid istället för 1.0f - Hälsningar Johan och Andreas :) - if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { - + if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { if (modelJob->Animation != nullptr) { - std::vector frameBones = modelJob->Skeleton->GetFrameBones( *modelJob->Animation, modelJob->AnimationTime); + std::vector frameBones = modelJob->Skeleton->GetFrameBones(*modelJob->Animation, modelJob->AnimationTime); +// std::vector frameBones2 = modelJob->Skeleton->GetFrameBones(*modelJob->Skeleton->GetAnimation("Walk"), modelJob->AnimationTime); +// +// +// for (int i = 0; i < frameBones.size(); i++) { +// frameBones[i] = frameBones[i] * glm::mat4(glm::quat(glm::vec3(0.f, 0.f, 0.f)));//* frameBones2[i]; +// } + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); } } diff --git a/src/Engine/Rendering/Skeleton.cpp b/src/Engine/Rendering/Skeleton.cpp index cebabb67..8326dea9 100644 --- a/src/Engine/Rendering/Skeleton.cpp +++ b/src/Engine/Rendering/Skeleton.cpp @@ -66,6 +66,8 @@ std::vector Skeleton::GetFrameBones(const Animation& animation, doubl return finalMatrices; } + + void Skeleton::AccumulateBoneTransforms(bool noRootMotion, const Animation::Keyframe ¤tFrame, const Animation::Keyframe &nextFrame, float progress, std::map &boneMatrices, const Bone* bone, glm::mat4 parentMatrix) { glm::mat4 boneMatrix; @@ -101,6 +103,34 @@ void Skeleton::AccumulateBoneTransforms(bool noRootMotion, const Animation::Keyf } +glm::mat4 Skeleton::GetBoneTransform(const Bone* bone, const Animation::Keyframe& currentFrame, const Animation::Keyframe& nextFrame, float progress, glm::mat4 parentMatrix) +{ + glm::mat4 boneMatrix; + + if (currentFrame.BoneProperties.find(bone->ID) != currentFrame.BoneProperties.end() || nextFrame.BoneProperties.find(bone->ID) != nextFrame.BoneProperties.end()) { + Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties.at(bone->ID); + Animation::Keyframe::BoneProperty nextBoneProperty = nextFrame.BoneProperties.at(bone->ID); + + glm::vec3 positionInterp = currentBoneProperty.Position * (1.f - progress) + nextBoneProperty.Position * progress; + glm::quat rotationInterp = glm::slerp(currentBoneProperty.Rotation, nextBoneProperty.Rotation, progress); + glm::vec3 scaleInterp = currentBoneProperty.Scale * (1.f - progress) + nextBoneProperty.Scale * progress; + + + boneMatrix = (glm::translate(positionInterp) * glm::toMat4(rotationInterp) * glm::scale(scaleInterp)) * parentMatrix; + } else { + if (bone->Parent) { + boneMatrix = parentMatrix; + } + } + + if(bone->Parent) { + return GetBoneTransform(bone->Parent, currentFrame, nextFrame, progress, boneMatrix); + } else { + return boneMatrix; + } + +} + int Skeleton::GetBoneID(std::string name) { if (m_BonesByName.find(name) == m_BonesByName.end()) { diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index 6384297c..b22f86ff 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -10,7 +10,8 @@ #include "Core/EntityFileWriter.h" #include "Game/Systems/CapturePointSystem.h" #include "Game/Systems/WeaponSystem.h" -#include "../Engine/Rendering/AnimationSystem.h" +#include "Rendering/AnimationSystem.h" +#include "Rendering/BoneAttachmentSystem.h" Game::Game(int argc, char* argv[]) { @@ -90,6 +91,7 @@ Game::Game(int argc, char* argv[]) m_SystemPipeline->AddSystem(updateOrderLevel); // Collision and TriggerSystem should update after player. ++updateOrderLevel; + m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeCollision); m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeCollision); ++updateOrderLevel; From 2ec5023752da427968e7e17ccb13e756de7cb730 Mon Sep 17 00:00:00 2001 From: viktorljung Date: Wed, 27 Jan 2016 17:27:34 +0100 Subject: [PATCH 019/355] Changed Animation and BoneAttachment "Name" field to "AnimationName" and "BoneName" --- include/Engine/Rendering/ModelJob.h | 2 +- resources/Schema/Components/Animation.xml | 2 +- resources/Schema/Components/Animation.xsd | 2 +- .../Schema/Components/BoneAttachment.xml | 2 +- .../Schema/Components/BoneAttachment.xsd | 2 +- resources/Schema/Entities/AnimationTests.xml | 20 +++++++++---------- src/Engine/Rendering/AnimationSystem.cpp | 4 ++-- src/Engine/Rendering/BoneAttachmentSystem.cpp | 4 ++-- src/Engine/Rendering/DrawFinalPass.cpp | 8 -------- 9 files changed, 19 insertions(+), 27 deletions(-) diff --git a/include/Engine/Rendering/ModelJob.h b/include/Engine/Rendering/ModelJob.h index df7f1aec..21f7c1ca 100644 --- a/include/Engine/Rendering/ModelJob.h +++ b/include/Engine/Rendering/ModelJob.h @@ -46,7 +46,7 @@ struct ModelJob : RenderJob if (world->HasComponent(Entity, "Animation") && Skeleton != nullptr) { auto animationComponent = world->GetComponent(Entity, "Animation"); - Animation = model->m_RawModel->m_Skeleton->GetAnimation(animationComponent["Name"]); + Animation = model->m_RawModel->m_Skeleton->GetAnimation(animationComponent["AnimationName"]); AnimationTime = (double)animationComponent["Time"]; } }; diff --git a/resources/Schema/Components/Animation.xml b/resources/Schema/Components/Animation.xml index 66d2865d..ab589698 100644 --- a/resources/Schema/Components/Animation.xml +++ b/resources/Schema/Components/Animation.xml @@ -1,6 +1,6 @@ - + 0 true diff --git a/resources/Schema/Components/Animation.xsd b/resources/Schema/Components/Animation.xsd index 0dd21f29..388dfc07 100644 --- a/resources/Schema/Components/Animation.xsd +++ b/resources/Schema/Components/Animation.xsd @@ -6,7 +6,7 @@ - + diff --git a/resources/Schema/Components/BoneAttachment.xml b/resources/Schema/Components/BoneAttachment.xml index c8a8971a..47df9e40 100644 --- a/resources/Schema/Components/BoneAttachment.xml +++ b/resources/Schema/Components/BoneAttachment.xml @@ -1,6 +1,6 @@ - + diff --git a/resources/Schema/Components/BoneAttachment.xsd b/resources/Schema/Components/BoneAttachment.xsd index bc1dc444..aee1868f 100644 --- a/resources/Schema/Components/BoneAttachment.xsd +++ b/resources/Schema/Components/BoneAttachment.xsd @@ -6,7 +6,7 @@ - + diff --git a/resources/Schema/Entities/AnimationTests.xml b/resources/Schema/Entities/AnimationTests.xml index cdb80769..8a757639 100644 --- a/resources/Schema/Entities/AnimationTests.xml +++ b/resources/Schema/Entities/AnimationTests.xml @@ -34,8 +34,8 @@ - Run - + Walk + 0.5 @@ -75,8 +75,8 @@ + L_Foot - L_Foot true @@ -84,9 +84,9 @@ - - - + + + @@ -94,8 +94,8 @@ + R_Foot - R_Foot true @@ -103,9 +103,9 @@ - - - + + + diff --git a/src/Engine/Rendering/AnimationSystem.cpp b/src/Engine/Rendering/AnimationSystem.cpp index e164c7fb..c79b5a36 100644 --- a/src/Engine/Rendering/AnimationSystem.cpp +++ b/src/Engine/Rendering/AnimationSystem.cpp @@ -15,7 +15,7 @@ void AnimationSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& a Skeleton* skeleton = model->m_RawModel->m_Skeleton; - const Skeleton::Animation* animation = skeleton->GetAnimation(animationComponent["Name"]); + const Skeleton::Animation* animation = skeleton->GetAnimation(animationComponent["AnimationName"]); if(animation != nullptr) { double animationSpeed = (double)animationComponent["Speed"]; @@ -29,7 +29,7 @@ void AnimationSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& a (double&)animationComponent["Speed"] = 0.0; Events::AnimationComplete e; e.Entity = entity; - e.Name = (std::string)animationComponent["Name"]; + e.Name = (std::string)animationComponent["AnimationName"]; m_EventBroker->Publish(e); } else { if (glm::abs(nextTime) > animation->Duration) { diff --git a/src/Engine/Rendering/BoneAttachmentSystem.cpp b/src/Engine/Rendering/BoneAttachmentSystem.cpp index 82ef7764..2a2e5c7d 100644 --- a/src/Engine/Rendering/BoneAttachmentSystem.cpp +++ b/src/Engine/Rendering/BoneAttachmentSystem.cpp @@ -20,13 +20,13 @@ void BoneAttachmentSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapp Skeleton* skeleton = model->m_RawModel->m_Skeleton; - const Skeleton::Animation* animation = skeleton->GetAnimation(parent["Animation"]["Name"]); + const Skeleton::Animation* animation = skeleton->GetAnimation(parent["Animation"]["AnimationName"]); if (!animation) { return; } - int id = skeleton->GetBoneID(entity["BoneAttachment"]["Name"]); + int id = skeleton->GetBoneID(entity["BoneAttachment"]["BoneName"]); if(id == -1) { return; diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index 006790cd..72329f5b 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -156,17 +156,9 @@ void DrawFinalPass::Draw(RenderScene& scene) glBindTexture(GL_TEXTURE_2D, m_BlackTexture->m_Texture); }*/ - //TODO: Fixa så att modelsJobs kan spela upp olika animationer och så att den kan få in en tid istället för 1.0f - Hälsningar Johan och Andreas :) if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { if (modelJob->Animation != nullptr) { std::vector frameBones = modelJob->Skeleton->GetFrameBones(*modelJob->Animation, modelJob->AnimationTime); -// std::vector frameBones2 = modelJob->Skeleton->GetFrameBones(*modelJob->Skeleton->GetAnimation("Walk"), modelJob->AnimationTime); -// -// -// for (int i = 0; i < frameBones.size(); i++) { -// frameBones[i] = frameBones[i] * glm::mat4(glm::quat(glm::vec3(0.f, 0.f, 0.f)));//* frameBones2[i]; -// } - glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); } } From c9b982bc89cb627bae518ce0c0cbd2809f3f931d Mon Sep 17 00:00:00 2001 From: viktorljung Date: Wed, 27 Jan 2016 17:31:57 +0100 Subject: [PATCH 020/355] Added BoneAttachment to Entity.xsd --- resources/Schema/Types/Entity.xsd | 1 + 1 file changed, 1 insertion(+) diff --git a/resources/Schema/Types/Entity.xsd b/resources/Schema/Types/Entity.xsd index 99b90caa..addabff2 100644 --- a/resources/Schema/Types/Entity.xsd +++ b/resources/Schema/Types/Entity.xsd @@ -37,6 +37,7 @@ + From 7497ff39d2e3d73ed4a3d34b8345236e575b6cf9 Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Wed, 27 Jan 2016 18:00:31 +0100 Subject: [PATCH 021/355] Simon added Copy method to ComponentWrapper. Its being used in PlayerDeathSystem to copy model,animation,transform. TODO: 3rd person camera, cleanup, tests --- include/Engine/Core/ComponentWrapper.h | 5 ++ include/Engine/Core/EPlayerDeath.h | 3 +- src/Game/Systems/HealthSystem.cpp | 4 +- src/Game/Systems/PlayerDeathSystem.cpp | 69 +++++++++++++++++++++++++- 4 files changed, 77 insertions(+), 4 deletions(-) diff --git a/include/Engine/Core/ComponentWrapper.h b/include/Engine/Core/ComponentWrapper.h index f09bbfe3..1ca0347d 100644 --- a/include/Engine/Core/ComponentWrapper.h +++ b/include/Engine/Core/ComponentWrapper.h @@ -43,6 +43,11 @@ struct ComponentWrapper // Specialization for string literals template void SetField(std::string name, const char(&value)[N]) { Field(name) = std::string(value); } + + void Copy(ComponentWrapper& destination) + { + memcpy(destination.Data, this->Data, Info.Stride); + } struct SubscriptProxy { diff --git a/include/Engine/Core/EPlayerDeath.h b/include/Engine/Core/EPlayerDeath.h index 00ede5ed..53dfd013 100644 --- a/include/Engine/Core/EPlayerDeath.h +++ b/include/Engine/Core/EPlayerDeath.h @@ -2,7 +2,7 @@ #define EPlayerDeath_h__ #include "EventBroker.h" -#include "../Core/Entity.h" +#include "../Core/EntityWrapper.h" namespace Events { @@ -12,6 +12,7 @@ struct PlayerDeath : Event //KilledBy,KilledByWhat is optional for now. It might be used later in the playerlog-system EntityID KilledBy; EntityID PlayerID; + EntityWrapper Player; std::string KilledByWhat; }; diff --git a/src/Game/Systems/HealthSystem.cpp b/src/Game/Systems/HealthSystem.cpp index 26d38c69..102a4be6 100644 --- a/src/Game/Systems/HealthSystem.cpp +++ b/src/Game/Systems/HealthSystem.cpp @@ -22,9 +22,9 @@ bool HealthSystem::OnPlayerDamaged(Events::PlayerDamage& e) if (health <= 0.0) { Events::PlayerDeath ePlayerDeath; ePlayerDeath.PlayerID = e.Player.ID; + ePlayerDeath.Player = e.Player; m_EventBroker->Publish(ePlayerDeath); - - m_World->DeleteEntity(e.Player.ID); + //m_World->DeleteEntity(e.Player.ID); } return true; diff --git a/src/Game/Systems/PlayerDeathSystem.cpp b/src/Game/Systems/PlayerDeathSystem.cpp index dcee3a92..ab20dbce 100644 --- a/src/Game/Systems/PlayerDeathSystem.cpp +++ b/src/Game/Systems/PlayerDeathSystem.cpp @@ -112,5 +112,72 @@ bool PlayerDeathSystem::OnPlayerDeath(Events::PlayerDeath& e) // playerName["Text"]["Content"] = e.PlayerName; //} + //m_World->DeleteEntity(e.Player.ID); + + //koppla till en kamera modell för att explodera den + + auto cameras = m_World->GetComponents("Camera"); + + for (auto& someCamera : *cameras) { + EntityWrapper entity = EntityWrapper(m_World, someCamera.EntityID); + auto cameraID = entity.ID; + auto modelID = entity.FirstChildByName("HUD"); + auto weapID = entity.FirstChildByName("Weapon").ID; + + // auto modelID = m_World->GetComponent(e.PlayerID, "Camera"); + ComponentWrapper& explosionEffect = m_World->AttachComponent(weapID, "ExplosionEffect"); + ComponentWrapper& lifeTime = m_World->AttachComponent(weapID, "Lifetime"); + (glm::vec3)explosionEffect["ExplosionOrigin"] = glm::vec3(0, 0, 0); + //explosionEffect["ExplosionOrigin"] = e.Player["Transform"]["Position"]; + (double)explosionEffect["TimeSinceDeath"] = 0.0; + (double)explosionEffect["ExplosionDuration"] = 2.0; + explosionEffect["EndColor"] = glm::vec4(0, 0, 0, 1); + (bool)explosionEffect["Randomness"] = false; + (double)explosionEffect["RandomnessScalar"] = 1.0; + (glm::vec2)explosionEffect["Velocity"] = glm::vec2(1, 1); + (bool)explosionEffect["ColorByDistance"] = false; + (bool)explosionEffect["ExponentialAccelaration"] = false; + lifeTime["Lifetime"] = 2.0; + } + + + auto t = e.Player.FirstChildByName("PlayerModel"); + auto playerEntityModel = t["Model"]; + auto playerEntityAnimation = t["Animation"]; + auto playerEntityTransform = t["Transform"]; + //auto playerEntityModel = e.Player["PlayerModel"]; +// ComponentWrapper& playerEntityModel = e.Player.FirstChildByName("PlayerModel"); + + auto newEntity = m_World->CreateEntity(); + ComponentWrapper& newEntityModel = m_World->AttachComponent(newEntity, "Model"); + ComponentWrapper& newAnimationModel = m_World->AttachComponent(newEntity, "Animation"); + ComponentWrapper& newTransformModel = m_World->AttachComponent(newEntity, "Transform"); + + //ComponentWrapper& playerEntityModel = m_World->GetComponent(e.PlayerID, "PlayerModel"); + playerEntityModel.Copy(newEntityModel); + playerEntityAnimation.Copy(newAnimationModel); + playerEntityTransform.Copy(newTransformModel); + newAnimationModel["Speed"] = (double)0.0; + auto t2 = e.Player["Transform"]["Position"]; + newTransformModel["Position"] = (glm::vec3)e.Player["Transform"]["Position"]; + newTransformModel["Scale"] = glm::vec3(5, 5, 5); + //auto tr = m_World->GetComponent(newEntityModel.EntityID, "Transform"); + //tr["Position"] = glm::vec3(0, 50, 0); + + ComponentWrapper& explosionEffect = m_World->AttachComponent(newEntityModel.EntityID, "ExplosionEffect"); + ComponentWrapper& lifeTime = m_World->AttachComponent(newEntityModel.EntityID, "Lifetime"); + (glm::vec3)explosionEffect["ExplosionOrigin"] = (glm::vec3)e.Player["Transform"]["Position"]; + //explosionEffect["ExplosionOrigin"] = e.Player["Transform"]["Position"]; + (double)explosionEffect["TimeSinceDeath"] = 0.0; + (double)explosionEffect["ExplosionDuration"] = 8.0; + explosionEffect["EndColor"] = glm::vec4(0, 0, 0, 1); + (bool)explosionEffect["Randomness"] = false; + (double)explosionEffect["RandomnessScalar"] = 1.0; + (glm::vec2)explosionEffect["Velocity"] = glm::vec2(1, 1); + (bool)explosionEffect["ColorByDistance"] = false; + (bool)explosionEffect["ExponentialAccelaration"] = false; + lifeTime["Lifetime"] = 8.0; + return true; -} \ No newline at end of file +} +//on deathanim done -> del entity From 8834d5f7a00d69e4e64bd28e40cf9f7ba87cf7f0 Mon Sep 17 00:00:00 2001 From: antc13 Date: Wed, 27 Jan 2016 18:37:56 +0100 Subject: [PATCH 022/355] Fixed Animation Export --- tools/MayaExporter/MayaExporter/Material.cpp | 4 +- tools/MayaExporter/MayaExporter/Mesh.cpp | 9 +--- tools/MayaExporter/MayaExporter/Skeleton.cpp | 46 ++++++++++++++------ 3 files changed, 35 insertions(+), 24 deletions(-) diff --git a/tools/MayaExporter/MayaExporter/Material.cpp b/tools/MayaExporter/MayaExporter/Material.cpp index 03521231..0ec752f7 100644 --- a/tools/MayaExporter/MayaExporter/Material.cpp +++ b/tools/MayaExporter/MayaExporter/Material.cpp @@ -85,9 +85,6 @@ bool Material::findColorTexture(MaterialNode& material_node, MFnDependencyNode& material_node.ColorMapFile = FullPath.erase(FullPath.find_last_of("."), FullPath.find_last_of(".") - FullPath.size()); material_node.ColorMapFileLength = material_node.ColorMapFile.length() + 1; - // Test - MGlobal::displayInfo(MString() + "getAbsolutePathToResources: " + workspace); - MGlobal::displayInfo(MString() + "Texture file: " + FullPath.c_str()); return true; } } @@ -209,6 +206,7 @@ std::vector* Material::DoIt(Mesh mesh) meshHasMaterial = true; MaterialStorage.IndexStart = totalIndices; MaterialStorage.IndexEnd = totalIndices + aMeshMaterial.second.size() - 1; + MGlobal::displayInfo("Oh noes, breaking in material"); break; } totalIndices += aMeshMaterial.second.size(); diff --git a/tools/MayaExporter/MayaExporter/Mesh.cpp b/tools/MayaExporter/MayaExporter/Mesh.cpp index 6af8a557..43b76d55 100644 --- a/tools/MayaExporter/MayaExporter/Mesh.cpp +++ b/tools/MayaExporter/MayaExporter/Mesh.cpp @@ -87,10 +87,6 @@ std::map MeshClass::GetWeightData() } weightMap[geomIter.index()] = weightInfo; - - for (unsigned int k = 0; k!=nrOfWeights; k++) { - MGlobal::displayInfo(MString() + "influence: " + weightInfo.BoneIndices[k] + " weight: " + weightInfo.BoneWeights[k]); - } geomIter.next(); } it.next(); @@ -112,7 +108,6 @@ Mesh MeshClass::GetMeshData(MObjectArray object) MFnDependencyNode thisNode(node); MPlugArray connections; thisNode.findPlug("inMesh").connectedTo(connections, true, true); - MGlobal::displayInfo(MString() + "inMesh"); bool hasSkin = false; MPlug weightList, weights; MObject weightListObject; @@ -138,7 +133,6 @@ Mesh MeshClass::GetMeshData(MObjectArray object) } for (int pathID = 0; pathID < dagPaths.length(); pathID++) { - MGlobal::displayInfo(dagPaths[pathID].fullPathName()); MDagPath thisMeshPath(dagPaths[pathID]); MMatrix transformMatrix = thisMeshPath.inclusiveMatrix(&status); @@ -173,8 +167,7 @@ Mesh MeshClass::GetMeshData(MObjectArray object) break; } map> materialFaceIDs; - MGlobal::displayInfo(MString() + "shaderIndexList: " + shaderIndexList.length()); - MGlobal::displayInfo(MString() + "shaderList: " + shaderList.length()); + MPlugArray plugArray; for (int i = 0; i < shaderIndexList.length(); i++) { MFnDependencyNode shader(shaderList[shaderIndexList[i]]); diff --git a/tools/MayaExporter/MayaExporter/Skeleton.cpp b/tools/MayaExporter/MayaExporter/Skeleton.cpp index c30311b8..94031629 100644 --- a/tools/MayaExporter/MayaExporter/Skeleton.cpp +++ b/tools/MayaExporter/MayaExporter/Skeleton.cpp @@ -60,7 +60,7 @@ // // return m_AllSkeletons; //} -std::string attr[9] = { "scaleX", "scaleY", "scaleZ", "translateX", "translateY", "translateZ", "rotateX", "rotateY", "rotateZ" }; +static std::string attr[9] = { "scaleX", "scaleY", "scaleZ", "translateX", "translateY", "translateZ", "rotateX", "rotateY", "rotateZ" }; Animation Skeleton::GetAnimData(std::string animationName, int startFrame, int endFrame) { @@ -80,6 +80,9 @@ Animation Skeleton::GetAnimData(std::string animationName, int startFrame, int e m_Hierarchy.push_back(jointIt.item()); MFnDependencyNode depNode(jointIt.item()); + MGlobal::displayInfo("-------- INFO ---------"); + MGlobal::displayInfo("Joint name: " + depNode.name()); + //Loop toght the attr Array to find keyframes; for (int i = 0; i < 9; i++) { MStatus tmp; @@ -94,21 +97,38 @@ Animation Skeleton::GetAnimData(std::string animationName, int startFrame, int e MFnAnimCurve jointAnim(connected); + //MGlobal::displayInfo(MString() + "curve : " + jointAnim.name()); + //MGlobal::displayInfo(MString() + "curve keys : " + jointAnim.numKeys()); + //MGlobal::displayInfo(MString() + "curve keyframes : " + jointAnim.numKeyframes()); + //MGlobal::displayInfo(MString() + "startFrame : " + startFrame); + //MGlobal::displayInfo(MString() + "endFrame : " + endFrame); + unsigned int startKeyFrameIndex = jointAnim.findClosest(MTime(startFrame, MTime::kNTSCField), &tmp); if (tmp == MStatus::kFailure) MGlobal::displayInfo(MString() + "Fail :c"); - if (startFrame * oneDivSixty <= jointAnim.time(startKeyFrameIndex).value() && jointAnim.time(startKeyFrameIndex).value() <= endFrame * oneDivSixty) { + //MGlobal::displayInfo(MString() + "Start key index : " + startKeyFrameIndex); + //MGlobal::displayInfo(MString() + "Start key time : " + jointAnim.time(startKeyFrameIndex).value()); + + + if (startFrame <= jointAnim.time(startKeyFrameIndex).value() && jointAnim.time(startKeyFrameIndex).value() <= endFrame ) { animatedJoints.push_back(jointIt.item()); i = 9; break; - } + } - unsigned int endKeyFrameIndex = jointAnim.findClosest(MTime(endFrame, MTime::kNTSCField)); - MGlobal::displayInfo(MString() + startKeyFrameIndex + " " + endKeyFrameIndex); + unsigned int endKeyFrameIndex = jointAnim.findClosest(MTime(endFrame, MTime::kNTSCField), &tmp); + if (tmp == MStatus::kFailure) + MGlobal::displayInfo(MString() + "Fail!!!!!!!!!!!!!!!!!!!!!!!!!"); - if (startFrame * oneDivSixty <= jointAnim.time(endKeyFrameIndex).value() && jointAnim.time(endKeyFrameIndex).value() <= endFrame * oneDivSixty || endKeyFrameIndex - startKeyFrameIndex > 0) { + + //MGlobal::displayInfo(MString() + "End key index : " + endKeyFrameIndex); + //MGlobal::displayInfo(MString() + "end key time : " + jointAnim.time(endKeyFrameIndex).value()); + + /*MGlobal::displayInfo(MString() + "start keyfram index: " + startKeyFrameIndex + ". End keyfram index: " + endKeyFrameIndex + ".");*/ + + if (startFrame <= jointAnim.time(endKeyFrameIndex).value() && jointAnim.time(endKeyFrameIndex).value() <= endFrame || endKeyFrameIndex - startKeyFrameIndex > 0) { animatedJoints.push_back(jointIt.item()); i = 9; break; @@ -122,16 +142,19 @@ Animation Skeleton::GetAnimData(std::string animationName, int startFrame, int e MFnMatrixData MartixFn(DataHandle.data()); MMatrix BindPoseMatrix = MartixFn.matrix(); - if (!BindPoseMatrix.isEquivalent(MayaJoint.transformationMatrix())) + if (!BindPoseMatrix.isEquivalent(MayaJoint.transformationMatrix(), 0.0000001f)) { MGlobal::displayError(MString() + animationName.c_str() + " is using " + MayaJoint.name() + " that is not in bind pose nor is it key framed in the animation, the exported animation will NOT correspond to the animation in Maya"); } } - } - } + }//end of connections.length() loop + } // end of int i loop jointIt.next(); - } + } // enf of while (!jointIt.isDone()) + + + int currentFrame = startFrame; while (currentFrame != endFrame + 1) { // ANDREAS @@ -251,18 +274,15 @@ std::vector Skeleton::GetBindPoses() MVector tmp = MayaJoint.transformation().getTranslation(MSpace::kObject); - MGlobal::displayError(MString() + "translation befor: " + tmp[0] + " " + tmp[1] + " " + tmp[2]); //Matrix[3][0] *= -1; //Matrix[3][2] *= -1; //Matrix[3][1] *= -1; double test[3]; MayaJoint.transformation().getScale(test, MSpace::kObject); - MGlobal::displayError(MString() + "scale: " + test[0] + " " + test[1] + " " + test[2]); MTransformationMatrix::RotationOrder order = MTransformationMatrix::RotationOrder::kXYZ; MayaJoint.transformation().getRotation(test, order); - MGlobal::displayError(MString() + "rotation: " + test[0] + " " + test[1] + " " + test[2]); //----- test From df05f1909b08b37a3e02d86e1a73730d6b2b7f5a Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Thu, 28 Jan 2016 11:43:38 +0100 Subject: [PATCH 023/355] Completed the code to trigger the 3rd person camera on death. Cleaned up PlayerDeathSystem. Fixed HealthSystemTest. Removed the test for PlayerDeathSystem --- include/Game/Systems/PlayerDeathSystem.h | 18 +-- src/Game/Systems/HealthSystem.cpp | 2 +- src/Game/Systems/PlayerDeathSystem.cpp | 191 +++++------------------ src/Tests/HealthSystemTest.cpp | 22 ++- 4 files changed, 52 insertions(+), 181 deletions(-) diff --git a/include/Game/Systems/PlayerDeathSystem.h b/include/Game/Systems/PlayerDeathSystem.h index 3f7268ca..c59aea03 100644 --- a/include/Game/Systems/PlayerDeathSystem.h +++ b/include/Game/Systems/PlayerDeathSystem.h @@ -3,15 +3,11 @@ #include "Core/System.h" #include "Input/EInputCommand.h" -#include "Systems/SpawnerSystem.h" -#include "Events/ESpawnerSpawn.h" -#include "Core/EPlayerSpawned.h" +#include "GLM.h" #include "Rendering/ESetCamera.h" #include "Core/ConfigFile.h" #include "Core/EPlayerDeath.h" -//tests -#include "Core/EPlayerDamage.h" class PlayerDeathSystem : public ImpureSystem { @@ -21,18 +17,6 @@ public: virtual void Update(double dt) override; private: - struct SpawnRequest - { - int PlayerID; - ComponentInfo::EnumType Team; - }; - - bool m_NetworkEnabled = false; - std::vector m_SpawnRequests; - std::map m_PlayerEntities; - - EventRelay m_OnInputCommand; - bool OnInputCommand(const Events::InputCommand& e); EventRelay m_OnPlayerDeath; bool OnPlayerDeath(Events::PlayerDeath& e); }; diff --git a/src/Game/Systems/HealthSystem.cpp b/src/Game/Systems/HealthSystem.cpp index 102a4be6..1b747046 100644 --- a/src/Game/Systems/HealthSystem.cpp +++ b/src/Game/Systems/HealthSystem.cpp @@ -24,7 +24,7 @@ bool HealthSystem::OnPlayerDamaged(Events::PlayerDamage& e) ePlayerDeath.PlayerID = e.Player.ID; ePlayerDeath.Player = e.Player; m_EventBroker->Publish(ePlayerDeath); - //m_World->DeleteEntity(e.Player.ID); + //Note: we will delete the entity in PlayerDeathSystem } return true; diff --git a/src/Game/Systems/PlayerDeathSystem.cpp b/src/Game/Systems/PlayerDeathSystem.cpp index ab20dbce..7085a23f 100644 --- a/src/Game/Systems/PlayerDeathSystem.cpp +++ b/src/Game/Systems/PlayerDeathSystem.cpp @@ -3,181 +3,72 @@ PlayerDeathSystem::PlayerDeathSystem(World* m_World, EventBroker* eventBroker) : System(m_World, eventBroker) { - EVENT_SUBSCRIBE_MEMBER(m_OnInputCommand, &PlayerDeathSystem::OnInputCommand); EVENT_SUBSCRIBE_MEMBER(m_OnPlayerDeath, &PlayerDeathSystem::OnPlayerDeath); - m_NetworkEnabled = ResourceManager::Load("Config.ini")->Get("Networking.StartNetwork", false); } void PlayerDeathSystem::Update(double dt) { - auto playerSpawns = m_World->GetComponents("PlayerSpawn"); - if (playerSpawns == nullptr) { - return; - } - - for (auto& req : m_SpawnRequests) { - for (auto& cPlayerSpawn : *playerSpawns) { - EntityWrapper spawner(m_World, cPlayerSpawn.EntityID); - if (!spawner.HasComponent("Spawner")) { - continue; - } - - // If the spawner has a team affiliation, check it - if (spawner.HasComponent("Team")) { - if ((int)spawner["Team"]["Team"] != req.Team) { - continue; - } - } - - // Spawn the player! - EntityWrapper player = SpawnerSystem::Spawn(spawner); - // Set the player team affiliation - player["Team"]["Team"] = req.Team; - - // Publish a PlayerSpawned event - Events::PlayerSpawned e; - e.PlayerID = req.PlayerID; - e.Player = player; - e.Spawner = spawner; - m_EventBroker->Publish(e); - - } - } - m_SpawnRequests.clear(); -} - -bool PlayerDeathSystem::OnInputCommand(const Events::InputCommand& e) -{ - //testing: Jump -> playerdamage - if (e.Command != "Jump") { - return false; - } - - // 0 = released - if (e.Value != 0) { - return false; - } - - auto players = m_World->GetComponents("Player"); - - for (auto& cPlayer : *players) { - EntityWrapper player(m_World, cPlayer.EntityID); - Events::PlayerDamage e; - e.Player = player; - e.Damage = 50; - m_EventBroker->Publish(e); - } - - - - return true; } bool PlayerDeathSystem::OnPlayerDeath(Events::PlayerDeath& e) { - //// When a player is actually spawned (since the actual spawning is handled on the server) - - //// Check if a player already exists - //if (m_PlayerEntities.count(e.PlayerID) != 0) { - // // TODO: Disallow infinite respawning here - // m_World->DeleteEntity(m_PlayerEntities[e.PlayerID].ID); - //} - - //// Store the player for future reference - //m_PlayerEntities[e.PlayerID] = e.Player; - - //// Set the camera to the correct entity - //EntityWrapper cameraEntity = e.Player.FirstChildByName("Camera"); - //if (cameraEntity.Valid()) { - // Events::SetCamera e; - // e.CameraEntity = cameraEntity; - // m_EventBroker->Publish(e); - //} - - //// HACK: Set the player model color to team color - //EntityWrapper playerModel = e.Player.FirstChildByName("PlayerModel"); - //if (playerModel.Valid() && e.Player.HasComponent("Team")) { - // ComponentWrapper cTeam = e.Player["Team"]; - // ComponentWrapper cModel = playerModel["Model"]; - // if ((ComponentInfo::EnumType)cTeam["Team"] == cTeam["Team"].Enum("Red")) { - // cModel["Color"] = glm::vec3(1.f, 0.f, 0.f); - // } else if ((ComponentInfo::EnumType)cTeam["Team"] == cTeam["Team"].Enum("Blue")) { - // cModel["Color"] = glm::vec3(0.f, 0.25f, 1.f); - // } - //} - - //// TODO: Set the player name to whatever - //EntityWrapper playerName = e.Player.FirstChildByName("PlayerName"); - //if (playerName.Valid()) { - // playerName["Text"]["Content"] = e.PlayerName; - //} - - //m_World->DeleteEntity(e.Player.ID); - - //koppla till en kamera modell för att explodera den - - auto cameras = m_World->GetComponents("Camera"); - - for (auto& someCamera : *cameras) { - EntityWrapper entity = EntityWrapper(m_World, someCamera.EntityID); - auto cameraID = entity.ID; - auto modelID = entity.FirstChildByName("HUD"); - auto weapID = entity.FirstChildByName("Weapon").ID; - - // auto modelID = m_World->GetComponent(e.PlayerID, "Camera"); - ComponentWrapper& explosionEffect = m_World->AttachComponent(weapID, "ExplosionEffect"); - ComponentWrapper& lifeTime = m_World->AttachComponent(weapID, "Lifetime"); - (glm::vec3)explosionEffect["ExplosionOrigin"] = glm::vec3(0, 0, 0); - //explosionEffect["ExplosionOrigin"] = e.Player["Transform"]["Position"]; - (double)explosionEffect["TimeSinceDeath"] = 0.0; - (double)explosionEffect["ExplosionDuration"] = 2.0; - explosionEffect["EndColor"] = glm::vec4(0, 0, 0, 1); - (bool)explosionEffect["Randomness"] = false; - (double)explosionEffect["RandomnessScalar"] = 1.0; - (glm::vec2)explosionEffect["Velocity"] = glm::vec2(1, 1); - (bool)explosionEffect["ColorByDistance"] = false; - (bool)explosionEffect["ExponentialAccelaration"] = false; - lifeTime["Lifetime"] = 2.0; - } - - - auto t = e.Player.FirstChildByName("PlayerModel"); - auto playerEntityModel = t["Model"]; - auto playerEntityAnimation = t["Animation"]; - auto playerEntityTransform = t["Transform"]; - //auto playerEntityModel = e.Player["PlayerModel"]; -// ComponentWrapper& playerEntityModel = e.Player.FirstChildByName("PlayerModel"); + //current components for player that we need + auto playerModelEWrapper = e.Player.FirstChildByName("PlayerModel"); + auto playerEntityModel = playerModelEWrapper["Model"]; + auto playerEntityAnimation = playerModelEWrapper["Animation"]; + auto playerEntityTransform = playerModelEWrapper["Transform"]; + //create new entity with those components + //graphics bug: model must have an animationcomponent to be able to display it auto newEntity = m_World->CreateEntity(); ComponentWrapper& newEntityModel = m_World->AttachComponent(newEntity, "Model"); ComponentWrapper& newAnimationModel = m_World->AttachComponent(newEntity, "Animation"); ComponentWrapper& newTransformModel = m_World->AttachComponent(newEntity, "Transform"); - - //ComponentWrapper& playerEntityModel = m_World->GetComponent(e.PlayerID, "PlayerModel"); playerEntityModel.Copy(newEntityModel); playerEntityAnimation.Copy(newAnimationModel); playerEntityTransform.Copy(newTransformModel); - newAnimationModel["Speed"] = (double)0.0; - auto t2 = e.Player["Transform"]["Position"]; - newTransformModel["Position"] = (glm::vec3)e.Player["Transform"]["Position"]; - newTransformModel["Scale"] = glm::vec3(5, 5, 5); - //auto tr = m_World->GetComponent(newEntityModel.EntityID, "Transform"); - //tr["Position"] = glm::vec3(0, 50, 0); - ComponentWrapper& explosionEffect = m_World->AttachComponent(newEntityModel.EntityID, "ExplosionEffect"); - ComponentWrapper& lifeTime = m_World->AttachComponent(newEntityModel.EntityID, "Lifetime"); + //change the animation speed and make sure the explosioneffect spawns at the players position + newAnimationModel["Speed"] = (double)0.0; + newEntityModel["Color"] = glm::vec4(1, 0, 0, 1); + newTransformModel["Position"] = (glm::vec3)e.Player["Transform"]["Position"]; + newTransformModel["Scale"] = glm::vec3(1, 1, 1); + + //add the explosion with a lifetime + ComponentWrapper& explosionEffect = m_World->AttachComponent(newEntity, "ExplosionEffect"); + ComponentWrapper& lifeTime = m_World->AttachComponent(newEntity, "Lifetime"); (glm::vec3)explosionEffect["ExplosionOrigin"] = (glm::vec3)e.Player["Transform"]["Position"]; - //explosionEffect["ExplosionOrigin"] = e.Player["Transform"]["Position"]; (double)explosionEffect["TimeSinceDeath"] = 0.0; (double)explosionEffect["ExplosionDuration"] = 8.0; - explosionEffect["EndColor"] = glm::vec4(0, 0, 0, 1); + (glm::vec4)explosionEffect["EndColor"] = glm::vec4(0, 0, 0, 1); (bool)explosionEffect["Randomness"] = false; (double)explosionEffect["RandomnessScalar"] = 1.0; - (glm::vec2)explosionEffect["Velocity"] = glm::vec2(1, 1); + (glm::vec2)explosionEffect["Velocity"] = glm::vec2(0.1f, 0.1f); (bool)explosionEffect["ColorByDistance"] = false; (bool)explosionEffect["ExponentialAccelaration"] = false; - lifeTime["Lifetime"] = 8.0; + lifeTime["Lifetime"] = (double)8.0; + //create a camera (with lifetime) slightly above the player and look down at the player + auto cameraEntity = m_World->CreateEntity(); + ComponentWrapper& thirdPersonCameraLifeTime = m_World->AttachComponent(cameraEntity, "Lifetime"); + ComponentWrapper& thirdPersonCamera = m_World->AttachComponent(cameraEntity, "Camera"); + ComponentWrapper& thirdPersonCameraTransform = m_World->AttachComponent(cameraEntity, "Transform"); + auto pos = (glm::vec3)e.Player["Transform"]["Position"]; + pos.y += 10.0f; + thirdPersonCameraTransform["Position"] = (glm::vec3)pos; + //http://www.opengl-tutorial.org/intermediate-tutorials/tutorial-17-quaternions/ + thirdPersonCameraTransform["Orientation"] = glm::vec3(-0.7f, 1.46f, 0.8f); + thirdPersonCamera["FOV"] = 120.0; + thirdPersonCamera["NearClip"] = 0.1; + thirdPersonCamera["FarClip"] = 10000.0; + thirdPersonCameraLifeTime["Lifetime"] = (double)1.0; + + //set 3rd person camera + Events::SetCamera eSetCamera; + eSetCamera.CameraEntity = EntityWrapper(m_World, cameraEntity); + m_EventBroker->Publish(eSetCamera); + + //on deathanim done -> del entity + m_World->DeleteEntity(e.Player.ID); return true; } -//on deathanim done -> del entity diff --git a/src/Tests/HealthSystemTest.cpp b/src/Tests/HealthSystemTest.cpp index 6a434a9a..280b8d14 100644 --- a/src/Tests/HealthSystemTest.cpp +++ b/src/Tests/HealthSystemTest.cpp @@ -54,36 +54,32 @@ GameHealthSystemTest::GameHealthSystemTest() //The Test //create entity which has transform,player,model,health in it. i.e. is a player EntityID playerID = m_World->CreateEntity(); - ComponentWrapper transform = m_World->AttachComponent(playerID, "Transform"); - ComponentWrapper model = m_World->AttachComponent(playerID, "Model"); - model["Resource"] = "Models/Core/UnitSphere.mesh"; // 360NoScope UnitSphere ComponentWrapper player = m_World->AttachComponent(playerID, "Player"); ComponentWrapper health = m_World->AttachComponent(playerID, "Health"); healthsID = playerID; - double currentHealth = (double)m_World->GetComponent(healthsID, "Health")["Health"]; + + EntityID playerID2 = m_World->CreateEntity(); + ComponentWrapper player2 = m_World->AttachComponent(playerID2, "Player"); + ComponentWrapper health2 = m_World->AttachComponent(playerID2, "Health"); //heal player with 40 Events::PlayerHealthPickup e3; e3.HealthAmount = 40.0f; - e3.PlayerHealedID = healthsID; + e3.Player = EntityWrapper(m_World, player.EntityID); m_EventBroker->Publish(e3); + //damage player with 50 Events::PlayerDamage e; e.Damage = 50.0f; -// e.PlayerDamagedID = healthsID; + e.Player = EntityWrapper(m_World, player.EntityID); m_EventBroker->Publish(e); + //heal some other player with 40 Events::PlayerHealthPickup e2; e2.HealthAmount = 40.0f; - e2.PlayerHealedID = healthsID + 1; + e2.Player = EntityWrapper(m_World, player2.EntityID); m_EventBroker->Publish(e2); - EntityID playerID2 = m_World->CreateEntity(); - ComponentWrapper transform2 = m_World->AttachComponent(playerID2, "Transform"); - ComponentWrapper model2 = m_World->AttachComponent(playerID2, "Model"); - model2["Resource"] = "Models/Core/UnitSphere.mesh"; // 360NoScope UnitSphere - ComponentWrapper player2 = m_World->AttachComponent(playerID2, "Player"); - ComponentWrapper health2 = m_World->AttachComponent(playerID2, "Health"); //END TEST } From 7987d4b27cabe927d75da234a0e201ec502b66ac Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Fri, 29 Jan 2016 12:06:14 +0100 Subject: [PATCH 024/355] Added AssaultDash and all its logic, including a doubletapkey. Doubletapkey could be made more generic. --- include/Game/Systems/PlayerMovementSystem.h | 16 +++++++ src/Game/Systems/PlayerMovementSystem.cpp | 52 +++++++++++++++++++-- 2 files changed, 64 insertions(+), 4 deletions(-) diff --git a/include/Game/Systems/PlayerMovementSystem.h b/include/Game/Systems/PlayerMovementSystem.h index f39740ec..554d174e 100644 --- a/include/Game/Systems/PlayerMovementSystem.h +++ b/include/Game/Systems/PlayerMovementSystem.h @@ -20,4 +20,20 @@ private: EventRelay m_EPlayerSpawned; bool OnPlayerSpawned(Events::PlayerSpawned& e); + + double m_AssaultDashDoubleTapDeltaTime = 0.0f; + double m_AssaultDashCoolDownTimer = 0.0f; + double m_AssaultDashCoolDownMaxTimer = 3.0f; + ImGuiKey m_AssaultDashDoubleTapLastKey = ImGuiKey_Escape; + const float m_AssaultDashDoubleTapSensitivityTimer = 0.25f; + enum class AssaultDashDirection { + Left, + Right, + None + }; + AssaultDashDirection m_AssaultDashTapDirection = AssaultDashDirection::None; + bool m_AssaultDashDoubleTapped = false; + bool m_PlayerIsDashing = false; + + void assaultDashCheck(glm::vec3 controllerMovement, double dt, bool isJumping); }; \ No newline at end of file diff --git a/src/Game/Systems/PlayerMovementSystem.cpp b/src/Game/Systems/PlayerMovementSystem.cpp index 6eab02c5..fe28ff8e 100644 --- a/src/Game/Systems/PlayerMovementSystem.cpp +++ b/src/Game/Systems/PlayerMovementSystem.cpp @@ -1,6 +1,6 @@ #include "Systems/PlayerMovementSystem.h" -PlayerMovementSystem::PlayerMovementSystem(World* world, EventBroker* eventBroker) +PlayerMovementSystem::PlayerMovementSystem(World* world, EventBroker* eventBroker) : System(world, eventBroker) , PureSystem("Player") { @@ -41,7 +41,9 @@ void PlayerMovementSystem::Update(double dt) if (player.HasComponent("Physics")) { ComponentWrapper cPhysics = player["Physics"]; - + //Assault Dash Check - + //TODO: check if playerclass is assault! + assaultDashCheck(controller->Movement(), dt, ((glm::vec3)cPhysics["Velocity"]).y != 0.0f); glm::vec3 wishDirection = controller->Movement() * glm::inverse(glm::quat(ori)); float wishSpeed; if (controller->Crouching()) { @@ -71,12 +73,15 @@ void PlayerMovementSystem::Update(double dt) static float surfaceFriction = 5.f; ImGui::InputFloat("surfaceFriction", &surfaceFriction); float accelerationSpeed = actualAccel * (float)dt * wishSpeed * surfaceFriction; - accelerationSpeed = glm::min(accelerationSpeed, addSpeed); + //if doubleTapped do Assault Dash - but only boost maximum 50.0f + float doubleTapDashBoost = m_AssaultDashDoubleTapped ? 20.0f : 1.0f; + accelerationSpeed = glm::min(doubleTapDashBoost*glm::min(accelerationSpeed, addSpeed), 50.0f); velocity += accelerationSpeed * wishDirection; ImGui::Text("velocity: (%f, %f, %f) |%f|", velocity.x, velocity.y, velocity.z, glm::length(velocity)); } - if (controller->Jumping() && !controller->Crouching() && velocity.y == 0.f) { + //you cant jump and dash at the same time - since there is no friction in the air and we would thus dash much further in the air + if (!m_PlayerIsDashing && controller->Jumping() && !controller->Crouching() && velocity.y == 0.f) { velocity.y += 4.f; } @@ -95,6 +100,7 @@ void PlayerMovementSystem::Update(double dt) ComponentWrapper cAnimation = playerModel["Animation"]; float movementLength = glm::length(groundVelocity); + //TODO: add assault dash animation here if (glm::length(controller->Movement()) > 0.f) { if (controller->Crouching()) { cAnimation["Name"] = "Crouch Walk"; @@ -158,3 +164,41 @@ bool PlayerMovementSystem::OnPlayerSpawned(Events::PlayerSpawned& e) return true; } +void PlayerMovementSystem::assaultDashCheck(glm::vec3 controllerMovement, double dt, bool isJumping) { + m_AssaultDashDoubleTapDeltaTime += dt; + m_AssaultDashCoolDownTimer -= dt; + //cooldown = m_AssaultDashCoolDownMaxTimer sec, pretend the dash lasts 0.25 sec (for friction to do its work) + if (m_AssaultDashCoolDownTimer > (m_AssaultDashCoolDownMaxTimer - 0.25f)) { + m_PlayerIsDashing = true; + } else { + m_PlayerIsDashing = false; + } + //reset the DoubleTapped state in case we recently doubleTapped + if (m_AssaultDashDoubleTapped) { + m_AssaultDashDoubleTapped = false; + } + //Assault Dash logic: tap left or right twice within 0.5sec to activate the doubletap-dash + if (controllerMovement.x > 0 && controllerMovement.y == 0.f && controllerMovement.z == 0.f) { + if (m_AssaultDashDoubleTapLastKey != ImGuiKey_RightArrow && m_AssaultDashDoubleTapDeltaTime < m_AssaultDashDoubleTapSensitivityTimer + && m_AssaultDashTapDirection == AssaultDashDirection::Right && m_AssaultDashCoolDownTimer <= 0.0f && !isJumping) { + m_AssaultDashDoubleTapped = true; + m_AssaultDashDoubleTapDeltaTime = 0.f; + m_AssaultDashCoolDownTimer = m_AssaultDashCoolDownMaxTimer; + } + m_AssaultDashDoubleTapLastKey = ImGuiKey_RightArrow; + m_AssaultDashDoubleTapDeltaTime = 0.f; + m_AssaultDashTapDirection = AssaultDashDirection::Right; + } else if (controllerMovement.x < 0 && controllerMovement.y == 0.f && controllerMovement.z == 0.f) { + if (m_AssaultDashDoubleTapLastKey != ImGuiKey_LeftArrow && m_AssaultDashDoubleTapDeltaTime < m_AssaultDashDoubleTapSensitivityTimer + && m_AssaultDashTapDirection == AssaultDashDirection::Left && m_AssaultDashCoolDownTimer <= 0.0f && !isJumping) { + m_AssaultDashDoubleTapped = true; + m_AssaultDashDoubleTapDeltaTime = 0.f; + m_AssaultDashCoolDownTimer = m_AssaultDashCoolDownMaxTimer; + } + m_AssaultDashDoubleTapLastKey = ImGuiKey_LeftArrow; + m_AssaultDashDoubleTapDeltaTime = 0.f; + m_AssaultDashTapDirection = AssaultDashDirection::Left; + } else { + m_AssaultDashDoubleTapLastKey = ImGuiKey_Escape; + } +} From 51075aefc819edd09a0737f056f517970718124b Mon Sep 17 00:00:00 2001 From: viktorljung Date: Mon, 1 Feb 2016 10:24:50 +0100 Subject: [PATCH 025/355] Model that has animations is now visible when it does not play an animation (T-pose) --- include/Engine/Rendering/Skeleton.h | 2 +- resources/Schema/Entities/AnimatedArmy.xml | 4 +- resources/Schema/Entities/AnimationTests.xml | 73 ++++++++++++-------- resources/Schema/Entities/RenderingWorld.xml | 6 +- src/Engine/Rendering/DrawFinalPass.cpp | 14 ++-- src/Engine/Rendering/PickingPass.cpp | 2 +- src/Engine/Rendering/Skeleton.cpp | 23 ++++-- 7 files changed, 72 insertions(+), 52 deletions(-) diff --git a/include/Engine/Rendering/Skeleton.h b/include/Engine/Rendering/Skeleton.h index 15749b85..dca78e4c 100644 --- a/include/Engine/Rendering/Skeleton.h +++ b/include/Engine/Rendering/Skeleton.h @@ -83,7 +83,7 @@ public: int GetBoneID(std::string name); const Animation* GetAnimation(std::string name); - std::vector GetFrameBones(const Animation& animation, double time, bool noRootMotion = false); + std::vector GetFrameBones(const Animation* animation, double time, bool noRootMotion = false); void AccumulateBoneTransforms(bool noRootMotion, const Animation::Keyframe& currentFrame, const Animation::Keyframe& nextFrame, float progress, std::map& boneMatrices, const Bone* bone, glm::mat4 parentMatrix); void PrintSkeleton(); void PrintSkeleton(const Bone* parent, int depthCount); diff --git a/resources/Schema/Entities/AnimatedArmy.xml b/resources/Schema/Entities/AnimatedArmy.xml index b711a0fe..0baa457a 100644 --- a/resources/Schema/Entities/AnimatedArmy.xml +++ b/resources/Schema/Entities/AnimatedArmy.xml @@ -91,7 +91,7 @@ - + @@ -154,7 +154,7 @@ - + diff --git a/resources/Schema/Entities/AnimationTests.xml b/resources/Schema/Entities/AnimationTests.xml index 8a757639..453a18cb 100644 --- a/resources/Schema/Entities/AnimationTests.xml +++ b/resources/Schema/Entities/AnimationTests.xml @@ -12,8 +12,7 @@ Models/Core/UnitPlane.mesh - - + @@ -34,16 +33,15 @@ - Walk - - 0.5 + Run + + 1 Models/AssaultAnimated.mesh - - + @@ -84,34 +82,51 @@ - - - - - - - - - - - R_Foot - - true - - - Models/Core/UnitCube.mesh - - - - - - + + + + + + + Walk + + 1 + + + Models/AssaultAnimated.mesh + + + + + + + + + + + Crouch Walk + + 1 + + + + + + Models/AssaultAnimated.mesh + + + + + + + + diff --git a/resources/Schema/Entities/RenderingWorld.xml b/resources/Schema/Entities/RenderingWorld.xml index 20301d5f..1ac95a3b 100644 --- a/resources/Schema/Entities/RenderingWorld.xml +++ b/resources/Schema/Entities/RenderingWorld.xml @@ -52,11 +52,11 @@ - 0.65990006923675537 + Models/Core/UnitHexagon.mesh @@ -161,7 +161,7 @@ - + @@ -308,7 +308,7 @@ - Models/Assault.mesh + Models/AssaultAnimated.mesh diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index 72329f5b..b5808117 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -88,11 +88,8 @@ void DrawFinalPass::Draw(RenderScene& scene) GLERROR("DrawFinalPass::ExplosionEffect: 2"); if (explosionEffectJob->Model->m_RawModel->m_Skeleton != nullptr) { - - if (explosionEffectJob->Animation != nullptr) { - std::vector frameBones = explosionEffectJob->Skeleton->GetFrameBones(*explosionEffectJob->Animation, explosionEffectJob->AnimationTime); - glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - } + std::vector frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animation, explosionEffectJob->AnimationTime); + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); } //TODO: Renderer: bättre textur felhantering samt fler texturer stöd @@ -157,10 +154,9 @@ void DrawFinalPass::Draw(RenderScene& scene) }*/ if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { - if (modelJob->Animation != nullptr) { - std::vector frameBones = modelJob->Skeleton->GetFrameBones(*modelJob->Animation, modelJob->AnimationTime); - glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - } + std::vector frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animation, modelJob->AnimationTime); + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + } glBindVertexArray(modelJob->Model->VAO); diff --git a/src/Engine/Rendering/PickingPass.cpp b/src/Engine/Rendering/PickingPass.cpp index 3a7d5bfd..b509bd3d 100644 --- a/src/Engine/Rendering/PickingPass.cpp +++ b/src/Engine/Rendering/PickingPass.cpp @@ -91,7 +91,7 @@ void PickingPass::Draw(RenderScene& scene) if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { if (modelJob->Animation != nullptr) { - std::vector frameBones = modelJob->Skeleton->GetFrameBones(*modelJob->Animation, modelJob->AnimationTime); + std::vector frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animation, modelJob->AnimationTime); glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); } } diff --git a/src/Engine/Rendering/Skeleton.cpp b/src/Engine/Rendering/Skeleton.cpp index 8326dea9..150fad7d 100644 --- a/src/Engine/Rendering/Skeleton.cpp +++ b/src/Engine/Rendering/Skeleton.cpp @@ -39,20 +39,29 @@ const Skeleton::Animation* Skeleton::GetAnimation(std::string name) } } -std::vector Skeleton::GetFrameBones(const Animation& animation, double time, bool noRootMotion /*= false*/) +std::vector Skeleton::GetFrameBones(const Animation* animation, double time, bool noRootMotion /*= false*/) { + if(animation == nullptr) { + std::vector finalMatrices; + for(auto& b : Bones) { + finalMatrices.push_back(glm::mat4(1));//b.second->OffsetMatrix); + } + return finalMatrices; + } + + // HACK: Animation wrap-around while (time < 0) { - time += animation.Duration; + time += animation->Duration; } - while (time > animation.Duration) { - time -= animation.Duration; + while (time > animation->Duration) { + time -= animation->Duration; } - int currentKeyframeIndex = GetKeyframe(animation, time); + int currentKeyframeIndex = GetKeyframe(*animation, time); - const Animation::Keyframe& currentFrame = animation.Keyframes[currentKeyframeIndex]; - const Animation::Keyframe& nextFrame = animation.Keyframes[(currentKeyframeIndex + 1) % animation.Keyframes.size()]; + const Animation::Keyframe& currentFrame = animation->Keyframes[currentKeyframeIndex]; + const Animation::Keyframe& nextFrame = animation->Keyframes[(currentKeyframeIndex + 1) % animation->Keyframes.size()]; float alpha = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); //auto animationFrame = Animations[""].Keyframes[frame]; From 6ba87d2942c50d7310c9b87da90b88df82ddf359 Mon Sep 17 00:00:00 2001 From: viktorljung Date: Mon, 1 Feb 2016 10:42:23 +0100 Subject: [PATCH 026/355] Fixed, Crash when trying to animate a model that doesn't contain animations --- include/Engine/Rendering/ModelJob.h | 1 + resources/Schema/Entities/AnimationTests.xml | 29 +++++++++++++------- src/Engine/Rendering/AnimationSystem.cpp | 6 ++++ src/Engine/Rendering/DrawFinalPass.cpp | 1 - src/Engine/Rendering/PickingPass.cpp | 3 -- 5 files changed, 26 insertions(+), 14 deletions(-) diff --git a/include/Engine/Rendering/ModelJob.h b/include/Engine/Rendering/ModelJob.h index 21f7c1ca..6598b950 100644 --- a/include/Engine/Rendering/ModelJob.h +++ b/include/Engine/Rendering/ModelJob.h @@ -42,6 +42,7 @@ struct ModelJob : RenderJob FillColor = fillColor; FillPercentage = fillPercentage; + Skeleton = Model->m_RawModel->m_Skeleton; if (world->HasComponent(Entity, "Animation") && Skeleton != nullptr) { diff --git a/resources/Schema/Entities/AnimationTests.xml b/resources/Schema/Entities/AnimationTests.xml index 453a18cb..578db574 100644 --- a/resources/Schema/Entities/AnimationTests.xml +++ b/resources/Schema/Entities/AnimationTests.xml @@ -12,7 +12,8 @@ Models/Core/UnitPlane.mesh - + + @@ -34,7 +35,7 @@ Run - + 1 @@ -82,9 +83,9 @@ - - - + + + @@ -95,7 +96,7 @@ Walk - + 1 @@ -111,12 +112,9 @@ Crouch Walk - + 1 - - - Models/AssaultAnimated.mesh @@ -127,6 +125,17 @@ + + + + Models/Core/UnitCube.mesh + + + + + + + diff --git a/src/Engine/Rendering/AnimationSystem.cpp b/src/Engine/Rendering/AnimationSystem.cpp index c79b5a36..9c1e68cf 100644 --- a/src/Engine/Rendering/AnimationSystem.cpp +++ b/src/Engine/Rendering/AnimationSystem.cpp @@ -15,6 +15,12 @@ void AnimationSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& a Skeleton* skeleton = model->m_RawModel->m_Skeleton; + + if(skeleton == nullptr) { + return; + } + + const Skeleton::Animation* animation = skeleton->GetAnimation(animationComponent["AnimationName"]); if(animation != nullptr) { diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index b5808117..66c4d52b 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -156,7 +156,6 @@ void DrawFinalPass::Draw(RenderScene& scene) if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { std::vector frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animation, modelJob->AnimationTime); glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - } glBindVertexArray(modelJob->Model->VAO); diff --git a/src/Engine/Rendering/PickingPass.cpp b/src/Engine/Rendering/PickingPass.cpp index b509bd3d..4c39bfc9 100644 --- a/src/Engine/Rendering/PickingPass.cpp +++ b/src/Engine/Rendering/PickingPass.cpp @@ -89,11 +89,8 @@ void PickingPass::Draw(RenderScene& scene) glUniform2fv(glGetUniformLocation(shaderHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1]))); if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { - - if (modelJob->Animation != nullptr) { std::vector frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animation, modelJob->AnimationTime); glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - } } glBindVertexArray(modelJob->Model->VAO); From 76274c326e66beeae725b6638fd46b1d2814e364 Mon Sep 17 00:00:00 2001 From: William Moberg Date: Mon, 1 Feb 2016 13:34:39 +0100 Subject: [PATCH 027/355] Fixed going through flat large triangles. Velocity affected by collision. --- include/Engine/Collision/Collision.h | 2 +- .../Schema/Entities/CollisionSpawnTest.xml | 164 ++++++++++++++ resources/Schema/Entities/GameMap.xml | 1 + .../Schema/Entities/LevelCollisionTest.xml | 4 +- src/Engine/Collision/Collision.cpp | 203 +++++++++--------- src/Engine/Collision/CollisionSystem.cpp | 5 +- 6 files changed, 267 insertions(+), 112 deletions(-) create mode 100644 resources/Schema/Entities/CollisionSpawnTest.xml diff --git a/include/Engine/Collision/Collision.h b/include/Engine/Collision/Collision.h index b8625b73..dfc71496 100644 --- a/include/Engine/Collision/Collision.h +++ b/include/Engine/Collision/Collision.h @@ -66,7 +66,7 @@ bool AABBvsTriangles(const AABB& box, const std::vector& modelVertices, const std::vector& modelIndices, const glm::mat4& modelMatrix, - const glm::vec3& boxVelocity, + glm::vec3& boxVelocity, glm::vec3& outResolutionVector); //Return true if the boxes are intersecting. diff --git a/resources/Schema/Entities/CollisionSpawnTest.xml b/resources/Schema/Entities/CollisionSpawnTest.xml new file mode 100644 index 00000000..331beae6 --- /dev/null +++ b/resources/Schema/Entities/CollisionSpawnTest.xml @@ -0,0 +1,164 @@ + + + + + + + + + + + + + + ../assets/Models/Test/ObstacleCourse.mesh + + + + + + + + + + + 0.46000027656555176 + + + + + + + + + + + + + ../assets/Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + false + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + false + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/GameMap.xml b/resources/Schema/Entities/GameMap.xml index 97fd3f4d..e206d31f 100644 --- a/resources/Schema/Entities/GameMap.xml +++ b/resources/Schema/Entities/GameMap.xml @@ -8,6 +8,7 @@ + Models\MapVersion1.mesh diff --git a/resources/Schema/Entities/LevelCollisionTest.xml b/resources/Schema/Entities/LevelCollisionTest.xml index ce0fe405..3c3f3bab 100644 --- a/resources/Schema/Entities/LevelCollisionTest.xml +++ b/resources/Schema/Entities/LevelCollisionTest.xml @@ -4,7 +4,7 @@ - ../assets\Models/MapVersion1.obj + ../assets/Models/MapVersion1.mesh @@ -15,7 +15,7 @@ - ../assets/Models/Core/UnitCube.obj + ../assets/Models/Core/UnitCube.mesh false diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index 96d908ff..8134bab7 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -253,8 +253,10 @@ bool rectangleVsTriangle(const glm::vec2& boxMin, const glm::vec2& boxMax, const std::array& triPos, glm::vec2& resolutionDirection, - float& resolutionDistance) + float& resolutionDistance, + bool& pushedFromTriNormal) { + pushedFromTriNormal = false; resolutionDistance = INFINITY; //Project along box normals (coordinate axes, since it's axis-aligned). for (int ax = 0; ax < 2; ++ax) { @@ -264,14 +266,20 @@ bool rectangleVsTriangle(const glm::vec2& boxMin, minTri = std::min(t[ax], minTri); maxTri = std::max(t[ax], maxTri); } - if (minTri > boxMax[ax] || maxTri < boxMin[ax]) { + if (boxMax[ax] <= minTri || maxTri <= boxMin[ax]) { return false; } - float push = std::min(maxTri - boxMin[ax], boxMax[ax] - minTri); - if (push < resolutionDistance) { - resolutionDistance = push; + + //Here: maxBox > minTri && minBox < maxTri + //Left is negative. + float leftRes = minTri - boxMax[ax]; + float rightRes = maxTri - boxMin[ax]; + float push = rightRes < -leftRes ? rightRes : leftRes; + float absPush = abs(push); + if (absPush < resolutionDistance) { + resolutionDistance = absPush; resolutionDirection[1 - ax] = 0.f; - resolutionDirection[ax] = resolutionDistance; + resolutionDirection[ax] = push; } } //Project along triangle normals. @@ -292,7 +300,7 @@ bool rectangleVsTriangle(const glm::vec2& boxMin, continue; } //Rotate edge to a normal. - normal = glm::vec2(-normal.y, normal.x); + normal = glm::normalize(glm::vec2(-normal.y, normal.x)); //Project triangle onto the normal. float minTri = INFINITY; float maxTri = -INFINITY; @@ -309,14 +317,20 @@ bool rectangleVsTriangle(const glm::vec2& boxMin, minBox = std::min(dot, minBox); maxBox = std::max(dot, maxBox); } - if (maxBox < minTri || minBox > maxTri) { + if (maxBox <= minTri || maxTri <= minBox) { return false; } + //Here: maxBox > minTri && minBox < maxTri - float push = std::min(maxTri - minBox, maxBox - minTri); - if (push < resolutionDistance) { - resolutionDistance = push; - resolutionDirection = resolutionDistance * glm::normalize(normal); + //Left is negative. + float leftRes = minTri - maxBox; + float rightRes = maxTri - minBox; + float push = rightRes < -leftRes ? rightRes : leftRes; + float absPush = abs(push); + if (absPush < resolutionDistance) { + resolutionDistance = absPush; + resolutionDirection = push * normal; + pushedFromTriNormal = true; } } return true; @@ -326,18 +340,26 @@ bool rectangleVsTriangle(const glm::vec2& boxMin, constexpr std::array, 3> dimensionPairs({ std::pair(0, 2), std::pair(0, 1), std::pair(1, 2) }); bool AABBvsTriangle(const AABB& box, - const std::array& triPos, - const glm::vec3& boxVelocity, + const std::array& triPos, + const glm::vec3& wantDirection, + glm::vec3& boxVelocity, glm::vec3& outVector) { //Check so we don't have a zero area triangle when calculating the normal. //Also, don't check a triangle facing away from the player. //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, boxVelocity) > 0) { + if (!vectorHasLength(triNormal) || (glm::dot(triNormal, boxVelocity) > 0) && vectorHasLength(boxVelocity)) { return false; } + enum BoxTriResolveCase + { + Vertex, + Line, + Corner + } resolveCase; + const glm::vec3& origin = box.Origin(); const glm::vec3& half = box.HalfSize(); const glm::vec3& min = box.MinCorner(); @@ -358,14 +380,16 @@ bool AABBvsTriangle(const AABB& box, glm::vec2 boxMax(max[dim.first], max[dim.second]); glm::vec2 resolutionVector; float resolutionDist; + bool pushedFromTriangleLine; //if projections don't overlap, return false. - if (!rectangleVsTriangle(boxMin, boxMax, t2D, resolutionVector, resolutionDist)) { + if (!rectangleVsTriangle(boxMin, boxMax, t2D, resolutionVector, resolutionDist, pushedFromTriangleLine)) { return false; } else if (resolutionDist < minimumTranslation) { outVector = glm::vec3(0.f); outVector[dim.first] = resolutionVector.x; outVector[dim.second] = resolutionVector.y; minimumTranslation = resolutionDist; + resolveCase = pushedFromTriangleLine ? Line : Vertex; } } @@ -384,6 +408,56 @@ bool AABBvsTriangle(const AABB& box, glm::vec3 cornerResolution = (1+t) * diagonal; if (glm::length(cornerResolution) < minimumTranslation) { outVector = cornerResolution; + resolveCase = Corner; + } + + bool groundCollision = triNormal.y > 0.5f; + //ImGui::Text(groundCollision ? "Ground" : "Slope"); + + glm::vec3 projNorm; + switch (resolveCase) { + case Vertex: + { + int maxD = 0; + float maxResolution = 0.f; + for (int d = 0; d < 3; ++d) { + float resolve = glm::abs(outVector[d]); + if (resolve > maxResolution) { + maxResolution = resolve; + maxD = d; + } + } + boxVelocity[maxD] = 0.f; + return true; + } + case Line: + projNorm = glm::normalize(outVector); + break; + case Corner: + projNorm = triNormal; + break; + default: + break; + } + + //Project the velocity onto the normal of the hit line/face. + //w = v - *n, |n|==1. + boxVelocity = boxVelocity - glm::dot(boxVelocity, projNorm) * projNorm; + if (groundCollision) { + float len = glm::length2(boxVelocity); + if (len > 0.0001f) { + len = glm::sqrt(len); + boxVelocity = len * glm::normalize(wantDirection); + } + + len = glm::length(outVector); + float ang = glm::half_pi() - glm::acos(outVector.y / len); + if (len > 0.0000001f && ang > 0.0000001f) { + //ImGui::Text("ang=%f, len=%f, acos=%f, outY=%f", ang, len, glm::acos(outVector.y / len), outVector.y); + outVector.x = 0; + outVector.y = len / glm::sin(ang); + outVector.z = 0; + } } return true; } @@ -392,15 +466,16 @@ bool AABBvsTriangles(const AABB& box, const std::vector& modelVertices, const std::vector& modelIndices, const glm::mat4& modelMatrix, - const glm::vec3& boxVelocity, - glm::vec3& outResolutionVector, - int startIndex, - int recursiveDepth) + glm::vec3& boxVelocity, + glm::vec3& outResolutionVector) { bool hit = false; AABB newBox = box; outResolutionVector = glm::vec3(0.f); + glm::vec3 wantDirection(boxVelocity); + wantDirection.y = 0; + wantDirection = glm::normalize(wantDirection); for (int i = 0; i < modelIndices.size(); ) { std::array triVertices = { Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix), @@ -408,101 +483,15 @@ bool AABBvsTriangles(const AABB& box, Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix) }; glm::vec3 outVec; - if (AABBvsTriangle(newBox, triVertices, boxVelocity, outVec)) { + if (AABBvsTriangle(newBox, triVertices, wantDirection, boxVelocity, outVec)) { hit = true; outResolutionVector += outVec; newBox = AABB::FromOriginSize(newBox.Origin() + outVec, newBox.Size()); } } - //outResolutionVector = glm::vec3(INFINITY); - //if (recursiveDepth > 2) { - // return true; - //} - //for (int i = startIndex; i < modelIndices.size(); ) { - // std::array triVertices = { - // Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix), - // Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix), - // Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix) - // }; - // glm::vec3 outVec; - // if (AABBvsTriangle(box, triVertices, boxVelocity, outVec) && glm::length2(outVec) < glm::length2(outResolutionVector)) { - // hit = true; - // glm::vec3 potentialResolution = outVec; - // const AABB& resolvedBox = AABB::FromOriginSize(box.Origin() + potentialResolution, box.Size()); - // if (AABBvsTriangles(resolvedBox, modelVertices, modelIndices, modelMatrix, boxVelocity, outVec, i, recursiveDepth+1)) { - // potentialResolution += outVec; - // if (glm::length2(potentialResolution) > glm::length2(outResolutionVector)) { - // continue; - // } - // } - // outResolutionVector = potentialResolution; - // } - //} - - //outResolutionVector = glm::vec3(INFINITY); - //std::stack testBoxes; - //std::stack resolveIndices; - //std::stack resolveVectors; - //resolveVectors.push(glm::vec3(0.f)); - //resolveIndices.push(0); - //testBoxes.push(box); - //do { - // int i = resolveIndices.top(); - // resolveIndices.pop(); - // while (i < modelIndices.size()) { - // std::array triVertices = { - // Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix), - // Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix), - // Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix) - // }; - // glm::vec3 outVec; - // bool test = AABBvsTriangle(testBoxes.top(), triVertices, outVec); - // if (test) { - // hit = true; - // //emplace? - // resolveIndices.push(i); - // testBoxes.push(AABB::FromOriginSize(box.Origin() + outVec, box.Size())); - // resolveVectors.top() += outVec; - // } - // } - // testBoxes.pop(); - // resolveVectors.push(glm::vec3(0.f)); - //} while (!resolveIndices.empty()); - //if (hit) { - // if (!resolveVectors.empty()) { - // while (!resolveVectors.empty()) { - // if (glm::length2(resolveVectors.top()) < glm::length2(outResolutionVector)) { - // outResolutionVector = resolveVectors.top(); - // } - // resolveVectors.pop(); - // } - // } else { - // //TODO: This won't happen. - // ImGui::Text("Collision, but not resolved."); - // } - // return true; - //} return hit; } -bool AABBvsTriangles(const AABB& box, - const std::vector& modelVertices, - const std::vector& modelIndices, - const glm::mat4& modelMatrix, - const glm::vec3& boxVelocity, - glm::vec3& outResolutionVector) -{ - return AABBvsTriangles( - box, - modelVertices, - modelIndices, - modelMatrix, - boxVelocity, - outResolutionVector, - 0, - 0 - ); -} bool IsSameBoxProbably(const AABB& first, const AABB& second, const float epsilon) { diff --git a/src/Engine/Collision/CollisionSystem.cpp b/src/Engine/Collision/CollisionSystem.cpp index 8d43534c..81e76410 100644 --- a/src/Engine/Collision/CollisionSystem.cpp +++ b/src/Engine/Collision/CollisionSystem.cpp @@ -54,9 +54,10 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c glm::mat4 modelMatrix = glm::translate(absPosition) * glm::toMat4(absOrientation) * glm::scale(absScale); glm::vec3 resolutionVector; - if (Collision::AABBvsTriangles(boxA, model->m_Vertices, model->m_Indices, modelMatrix, (glm::vec3&)cPhysics["Velocity"], resolutionVector)) { + glm::vec3 newVelocity = (glm::vec3)cPhysics["Velocity"]; + if (Collision::AABBvsTriangles(boxA, model->m_Vertices, model->m_Indices, modelMatrix, newVelocity, resolutionVector)) { (glm::vec3&)cTransform["Position"] += resolutionVector; - cPhysics["Velocity"] = glm::vec3(0, 0, 0); + cPhysics["Velocity"] = newVelocity; } } } From 25b3c02d29bb8fdc4161867ad42899c4c9229416 Mon Sep 17 00:00:00 2001 From: stiffly Date: Mon, 1 Feb 2016 14:32:01 +0100 Subject: [PATCH 028/355] Adding sounds for: jump, walk, shoot --- assets | 2 +- include/Engine/Sound/SoundSystem.h | 39 ++++- resources/Schema/Entities/aim_rays.xml | 210 +++++++++++++++++++++++++ src/Engine/Sound/SoundSystem.cpp | 129 ++++++++++++++- 4 files changed, 368 insertions(+), 12 deletions(-) create mode 100644 resources/Schema/Entities/aim_rays.xml diff --git a/assets b/assets index e4dc9529..9b4f9ab2 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit e4dc9529f2178d373808ddf487165fa50a641a78 +Subproject commit 9b4f9ab2e67fc09863f35b33bb0a61ce75ef6aa8 diff --git a/include/Engine/Sound/SoundSystem.h b/include/Engine/Sound/SoundSystem.h index b9cc2589..5d57d5b6 100644 --- a/include/Engine/Sound/SoundSystem.h +++ b/include/Engine/Sound/SoundSystem.h @@ -20,6 +20,10 @@ #include "Sound/EStopSound.h" #include "Sound/ESetBGMGain.h" #include "Sound/ESetSFXGain.h" +#include "Core/EShoot.h" +#include "Core/EPlayerSpawned.h" +#include "Input/EInputCommand.h" +#include "Core/ECaptured.h" enum class SoundType { SFX, @@ -55,18 +59,24 @@ private: // Logic void initOpenAL(); - void updateEmitters(double dt); - void updateListener(double dt); - void deleteInactiveEmitters(); void addNewEmitters(double dt); - Source* createSource(std::string filePath); - void playSound(Source* source); - void stopSound(Source* source); + void updateEmitters(double dt); + void deleteInactiveEmitters(); void stopEmitters(); + void updateListener(double dt); + Source* createSource(std::string filePath); ALenum getSourceState(ALuint source); void setGain(Source* source, float gain); void setSoundProperties(ALuint source, ComponentWrapper* soundComponent); + // Specific logic + void playSound(Source* source); + void stopSound(Source* source); + void playerDamaged(); + void playerShot(); + void playerJumps(); + void playerStep(double dt); + // OpenAL system variables ALCdevice* m_ALCdevice = nullptr; ALCcontext* m_ALCcontext = nullptr; @@ -75,9 +85,14 @@ private: World* m_World = nullptr; EventBroker* m_EventBroker = nullptr; std::unordered_map m_Sources; - float m_BGMVolumeChannel = 1.0f; + float m_BGMVolumeChannel = 1.f; float m_SFXVolumeChannel = 1.f; bool m_EditorEnabled = false; + const double m_PlayerFootstepInterval = 0.5; + double m_TimeSinceLastFootstep = 0; + // TEMP + EntityID m_LocalPlayer = EntityID_Invalid; + bool m_LeftFoot = false; // Events EventRelay m_EPlaySoundOnEntity; @@ -96,6 +111,16 @@ private: bool OnSetBGMGain(const Events::SetBGMGain &e); // Not tested EventRelay m_ESetSFXGain; bool OnSetSFXGain(const Events::SetSFXGain &e); // Not tested + + EventRelay m_EShoot; + bool OnShoot(const Events::Shoot &e); + EventRelay m_EPlayerSpawned; + bool OnPlayerSpawned(const Events::PlayerSpawned &e); + EventRelay m_EInputCommand; + bool OnInputCommand(const Events::InputCommand &e); + EventRelay m_ECaptured; + bool OnCaptured(const Events::Captured &e); + }; #endif \ No newline at end of file diff --git a/resources/Schema/Entities/aim_rays.xml b/resources/Schema/Entities/aim_rays.xml new file mode 100644 index 00000000..c488ca51 --- /dev/null +++ b/resources/Schema/Entities/aim_rays.xml @@ -0,0 +1,210 @@ + + + + + + + + + + + + + + models/core/unitcube.mesh + + + + + + + + + + + + + + + models/core/unitcube.mesh + + + + + + + + + + + + + + + + + + + + + + + + models/core/unitcube.mesh + + + + + + + + + + + + + + + models/core/unitcube.mesh + + + + + + + + + + + + + + + models/core/unitcube.mesh + + + + + + + + + + + + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + models/core/unitcube.mesh + + + + + + + + + + + diff --git a/src/Engine/Sound/SoundSystem.cpp b/src/Engine/Sound/SoundSystem.cpp index d0887c05..dbabb32d 100644 --- a/src/Engine/Sound/SoundSystem.cpp +++ b/src/Engine/Sound/SoundSystem.cpp @@ -20,6 +20,10 @@ SoundSystem::SoundSystem(World* world, EventBroker* eventBroker, bool editorMode EVENT_SUBSCRIBE_MEMBER(m_EContinueSound, &SoundSystem::OnContinueSound); EVENT_SUBSCRIBE_MEMBER(m_ESetBGMGain, &SoundSystem::OnSetBGMGain); EVENT_SUBSCRIBE_MEMBER(m_ESetSFXGain, &SoundSystem::OnSetSFXGain); + EVENT_SUBSCRIBE_MEMBER(m_EShoot, &SoundSystem::OnShoot); + EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &SoundSystem::OnPlayerSpawned); + EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &SoundSystem::OnInputCommand); + EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &SoundSystem::OnCaptured); } SoundSystem::~SoundSystem() @@ -48,19 +52,20 @@ void SoundSystem::stopEmitters() } void SoundSystem::Update(double dt) -{ +{ m_EventBroker->Process(); + playerStep(dt); addNewEmitters(dt); // can be optimized with "EEntityCreated" deleteInactiveEmitters(); // can be optimized with "EEntityDeleted" - updateEmitters( dt); - updateListener( dt); + updateEmitters(dt); + updateListener(dt); } void SoundSystem::deleteInactiveEmitters() { std::unordered_map::iterator it; for (it = m_Sources.begin(); it != m_Sources.end();) { - if (m_World->ValidEntity(it->first) + if (m_World->ValidEntity(it->first) && m_World->HasComponent(it->first, "SoundEmitter")) { if (getSourceState(it->second->ALsource) != AL_STOPPED) { // Nothing to see here, move along @@ -70,6 +75,7 @@ void SoundSystem::deleteInactiveEmitters() // Sound has been stopped / finished playing. alDeleteBuffers(1, &it->second->ALsource); alDeleteSources(1, &it->second->ALsource); + m_World->DeleteEntity(it->first); delete it->second; it = m_Sources.erase(it); } @@ -174,6 +180,58 @@ void SoundSystem::stopSound(Source* source) alSourceStop(source->ALsource); } +void SoundSystem::playerDamaged() +{ + +} + +void SoundSystem::playerShot() +{ } + +void SoundSystem::playerJumps() +{ + glm::vec3 vel = (glm::vec3)m_World->GetComponent(m_LocalPlayer, "Physics")["Velocity"]; + if (vel.y > 1) { + Source* source = createSource("Audio/jump/jump1.wav"); + auto emitterID = m_World->CreateEntity(m_LocalPlayer); + m_World->AttachComponent(emitterID, "Transform"); + m_World->AttachComponent(emitterID, "SoundEmitter"); + source->Type = SoundType::SFX; + m_Sources[emitterID] = source; + playSound(source); + } +} + +void SoundSystem::playerStep(double dt) +{ + if (m_LocalPlayer == EntityID_Invalid) { + return; + } + m_TimeSinceLastFootstep += dt; + glm::vec3 vel = (glm::vec3)m_World->GetComponent(m_LocalPlayer, "Physics")["Velocity"]; + float playerSpeed = glm::length(vel); + bool isAirborne = vel.y != 0; + if (playerSpeed > 1 && !isAirborne) { + // Player is walking + if (m_TimeSinceLastFootstep > m_PlayerFootstepInterval) { + // Create footstep sound + EntityID child = m_World->CreateEntity(m_LocalPlayer); + m_World->AttachComponent(child, "Transform"); + m_World->AttachComponent(child, "SoundEmitter"); + Events::PlaySoundOnEntity e; + e.EmitterID = child; + if (m_LeftFoot) { + e.FilePath = "Audio/footstep/footstep2.wav"; + } else { + e.FilePath = "Audio/footstep/footstep3.wav"; + } + m_LeftFoot = !m_LeftFoot; + m_EventBroker->Publish(e); + m_TimeSinceLastFootstep = 0; + } + } +} + bool SoundSystem::OnPlaySoundOnEntity(const Events::PlaySoundOnEntity & e) { Source* source = createSource(e.FilePath); @@ -251,6 +309,69 @@ bool SoundSystem::OnSetSFXGain(const Events::SetSFXGain & e) return true; } +bool SoundSystem::OnShoot(const Events::Shoot & e) +{ + Source* source = createSource("Audio/laser/laser1.wav"); + auto emitterID = m_World->CreateEntity(e.Player.ID); + m_World->AttachComponent(emitterID, "Transform"); + auto emitter = m_World->AttachComponent(emitterID, "SoundEmitter"); + source->Type = SoundType::SFX; + m_Sources[emitterID] = source; + playSound(source); + return true; +} + +bool SoundSystem::OnPlayerSpawned(const Events::PlayerSpawned & e) +{ + if (e.PlayerID == -1) { // Local player + m_World->AttachComponent(e.Player.ID, "Listener"); + m_LocalPlayer = e.Player.ID; + EntityID child = m_World->CreateEntity(e.Player.ID); + m_World->AttachComponent(child, "SoundEmitter"); // Temp + m_World->AttachComponent(child, "Transform"); // Temp + Events::PlaySoundOnEntity event; + event.EmitterID = child; + event.FilePath = "Audio/announcer/go.wav"; + m_EventBroker->Publish(event); + } + return true; +} + +bool SoundSystem::OnInputCommand(const Events::InputCommand & e) +{ + if (e.Player.ID == EntityID_Invalid) { + //return false; + } + if (e.Command == "Jump" && e.Value > 0) { + if (e.PlayerID == -1) { // local player + //bool airBorne = ((glm::vec3)m_World->GetComponent(e.Player.ID, "Physics")["Velocity"]).y != 0; + //if (!airBorne) { + playerJumps(); + //} + return true; + } + } + return false; +} + +bool SoundSystem::OnCaptured(const Events::Captured & e) +{ + int homeTeam = (int)m_World->GetComponent(e.CapturePointID, "CapturePoint")["HomePointForTeam"]; + int team = (int)m_World->GetComponent(m_LocalPlayer, "Team")["Team"]; + Events::PlaySoundOnEntity ev; + if (team == homeTeam) { + ev.FilePath = "Audio/announcer/objective_achieved.wav"; + } else { + ev.FilePath = "Audio/announcer/objective_failed.wav"; + } + EntityID child = m_World->CreateEntity(m_LocalPlayer); + m_World->AttachComponent(child, "Transform"); + m_World->AttachComponent(child, "SoundEmitter"); + ev.EmitterID = child; + m_EventBroker->Publish(ev); + return false; +} + void SoundSystem::setListenerOri(glm::vec3 ori) { // Calculate forward and up vector. From 3cfbbbbf54c0365bb0244d1f7289970cea4efddb Mon Sep 17 00:00:00 2001 From: William Moberg Date: Mon, 1 Feb 2016 16:13:48 +0100 Subject: [PATCH 029/355] CollisionSystem now utilizes Octree for collision detection. --- resources/Schema/Components/AABB.xsd | 4 +-- resources/Schema/Entities/GameMap.xml | 3 ++ src/Engine/Collision/CollisionSystem.cpp | 44 +++++++++++------------- 3 files changed, 25 insertions(+), 26 deletions(-) diff --git a/resources/Schema/Components/AABB.xsd b/resources/Schema/Components/AABB.xsd index daa633a6..7dec510f 100644 --- a/resources/Schema/Components/AABB.xsd +++ b/resources/Schema/Components/AABB.xsd @@ -7,10 +7,10 @@ - Middle point of the bounding box + Middle point of the bounding box, in model space - Size of the bounding box + Size of the bounding box, in model space diff --git a/resources/Schema/Entities/GameMap.xml b/resources/Schema/Entities/GameMap.xml index e206d31f..4d0a2716 100644 --- a/resources/Schema/Entities/GameMap.xml +++ b/resources/Schema/Entities/GameMap.xml @@ -8,6 +8,9 @@ + + + Models\MapVersion1.mesh diff --git a/src/Engine/Collision/CollisionSystem.cpp b/src/Engine/Collision/CollisionSystem.cpp index 382238e7..846d38a7 100644 --- a/src/Engine/Collision/CollisionSystem.cpp +++ b/src/Engine/Collision/CollisionSystem.cpp @@ -1,6 +1,7 @@ #include "Collision/Collision.h" #include "Collision/CollisionSystem.h" #include "Core/AABB.h" +#include "Rendering/Model.h" void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) { @@ -25,33 +26,28 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c continue; } - if (Collision::AABBVsAABB(boxA, boxB, resolutionVector)) { + if (boxB.Entity.HasComponent("Model") && Collision::AABBVsAABB(boxA, boxB)) { + //Here we know boxB is a entity with Collideable, AABB, and Model. + RawModel* model; + try { + model = ResourceManager::Load(boxB.Entity["Model"]["Resource"]); + } catch (const std::exception&) { + continue; + } + + glm::mat4 modelMatrix = Transform::ModelMatrix(boxB.Entity); + + glm::vec3 newVelocity = (glm::vec3)cPhysics["Velocity"]; + if (Collision::AABBvsTriangles(boxA, model->m_Vertices, model->m_Indices, modelMatrix, newVelocity, resolutionVector)) { + (glm::vec3&)cTransform["Position"] += resolutionVector; + cPhysics["Velocity"] = newVelocity; + } + } else if (Collision::AABBVsAABB(boxA, boxB, resolutionVector)) { + //Enter here if boxB has no Model. (glm::vec3&)cTransform["Position"] += resolutionVector; if (resolutionVector.y > 0) { ((glm::vec3&)cPhysics["Velocity"]).y = 0.f; } } } - - // HACK: Temporarily collide against all collidable models since they're not in the octree yet - //auto otherCollidables = world->GetComponents("Model"); - //for (auto& cModel : *otherCollidables) { - // if (cModel.EntityID == entity) { - // continue; - // } - // if (!world->HasComponent(cModel.EntityID, "Collidable")) { - // continue; - // } - - // auto absPosition = RenderQueueFactory::AbsolutePosition(world, cModel.EntityID); - // auto absOrientation = RenderQueueFactory::AbsoluteOrientation(world, cModel.EntityID); - // auto absScale = RenderQueueFactory::AbsoluteScale(world, cModel.EntityID); - // glm::mat4 modelMatrix = glm::translate(absPosition); // *glm::toMat4(absOrientation) * glm::scale(absScale); - - // auto model = ResourceManager::Load(cModel["Resource"]); - // glm::vec3 resolutionVector; - // if (Collision::AABBvsTriangles(boxA, model->m_Vertices, model->m_Indices, modelMatrix, resolutionVector)) { - // (glm::vec3&)cTransform["Position"] += resolutionVector; - // } - //} -} \ No newline at end of file +} From 5a45f778e68498933486e77a5b2108170318938d Mon Sep 17 00:00:00 2001 From: William Moberg Date: Mon, 1 Feb 2016 17:01:58 +0100 Subject: [PATCH 030/355] Fixed so players don't teleport to (NaN, NaN, NaN) on spawning. --- include/Engine/Core/MemoryPool.h | 2 +- src/Engine/Collision/Collision.cpp | 9 ++++----- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/include/Engine/Core/MemoryPool.h b/include/Engine/Core/MemoryPool.h index 3a1cc069..f4073294 100644 --- a/include/Engine/Core/MemoryPool.h +++ b/include/Engine/Core/MemoryPool.h @@ -102,7 +102,7 @@ public: m_ExtraMemory.push_back((char*)malloc(m_Stride)); //We should preferably not enter here to avoid performance issues. Set more numMaxElements in constructor instead. if (!DisableMemoryPool::Value) { - LOG_WARNING("Allocated slots exceed Pool size, extra memory allocated dynamically. Pool size: %u, dynamic size: %u.", m_NumSlots, m_ExtraMemory.size()); + LOG_DEBUG("Allocated slots exceed Pool size, extra memory allocated dynamically. Pool size: %u, dynamic size: %u.", m_NumSlots, m_ExtraMemory.size()); } return m_ExtraMemory.back(); } diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index 67ed6c99..a17e347c 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -412,7 +412,6 @@ bool AABBvsTriangle(const AABB& box, } bool groundCollision = triNormal.y > 0.5f; - //ImGui::Text(groundCollision ? "Ground" : "Slope"); glm::vec3 projNorm; switch (resolveCase) { @@ -446,14 +445,12 @@ bool AABBvsTriangle(const AABB& box, if (groundCollision) { float len = glm::length2(boxVelocity); if (len > 0.0001f) { - len = glm::sqrt(len); - boxVelocity = len * glm::normalize(wantDirection); + boxVelocity = glm::sqrt(len) * wantDirection; } len = glm::length(outVector); float ang = glm::half_pi() - glm::acos(outVector.y / len); if (len > 0.0000001f && ang > 0.0000001f) { - //ImGui::Text("ang=%f, len=%f, acos=%f, outY=%f", ang, len, glm::acos(outVector.y / len), outVector.y); outVector.x = 0; outVector.y = len / glm::sin(ang); outVector.z = 0; @@ -475,7 +472,9 @@ bool AABBvsTriangles(const AABB& box, outResolutionVector = glm::vec3(0.f); glm::vec3 wantDirection(boxVelocity); wantDirection.y = 0; - wantDirection = glm::normalize(wantDirection); + if (vectorHasLength(wantDirection)) { + wantDirection = glm::normalize(wantDirection); + } for (int i = 0; i < modelIndices.size(); ) { std::array triVertices = { Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix), From 4ccda5ee43950a251449769dbdece96e50c02a88 Mon Sep 17 00:00:00 2001 From: stiffly Date: Mon, 1 Feb 2016 17:03:41 +0100 Subject: [PATCH 031/355] WIP --- include/Engine/Sound/SoundSystem.h | 11 ++++++++ src/Engine/Sound/SoundSystem.cpp | 43 ++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/include/Engine/Sound/SoundSystem.h b/include/Engine/Sound/SoundSystem.h index 5d57d5b6..4ceed60f 100644 --- a/include/Engine/Sound/SoundSystem.h +++ b/include/Engine/Sound/SoundSystem.h @@ -24,6 +24,9 @@ #include "Core/EPlayerSpawned.h" #include "Input/EInputCommand.h" #include "Core/ECaptured.h" +#include "Core/EPlayerDamage.h" +#include "Core/EPlayerDeath.h" +#include "Core/EPlayerHealthPickup.h" enum class SoundType { SFX, @@ -120,6 +123,14 @@ private: bool OnInputCommand(const Events::InputCommand &e); EventRelay m_ECaptured; bool OnCaptured(const Events::Captured &e); + EventRelay m_EPlayerDamage; + bool OnPlayerDamage(const Events::PlayerDamage &e); + EventRelay m_EPlayerDeath; + bool OnPlayerDeath(const Events::PlayerDeath &e); + EventRelay m_EPlayerHealthPickup; + bool OnPlayerHealthPickup(const Events::PlayerHealthPickup &e); + + }; diff --git a/src/Engine/Sound/SoundSystem.cpp b/src/Engine/Sound/SoundSystem.cpp index dbabb32d..b4de9d31 100644 --- a/src/Engine/Sound/SoundSystem.cpp +++ b/src/Engine/Sound/SoundSystem.cpp @@ -122,6 +122,7 @@ void SoundSystem::updateEmitters(double dt) setSourceVel(it->second->ALsource, velocity); float gain; (bool)(it->second->Type) ? gain = m_SFXVolumeChannel : gain = m_BGMVolumeChannel; + auto emitter = m_World->GetComponent(it->first, "SoundEmitter"); setSoundProperties(it->second->ALsource, &emitter); @@ -372,6 +373,48 @@ bool SoundSystem::OnCaptured(const Events::Captured & e) return false; } +bool SoundSystem::OnPlayerDamage(const Events::PlayerDamage & e) +{ + if (e.Player.ID == m_LocalPlayer) { + Events::PlaySoundOnEntity ev; + EntityID child = m_World->CreateEntity(m_LocalPlayer); + m_World->AttachComponent(child, "Transform"); + m_World->AttachComponent(child, "SoundEmitter"); + ev.EmitterID = child; + ev.FilePath = "Audio/hurt/hurt3.wav"; // random between a bunch + m_EventBroker->Publish(ev); + } + return false; +} + +bool SoundSystem::OnPlayerDeath(const Events::PlayerDeath & e) +{ + if (e.PlayerID == m_LocalPlayer) { + Events::PlaySoundOnEntity ev; + EntityID child = m_World->CreateEntity(m_LocalPlayer); + m_World->AttachComponent(child, "Transform"); + m_World->AttachComponent(child, "SoundEmitter"); + ev.EmitterID = child; + ev.FilePath = "Audio/die/die2.wav"; // random between a bunch + m_EventBroker->Publish(ev); + } + return false; +} + +bool SoundSystem::OnPlayerHealthPickup(const Events::PlayerHealthPickup & e) +{ + if (e.PlayerHealedID == m_LocalPlayer) { + Events::PlaySoundOnEntity ev; + EntityID child = m_World->CreateEntity(m_LocalPlayer); + m_World->AttachComponent(child, "Transform"); + m_World->AttachComponent(child, "SoundEmitter"); + ev.EmitterID = child; + ev.FilePath = "Audio/pickup/pickup2.wav"; + m_EventBroker->Publish(ev); + } + return false; +} + void SoundSystem::setListenerOri(glm::vec3 ori) { // Calculate forward and up vector. From 4dcf5a8fa089a19e220667c193f0903704139a18 Mon Sep 17 00:00:00 2001 From: stiffly Date: Mon, 1 Feb 2016 17:05:15 +0100 Subject: [PATCH 032/355] #68 fixed warning. --- src/Engine/Sound/SoundSystem.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/Engine/Sound/SoundSystem.cpp b/src/Engine/Sound/SoundSystem.cpp index b4de9d31..89798516 100644 --- a/src/Engine/Sound/SoundSystem.cpp +++ b/src/Engine/Sound/SoundSystem.cpp @@ -121,7 +121,11 @@ void SoundSystem::updateEmitters(double dt) setSourcePos(it->second->ALsource, nextPos); setSourceVel(it->second->ALsource, velocity); float gain; - (bool)(it->second->Type) ? gain = m_SFXVolumeChannel : gain = m_BGMVolumeChannel; + if (it->second->Type == SoundType::SFX) { + gain = m_SFXVolumeChannel; + } else if (it->second->Type == SoundType::BGM) { + gain = m_BGMVolumeChannel; + } auto emitter = m_World->GetComponent(it->first, "SoundEmitter"); setSoundProperties(it->second->ALsource, &emitter); From 4d19158600b1a01e19a0decf551e4162c842ba88 Mon Sep 17 00:00:00 2001 From: Teejoon Date: Mon, 1 Feb 2016 18:04:16 +0100 Subject: [PATCH 033/355] No longer need to key frame joins for exporting. Also don't save animations between exports --- tools/MayaExporter/MayaExporter/Export.cpp | 2 + tools/MayaExporter/MayaExporter/Menu.cpp | 2 - tools/MayaExporter/MayaExporter/Skeleton.cpp | 157 +++++++++++++------ tools/MayaExporter/MayaExporter/Skeleton.h | 1 + 4 files changed, 113 insertions(+), 49 deletions(-) diff --git a/tools/MayaExporter/MayaExporter/Export.cpp b/tools/MayaExporter/MayaExporter/Export.cpp index d8f1abd4..d516d058 100644 --- a/tools/MayaExporter/MayaExporter/Export.cpp +++ b/tools/MayaExporter/MayaExporter/Export.cpp @@ -109,6 +109,8 @@ bool Export::Materials(std::string pathName) bool Export::Animations(std::string pathName, std::vector animInfo) { + allAnimations.clear(); + allBindPoses.clear(); if (MAnimControl::currentTime().unit() != MTime::kNTSCField) { MGlobal::displayError(MString() + "Please change to 60 FPS under Preferences/Settings!"); diff --git a/tools/MayaExporter/MayaExporter/Menu.cpp b/tools/MayaExporter/MayaExporter/Menu.cpp index 9cc6de91..02810018 100644 --- a/tools/MayaExporter/MayaExporter/Menu.cpp +++ b/tools/MayaExporter/MayaExporter/Menu.cpp @@ -60,8 +60,6 @@ Menu::Menu(QDialog* dialog) m_ExportPath = new QLineEdit; m_FileDialog = new QFileDialog; - QString tmpPath("C:/Users/Nickelodion/Desktop/workspace/tacticalZ/assets/models/"); - m_ExportPath->setText(tmpPath); QLabel* exportLabel = new QLabel; exportLabel->setText("Export Path:"); QLabel* nameLabel = new QLabel; diff --git a/tools/MayaExporter/MayaExporter/Skeleton.cpp b/tools/MayaExporter/MayaExporter/Skeleton.cpp index c30311b8..780466fa 100644 --- a/tools/MayaExporter/MayaExporter/Skeleton.cpp +++ b/tools/MayaExporter/MayaExporter/Skeleton.cpp @@ -74,67 +74,130 @@ Animation Skeleton::GetAnimData(std::string animationName, int startFrame, int e returnData.nameLength = animationName.size() + 1; returnData.Duration = (endFrame - startFrame) * oneDivSixty; + std::map, 4>> joinCheckMap; + std::map exportJoint; + MItDag jointIt(MItDag::TraversalType::kDepthFirst, MFn::kJoint); - while (!jointIt.isDone()) + for (unsigned int i = startFrame; i <= endFrame; i++) { - m_Hierarchy.push_back(jointIt.item()); - - MFnDependencyNode depNode(jointIt.item()); - for (int i = 0; i < 9; i++) + MAnimControl::setCurrentTime(MTime(i, MTime::kNTSCField)); + while (!jointIt.isDone()) { - MStatus tmp; - MPlug plug = depNode.findPlug(attr[i].c_str(), &tmp); + m_Hierarchy.push_back(jointIt.item()); - MPlugArray connections; - plug.connectedTo(connections, true, false, 0); - for (int j = 0; j != connections.length(); j++) { - MObject connected = connections[j].node(); + MFnTransform MayaJoint(jointIt.item()); + MMatrix transformationMatrix = MayaJoint.transformationMatrix(); - if (connected.hasFn(MFn::kAnimCurve)) { + if (i == startFrame) + { + double doubleMat[4][4]; + transformationMatrix.get(doubleMat); - MFnAnimCurve jointAnim(connected); + joinCheckMap[MayaJoint.name().asChar()][0][0] = doubleMat[0][0]; + joinCheckMap[MayaJoint.name().asChar()][0][1] = doubleMat[0][1]; + joinCheckMap[MayaJoint.name().asChar()][0][2] = doubleMat[0][2]; + joinCheckMap[MayaJoint.name().asChar()][0][3] = doubleMat[0][3]; + joinCheckMap[MayaJoint.name().asChar()][1][0] = doubleMat[1][0]; + joinCheckMap[MayaJoint.name().asChar()][1][1] = doubleMat[1][1]; + joinCheckMap[MayaJoint.name().asChar()][1][2] = doubleMat[1][2]; + joinCheckMap[MayaJoint.name().asChar()][1][3] = doubleMat[1][3]; + joinCheckMap[MayaJoint.name().asChar()][2][0] = doubleMat[2][0]; + joinCheckMap[MayaJoint.name().asChar()][2][1] = doubleMat[2][1]; + joinCheckMap[MayaJoint.name().asChar()][2][2] = doubleMat[2][2]; + joinCheckMap[MayaJoint.name().asChar()][2][3] = doubleMat[2][3]; + joinCheckMap[MayaJoint.name().asChar()][3][0] = doubleMat[3][0]; + joinCheckMap[MayaJoint.name().asChar()][3][1] = doubleMat[3][1]; + joinCheckMap[MayaJoint.name().asChar()][3][2] = doubleMat[3][2]; + joinCheckMap[MayaJoint.name().asChar()][3][3] = doubleMat[3][3]; - unsigned int startKeyFrameIndex = jointAnim.findClosest(MTime(startFrame, MTime::kNTSCField), &tmp); + exportJoint[MayaJoint.name().asChar()] = false; + } + else if(!exportJoint[MayaJoint.name().asChar()])//!exportJoint[MayaJoint.name().asChar()]) + { + double doubleMat[4][4]; - if (tmp == MStatus::kFailure) - MGlobal::displayInfo(MString() + "Fail :c"); + doubleMat[0][0] = joinCheckMap[MayaJoint.name().asChar()][0][0]; + doubleMat[0][1] = joinCheckMap[MayaJoint.name().asChar()][0][1]; + doubleMat[0][2] = joinCheckMap[MayaJoint.name().asChar()][0][2]; + doubleMat[0][3] = joinCheckMap[MayaJoint.name().asChar()][0][3]; + doubleMat[1][0] = joinCheckMap[MayaJoint.name().asChar()][1][0]; + doubleMat[1][1] = joinCheckMap[MayaJoint.name().asChar()][1][1]; + doubleMat[1][2] = joinCheckMap[MayaJoint.name().asChar()][1][2]; + doubleMat[1][3] = joinCheckMap[MayaJoint.name().asChar()][1][3]; + doubleMat[2][0] = joinCheckMap[MayaJoint.name().asChar()][2][0]; + doubleMat[2][1] = joinCheckMap[MayaJoint.name().asChar()][2][1]; + doubleMat[2][2] = joinCheckMap[MayaJoint.name().asChar()][2][2]; + doubleMat[2][3] = joinCheckMap[MayaJoint.name().asChar()][2][3]; + doubleMat[3][0] = joinCheckMap[MayaJoint.name().asChar()][3][0]; + doubleMat[3][1] = joinCheckMap[MayaJoint.name().asChar()][3][1]; + doubleMat[3][2] = joinCheckMap[MayaJoint.name().asChar()][3][2]; + doubleMat[3][3] = joinCheckMap[MayaJoint.name().asChar()][3][3]; - if (startFrame * oneDivSixty <= jointAnim.time(startKeyFrameIndex).value() && jointAnim.time(startKeyFrameIndex).value() <= endFrame * oneDivSixty) { - animatedJoints.push_back(jointIt.item()); - i = 9; - break; - } - - unsigned int endKeyFrameIndex = jointAnim.findClosest(MTime(endFrame, MTime::kNTSCField)); - MGlobal::displayInfo(MString() + startKeyFrameIndex + " " + endKeyFrameIndex); - - if (startFrame * oneDivSixty <= jointAnim.time(endKeyFrameIndex).value() && jointAnim.time(endKeyFrameIndex).value() <= endFrame * oneDivSixty || endKeyFrameIndex - startKeyFrameIndex > 0) { - animatedJoints.push_back(jointIt.item()); - i = 9; - break; - } - - MFnTransform MayaJoint(jointIt.item()); - - MPlug BindPose = MayaJoint.findPlug("bindPose"); - MDataHandle DataHandle; - BindPose.getValue(DataHandle); - MFnMatrixData MartixFn(DataHandle.data()); - MMatrix BindPoseMatrix = MartixFn.matrix(); - - if (!BindPoseMatrix.isEquivalent(MayaJoint.transformationMatrix())) - { - MGlobal::displayError(MString() + animationName.c_str() + " is using " + MayaJoint.name() + " that is not in bind pose nor is it key framed in the animation, the exported animation will NOT correspond to the animation in Maya"); - } + MMatrix tmp(doubleMat); + if (!tmp.isEquivalent(transformationMatrix)) { + MGlobal::displayInfo(MString() + MayaJoint.name() + " is exported"); + exportJoint[MayaJoint.name().asChar()] = true; + animatedJoints.push_back(MayaJoint.object()); } } - } - jointIt.next(); + /*for (int i = 0; i < 9; i++) + { + MStatus tmp; + MPlug plug = depNode.findPlug(attr[i].c_str(), &tmp); + + MPlugArray connections; + plug.connectedTo(connections, true, false, 0); + for (int j = 0; j != connections.length(); j++) { + MObject connected = connections[j].node(); + + if (connected.hasFn(MFn::kAnimCurve)) { + + MFnAnimCurve jointAnim(connected); + + unsigned int startKeyFrameIndex = jointAnim.findClosest(MTime(startFrame, MTime::kNTSCField), &tmp); + + if (tmp == MStatus::kFailure) + MGlobal::displayInfo(MString() + "Fail :c"); + + if (startFrame * oneDivSixty <= jointAnim.time(startKeyFrameIndex).value() && jointAnim.time(startKeyFrameIndex).value() <= endFrame * oneDivSixty) { + animatedJoints.push_back(jointIt.item()); + i = 9; + break; + } + + unsigned int endKeyFrameIndex = jointAnim.findClosest(MTime(endFrame, MTime::kNTSCField)); + MGlobal::displayInfo(MString() + startKeyFrameIndex + " " + endKeyFrameIndex); + + if (startFrame * oneDivSixty <= jointAnim.time(endKeyFrameIndex).value() && jointAnim.time(endKeyFrameIndex).value() <= endFrame * oneDivSixty || endKeyFrameIndex - startKeyFrameIndex > 0) { + animatedJoints.push_back(jointIt.item()); + i = 9; + break; + } + + MFnTransform MayaJoint(jointIt.item()); + + MPlug BindPose = MayaJoint.findPlug("bindPose"); + MDataHandle DataHandle; + BindPose.getValue(DataHandle); + MFnMatrixData MartixFn(DataHandle.data()); + MMatrix BindPoseMatrix = MartixFn.matrix(); + + if (!BindPoseMatrix.isEquivalent(MayaJoint.transformationMatrix())) + { + MGlobal::displayError(MString() + animationName.c_str() + " is using " + MayaJoint.name() + " that is not in bind pose nor is it key framed in the animation, the exported animation will NOT correspond to the animation in Maya"); + } + } + } + }*/ + + jointIt.next(); + } + jointIt.reset(); } int currentFrame = startFrame; - while (currentFrame != endFrame + 1) { // ANDREAS + while (currentFrame <= endFrame) { // ANDREAS Animation::Keyframe thisKeyFrame; thisKeyFrame.Index = currentFrame - startFrame; thisKeyFrame.Time = thisKeyFrame.Index * oneDivSixty; @@ -219,7 +282,7 @@ std::vector Skeleton::GetBindPoses() MFnTransform MayaJoint(jointIt.currentItem()); BindPoseSkeletonNode::BindPoseJoint NewJoint; - if (MFnDependencyNode(MayaJoint.parent(0)).name() == "world") { + if (MFnDependencyNode(MayaJoint.parent(0)).object().apiType() != MFn::kJoint) { if (SkeletonStorage.Joints.size() != 0) { m_AllSkeletons.push_back(SkeletonStorage); diff --git a/tools/MayaExporter/MayaExporter/Skeleton.h b/tools/MayaExporter/MayaExporter/Skeleton.h index 6a288c8a..9033441d 100644 --- a/tools/MayaExporter/MayaExporter/Skeleton.h +++ b/tools/MayaExporter/MayaExporter/Skeleton.h @@ -3,6 +3,7 @@ #include #include +#include #include #include "MayaIncludes.h" #include "OutputData.h" From 30b1dab7640406c180de7f2ce5ef6c53de0319b4 Mon Sep 17 00:00:00 2001 From: William Moberg Date: Mon, 1 Feb 2016 18:06:28 +0100 Subject: [PATCH 034/355] More efficient collision resolution case + comments. --- src/Engine/Collision/Collision.cpp | 43 +++++++++++++++++------------- 1 file changed, 25 insertions(+), 18 deletions(-) diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index a17e347c..edb6c9a9 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -336,6 +336,11 @@ bool rectangleVsTriangle(const glm::vec2& boxMin, return true; } +constexpr float SlopeConstant(float degrees) +{ + return (1.0 - degrees / 90.f); +} + //An array containing 3 int pairs { 0, 2 }, { 0, 1 }, { 1, 2 } constexpr std::array, 3> dimensionPairs({ std::pair(0, 2), std::pair(0, 1), std::pair(1, 2) }); @@ -355,9 +360,11 @@ bool AABBvsTriangle(const AABB& box, enum BoxTriResolveCase { - Vertex, - Line, - Corner + ResolveDimX, + ResolveDimY, + ResolveDimZ, + Line, //Box edge colliding with triangle line. + Corner //Box corner colliding with the triangle face. } resolveCase; const glm::vec3& origin = box.Origin(); @@ -389,7 +396,9 @@ bool AABBvsTriangle(const AABB& box, outVector[dim.first] = resolutionVector.x; outVector[dim.second] = resolutionVector.y; minimumTranslation = resolutionDist; - resolveCase = pushedFromTriangleLine ? Line : Vertex; + //If we pushed away from triangle line (edge), or if we + //move the player along one coordinate axis (pick the dimension that isn't zero). + resolveCase = pushedFromTriangleLine ? Line : static_cast((abs(outVector[dim.first]) < 0.0001f) ? dim.second : dim.first); } } @@ -411,22 +420,15 @@ bool AABBvsTriangle(const AABB& box, resolveCase = Corner; } - bool groundCollision = triNormal.y > 0.5f; - glm::vec3 projNorm; switch (resolveCase) { - case Vertex: + case ResolveDimX: + case ResolveDimY: + case ResolveDimZ: { - int maxD = 0; - float maxResolution = 0.f; - for (int d = 0; d < 3; ++d) { - float resolve = glm::abs(outVector[d]); - if (resolve > maxResolution) { - maxResolution = resolve; - maxD = d; - } - } - boxVelocity[maxD] = 0.f; + //If we get here, the resolution is along one coordinate axis. + //set velocity to 0 in that dimension. + boxVelocity[resolveCase] = 0.f; return true; } case Line: @@ -442,12 +444,17 @@ bool AABBvsTriangle(const AABB& box, //Project the velocity onto the normal of the hit line/face. //w = v - *n, |n|==1. boxVelocity = boxVelocity - glm::dot(boxVelocity, projNorm) * projNorm; - if (groundCollision) { + //If the collision was not on steep wall or similarly (e.g. walking on the ground), do special treatment. + //Magic value that makes condition correspond to: + //if the angle between horizon and the collision surface is less than 45 degrees. + if (projNorm.y > SlopeConstant(45.0f)) { + //Make sure the player keeps moving in their desired direction, just slower. float len = glm::length2(boxVelocity); if (len > 0.0001f) { boxVelocity = glm::sqrt(len) * wantDirection; } + //Ensure that the player always is moved upwards, instead of sliding down. len = glm::length(outVector); float ang = glm::half_pi() - glm::acos(outVector.y / len); if (len > 0.0000001f && ang > 0.0000001f) { From 9573958a86f35ab3f950ea45eb8d5a167fa92539 Mon Sep 17 00:00:00 2001 From: Teejoon Date: Tue, 2 Feb 2016 10:19:00 +0100 Subject: [PATCH 035/355] Fixed Git's shitty merge in Skeleton.cpp and The Exporter now Exports meshes with and without skins --- tools/MayaExporter/MayaExporter/Mesh.cpp | 10 +++--- tools/MayaExporter/MayaExporter/Mesh.h | 20 ++++++++--- tools/MayaExporter/MayaExporter/Skeleton.cpp | 38 ++++++++++---------- 3 files changed, 41 insertions(+), 27 deletions(-) diff --git a/tools/MayaExporter/MayaExporter/Mesh.cpp b/tools/MayaExporter/MayaExporter/Mesh.cpp index 43b76d55..01737683 100644 --- a/tools/MayaExporter/MayaExporter/Mesh.cpp +++ b/tools/MayaExporter/MayaExporter/Mesh.cpp @@ -108,7 +108,6 @@ Mesh MeshClass::GetMeshData(MObjectArray object) MFnDependencyNode thisNode(node); MPlugArray connections; thisNode.findPlug("inMesh").connectedTo(connections, true, true); - bool hasSkin = false; MPlug weightList, weights; MObject weightListObject; for (unsigned int i = 0; i < connections.length(); i++) { @@ -117,7 +116,7 @@ Mesh MeshClass::GetMeshData(MObjectArray object) weightList = skinCluster.findPlug("weightList", &status); weightListObject = weightList.attribute(); weights = skinCluster.findPlug("weights"); - hasSkin = true; + newMesh.hasSkin = true; break; } } @@ -301,7 +300,8 @@ Mesh MeshClass::GetMeshData(MObjectArray object) thisVertex.Uv[1] = UV[1]; - if (hasSkin) { + if (newMesh.hasSkin) { + thisVertex.useWeights = true; float totalWeight = 0.0f; unsigned int totalBones = 0; MIntArray jointIDs /* ??? */; @@ -319,7 +319,9 @@ Mesh MeshClass::GetMeshData(MObjectArray object) for (unsigned int i = 0; i < 4; i++) { thisVertex.BoneWeights[i] = thisVertex.BoneWeights[i] / totalWeight; } - } + } else { + thisVertex.useWeights = false; + } //float totalWeight = thisVertex.BoneWeights[0] + thisVertex.BoneWeights[1] + thisVertex.BoneWeights[2] + thisVertex.BoneWeights[3]; //if (totalWeight > 0.0001f) { diff --git a/tools/MayaExporter/MayaExporter/Mesh.h b/tools/MayaExporter/MayaExporter/Mesh.h index 11f6bcf8..affc4320 100644 --- a/tools/MayaExporter/MayaExporter/Mesh.h +++ b/tools/MayaExporter/MayaExporter/Mesh.h @@ -11,6 +11,7 @@ class VertexLayout : public OutputData { public: + bool useWeights = true; float Pos[3]{ 0 }; float Normal[3]{ 0 }; float Tangent[3]{ 0 }; @@ -26,8 +27,10 @@ public: out.write((char*)&Tangent, sizeof(float) * 3); out.write((char*)&BiNormal, sizeof(float) * 3); out.write((char*)&Uv, sizeof(float) * 2); - out.write((char*)&BoneIndices, sizeof(float) * 4); - out.write((char*)&BoneWeights, sizeof(float) * 4); + if (useWeights) { + out.write((char*)&BoneIndices, sizeof(float) * 4); + out.write((char*)&BoneWeights, sizeof(float) * 4); + } } virtual void WriteASCII(std::ostream& out) const @@ -37,8 +40,10 @@ public: out << Tangent[0] << " " << Tangent[1] << " " << Tangent[2] << endl; out << BiNormal[0] << " " << BiNormal[1] << " " << BiNormal[2] << endl; out << Uv[0] << " " << Uv[1] << endl; - out << BoneIndices[0] << " " << BoneIndices[1] << " " << BoneIndices[2] << " " << BoneIndices[3] << endl; - out << BoneWeights[0] << " " << BoneWeights[1] << " " << BoneWeights[2] << " " << BoneWeights[3] << endl; + if (useWeights) { + out << BoneIndices[0] << " " << BoneIndices[1] << " " << BoneIndices[2] << " " << BoneIndices[3] << endl; + out << BoneWeights[0] << " " << BoneWeights[1] << " " << BoneWeights[2] << " " << BoneWeights[3] << endl; + } } bool operator==(const VertexLayout& right) @@ -57,6 +62,7 @@ public: class Mesh : public OutputData { public: + bool hasSkin = false; unsigned int NumVertices; unsigned int NumIndices; std::vector Vertices; @@ -64,6 +70,7 @@ public: virtual void WriteBinary(std::ostream& out) { + out.write((char*)&hasSkin, sizeof(bool)); out.write((char*)&NumVertices, sizeof(int)); out.write((char*)&NumIndices, sizeof(int)); for (auto aVertex : Vertices) { @@ -79,6 +86,11 @@ public: virtual void WriteASCII(std::ostream& out) const { out << "New Mesh _ not in binary" << endl; + out << "hasSkin: "; + if(hasSkin) + out << "true" << endl; + else + out << "false" << endl; out << "Number of vertices: " << NumVertices << endl; out << "number of indices: " << NumIndices << endl; int vertexNumber = 0; diff --git a/tools/MayaExporter/MayaExporter/Skeleton.cpp b/tools/MayaExporter/MayaExporter/Skeleton.cpp index bde87247..bb8c10d3 100644 --- a/tools/MayaExporter/MayaExporter/Skeleton.cpp +++ b/tools/MayaExporter/MayaExporter/Skeleton.cpp @@ -186,29 +186,29 @@ Animation Skeleton::GetAnimData(std::string animationName, int startFrame, int e /*MGlobal::displayInfo(MString() + "start keyfram index: " + startKeyFrameIndex + ". End keyfram index: " + endKeyFrameIndex + ".");*/ - if (startFrame <= jointAnim.time(endKeyFrameIndex).value() && jointAnim.time(endKeyFrameIndex).value() <= endFrame || endKeyFrameIndex - startKeyFrameIndex > 0) { - animatedJoints.push_back(jointIt.item()); - i = 9; - break; - } + // if (startFrame <= jointAnim.time(endKeyFrameIndex).value() && jointAnim.time(endKeyFrameIndex).value() <= endFrame || endKeyFrameIndex - startKeyFrameIndex > 0) { + // animatedJoints.push_back(jointIt.item()); + // i = 9; + // break; + // } - MFnTransform MayaJoint(jointIt.item()); + // MFnTransform MayaJoint(jointIt.item()); - MPlug BindPose = MayaJoint.findPlug("bindPose"); - MDataHandle DataHandle; - BindPose.getValue(DataHandle); - MFnMatrixData MartixFn(DataHandle.data()); - MMatrix BindPoseMatrix = MartixFn.matrix(); + // MPlug BindPose = MayaJoint.findPlug("bindPose"); + // MDataHandle DataHandle; + // BindPose.getValue(DataHandle); + // MFnMatrixData MartixFn(DataHandle.data()); + // MMatrix BindPoseMatrix = MartixFn.matrix(); - if (!BindPoseMatrix.isEquivalent(MayaJoint.transformationMatrix())) - { - MGlobal::displayError(MString() + animationName.c_str() + " is using " + MayaJoint.name() + " that is not in bind pose nor is it key framed in the animation, the exported animation will NOT correspond to the animation in Maya"); - } - } - } - }*/ + // if (!BindPoseMatrix.isEquivalent(MayaJoint.transformationMatrix())) + // { + // MGlobal::displayError(MString() + animationName.c_str() + " is using " + MayaJoint.name() + " that is not in bind pose nor is it key framed in the animation, the exported animation will NOT correspond to the animation in Maya"); + // } + // } + // } + // } - } // end of int i loop + //} // end of int i loop jointIt.next(); } jointIt.reset(); From 563fd4082e090cb46e5eebc23095a2c86154e323 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Tue, 2 Feb 2016 12:10:39 +0100 Subject: [PATCH 036/355] Updated movement test for model collisions --- resources/Schema/Entities/MovementTest.xml | 67 ++-------------------- 1 file changed, 5 insertions(+), 62 deletions(-) diff --git a/resources/Schema/Entities/MovementTest.xml b/resources/Schema/Entities/MovementTest.xml index 1378f623..f5197830 100644 --- a/resources/Schema/Entities/MovementTest.xml +++ b/resources/Schema/Entities/MovementTest.xml @@ -6,22 +6,6 @@ - - - - - - Models/Core/UnitCube.mesh - - false - - - - - - - - @@ -81,6 +65,10 @@ + + + + Models/Test/ObstacleCourse.mesh @@ -88,51 +76,6 @@ - - - - - - Models/Core/UnitCube.mesh - false - - - - - - - - - - - - - - Models/Core/UnitCube.mesh - false - - - - - - - - - - - - - - Models/Core/UnitCube.mesh - false - - - - - - - - @@ -197,7 +140,7 @@ - + From cb0feb0b84acd312f5ea8a145819e7de6ef702c7 Mon Sep 17 00:00:00 2001 From: stiffly Date: Tue, 2 Feb 2016 13:25:25 +0100 Subject: [PATCH 037/355] Tested hurt event. Randomizes between several different ones. --- assets | 2 +- include/Engine/Sound/SoundSystem.h | 9 +++-- src/Engine/Sound/SoundSystem.cpp | 55 +++++++++++++++++++----------- src/Game/Game.cpp | 3 +- 4 files changed, 45 insertions(+), 24 deletions(-) diff --git a/assets b/assets index 9b4f9ab2..5bf03ccd 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit 9b4f9ab2e67fc09863f35b33bb0a61ce75ef6aa8 +Subproject commit 5bf03ccd54bed358d525840635573f931adf584e diff --git a/include/Engine/Sound/SoundSystem.h b/include/Engine/Sound/SoundSystem.h index 4ceed60f..e161af77 100644 --- a/include/Engine/Sound/SoundSystem.h +++ b/include/Engine/Sound/SoundSystem.h @@ -2,6 +2,7 @@ #define SoundSystem_h__ #include +#include #include "glm/common.hpp" #include "glm/gtx/rotate_vector.hpp" // Calculate Up vector @@ -27,6 +28,7 @@ #include "Core/EPlayerDamage.h" #include "Core/EPlayerDeath.h" #include "Core/EPlayerHealthPickup.h" +#include "Core/EComponentAttached.h" enum class SoundType { SFX, @@ -70,7 +72,7 @@ private: Source* createSource(std::string filePath); ALenum getSourceState(ALuint source); void setGain(Source* source, float gain); - void setSoundProperties(ALuint source, ComponentWrapper* soundComponent); + void setSoundProperties(Source* source, ComponentWrapper* soundComponent); // Specific logic void playSound(Source* source); @@ -91,11 +93,12 @@ private: float m_BGMVolumeChannel = 1.f; float m_SFXVolumeChannel = 1.f; bool m_EditorEnabled = false; - const double m_PlayerFootstepInterval = 0.5; + const double m_PlayerFootstepInterval = 1.0; double m_TimeSinceLastFootstep = 0; // TEMP EntityID m_LocalPlayer = EntityID_Invalid; bool m_LeftFoot = false; + std::default_random_engine generator; // Events EventRelay m_EPlaySoundOnEntity; @@ -129,6 +132,8 @@ private: bool OnPlayerDeath(const Events::PlayerDeath &e); EventRelay m_EPlayerHealthPickup; bool OnPlayerHealthPickup(const Events::PlayerHealthPickup &e); + EventRelay m_EComponentAttached; + bool OnComponentAttached(const Events::ComponentAttached &e); diff --git a/src/Engine/Sound/SoundSystem.cpp b/src/Engine/Sound/SoundSystem.cpp index 89798516..d08232ec 100644 --- a/src/Engine/Sound/SoundSystem.cpp +++ b/src/Engine/Sound/SoundSystem.cpp @@ -22,6 +22,7 @@ SoundSystem::SoundSystem(World* world, EventBroker* eventBroker, bool editorMode EVENT_SUBSCRIBE_MEMBER(m_ESetSFXGain, &SoundSystem::OnSetSFXGain); EVENT_SUBSCRIBE_MEMBER(m_EShoot, &SoundSystem::OnShoot); EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &SoundSystem::OnPlayerSpawned); + EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &SoundSystem::OnPlayerDamage); EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &SoundSystem::OnInputCommand); EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &SoundSystem::OnCaptured); } @@ -120,15 +121,9 @@ void SoundSystem::updateEmitters(double dt) glm::vec3 velocity = glm::vec3(nextPos - previousPos) / (float)dt; setSourcePos(it->second->ALsource, nextPos); setSourceVel(it->second->ALsource, velocity); - float gain; - if (it->second->Type == SoundType::SFX) { - gain = m_SFXVolumeChannel; - } else if (it->second->Type == SoundType::BGM) { - gain = m_BGMVolumeChannel; - } auto emitter = m_World->GetComponent(it->first, "SoundEmitter"); - setSoundProperties(it->second->ALsource, &emitter); + setSoundProperties(it->second, &emitter); // To make an emitter play when spawned in editor mode if (m_EditorEnabled) { @@ -196,7 +191,7 @@ void SoundSystem::playerShot() void SoundSystem::playerJumps() { glm::vec3 vel = (glm::vec3)m_World->GetComponent(m_LocalPlayer, "Physics")["Velocity"]; - if (vel.y > 1) { + if (vel.y == 0) { Source* source = createSource("Audio/jump/jump1.wav"); auto emitterID = m_World->CreateEntity(m_LocalPlayer); m_World->AttachComponent(emitterID, "Transform"); @@ -205,6 +200,7 @@ void SoundSystem::playerJumps() m_Sources[emitterID] = source; playSound(source); } + } void SoundSystem::playerStep(double dt) @@ -218,7 +214,7 @@ void SoundSystem::playerStep(double dt) bool isAirborne = vel.y != 0; if (playerSpeed > 1 && !isAirborne) { // Player is walking - if (m_TimeSinceLastFootstep > m_PlayerFootstepInterval) { + if (m_TimeSinceLastFootstep * playerSpeed > m_PlayerFootstepInterval) { // Create footstep sound EntityID child = m_World->CreateEntity(m_LocalPlayer); m_World->AttachComponent(child, "Transform"); @@ -351,11 +347,19 @@ bool SoundSystem::OnInputCommand(const Events::InputCommand & e) if (e.PlayerID == -1) { // local player //bool airBorne = ((glm::vec3)m_World->GetComponent(e.Player.ID, "Physics")["Velocity"]).y != 0; //if (!airBorne) { - playerJumps(); + playerJumps(); //} return true; } } + if (e.Command == "TakeDamage" && e.Value > 0) { + if (e.PlayerID == -1) { //Local Player + Events::PlayerDamage ePlayerDamage; + ePlayerDamage.Damage = 1; + ePlayerDamage.Player = EntityWrapper(m_World, e.Player.ID); + m_EventBroker->Publish(ePlayerDamage); + } + } return false; } @@ -379,15 +383,17 @@ bool SoundSystem::OnCaptured(const Events::Captured & e) bool SoundSystem::OnPlayerDamage(const Events::PlayerDamage & e) { - if (e.Player.ID == m_LocalPlayer) { + //if (e.Player.ID == m_LocalPlayer) { Events::PlaySoundOnEntity ev; EntityID child = m_World->CreateEntity(m_LocalPlayer); m_World->AttachComponent(child, "Transform"); m_World->AttachComponent(child, "SoundEmitter"); ev.EmitterID = child; - ev.FilePath = "Audio/hurt/hurt3.wav"; // random between a bunch + std::uniform_int_distribution dist(1, 12); + int rand = dist(generator); + ev.FilePath = "Audio/hurt/hurt" + std::to_string(rand) + ".wav"; m_EventBroker->Publish(ev); - } + //} return false; } @@ -419,6 +425,14 @@ bool SoundSystem::OnPlayerHealthPickup(const Events::PlayerHealthPickup & e) return false; } +bool SoundSystem::OnComponentAttached(const Events::ComponentAttached & e) +{ + if (e.Component.Info.Name == "SoundEmitter") { + + } + return false; +} + void SoundSystem::setListenerOri(glm::vec3 ori) { // Calculate forward and up vector. @@ -448,14 +462,15 @@ void SoundSystem::setGain(Source * source, float gain) alSourcef(source->ALsource, AL_GAIN, gain); } -void SoundSystem::setSoundProperties(ALuint source, ComponentWrapper* soundComponent) +void SoundSystem::setSoundProperties(Source* source, ComponentWrapper* soundComponent) { - alSourcef(source, AL_GAIN, (float)(double)(*soundComponent)["Gain"]); - alSourcef(source, AL_PITCH, (float)(double)(*soundComponent)["Pitch"]); - alSourcei(source, AL_LOOPING, (int)(bool)(*soundComponent)["Loop"]); // YOLO - alSourcef(source, AL_MAX_DISTANCE, (float)(double)(*soundComponent)["MaxDistance"]); - alSourcef(source, AL_ROLLOFF_FACTOR, (float)(double)(*soundComponent)["RollOffFactor"]); - alSourcef(source, AL_REFERENCE_DISTANCE, (float)(double)(*soundComponent)["ReferenceDistance"]); + float gain = (source->Type == SoundType::SFX) ? m_SFXVolumeChannel : m_BGMVolumeChannel; + alSourcef(source->ALsource, AL_GAIN, (float)(double)(*soundComponent)["Gain"] * gain); + alSourcef(source->ALsource, AL_PITCH, (float)(double)(*soundComponent)["Pitch"]); + alSourcei(source->ALsource, AL_LOOPING, (int)(bool)(*soundComponent)["Loop"]); // YOLO + alSourcef(source->ALsource, AL_MAX_DISTANCE, (float)(double)(*soundComponent)["MaxDistance"]); + alSourcef(source->ALsource, AL_ROLLOFF_FACTOR, (float)(double)(*soundComponent)["RollOffFactor"]); + alSourcef(source->ALsource, AL_REFERENCE_DISTANCE, (float)(double)(*soundComponent)["ReferenceDistance"]); } void SoundSystem::initOpenAL() diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index 515540bf..e0e7f611 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -154,12 +154,13 @@ void Game::Tick() if (m_IsClientOrServer) { m_ClientOrServer->Update(); } + m_SoundSystem->Update(dt); + // Iterate through systems and update world! m_EventBroker->Process(); m_SystemPipeline->Update(dt); debugTick(dt); m_Renderer->Update(dt); - m_SoundSystem->Update(dt); GLERROR("Game::Tick m_RenderQueueFactory->Update"); m_Renderer->Draw(*m_RenderFrame); m_RenderFrame->Clear(); From 83281fdaf14cc5ff3151841e81b60fd4d41df728 Mon Sep 17 00:00:00 2001 From: stiffly Date: Tue, 2 Feb 2016 13:39:11 +0100 Subject: [PATCH 038/355] Changed model in player.xml --- resources/Schema/Entities/Player.xml | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/resources/Schema/Entities/Player.xml b/resources/Schema/Entities/Player.xml index e81ec5aa..15198dcb 100644 --- a/resources/Schema/Entities/Player.xml +++ b/resources/Schema/Entities/Player.xml @@ -2,14 +2,15 @@ - + + - + 5 @@ -20,7 +21,8 @@ - + + @@ -30,12 +32,14 @@ + + Fonts/DroidSans.ttf,100 @@ -102,11 +106,11 @@ - Models/AssaultWeapon.mesh + Models/AssaultWeaponBlue.mesh - + @@ -141,7 +145,7 @@ Hold Pos - + 1 @@ -180,6 +184,13 @@ + + + + + + + From e8186a706294d3af016f130427d07128e7d23b6e Mon Sep 17 00:00:00 2001 From: antc13 Date: Tue, 2 Feb 2016 14:47:22 +0100 Subject: [PATCH 039/355] Changed the way we're exporting animations. --- include/Engine/Rendering/RawModelCustom.h | 2 +- src/Engine/Rendering/RawModelCustom.cpp | 16 +- tools/MayaExporter/MayaExporter/Skeleton.cpp | 460 ++++++++++--------- tools/MayaExporter/MayaExporter/Skeleton.h | 8 +- 4 files changed, 267 insertions(+), 219 deletions(-) diff --git a/include/Engine/Rendering/RawModelCustom.h b/include/Engine/Rendering/RawModelCustom.h index f1bc0e24..167d2ec1 100644 --- a/include/Engine/Rendering/RawModelCustom.h +++ b/include/Engine/Rendering/RawModelCustom.h @@ -89,7 +89,7 @@ private: void ReadAnimationJoint(unsigned int &offset, char* fileData, unsigned int& fileByteSize); void ReadAnimationClips(unsigned int &offset, char* fileData, unsigned int& fileByteSize, unsigned int numberOfClips); void ReadAnimationClipSingle(unsigned int &offset, char* fileData, unsigned int& fileByteSize, unsigned int clipIndex); - void ReadAnimationKeyFrame(unsigned int &offset, char* fileData, unsigned int& fileByteSize, unsigned int numberOfJoints, Skeleton::Animation& animation); + void ReadAnimationKeyFrame(unsigned int &offset, char* fileData, unsigned int& fileByteSize, Skeleton::Animation& animation); //void CreateSkeleton(std::vector> &boneInfo, std::map &boneNameMapping, aiNode* node, int parentID); }; diff --git a/src/Engine/Rendering/RawModelCustom.cpp b/src/Engine/Rendering/RawModelCustom.cpp index 83f6e703..83c68e47 100644 --- a/src/Engine/Rendering/RawModelCustom.cpp +++ b/src/Engine/Rendering/RawModelCustom.cpp @@ -327,22 +327,16 @@ void RawModelCustom::ReadAnimationClipSingle(unsigned int &offset, char* fileDat unsigned int nrOfKeyframes = *(unsigned int*)(fileData + offset); offset += sizeof(unsigned int); - if (offset + sizeof(unsigned int) > fileByteSize) { - throw Resource::FailedLoadingException("Reading AnimationClip NrOfJoints failed"); - } - unsigned int nrOfJoints = *(unsigned int*)(fileData + offset); - offset += sizeof(unsigned int); - newAnimation.Keyframes.reserve(nrOfKeyframes); for (unsigned int i = 0; i < nrOfKeyframes; i++) { - ReadAnimationKeyFrame(offset, fileData, fileByteSize, nrOfJoints, newAnimation); + ReadAnimationKeyFrame(offset, fileData, fileByteSize, newAnimation); } m_Skeleton->Animations[newAnimation.Name] = newAnimation; #else #endif } -void RawModelCustom::ReadAnimationKeyFrame(unsigned int &offset, char* fileData, unsigned int& fileByteSize, unsigned int nrOfJoints, Skeleton::Animation& animation) +void RawModelCustom::ReadAnimationKeyFrame(unsigned int &offset, char* fileData, unsigned int& fileByteSize, Skeleton::Animation& animation) { Skeleton::Animation::Keyframe newKeyFrame; @@ -358,6 +352,12 @@ void RawModelCustom::ReadAnimationKeyFrame(unsigned int &offset, char* fileData, newKeyFrame.Time = *(float*)(fileData + offset); offset += sizeof(float); + if (offset + sizeof(unsigned int) > fileByteSize) { + throw Resource::FailedLoadingException("Reading AnimationKeyFrame NrOfJoints failed"); + } + unsigned int nrOfJoints = *(unsigned int*)(fileData + offset); + offset += sizeof(unsigned int); + if (offset + sizeof(Skeleton::Animation::Keyframe::BoneProperty) * nrOfJoints> fileByteSize) { throw Resource::FailedLoadingException("Reading AnimationKeyFrame joints failed"); } diff --git a/tools/MayaExporter/MayaExporter/Skeleton.cpp b/tools/MayaExporter/MayaExporter/Skeleton.cpp index bde87247..a6ee5897 100644 --- a/tools/MayaExporter/MayaExporter/Skeleton.cpp +++ b/tools/MayaExporter/MayaExporter/Skeleton.cpp @@ -68,92 +68,92 @@ Animation Skeleton::GetAnimData(std::string animationName, int startFrame, int e std::vector animatedJoints; std::vector m_Hierarchy; - Animation returnData; - double oneDivSixty = 1 / 60.0; - returnData.Name = animationName; + Animation returnData; + double oneDivSixty = 1 / 60.0; + returnData.Name = animationName; returnData.nameLength = animationName.size() + 1; - returnData.Duration = (endFrame - startFrame) * oneDivSixty; + returnData.Duration = (endFrame - startFrame) * oneDivSixty; - std::map, 4>> joinCheckMap; - std::map exportJoint; + std::map, 4>> joinCheckMap; + std::map exportJoint; - MItDag jointIt(MItDag::TraversalType::kDepthFirst, MFn::kJoint); - for (unsigned int i = startFrame; i <= endFrame; i++) - { - MAnimControl::setCurrentTime(MTime(i, MTime::kNTSCField)); - while (!jointIt.isDone()) - { - m_Hierarchy.push_back(jointIt.item()); + //MItDag jointIt(MItDag::TraversalType::kDepthFirst, MFn::kJoint); + //for (unsigned int i = startFrame; i <= endFrame; i++) + //{ + // MAnimControl::setCurrentTime(MTime(i, MTime::kNTSCField)); + // while (!jointIt.isDone()) + // { + // m_Hierarchy.push_back(jointIt.item()); - MFnTransform MayaJoint(jointIt.item()); - MMatrix transformationMatrix = MayaJoint.transformationMatrix(); + // MFnTransform MayaJoint(jointIt.item()); + // MMatrix transformationMatrix = MayaJoint.transformationMatrix(); - if (i == startFrame) - { - double doubleMat[4][4]; - transformationMatrix.get(doubleMat); + // if (i == startFrame) + // { + // double doubleMat[4][4]; + // transformationMatrix.get(doubleMat); - joinCheckMap[MayaJoint.name().asChar()][0][0] = doubleMat[0][0]; - joinCheckMap[MayaJoint.name().asChar()][0][1] = doubleMat[0][1]; - joinCheckMap[MayaJoint.name().asChar()][0][2] = doubleMat[0][2]; - joinCheckMap[MayaJoint.name().asChar()][0][3] = doubleMat[0][3]; - joinCheckMap[MayaJoint.name().asChar()][1][0] = doubleMat[1][0]; - joinCheckMap[MayaJoint.name().asChar()][1][1] = doubleMat[1][1]; - joinCheckMap[MayaJoint.name().asChar()][1][2] = doubleMat[1][2]; - joinCheckMap[MayaJoint.name().asChar()][1][3] = doubleMat[1][3]; - joinCheckMap[MayaJoint.name().asChar()][2][0] = doubleMat[2][0]; - joinCheckMap[MayaJoint.name().asChar()][2][1] = doubleMat[2][1]; - joinCheckMap[MayaJoint.name().asChar()][2][2] = doubleMat[2][2]; - joinCheckMap[MayaJoint.name().asChar()][2][3] = doubleMat[2][3]; - joinCheckMap[MayaJoint.name().asChar()][3][0] = doubleMat[3][0]; - joinCheckMap[MayaJoint.name().asChar()][3][1] = doubleMat[3][1]; - joinCheckMap[MayaJoint.name().asChar()][3][2] = doubleMat[3][2]; - joinCheckMap[MayaJoint.name().asChar()][3][3] = doubleMat[3][3]; + // joinCheckMap[MayaJoint.name().asChar()][0][0] = doubleMat[0][0]; + // joinCheckMap[MayaJoint.name().asChar()][0][1] = doubleMat[0][1]; + // joinCheckMap[MayaJoint.name().asChar()][0][2] = doubleMat[0][2]; + // joinCheckMap[MayaJoint.name().asChar()][0][3] = doubleMat[0][3]; + // joinCheckMap[MayaJoint.name().asChar()][1][0] = doubleMat[1][0]; + // joinCheckMap[MayaJoint.name().asChar()][1][1] = doubleMat[1][1]; + // joinCheckMap[MayaJoint.name().asChar()][1][2] = doubleMat[1][2]; + // joinCheckMap[MayaJoint.name().asChar()][1][3] = doubleMat[1][3]; + // joinCheckMap[MayaJoint.name().asChar()][2][0] = doubleMat[2][0]; + // joinCheckMap[MayaJoint.name().asChar()][2][1] = doubleMat[2][1]; + // joinCheckMap[MayaJoint.name().asChar()][2][2] = doubleMat[2][2]; + // joinCheckMap[MayaJoint.name().asChar()][2][3] = doubleMat[2][3]; + // joinCheckMap[MayaJoint.name().asChar()][3][0] = doubleMat[3][0]; + // joinCheckMap[MayaJoint.name().asChar()][3][1] = doubleMat[3][1]; + // joinCheckMap[MayaJoint.name().asChar()][3][2] = doubleMat[3][2]; + // joinCheckMap[MayaJoint.name().asChar()][3][3] = doubleMat[3][3]; - exportJoint[MayaJoint.name().asChar()] = false; - } - else if(!exportJoint[MayaJoint.name().asChar()])//!exportJoint[MayaJoint.name().asChar()]) - { - double doubleMat[4][4]; + // exportJoint[MayaJoint.name().asChar()] = false; + // } + // else if(!exportJoint[MayaJoint.name().asChar()])//!exportJoint[MayaJoint.name().asChar()]) + // { + // double doubleMat[4][4]; - doubleMat[0][0] = joinCheckMap[MayaJoint.name().asChar()][0][0]; - doubleMat[0][1] = joinCheckMap[MayaJoint.name().asChar()][0][1]; - doubleMat[0][2] = joinCheckMap[MayaJoint.name().asChar()][0][2]; - doubleMat[0][3] = joinCheckMap[MayaJoint.name().asChar()][0][3]; - doubleMat[1][0] = joinCheckMap[MayaJoint.name().asChar()][1][0]; - doubleMat[1][1] = joinCheckMap[MayaJoint.name().asChar()][1][1]; - doubleMat[1][2] = joinCheckMap[MayaJoint.name().asChar()][1][2]; - doubleMat[1][3] = joinCheckMap[MayaJoint.name().asChar()][1][3]; - doubleMat[2][0] = joinCheckMap[MayaJoint.name().asChar()][2][0]; - doubleMat[2][1] = joinCheckMap[MayaJoint.name().asChar()][2][1]; - doubleMat[2][2] = joinCheckMap[MayaJoint.name().asChar()][2][2]; - doubleMat[2][3] = joinCheckMap[MayaJoint.name().asChar()][2][3]; - doubleMat[3][0] = joinCheckMap[MayaJoint.name().asChar()][3][0]; - doubleMat[3][1] = joinCheckMap[MayaJoint.name().asChar()][3][1]; - doubleMat[3][2] = joinCheckMap[MayaJoint.name().asChar()][3][2]; - doubleMat[3][3] = joinCheckMap[MayaJoint.name().asChar()][3][3]; + // doubleMat[0][0] = joinCheckMap[MayaJoint.name().asChar()][0][0]; + // doubleMat[0][1] = joinCheckMap[MayaJoint.name().asChar()][0][1]; + // doubleMat[0][2] = joinCheckMap[MayaJoint.name().asChar()][0][2]; + // doubleMat[0][3] = joinCheckMap[MayaJoint.name().asChar()][0][3]; + // doubleMat[1][0] = joinCheckMap[MayaJoint.name().asChar()][1][0]; + // doubleMat[1][1] = joinCheckMap[MayaJoint.name().asChar()][1][1]; + // doubleMat[1][2] = joinCheckMap[MayaJoint.name().asChar()][1][2]; + // doubleMat[1][3] = joinCheckMap[MayaJoint.name().asChar()][1][3]; + // doubleMat[2][0] = joinCheckMap[MayaJoint.name().asChar()][2][0]; + // doubleMat[2][1] = joinCheckMap[MayaJoint.name().asChar()][2][1]; + // doubleMat[2][2] = joinCheckMap[MayaJoint.name().asChar()][2][2]; + // doubleMat[2][3] = joinCheckMap[MayaJoint.name().asChar()][2][3]; + // doubleMat[3][0] = joinCheckMap[MayaJoint.name().asChar()][3][0]; + // doubleMat[3][1] = joinCheckMap[MayaJoint.name().asChar()][3][1]; + // doubleMat[3][2] = joinCheckMap[MayaJoint.name().asChar()][3][2]; + // doubleMat[3][3] = joinCheckMap[MayaJoint.name().asChar()][3][3]; - MMatrix tmp(doubleMat); - if (!tmp.isEquivalent(transformationMatrix)) { - MGlobal::displayInfo(MString() + MayaJoint.name() + " is exported"); - exportJoint[MayaJoint.name().asChar()] = true; - animatedJoints.push_back(MayaJoint.object()); - } - } + // MMatrix tmp(doubleMat); + // if (!tmp.isEquivalent(transformationMatrix)) { + // MGlobal::displayInfo(MString() + MayaJoint.name() + " is exported"); + // exportJoint[MayaJoint.name().asChar()] = true; + // animatedJoints.push_back(MayaJoint.object()); + // } + // } - /*for (int i = 0; i < 9; i++) - { - MStatus tmp; - MPlug plug = depNode.findPlug(attr[i].c_str(), &tmp); + /*for (int i = 0; i < 9; i++) + { + MStatus tmp; + MPlug plug = depNode.findPlug(attr[i].c_str(), &tmp); - MPlugArray connections; - plug.connectedTo(connections, true, false, 0); - for (int j = 0; j != connections.length(); j++) { - MObject connected = connections[j].node(); + MPlugArray connections; + plug.connectedTo(connections, true, false, 0); + for (int j = 0; j != connections.length(); j++) { + MObject connected = connections[j].node(); - if (connected.hasFn(MFn::kAnimCurve)) { + if (connected.hasFn(MFn::kAnimCurve)) { - MFnAnimCurve jointAnim(connected); + MFnAnimCurve jointAnim(connected); //MGlobal::displayInfo(MString() + "curve : " + jointAnim.name()); //MGlobal::displayInfo(MString() + "curve keys : " + jointAnim.numKeys()); @@ -161,89 +161,133 @@ Animation Skeleton::GetAnimData(std::string animationName, int startFrame, int e //MGlobal::displayInfo(MString() + "startFrame : " + startFrame); //MGlobal::displayInfo(MString() + "endFrame : " + endFrame); - unsigned int startKeyFrameIndex = jointAnim.findClosest(MTime(startFrame, MTime::kNTSCField), &tmp); + unsigned int startKeyFrameIndex = jointAnim.findClosest(MTime(startFrame, MTime::kNTSCField), &tmp); - if (tmp == MStatus::kFailure) - MGlobal::displayInfo(MString() + "Fail :c"); + if (tmp == MStatus::kFailure) + MGlobal::displayInfo(MString() + "Fail :c"); - if (startFrame * oneDivSixty <= jointAnim.time(startKeyFrameIndex).value() && jointAnim.time(startKeyFrameIndex).value() <= endFrame * oneDivSixty) { + if (startFrame * oneDivSixty <= jointAnim.time(startKeyFrameIndex).value() && jointAnim.time(startKeyFrameIndex).value() <= endFrame * oneDivSixty) { //MGlobal::displayInfo(MString() + "Start key time : " + jointAnim.time(startKeyFrameIndex).value()); - if (startFrame <= jointAnim.time(startKeyFrameIndex).value() && jointAnim.time(startKeyFrameIndex).value() <= endFrame ) { - animatedJoints.push_back(jointIt.item()); - i = 9; - break; - } + if (startFrame <= jointAnim.time(startKeyFrameIndex).value() && jointAnim.time(startKeyFrameIndex).value() <= endFrame ) { + animatedJoints.push_back(jointIt.item()); + i = 9; + break; + } - unsigned int endKeyFrameIndex = jointAnim.findClosest(MTime(endFrame, MTime::kNTSCField)); - MGlobal::displayInfo(MString() + startKeyFrameIndex + " " + endKeyFrameIndex); + unsigned int endKeyFrameIndex = jointAnim.findClosest(MTime(endFrame, MTime::kNTSCField)); + MGlobal::displayInfo(MString() + startKeyFrameIndex + " " + endKeyFrameIndex); MGlobal::displayInfo(MString() + "Fail!!!!!!!!!!!!!!!!!!!!!!!!!"); - if (startFrame * oneDivSixty <= jointAnim.time(endKeyFrameIndex).value() && jointAnim.time(endKeyFrameIndex).value() <= endFrame * oneDivSixty || endKeyFrameIndex - startKeyFrameIndex > 0) { + if (startFrame * oneDivSixty <= jointAnim.time(endKeyFrameIndex).value() && jointAnim.time(endKeyFrameIndex).value() <= endFrame * oneDivSixty || endKeyFrameIndex - startKeyFrameIndex > 0) { //MGlobal::displayInfo(MString() + "End key index : " + endKeyFrameIndex); //MGlobal::displayInfo(MString() + "end key time : " + jointAnim.time(endKeyFrameIndex).value()); - /*MGlobal::displayInfo(MString() + "start keyfram index: " + startKeyFrameIndex + ". End keyfram index: " + endKeyFrameIndex + ".");*/ + /*MGlobal::displayInfo(MString() + "start keyfram index: " + startKeyFrameIndex + ". End keyfram index: " + endKeyFrameIndex + ".");*/ - if (startFrame <= jointAnim.time(endKeyFrameIndex).value() && jointAnim.time(endKeyFrameIndex).value() <= endFrame || endKeyFrameIndex - startKeyFrameIndex > 0) { - animatedJoints.push_back(jointIt.item()); - i = 9; - break; - } + /*if (startFrame <= jointAnim.time(endKeyFrameIndex).value() && jointAnim.time(endKeyFrameIndex).value() <= endFrame || endKeyFrameIndex - startKeyFrameIndex > 0) { + animatedJoints.push_back(jointIt.item()); + i = 9; + break; + } - MFnTransform MayaJoint(jointIt.item()); + MFnTransform MayaJoint(jointIt.item()); - MPlug BindPose = MayaJoint.findPlug("bindPose"); - MDataHandle DataHandle; - BindPose.getValue(DataHandle); - MFnMatrixData MartixFn(DataHandle.data()); - MMatrix BindPoseMatrix = MartixFn.matrix(); + MPlug BindPose = MayaJoint.findPlug("bindPose"); + MDataHandle DataHandle; + BindPose.getValue(DataHandle); + MFnMatrixData MartixFn(DataHandle.data()); + MMatrix BindPoseMatrix = MartixFn.matrix(); - if (!BindPoseMatrix.isEquivalent(MayaJoint.transformationMatrix())) - { - MGlobal::displayError(MString() + animationName.c_str() + " is using " + MayaJoint.name() + " that is not in bind pose nor is it key framed in the animation, the exported animation will NOT correspond to the animation in Maya"); - } - } - } - }*/ + if (!BindPoseMatrix.isEquivalent(MayaJoint.transformationMatrix())) + { + MGlobal::displayError(MString() + animationName.c_str() + " is using " + MayaJoint.name() + " that is not in bind pose nor is it key framed in the animation, the exported animation will NOT correspond to the animation in Maya"); + } + } + } + } - } // end of int i loop - jointIt.next(); - } - jointIt.reset(); - } + } // end of int i loop*/ + /* jointIt.next(); + } + jointIt.reset(); + }*/ - int currentFrame = startFrame; - while (currentFrame <= endFrame) { // ANDREAS - Animation::Keyframe thisKeyFrame; - thisKeyFrame.Index = currentFrame - startFrame; - thisKeyFrame.Time = thisKeyFrame.Index * oneDivSixty; + int currentFrame = startFrame; + while (currentFrame <= endFrame) { // ANDREAS + Animation::Keyframe thisKeyFrame; + thisKeyFrame.Index = currentFrame - startFrame; + thisKeyFrame.Time = thisKeyFrame.Index * oneDivSixty; - MAnimControl::setCurrentTime(MTime(currentFrame, MTime::kNTSCField)); - MTime time = MAnimControl::currentTime(); + MAnimControl::setCurrentTime(MTime(currentFrame, MTime::kNTSCField)); + MTime time = MAnimControl::currentTime(); - for (auto aJoint : animatedJoints){ - MFnTransform thisJoint(aJoint); - Animation::Keyframe::JointProperty joint; + MItDag jointIt(MItDag::TraversalType::kDepthFirst, MFn::kJoint); + unsigned int jointID = 0; + while (!jointIt.isDone()) { + MFnTransform thisJoint(jointIt.currentItem()); + MMatrix transformationMatrix = thisJoint.transformationMatrix(); + + double doubleMat[4][4]; - auto it = std::find(m_Hierarchy.begin(), m_Hierarchy.end(), thisJoint.object()); - if (it != m_Hierarchy.end()) { - joint.ID = it - m_Hierarchy.begin(); - } - else { - MGlobal::displayError(MString() + "Could not find joint ID for: " + thisJoint.name()); - } - - MTransformationMatrix Matrix = thisJoint.transformation(); + if (currentFrame != startFrame){ + Animation::Keyframe::JointProperty joint; + + doubleMat[0][0] = joinCheckMap[thisJoint.name().asChar()][0][0]; + doubleMat[0][1] = joinCheckMap[thisJoint.name().asChar()][0][1]; + doubleMat[0][2] = joinCheckMap[thisJoint.name().asChar()][0][2]; + doubleMat[0][3] = joinCheckMap[thisJoint.name().asChar()][0][3]; + doubleMat[1][0] = joinCheckMap[thisJoint.name().asChar()][1][0]; + doubleMat[1][1] = joinCheckMap[thisJoint.name().asChar()][1][1]; + doubleMat[1][2] = joinCheckMap[thisJoint.name().asChar()][1][2]; + doubleMat[1][3] = joinCheckMap[thisJoint.name().asChar()][1][3]; + doubleMat[2][0] = joinCheckMap[thisJoint.name().asChar()][2][0]; + doubleMat[2][1] = joinCheckMap[thisJoint.name().asChar()][2][1]; + doubleMat[2][2] = joinCheckMap[thisJoint.name().asChar()][2][2]; + doubleMat[2][3] = joinCheckMap[thisJoint.name().asChar()][2][3]; + doubleMat[3][0] = joinCheckMap[thisJoint.name().asChar()][3][0]; + doubleMat[3][1] = joinCheckMap[thisJoint.name().asChar()][3][1]; + doubleMat[3][2] = joinCheckMap[thisJoint.name().asChar()][3][2]; + doubleMat[3][3] = joinCheckMap[thisJoint.name().asChar()][3][3]; + + MMatrix LastJointMatrix(doubleMat); + //Is same as last KeyFrame + if (LastJointMatrix.isEquivalent(transformationMatrix)) { + jointID++; + jointIt.next(); + continue; + } + } + + transformationMatrix.get(doubleMat); + + joinCheckMap[thisJoint.name().asChar()][0][0] = doubleMat[0][0]; + joinCheckMap[thisJoint.name().asChar()][0][1] = doubleMat[0][1]; + joinCheckMap[thisJoint.name().asChar()][0][2] = doubleMat[0][2]; + joinCheckMap[thisJoint.name().asChar()][0][3] = doubleMat[0][3]; + joinCheckMap[thisJoint.name().asChar()][1][0] = doubleMat[1][0]; + joinCheckMap[thisJoint.name().asChar()][1][1] = doubleMat[1][1]; + joinCheckMap[thisJoint.name().asChar()][1][2] = doubleMat[1][2]; + joinCheckMap[thisJoint.name().asChar()][1][3] = doubleMat[1][3]; + joinCheckMap[thisJoint.name().asChar()][2][0] = doubleMat[2][0]; + joinCheckMap[thisJoint.name().asChar()][2][1] = doubleMat[2][1]; + joinCheckMap[thisJoint.name().asChar()][2][2] = doubleMat[2][2]; + joinCheckMap[thisJoint.name().asChar()][2][3] = doubleMat[2][3]; + joinCheckMap[thisJoint.name().asChar()][3][0] = doubleMat[3][0]; + joinCheckMap[thisJoint.name().asChar()][3][1] = doubleMat[3][1]; + joinCheckMap[thisJoint.name().asChar()][3][2] = doubleMat[3][2]; + joinCheckMap[thisJoint.name().asChar()][3][3] = doubleMat[3][3]; + + MTransformationMatrix Matrix = thisJoint.transformation(); MPlug BindPose = thisJoint.findPlug("bindPose"); MDataHandle DataHandle; BindPose.getValue(DataHandle); MFnMatrixData MartixFn(DataHandle.data()); MMatrix BindPoseMatrix = MartixFn.matrix(); Matrix = Matrix.asMatrix(); - + MObject jointOrientObj = thisJoint.attribute("jointOrient"); MFnNumericAttribute jointOrient(jointOrientObj); double jointOrientDouble[3]; @@ -257,79 +301,83 @@ Animation Skeleton::GetAnimData(std::string animationName, int startFrame, int e MEulerRotation joEuler(jointOrientDouble[0], jointOrientDouble[1], jointOrientDouble[2]); MQuaternion jo = joEuler.asQuaternion(); - double tmp[4]; + double tmp[4]; Matrix.getRotationQuaternion(tmp[0], tmp[1], tmp[2], tmp[3]); MQuaternion rotation(tmp); rotation = rotation * jo; rotation.get(tmp); - joint.Rotation[0] = tmp[0]; - joint.Rotation[1] = tmp[1]; - joint.Rotation[2] = tmp[2]; - joint.Rotation[3] = tmp[3]; - Matrix.getTranslation(MSpace::kTransform).get(tmp); - joint.Position[0] = tmp[0]; - joint.Position[1] = tmp[1]; - joint.Position[2] = tmp[2]; - Matrix.getScale(tmp, MSpace::kTransform); - joint.Scale[0] = tmp[0]; - joint.Scale[1] = tmp[1]; - joint.Scale[2] = tmp[2]; + Animation::Keyframe::JointProperty joint; + joint.ID = jointID; - thisKeyFrame.JointProperties.push_back(joint); - } - returnData.Keyframes.push_back(thisKeyFrame); - currentFrame++; - } + joint.Rotation[0] = tmp[0]; + joint.Rotation[1] = tmp[1]; + joint.Rotation[2] = tmp[2]; + joint.Rotation[3] = tmp[3]; + Matrix.getTranslation(MSpace::kTransform).get(tmp); + joint.Position[0] = tmp[0]; + joint.Position[1] = tmp[1]; + joint.Position[2] = tmp[2]; + Matrix.getScale(tmp, MSpace::kTransform); + joint.Scale[0] = tmp[0]; + joint.Scale[1] = tmp[1]; + joint.Scale[2] = tmp[2]; + + thisKeyFrame.JointProperties.push_back(joint); + + jointID++; + jointIt.next(); + } + thisKeyFrame.NumberOfJoints = thisKeyFrame.JointProperties.size(); + returnData.Keyframes.push_back(thisKeyFrame); + currentFrame++; + } returnData.NumKeyFrames = returnData.Keyframes.size(); - returnData.NumberOfJoints = animatedJoints.size(); - return returnData; + return returnData; } std::vector Skeleton::GetBindPoses() { MStatus status; - std::vector m_AllSkeletons; - std::vector m_Hierarchy; + std::vector m_AllSkeletons; + std::vector m_Hierarchy; - MItDag jointIt(MItDag::TraversalType::kDepthFirst, MFn::kJoint); - BindPoseSkeletonNode SkeletonStorage; - while (!jointIt.isDone()) { - MFnTransform MayaJoint(jointIt.currentItem()); - BindPoseSkeletonNode::BindPoseJoint NewJoint; + MItDag jointIt(MItDag::TraversalType::kDepthFirst, MFn::kJoint); + BindPoseSkeletonNode SkeletonStorage; + while (!jointIt.isDone()) { + MFnTransform MayaJoint(jointIt.currentItem()); + BindPoseSkeletonNode::BindPoseJoint NewJoint; - if (MFnDependencyNode(MayaJoint.parent(0)).object().apiType() != MFn::kJoint) { - if (SkeletonStorage.Joints.size() != 0) { - m_AllSkeletons.push_back(SkeletonStorage); + if (MFnDependencyNode(MayaJoint.parent(0)).object().apiType() != MFn::kJoint) { + if (SkeletonStorage.Joints.size() != 0) { + m_AllSkeletons.push_back(SkeletonStorage); - SkeletonStorage.Joints.clear(); - SkeletonStorage.Name.clear(); - } - SkeletonStorage.Name = std::string(MayaJoint.name().asChar()); - NewJoint.ParentID = -1; // This joint is root - } - else { - auto it = std::find(m_Hierarchy.begin(), m_Hierarchy.end(), MayaJoint.parent(0)); - if (it != m_Hierarchy.end()) { - NewJoint.ParentID = it - m_Hierarchy.begin(); - } - else { - MGlobal::displayError(MString() + "Could not find joint parent for: " + MayaJoint.name()); - } - } - m_Hierarchy.push_back(MayaJoint.object()); + SkeletonStorage.Joints.clear(); + SkeletonStorage.Name.clear(); + } + SkeletonStorage.Name = std::string(MayaJoint.name().asChar()); + NewJoint.ParentID = -1; // This joint is root + } else { + auto it = std::find(m_Hierarchy.begin(), m_Hierarchy.end(), MayaJoint.parent(0)); + if (it != m_Hierarchy.end()) { + NewJoint.ParentID = it - m_Hierarchy.begin(); + } else { + MGlobal::displayError(MString() + "Could not find joint parent for: " + MayaJoint.name()); + } + } + m_Hierarchy.push_back(MayaJoint.object()); - MPlug BindPose = MayaJoint.findPlug("bindPose", &status); - if (status != MS::kSuccess) { + MPlug BindPose = MayaJoint.findPlug("bindPose", &status); + if (status != MS::kSuccess) { MGlobal::displayError(MString() + "Could not find bindPose plug: " + status.errorString()); } - MDataHandle DataHandle; - BindPose.getValue(DataHandle); - MFnMatrixData MartixFn(DataHandle.data()); - MMatrix Matrix = MartixFn.matrix(); + MDataHandle DataHandle; + BindPose.getValue(DataHandle); + MFnMatrixData MartixFn(DataHandle.data()); + MMatrix Matrix = MartixFn.matrix(); MVector tmp = MayaJoint.transformation().getTranslation(MSpace::kObject); @@ -342,7 +390,7 @@ std::vector Skeleton::GetBindPoses() MTransformationMatrix::RotationOrder order = MTransformationMatrix::RotationOrder::kXYZ; MayaJoint.transformation().getRotation(test, order); - + //----- test @@ -389,33 +437,33 @@ std::vector Skeleton::GetBindPoses() Matrix = Matrix.inverse(); - for (int i = 0; i < 4; i++) { - for (int j = 0; j < 4; j++) { - NewJoint.OffsetMatrix[i][j] = Matrix.matrix[i][j]; - } - } + for (int i = 0; i < 4; i++) { + for (int j = 0; j < 4; j++) { + NewJoint.OffsetMatrix[i][j] = Matrix.matrix[i][j]; + } + } - NewJoint.Name = MayaJoint.name().asChar(); + NewJoint.Name = MayaJoint.name().asChar(); NewJoint.NameLength = MayaJoint.name().length() + 1; NewJoint.ID = SkeletonStorage.Joints.size(); - //double tmp[3]; - //((MTransformationMatrix)Matrix).eulerRotation().asVector().get(tmp); - //NewJoint.Rotation[0] = tmp[0]; - //NewJoint.Rotation[1] = tmp[1]; - //NewJoint.Rotation[2] = tmp[2]; - //((MTransformationMatrix)Matrix).getScale(tmp, MSpace::Space::kTransform); - //NewJoint.Scale[0] = tmp[0]; - //NewJoint.Scale[1] = tmp[1]; - //NewJoint.Scale[2] = tmp[2]; - //((MTransformationMatrix)Matrix).getTranslation(MSpace::Space::kTransform).get(tmp); - //NewJoint.Translation[0] = tmp[0]; - //NewJoint.Translation[1] = tmp[1]; - //NewJoint.Translation[2] = tmp[2]; - SkeletonStorage.Joints.push_back(NewJoint); + //double tmp[3]; + //((MTransformationMatrix)Matrix).eulerRotation().asVector().get(tmp); + //NewJoint.Rotation[0] = tmp[0]; + //NewJoint.Rotation[1] = tmp[1]; + //NewJoint.Rotation[2] = tmp[2]; + //((MTransformationMatrix)Matrix).getScale(tmp, MSpace::Space::kTransform); + //NewJoint.Scale[0] = tmp[0]; + //NewJoint.Scale[1] = tmp[1]; + //NewJoint.Scale[2] = tmp[2]; + //((MTransformationMatrix)Matrix).getTranslation(MSpace::Space::kTransform).get(tmp); + //NewJoint.Translation[0] = tmp[0]; + //NewJoint.Translation[1] = tmp[1]; + //NewJoint.Translation[2] = tmp[2]; + SkeletonStorage.Joints.push_back(NewJoint); SkeletonStorage.numBones++; - jointIt.next(); - } - m_AllSkeletons.push_back(SkeletonStorage); + jointIt.next(); + } + m_AllSkeletons.push_back(SkeletonStorage); - return m_AllSkeletons; + return m_AllSkeletons; } \ No newline at end of file diff --git a/tools/MayaExporter/MayaExporter/Skeleton.h b/tools/MayaExporter/MayaExporter/Skeleton.h index 9033441d..47ae6f4c 100644 --- a/tools/MayaExporter/MayaExporter/Skeleton.h +++ b/tools/MayaExporter/MayaExporter/Skeleton.h @@ -22,6 +22,7 @@ public: int Index = 0; float Time = 0; + int NumberOfJoints; std::vector JointProperties; }; @@ -29,7 +30,6 @@ public: int nameLength = 0; float Duration = 0; int NumKeyFrames = 0; - int NumberOfJoints = 0; std::vector Keyframes; virtual void WriteBinary(std::ostream& out) @@ -38,11 +38,11 @@ public: out.write(Name.c_str(), Name.size() + 1); out.write((char*)&Duration, sizeof(float)); out.write((char*)&NumKeyFrames, sizeof(int)); - out.write((char*)&NumberOfJoints, sizeof(int)); //Här under loopas alla key frames igenom for (auto aKeyframe : Keyframes) { out.write((char*)&aKeyframe.Index, sizeof(int)); out.write((char*)&aKeyframe.Time, sizeof(float)); + out.write((char*)&aKeyframe.NumberOfJoints, sizeof(int)); for (auto aJoint : aKeyframe.JointProperties) { out.write((char*)&aJoint.ID, sizeof(int)); out.write((char*)aJoint.Position, sizeof(float) * 3); @@ -56,11 +56,11 @@ public: { out << "Animation Name: " << Name << endl; out << "Duration: " << Duration << endl; - out << "Number of KeyFrames: " << NumKeyFrames << endl; - out << "Number of Joints: " << NumberOfJoints << endl; + out << "Number of KeyFrames: " << NumKeyFrames << endl; for (auto aKeyframe : Keyframes) { out << "Frame: " << aKeyframe.Index << endl; out << "Time: " << aKeyframe.Time << endl; + out << "Number of Joints: " << aKeyframe.NumberOfJoints << endl; for (auto aJoint : aKeyframe.JointProperties) { out << "Joint ID: " << aJoint.ID << endl; out << aJoint.Position[0] << " " << aJoint.Position[1] << " " << aJoint.Position[2] << endl; From dba2fbdc0cbe2b2947ca45ab58108c1ef5bcbdc5 Mon Sep 17 00:00:00 2001 From: viktorljung Date: Tue, 2 Feb 2016 14:52:31 +0100 Subject: [PATCH 040/355] WIP --- include/Engine/Rendering/AnimationSystem.h | 6 +- include/Engine/Rendering/Skeleton.h | 1 + resources/Schema/Entities/AnimationTests.xml | 394 ++++++++++++++---- resources/Schema/Entities/AnimationTests2.xml | 341 +++++++++++++++ resources/Schema/Entities/BoneMarker | 22 + resources/Schema/Entities/FastWorld.xml | 4 +- resources/Schema/Entities/Testingu | 45 ++ src/Engine/Rendering/AnimationSystem.cpp | 112 ++++- src/Engine/Rendering/RenderSystem.cpp | 12 +- src/Engine/Rendering/Skeleton.cpp | 9 +- src/Game/Systems/PlayerMovementSystem.cpp | 8 +- 11 files changed, 842 insertions(+), 112 deletions(-) create mode 100644 resources/Schema/Entities/AnimationTests2.xml create mode 100644 resources/Schema/Entities/BoneMarker create mode 100644 resources/Schema/Entities/Testingu diff --git a/include/Engine/Rendering/AnimationSystem.h b/include/Engine/Rendering/AnimationSystem.h index fcdcbc92..15dbe39d 100644 --- a/include/Engine/Rendering/AnimationSystem.h +++ b/include/Engine/Rendering/AnimationSystem.h @@ -9,6 +9,7 @@ #include "Rendering/Model.h" #include "Rendering/EAnimationComplete.h" #include "Rendering/Skeleton.h" +#include class AnimationSystem : public PureSystem { @@ -22,8 +23,9 @@ public: ~AnimationSystem() { } virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& animationComponent, double dt) override; private: - - + float angle = 0.f; + bool b_forward = false; + char bone[100]; }; #endif \ No newline at end of file diff --git a/include/Engine/Rendering/Skeleton.h b/include/Engine/Rendering/Skeleton.h index dca78e4c..8ae3d487 100644 --- a/include/Engine/Rendering/Skeleton.h +++ b/include/Engine/Rendering/Skeleton.h @@ -41,6 +41,7 @@ public: std::string Name; glm::mat4 OffsetMatrix; + glm::mat4 ModificationMatrix = glm::mat4(1); int ID; Bone* Parent; diff --git a/resources/Schema/Entities/AnimationTests.xml b/resources/Schema/Entities/AnimationTests.xml index 578db574..77c87e64 100644 --- a/resources/Schema/Entities/AnimationTests.xml +++ b/resources/Schema/Entities/AnimationTests.xml @@ -34,108 +34,344 @@ - Run - + Crouch + 1 - Models/AssaultAnimated.mesh + Models/Asstest.mesh - + - - - - - 12 - 0.29999995231628418 - - - - - - - - - - - - 7 - - - - - - - - + - L_Foot + R_Leg_Top - true Models/Core/UnitCube.mesh - - - + + + + + + + + + + + R_Leg_Bottom + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Foot + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + L_Foot + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + L_Leg_Bottom + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + L_Leg_Top + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Hip + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Spine_1 + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Spine_2 + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Spine_3 + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Neck + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Shoulder + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Arm + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Elbow + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Hand + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Chin + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + L_Hand + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + L_Elbow + + + + Models/Core/UnitCube.mesh + + + + + + - - - - Walk - - 1 - - - Models/AssaultAnimated.mesh - - - - - - - - - - - Crouch Walk - - 1 - - - Models/AssaultAnimated.mesh - - - - - - - - - - - - Models/Core/UnitCube.mesh - - - - - - - diff --git a/resources/Schema/Entities/AnimationTests2.xml b/resources/Schema/Entities/AnimationTests2.xml new file mode 100644 index 00000000..23fc0548 --- /dev/null +++ b/resources/Schema/Entities/AnimationTests2.xml @@ -0,0 +1,341 @@ + + + + + + + + + + + + Models/Core/UnitPlane.mesh + + + + + + + + + + + + + Models/DirectionalLightWidget.mesh + + + + + + + + + + + + Run + + 1 + + + Models/Asstest.mesh + + + + + + + + + + R_Leg_Top + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Leg_Bottom + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Foot + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + L_Foot + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + L_Leg_Bottom + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + L_Leg_Top + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Hip + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Spine_1 + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Spine_2 + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Spine_3 + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Neck + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Shoulder + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Arm + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Elbow + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Hand + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Chin + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/BoneMarker b/resources/Schema/Entities/BoneMarker new file mode 100644 index 00000000..eda56d56 --- /dev/null +++ b/resources/Schema/Entities/BoneMarker @@ -0,0 +1,22 @@ + + + + + + R_Leg_Top + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + diff --git a/resources/Schema/Entities/FastWorld.xml b/resources/Schema/Entities/FastWorld.xml index 4863f8f7..94df077d 100644 --- a/resources/Schema/Entities/FastWorld.xml +++ b/resources/Schema/Entities/FastWorld.xml @@ -25,7 +25,9 @@ - Walk + Crouch Walk + + 8 Models/AssaultAnimated.mesh diff --git a/resources/Schema/Entities/Testingu b/resources/Schema/Entities/Testingu new file mode 100644 index 00000000..145550f4 --- /dev/null +++ b/resources/Schema/Entities/Testingu @@ -0,0 +1,45 @@ + + + + + + + + + + + + Models/Core/UnitPlane.mesh + + + + + + + + + + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Engine/Rendering/AnimationSystem.cpp b/src/Engine/Rendering/AnimationSystem.cpp index 9c1e68cf..93d52787 100644 --- a/src/Engine/Rendering/AnimationSystem.cpp +++ b/src/Engine/Rendering/AnimationSystem.cpp @@ -23,29 +23,109 @@ void AnimationSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& a const Skeleton::Animation* animation = skeleton->GetAnimation(animationComponent["AnimationName"]); - if(animation != nullptr) { - double animationSpeed = (double)animationComponent["Speed"]; + if (animation == nullptr) { + return; + } - if (animationSpeed != 0.0) { - double nextTime = (double)animationComponent["Time"] + animationSpeed * dt; + double animationSpeed = (double)animationComponent["Speed"]; + + if (animationSpeed != 0.0) { + double nextTime = (double)animationComponent["Time"] + animationSpeed * dt; - if (!(bool)animationComponent["Loop"] && glm::abs(nextTime) > animation->Duration) { - (double&)animationComponent["Time"] = glm::sign(nextTime) * animation->Duration; - (double&)animationComponent["Speed"] = 0.0; - Events::AnimationComplete e; - e.Entity = entity; - e.Name = (std::string)animationComponent["AnimationName"]; - m_EventBroker->Publish(e); + if (!(bool)animationComponent["Loop"] && glm::abs(nextTime) > animation->Duration) { + (double&)animationComponent["Time"] = glm::sign(nextTime) * animation->Duration; + (double&)animationComponent["Speed"] = 0.0; + Events::AnimationComplete e; + e.Entity = entity; + e.Name = (std::string)animationComponent["AnimationName"]; + m_EventBroker->Publish(e); + } else { + if (glm::abs(nextTime) > animation->Duration) { + (double&)animationComponent["Time"] = glm::abs(nextTime) - animation->Duration; } else { - if (glm::abs(nextTime) > animation->Duration) { - (double&)animationComponent["Time"] = glm::abs(nextTime) - animation->Duration; - } else { - (double&)animationComponent["Time"] = nextTime; - } + (double&)animationComponent["Time"] = nextTime; } } } + + + + ImGui::SliderFloat("Angle", &angle, -180.f, 180.f); + + int id = skeleton->GetBoneID("Spine_2"); + auto it = skeleton->Bones.find(id); + if (it != skeleton->Bones.end()) { + int currentKeyframeIndex = skeleton->GetKeyframe(*animation, entity["Animation"]["Time"]); + + const Skeleton::Animation::Keyframe& currentFrame = animation->Keyframes[currentKeyframeIndex]; + const Skeleton::Animation::Keyframe& nextFrame = animation->Keyframes[(currentKeyframeIndex + 1) % animation->Keyframes.size()]; + float alpha = ((double)entity["Animation"]["Time"] - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); + + glm::mat4 parentBoneTransform = skeleton->GetBoneTransform(it->second->Parent, currentFrame, nextFrame, alpha, glm::mat4(1)); + + + + glm::vec3 scale; + glm::quat rotation; + glm::vec3 translation; + glm::vec3 skew; + glm::vec4 perspective; + glm::decompose(parentBoneTransform, scale, rotation, translation, skew, perspective); + + + + glm::vec3 rot; + rot = glm::vec3(1, 0, 0); + rot = glm::normalize(rot) * glm::radians(angle); + glm::mat4 modmat = glm::mat4(glm::quat(rot)) * glm::inverse(glm::mat4(rotation)); + + + it->second->ModificationMatrix = modmat; + } + + + +/* + + { + int id = skeleton->GetBoneID("Neck"); + auto it = skeleton->Bones.find(id); + if (it != skeleton->Bones.end()) { + it->second->ModificationMatrix = glm::mat4(glm::quat(glm::vec3(glm::radians(angle/2.f), 0.f, 0.f))); + } + } + + { + int id = skeleton->GetBoneID("Spine_2"); + auto it = skeleton->Bones.find(id); + if (it != skeleton->Bones.end()) { + it->second->ModificationMatrix = glm::mat4(glm::quat(glm::vec3(glm::radians(angle/4.f), 0.f, 0.f))); + } + } + { + int id = skeleton->GetBoneID("R_Shoulder"); + auto it = skeleton->Bones.find(id); + if (it != skeleton->Bones.end()) { + it->second->ModificationMatrix = glm::mat4(glm::quat(glm::vec3(glm::radians(angle/2.f), 0.f, 0.f))); + } + } + { + int id = skeleton->GetBoneID("L_Shoulder"); + auto it = skeleton->Bones.find(id); + if (it != skeleton->Bones.end()) { + it->second->ModificationMatrix = glm::mat4(glm::quat(glm::vec3(glm::radians(angle/2.f), 0.f, 0.f))); + } + }*/ + + if (entity.HasComponent("Player")) { + EntityWrapper cameraEntity = entity.FirstChildByName("Camera"); + if (cameraEntity.Valid()) { + glm::vec3& cameraOrientation = cameraEntity["Transform"]["Orientation"]; + + + } + } } diff --git a/src/Engine/Rendering/RenderSystem.cpp b/src/Engine/Rendering/RenderSystem.cpp index f9114350..1998c3d7 100644 --- a/src/Engine/Rendering/RenderSystem.cpp +++ b/src/Engine/Rendering/RenderSystem.cpp @@ -61,14 +61,14 @@ void RenderSystem::fillModels(std::list>& jobs) EntityWrapper entity(m_World, cModel.EntityID); // Only render children of a camera if that camera is currently active - if (isChildOfACamera(entity) && !isChildOfCurrentCamera(entity)) { - continue; - } +// if (isChildOfACamera(entity) && !isChildOfCurrentCamera(entity)) { +// continue; +// } DO NOT COMMIT THIS DO NOT COMMIT THIS DO NOT COMMIT THIS DO NOT COMMIT THIS DO NOT COMMIT THIS DO NOT COMMIT THIS DO NOT COMMIT THIS // Hide things parented to local player if they have the HiddenFromLocalPlayer component - if (entity.HasComponent("HiddenForLocalPlayer") && (entity == m_LocalPlayer || entity.IsChildOf(m_LocalPlayer))) { - continue; - } +// if (entity.HasComponent("HiddenForLocalPlayer") && (entity == m_LocalPlayer || entity.IsChildOf(m_LocalPlayer))) { +// continue; +// } DO NOT COMMIT THIS DO NOT COMMIT THIS DO NOT COMMIT THIS DO NOT COMMIT THIS DO NOT COMMIT THIS DO NOT COMMIT THIS DO NOT COMMIT THIS Model* model; try { diff --git a/src/Engine/Rendering/Skeleton.cpp b/src/Engine/Rendering/Skeleton.cpp index 150fad7d..7fe36319 100644 --- a/src/Engine/Rendering/Skeleton.cpp +++ b/src/Engine/Rendering/Skeleton.cpp @@ -95,12 +95,13 @@ void Skeleton::AccumulateBoneTransforms(bool noRootMotion, const Animation::Keyf positionInterp.z = 0; } + - boneMatrix = parentMatrix * (glm::translate(positionInterp) * glm::toMat4(rotationInterp) * glm::scale(scaleInterp)); - boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix; + boneMatrix = parentMatrix * bone->ModificationMatrix * (glm::translate(positionInterp) * glm::toMat4(rotationInterp) * glm::scale(scaleInterp)); + boneMatrices[bone->ID] = boneMatrix *bone->OffsetMatrix; } else { if (bone->Parent) { - boneMatrix = parentMatrix; // * glm::inverse(bone->OffsetMatrix); + boneMatrix = parentMatrix;// *glm::inverse(bone->OffsetMatrix); } boneMatrices[bone->ID] = boneMatrix; // * bone->OffsetMatrix; } @@ -125,7 +126,7 @@ glm::mat4 Skeleton::GetBoneTransform(const Bone* bone, const Animation::Keyframe glm::vec3 scaleInterp = currentBoneProperty.Scale * (1.f - progress) + nextBoneProperty.Scale * progress; - boneMatrix = (glm::translate(positionInterp) * glm::toMat4(rotationInterp) * glm::scale(scaleInterp)) * parentMatrix; + boneMatrix = (glm::translate(positionInterp) * glm::toMat4(rotationInterp) * glm::scale(scaleInterp)) * bone->ModificationMatrix * parentMatrix; } else { if (bone->Parent) { boneMatrix = parentMatrix; diff --git a/src/Game/Systems/PlayerMovementSystem.cpp b/src/Game/Systems/PlayerMovementSystem.cpp index 6eab02c5..36dbcbd0 100644 --- a/src/Game/Systems/PlayerMovementSystem.cpp +++ b/src/Game/Systems/PlayerMovementSystem.cpp @@ -97,18 +97,18 @@ void PlayerMovementSystem::Update(double dt) float movementLength = glm::length(groundVelocity); if (glm::length(controller->Movement()) > 0.f) { if (controller->Crouching()) { - cAnimation["Name"] = "Crouch Walk"; + cAnimation["AnimationName"] = "Crouch Walk"; (double&)cAnimation["Speed"] = 1.f * -glm::sign(controller->Movement().z); } else { - cAnimation["Name"] = "Run"; + cAnimation["AnimationName"] = "Run"; (double&)cAnimation["Speed"] = 2.f * -glm::sign(controller->Movement().z); } } else { if (controller->Crouching()) { - cAnimation["Name"] = "Crouch"; + cAnimation["AnimationName"] = "Crouch"; (double&)cAnimation["Speed"] = 1.f; } else { - cAnimation["Name"] = "Hold Pos"; + cAnimation["AnimationName"] = "Hold Pos"; (double&)cAnimation["Speed"] = 1.f; } } From 88ad127d8de062991ac047afbbf48908ea4224d3 Mon Sep 17 00:00:00 2001 From: stiffly Date: Tue, 2 Feb 2016 14:57:03 +0100 Subject: [PATCH 041/355] plays notification on captured/lost point --- resources/Schema/Entities/aim_rays.xml | 51 ++++++++++++++++++++++++++ src/Engine/Sound/SoundSystem.cpp | 2 +- 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/resources/Schema/Entities/aim_rays.xml b/resources/Schema/Entities/aim_rays.xml index c488ca51..c8dac9a3 100644 --- a/resources/Schema/Entities/aim_rays.xml +++ b/resources/Schema/Entities/aim_rays.xml @@ -205,6 +205,57 @@ + + + + + + + + + + Models\Core\UnitCube.mesh + + + + + + + + + + + + + + + + + + + + + + + 1 + + + Models\Core\UnitCube.mesh + + + + + + + + + + + + + + + diff --git a/src/Engine/Sound/SoundSystem.cpp b/src/Engine/Sound/SoundSystem.cpp index d08232ec..e5684ac3 100644 --- a/src/Engine/Sound/SoundSystem.cpp +++ b/src/Engine/Sound/SoundSystem.cpp @@ -365,7 +365,7 @@ bool SoundSystem::OnInputCommand(const Events::InputCommand & e) bool SoundSystem::OnCaptured(const Events::Captured & e) { - int homeTeam = (int)m_World->GetComponent(e.CapturePointID, "CapturePoint")["HomePointForTeam"]; + int homeTeam = (int)m_World->GetComponent(e.CapturePointID, "Team")["Team"]; int team = (int)m_World->GetComponent(m_LocalPlayer, "Team")["Team"]; Events::PlaySoundOnEntity ev; if (team == homeTeam) { From 5e472cd69c9a24bc090211c7c15daf10ea6ee0bc Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Tue, 2 Feb 2016 17:18:12 +0100 Subject: [PATCH 042/355] DeathExplosion is now an XML file, changed PlayerDeathSystem accordingly. The effect should show as soon as the explosioneffect-fix is merged into master. TODO: remove the test --- include/Engine/Core/EPlayerDeath.h | 2 - include/Game/Systems/PlayerDeathSystem.h | 8 ++ .../PlayerDeathExplosionWithCamera.xml | 48 +++++++++ src/Game/Systems/HealthSystem.cpp | 1 - src/Game/Systems/PlayerDeathSystem.cpp | 102 +++++++++--------- src/Tests/CapturePointTest.cpp | 8 +- 6 files changed, 114 insertions(+), 55 deletions(-) create mode 100644 resources/Schema/Entities/PlayerDeathExplosionWithCamera.xml diff --git a/include/Engine/Core/EPlayerDeath.h b/include/Engine/Core/EPlayerDeath.h index 53dfd013..363745a6 100644 --- a/include/Engine/Core/EPlayerDeath.h +++ b/include/Engine/Core/EPlayerDeath.h @@ -10,8 +10,6 @@ namespace Events struct PlayerDeath : Event { //KilledBy,KilledByWhat is optional for now. It might be used later in the playerlog-system - EntityID KilledBy; - EntityID PlayerID; EntityWrapper Player; std::string KilledByWhat; }; diff --git a/include/Game/Systems/PlayerDeathSystem.h b/include/Game/Systems/PlayerDeathSystem.h index c59aea03..4734947e 100644 --- a/include/Game/Systems/PlayerDeathSystem.h +++ b/include/Game/Systems/PlayerDeathSystem.h @@ -7,7 +7,11 @@ #include "Rendering/ESetCamera.h" #include "Core/ConfigFile.h" +#include "Core/EntityFile.h" +#include "Core/EntityFileParser.h" + #include "Core/EPlayerDeath.h" +#include "Core/EPlayerDamage.h" class PlayerDeathSystem : public ImpureSystem { @@ -19,5 +23,9 @@ public: private: EventRelay m_OnPlayerDeath; bool OnPlayerDeath(Events::PlayerDeath& e); + + EventRelay m_OnInputCommand; + bool OnInputCommand(const Events::InputCommand& e); + }; #endif \ No newline at end of file diff --git a/resources/Schema/Entities/PlayerDeathExplosionWithCamera.xml b/resources/Schema/Entities/PlayerDeathExplosionWithCamera.xml new file mode 100644 index 00000000..bdebbfe7 --- /dev/null +++ b/resources/Schema/Entities/PlayerDeathExplosionWithCamera.xml @@ -0,0 +1,48 @@ + + + + + + Hold Pos + + 0 + + + 8 + + + 0 + 8 + + + + Models/AssaultAnimated.mesh + + true + + + + + + + + + + + 1 + + + 120 + 0.1 + 10000 + + + + + + + + + + + diff --git a/src/Game/Systems/HealthSystem.cpp b/src/Game/Systems/HealthSystem.cpp index 1b747046..18a15828 100644 --- a/src/Game/Systems/HealthSystem.cpp +++ b/src/Game/Systems/HealthSystem.cpp @@ -21,7 +21,6 @@ bool HealthSystem::OnPlayerDamaged(Events::PlayerDamage& e) if (health <= 0.0) { Events::PlayerDeath ePlayerDeath; - ePlayerDeath.PlayerID = e.Player.ID; ePlayerDeath.Player = e.Player; m_EventBroker->Publish(ePlayerDeath); //Note: we will delete the entity in PlayerDeathSystem diff --git a/src/Game/Systems/PlayerDeathSystem.cpp b/src/Game/Systems/PlayerDeathSystem.cpp index 7085a23f..d57caefc 100644 --- a/src/Game/Systems/PlayerDeathSystem.cpp +++ b/src/Game/Systems/PlayerDeathSystem.cpp @@ -3,69 +3,75 @@ PlayerDeathSystem::PlayerDeathSystem(World* m_World, EventBroker* eventBroker) : System(m_World, eventBroker) { + EVENT_SUBSCRIBE_MEMBER(m_OnInputCommand, &PlayerDeathSystem::OnInputCommand); EVENT_SUBSCRIBE_MEMBER(m_OnPlayerDeath, &PlayerDeathSystem::OnPlayerDeath); } +bool PlayerDeathSystem::OnInputCommand(const Events::InputCommand& e) +{ + //testing: Jump > playerdamage + if (e.Command != "Jump") { + return false; + + } + + // 0 = released + if (e.Value != 0) { + return false; + + } + + auto players = m_World->GetComponents("Player"); + + for (auto& cPlayer : *players) { + EntityWrapper player(m_World, cPlayer.EntityID); + Events::PlayerDamage e; + e.Player = player; + e.Damage = 50; + m_EventBroker->Publish(e); + + } + + + + return true; +} + void PlayerDeathSystem::Update(double dt) { } bool PlayerDeathSystem::OnPlayerDeath(Events::PlayerDeath& e) { - //current components for player that we need - auto playerModelEWrapper = e.Player.FirstChildByName("PlayerModel"); - auto playerEntityModel = playerModelEWrapper["Model"]; - auto playerEntityAnimation = playerModelEWrapper["Animation"]; - auto playerEntityTransform = playerModelEWrapper["Transform"]; + //LOAD THE XML + auto deathEffect = ResourceManager::Load("Schema/Entities/PlayerDeathExplosionWithCamera.xml"); - //create new entity with those components - //graphics bug: model must have an animationcomponent to be able to display it - auto newEntity = m_World->CreateEntity(); - ComponentWrapper& newEntityModel = m_World->AttachComponent(newEntity, "Model"); - ComponentWrapper& newAnimationModel = m_World->AttachComponent(newEntity, "Animation"); - ComponentWrapper& newTransformModel = m_World->AttachComponent(newEntity, "Transform"); - playerEntityModel.Copy(newEntityModel); - playerEntityAnimation.Copy(newAnimationModel); - playerEntityTransform.Copy(newTransformModel); + EntityFileParser parser(deathEffect); + EntityID deathEffectID = parser.MergeEntities(m_World); + EntityWrapper deathEffectEW = EntityWrapper(m_World, deathEffectID); + + //current components for player that we need + auto playerModelEW = e.Player.FirstChildByName("PlayerModel"); + auto playerEntityModel = playerModelEW["Model"]; + auto playerEntityTransform = playerModelEW["Transform"]; + + //copy the data from player to new playermodel + playerEntityModel.Copy(deathEffectEW["Model"]); + playerEntityTransform.Copy(deathEffectEW["Transform"]); //change the animation speed and make sure the explosioneffect spawns at the players position - newAnimationModel["Speed"] = (double)0.0; - newEntityModel["Color"] = glm::vec4(1, 0, 0, 1); - newTransformModel["Position"] = (glm::vec3)e.Player["Transform"]["Position"]; - newTransformModel["Scale"] = glm::vec3(1, 1, 1); - - //add the explosion with a lifetime - ComponentWrapper& explosionEffect = m_World->AttachComponent(newEntity, "ExplosionEffect"); - ComponentWrapper& lifeTime = m_World->AttachComponent(newEntity, "Lifetime"); - (glm::vec3)explosionEffect["ExplosionOrigin"] = (glm::vec3)e.Player["Transform"]["Position"]; - (double)explosionEffect["TimeSinceDeath"] = 0.0; - (double)explosionEffect["ExplosionDuration"] = 8.0; - (glm::vec4)explosionEffect["EndColor"] = glm::vec4(0, 0, 0, 1); - (bool)explosionEffect["Randomness"] = false; - (double)explosionEffect["RandomnessScalar"] = 1.0; - (glm::vec2)explosionEffect["Velocity"] = glm::vec2(0.1f, 0.1f); - (bool)explosionEffect["ColorByDistance"] = false; - (bool)explosionEffect["ExponentialAccelaration"] = false; - lifeTime["Lifetime"] = (double)8.0; - - //create a camera (with lifetime) slightly above the player and look down at the player - auto cameraEntity = m_World->CreateEntity(); - ComponentWrapper& thirdPersonCameraLifeTime = m_World->AttachComponent(cameraEntity, "Lifetime"); - ComponentWrapper& thirdPersonCamera = m_World->AttachComponent(cameraEntity, "Camera"); - ComponentWrapper& thirdPersonCameraTransform = m_World->AttachComponent(cameraEntity, "Transform"); - auto pos = (glm::vec3)e.Player["Transform"]["Position"]; - pos.y += 10.0f; - thirdPersonCameraTransform["Position"] = (glm::vec3)pos; //http://www.opengl-tutorial.org/intermediate-tutorials/tutorial-17-quaternions/ - thirdPersonCameraTransform["Orientation"] = glm::vec3(-0.7f, 1.46f, 0.8f); - thirdPersonCamera["FOV"] = 120.0; - thirdPersonCamera["NearClip"] = 0.1; - thirdPersonCamera["FarClip"] = 10000.0; - thirdPersonCameraLifeTime["Lifetime"] = (double)1.0; + auto playerPosition = (glm::vec3)e.Player["Transform"]["Position"]; + deathEffectEW["Transform"]["Position"] = playerPosition; + deathEffectEW["ExplosionEffect"]["ExplosionOrigin"] = playerPosition; - //set 3rd person camera + //camera (with lifetime) slightly above the player and looking down at the player + //camera will be positioned just above the player + glm::vec3 cameraPosition = glm::vec3(0, 10, 0); + auto cam = deathEffectEW.FirstChildByName("Camera"); + cam["Transform"]["Position"] = cameraPosition; Events::SetCamera eSetCamera; - eSetCamera.CameraEntity = EntityWrapper(m_World, cameraEntity); + eSetCamera.CameraEntity = cam; m_EventBroker->Publish(eSetCamera); //on deathanim done -> del entity diff --git a/src/Tests/CapturePointTest.cpp b/src/Tests/CapturePointTest.cpp index ffb01030..2c7bf430 100644 --- a/src/Tests/CapturePointTest.cpp +++ b/src/Tests/CapturePointTest.cpp @@ -255,14 +255,14 @@ void CapturePointTest::TestSetup8() } void CapturePointTest::DoTouchEvent(EntityID whoDidSomething, EntityID onWhatObject) { Events::TriggerTouch touchEvent; - touchEvent.Entity = whoDidSomething; - touchEvent.Trigger = onWhatObject; + touchEvent.Entity = EntityWrapper(m_World, whoDidSomething); + touchEvent.Trigger = EntityWrapper(m_World, onWhatObject); m_EventBroker->Publish(touchEvent); } void CapturePointTest::DoLeaveEvent(EntityID whoDidSomething, EntityID onWhatObject) { Events::TriggerLeave leaveEvent; - leaveEvent.Entity = whoDidSomething; - leaveEvent.Trigger = onWhatObject; + leaveEvent.Entity = EntityWrapper(m_World, whoDidSomething); + leaveEvent.Trigger = EntityWrapper(m_World, onWhatObject); m_EventBroker->Publish(leaveEvent); } void CapturePointTest::TestSuccess1() { From bb4a65a1db70c66c1bd33c9c9f0d4b86bdc6b793 Mon Sep 17 00:00:00 2001 From: Teejoon Date: Tue, 2 Feb 2016 17:18:42 +0100 Subject: [PATCH 043/355] Non-skined mesh WIP --- include/Engine/Rendering/Model.h | 5 +-- include/Engine/Rendering/RawModelCustom.h | 41 +++++++++++++++++------ src/Engine/Collision/Collision.cpp | 3 +- src/Engine/Rendering/Model.cpp | 27 +++++++++++---- src/Engine/Rendering/RawModelCustom.cpp | 28 ++++++++++++---- 5 files changed, 78 insertions(+), 26 deletions(-) diff --git a/include/Engine/Rendering/Model.h b/include/Engine/Rendering/Model.h index f751a8cc..aeb13e2f 100644 --- a/include/Engine/Rendering/Model.h +++ b/include/Engine/Rendering/Model.h @@ -16,8 +16,9 @@ public: ~Model(); const std::vector& MaterialGroups() const { return m_RawModel->MaterialGroups; } const glm::mat4& Matrix() const { return m_RawModel->m_Matrix; } - const std::vector& Vertices() const { return m_RawModel->m_Vertices; } - + const RawModel::Vertex* Vertices() const { return m_RawModel->Vertices(); } + unsigned int NumberOfVertices() const { return m_RawModel->NumVertices(); } + bool isSkined() const { return m_RawModel->isSkined; } GLuint VAO; GLuint ElementBuffer; RawModel* m_RawModel; diff --git a/include/Engine/Rendering/RawModelCustom.h b/include/Engine/Rendering/RawModelCustom.h index f1bc0e24..ef7a28e5 100644 --- a/include/Engine/Rendering/RawModelCustom.h +++ b/include/Engine/Rendering/RawModelCustom.h @@ -33,17 +33,20 @@ protected: public: ~RawModelCustom(); - struct Vertex - { - glm::vec3 Position; - glm::vec3 Normal; - glm::vec3 Tangent; - glm::vec3 BiNormal; - glm::vec2 TextureCoords; + struct Vertex + { + glm::vec3 Position; + glm::vec3 Normal; + glm::vec3 Tangent; + glm::vec3 BiNormal; + glm::vec2 TextureCoords; + }; + + struct SkinedVertex : public Vertex { glm::vec4 BoneIndices; glm::vec4 BoneWeights; }; - + struct MaterialGroup { float SpecularExponent; @@ -64,15 +67,33 @@ public: std::shared_ptr<::Texture> IncandescenceMap; }; - std::vector MaterialGroups; + const Vertex* Vertices() const { + if (isSkined) { + return m_SkinedVertices.data(); + } else { + return m_Vertices.data(); + } + }; + + unsigned int NumVertices() const { + if (isSkined) { + return m_SkinedVertices.size(); + } else { + return m_Vertices.size(); + } + }; + + std::vector MaterialGroups; + bool isSkined; - std::vector m_Vertices; std::vector m_Indices; Skeleton* m_Skeleton = nullptr; glm::mat4 m_Matrix; private: + std::vector m_Vertices; + std::vector m_SkinedVertices; void ReadMeshFile(std::string filePath); void ReadMeshFileHeader(unsigned int& offset, char* fileData, unsigned int& fileByteSize); diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index b30ae927..4a9c77a0 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -269,7 +269,8 @@ bool attachAABBComponentFromModel(World* world, EntityID id) glm::vec3 mini = glm::vec3(INFINITY, INFINITY, INFINITY); glm::vec3 maxi = glm::vec3(-INFINITY, -INFINITY, -INFINITY); - for (const auto& v : modelRes->Vertices()) { + for (unsigned int i = 0; i < modelRes->NumberOfVertices(); i++) { + const auto& v = modelRes->Vertices()[i]; const auto& wPos = modelMatrix * glm::vec4(v.Position.x, v.Position.y, v.Position.z, 1); maxi.x = std::max(wPos.x, maxi.x); maxi.y = std::max(wPos.y, maxi.y); diff --git a/src/Engine/Rendering/Model.cpp b/src/Engine/Rendering/Model.cpp index cf4923a3..129b77fa 100644 --- a/src/Engine/Rendering/Model.cpp +++ b/src/Engine/Rendering/Model.cpp @@ -24,7 +24,12 @@ Model::Model(std::string fileName) GLuint buffer; glGenBuffers(1, &buffer); glBindBuffer(GL_ARRAY_BUFFER, buffer); - glBufferData(GL_ARRAY_BUFFER, m_RawModel->m_Vertices.size() * sizeof(RawModel::Vertex), &m_RawModel->m_Vertices[0], GL_STATIC_DRAW); + + if (m_RawModel->isSkined) { + glBufferData(GL_ARRAY_BUFFER, m_RawModel->NumVertices() * sizeof(RawModel::SkinedVertex), m_RawModel->Vertices(), GL_STATIC_DRAW); + } else { + glBufferData(GL_ARRAY_BUFFER, m_RawModel->NumVertices() * sizeof(RawModel::Vertex), m_RawModel->Vertices(), GL_STATIC_DRAW); + } glGenBuffers(1, &ElementBuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ElementBuffer); @@ -35,7 +40,13 @@ Model::Model(std::string fileName) GLERROR("GLEW: BufferFail4"); glBindBuffer(GL_ARRAY_BUFFER, buffer); - std::vector structSizes = { 3, 3, 3, 3, 2, 4, 4 }; + std::vector structSizes; + if (m_RawModel->isSkined) { + structSizes = { 3, 3, 3, 3, 2, 4, 4 }; + } else { + structSizes = { 3, 3, 3, 3, 2 }; + } + int stride = 0; for (int size : structSizes) { stride += size; @@ -49,8 +60,10 @@ Model::Model(std::string fileName) glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++; glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++; glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++; - glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++; - glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++; + if (m_RawModel->isSkined) { + glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++; + glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++; + } } GLERROR("GLEW: BufferFail5"); @@ -59,8 +72,10 @@ Model::Model(std::string fileName) glEnableVertexAttribArray(2); glEnableVertexAttribArray(3); glEnableVertexAttribArray(4); - glEnableVertexAttribArray(5); - glEnableVertexAttribArray(6); + if (m_RawModel->isSkined) { + glEnableVertexAttribArray(5); + glEnableVertexAttribArray(6); + } GLERROR("GLEW: BufferFail5"); //CreateBuffers(); diff --git a/src/Engine/Rendering/RawModelCustom.cpp b/src/Engine/Rendering/RawModelCustom.cpp index 83f6e703..5d3c3fb0 100644 --- a/src/Engine/Rendering/RawModelCustom.cpp +++ b/src/Engine/Rendering/RawModelCustom.cpp @@ -40,7 +40,14 @@ void RawModelCustom::ReadMeshFile(std::string filePath) void RawModelCustom::ReadMeshFileHeader(unsigned int& offset, char* fileData, unsigned int& fileByteSize) { #ifdef BOOST_LITTLE_ENDIAN - m_Vertices.resize(*(unsigned int*)(fileData + offset)); + isSkined = *(unsigned int*)(fileData + offset); + offset += sizeof(bool); + if (isSkined) { + m_SkinedVertices.resize(*(unsigned int*)(fileData + offset)); + } + else { + m_Vertices.resize(*(unsigned int*)(fileData + offset)); + } offset += sizeof(unsigned int); m_Indices.resize(*(unsigned int*)(fileData + offset)); offset += sizeof(unsigned int); @@ -57,12 +64,19 @@ void RawModelCustom::ReadMesh(unsigned int& offset, char* fileData, unsigned int void RawModelCustom::ReadVertices(unsigned int& offset, char* fileData, unsigned int& fileByteSize) { #ifdef BOOST_LITTLE_ENDIAN - if (offset + m_Vertices.size() * sizeof(Vertex) > fileByteSize) { - throw Resource::FailedLoadingException("Reading vertices failed"); - } - - memcpy(&m_Vertices[0], fileData + offset, m_Vertices.size() * sizeof(Vertex)); - offset += m_Vertices.size() * sizeof(Vertex); + if (isSkined) { + if (offset + m_SkinedVertices.size() * sizeof(SkinedVertex) > fileByteSize) { + throw Resource::FailedLoadingException("Reading skined vertices failed"); + } + memcpy(&m_SkinedVertices[0], fileData + offset, m_Vertices.size() * sizeof(SkinedVertex)); + offset += m_SkinedVertices.size() * sizeof(SkinedVertex); + } else { + if (offset + m_Vertices.size() * sizeof(Vertex) > fileByteSize) { + throw Resource::FailedLoadingException("Reading vertices failed"); + } + memcpy(&m_Vertices[0], fileData + offset, m_Vertices.size() * sizeof(Vertex)); + offset += m_Vertices.size() * sizeof(Vertex); + } #else #endif } From affcc5305bc032b27eb3e50ac222144a0820bfc3 Mon Sep 17 00:00:00 2001 From: William Moberg Date: Tue, 2 Feb 2016 17:19:59 +0100 Subject: [PATCH 044/355] Collision affects velocity correctly, no wierd ice cream sliding along walls. --- src/Engine/Collision/Collision.cpp | 48 +++++++++++++++++++----------- 1 file changed, 30 insertions(+), 18 deletions(-) diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index edb6c9a9..81949cb5 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -344,9 +344,10 @@ constexpr float SlopeConstant(float degrees) //An array containing 3 int pairs { 0, 2 }, { 0, 1 }, { 1, 2 } constexpr std::array, 3> dimensionPairs({ std::pair(0, 2), std::pair(0, 1), std::pair(1, 2) }); +//TODO: Prefer to move in y - if the resolution is small enough, value in physics comp. +//TODO: Walking down slopes correctly. bool AABBvsTriangle(const AABB& box, const std::array& triPos, - const glm::vec3& wantDirection, glm::vec3& boxVelocity, glm::vec3& outVector) { @@ -354,7 +355,7 @@ bool AABBvsTriangle(const AABB& box, //Also, don't check a triangle facing away from the player. //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, boxVelocity) > 0) && vectorHasLength(boxVelocity)) { + if (!vectorHasLength(triNormal) || (glm::dot(triNormal, boxVelocity) > 0)) { return false; } @@ -428,40 +429,56 @@ bool AABBvsTriangle(const AABB& box, { //If we get here, the resolution is along one coordinate axis. //set velocity to 0 in that dimension. + //projNorm = glm::vec3(0.f); + //projNorm[resolveCase] = 1; + //ImGui::Text(("Axis " + std::string(projNorm.y > SlopeConstant(45.0f) ? "Ground" : "Slope") + "collision proj=(%f,%f,%f)").c_str(), projNorm.x, projNorm.y, projNorm.z); boxVelocity[resolveCase] = 0.f; return true; } case Line: projNorm = glm::normalize(outVector); + //ImGui::Text(("Line " + std::string(projNorm.y > SlopeConstant(45.0f) ? "Ground" : "Slope") + "collision proj=(%f,%f,%f)").c_str(), projNorm.x, projNorm.y, projNorm.z); break; case Corner: projNorm = triNormal; + //ImGui::Text(("Corner " + std::string(projNorm.y > SlopeConstant(45.0f) ? "Ground" : "Slope") + "collision proj=(%f,%f,%f)").c_str(), projNorm.x, projNorm.y, projNorm.z); break; default: break; } - //Project the velocity onto the normal of the hit line/face. - //w = v - *n, |n|==1. - boxVelocity = boxVelocity - glm::dot(boxVelocity, projNorm) * projNorm; //If the collision was not on steep wall or similarly (e.g. walking on the ground), do special treatment. //Magic value that makes condition correspond to: //if the angle between horizon and the collision surface is less than 45 degrees. if (projNorm.y > SlopeConstant(45.0f)) { - //Make sure the player keeps moving in their desired direction, just slower. - float len = glm::length2(boxVelocity); - if (len > 0.0001f) { - boxVelocity = glm::sqrt(len) * wantDirection; - } - //Ensure that the player always is moved upwards, instead of sliding down. - len = glm::length(outVector); + //Also zero the vertical velocity. + float len = glm::length(outVector); float ang = glm::half_pi() - glm::acos(outVector.y / len); if (len > 0.0000001f && ang > 0.0000001f) { outVector.x = 0; outVector.y = len / glm::sin(ang); outVector.z = 0; + boxVelocity.y = 0.f; } + } else if (projNorm.y > 0) { + //Enter here if the triangle is a steep slope, and it is not facing downwards. + //Project the velocity onto the normal of the hit line/face. + //w = v - *n, |n|==1. + boxVelocity = boxVelocity - glm::dot(boxVelocity, projNorm) * projNorm; + + //Ensure that the player will be pushed in the xz-plane. + //glm::vec3 moveDir(outVector); + //moveDir.y = 0; + //if (vectorHasLength(moveDir)) { + // moveDir = glm::normalize(moveDir); + // float len = glm::length(outVector); + // float dotMoveOut = moveDir.x * outVector.x + moveDir.z * outVector.z; + // float ang = glm::half_pi() - glm::acos(dotMoveOut / len); + // if (len > 0.0000001f && ang > 0.0000001f) { + // outVector = (len / glm::sin(ang)) * moveDir; + // } + //} } return true; } @@ -477,11 +494,6 @@ bool AABBvsTriangles(const AABB& box, AABB newBox = box; outResolutionVector = glm::vec3(0.f); - glm::vec3 wantDirection(boxVelocity); - wantDirection.y = 0; - if (vectorHasLength(wantDirection)) { - wantDirection = glm::normalize(wantDirection); - } for (int i = 0; i < modelIndices.size(); ) { std::array triVertices = { Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix), @@ -489,7 +501,7 @@ bool AABBvsTriangles(const AABB& box, Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix) }; glm::vec3 outVec; - if (AABBvsTriangle(newBox, triVertices, wantDirection, boxVelocity, outVec)) { + if (AABBvsTriangle(newBox, triVertices, boxVelocity, outVec)) { hit = true; outResolutionVector += outVec; newBox = AABB::FromOriginSize(newBox.Origin() + outVec, newBox.Size()); From 9cb41fcebe5a76747b2d468d54bbe8a5ac445c9c Mon Sep 17 00:00:00 2001 From: antc13 Date: Tue, 2 Feb 2016 17:21:51 +0100 Subject: [PATCH 045/355] Fixed the exported animation matrices --- assets | 2 +- tools/MayaExporter/MayaExporter/Skeleton.cpp | 37 +++++++++++++++----- 2 files changed, 29 insertions(+), 10 deletions(-) diff --git a/assets b/assets index 9b2fa74a..c4898d82 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit 9b2fa74a6d535d512c13429997385f7aa3fb50f5 +Subproject commit c4898d8281b5584d89b1caf14dab8e5fac120321 diff --git a/tools/MayaExporter/MayaExporter/Skeleton.cpp b/tools/MayaExporter/MayaExporter/Skeleton.cpp index a6ee5897..f44b9306 100644 --- a/tools/MayaExporter/MayaExporter/Skeleton.cpp +++ b/tools/MayaExporter/MayaExporter/Skeleton.cpp @@ -216,7 +216,7 @@ Animation Skeleton::GetAnimData(std::string animationName, int startFrame, int e int currentFrame = startFrame; - while (currentFrame <= endFrame) { // ANDREAS + while (currentFrame < endFrame) { // ANDREAS Animation::Keyframe thisKeyFrame; thisKeyFrame.Index = currentFrame - startFrame; thisKeyFrame.Time = thisKeyFrame.Index * oneDivSixty; @@ -280,13 +280,32 @@ Animation Skeleton::GetAnimData(std::string animationName, int startFrame, int e joinCheckMap[thisJoint.name().asChar()][3][2] = doubleMat[3][2]; joinCheckMap[thisJoint.name().asChar()][3][3] = doubleMat[3][3]; - MTransformationMatrix Matrix = thisJoint.transformation(); - MPlug BindPose = thisJoint.findPlug("bindPose"); + MPlug thisJointBindPose = thisJoint.findPlug("bindPose"); MDataHandle DataHandle; - BindPose.getValue(DataHandle); + thisJointBindPose.getValue(DataHandle); MFnMatrixData MartixFn(DataHandle.data()); - MMatrix BindPoseMatrix = MartixFn.matrix(); - Matrix = Matrix.asMatrix(); + MMatrix thisJointBindPoseMatrix = MartixFn.matrix(); + + MFnTransform Parent(thisJoint.parent(0), &status); + if (status == MS::kSuccess && thisJoint.parent(0).apiType() == MFn::kJoint) { + MTransformationMatrix Matrix = Parent.transformation(); + MPlug parentBindPose = Parent.findPlug("bindPose"); + MDataHandle DataHandle; + parentBindPose.getValue(DataHandle); + MFnMatrixData MartixFn(DataHandle.data()); + MMatrix parentBindPoseMatrix = MartixFn.matrix(); + + thisJointBindPoseMatrix = thisJointBindPoseMatrix * parentBindPoseMatrix.inverse(); + } + + MTransformationMatrix TransformationMatrix = thisJoint.transformation(); + + if (thisJointBindPoseMatrix.isEquivalent(TransformationMatrix.asMatrix())) { + jointID++; + jointIt.next(); + MGlobal::displayError(MString() + thisJoint.name() + " is in bindPose"); + continue; + } MObject jointOrientObj = thisJoint.attribute("jointOrient"); MFnNumericAttribute jointOrient(jointOrientObj); @@ -302,7 +321,7 @@ Animation Skeleton::GetAnimData(std::string animationName, int startFrame, int e MQuaternion jo = joEuler.asQuaternion(); double tmp[4]; - Matrix.getRotationQuaternion(tmp[0], tmp[1], tmp[2], tmp[3]); + TransformationMatrix.getRotationQuaternion(tmp[0], tmp[1], tmp[2], tmp[3]); MQuaternion rotation(tmp); rotation = rotation * jo; @@ -315,11 +334,11 @@ Animation Skeleton::GetAnimData(std::string animationName, int startFrame, int e joint.Rotation[1] = tmp[1]; joint.Rotation[2] = tmp[2]; joint.Rotation[3] = tmp[3]; - Matrix.getTranslation(MSpace::kTransform).get(tmp); + TransformationMatrix.getTranslation(MSpace::kTransform).get(tmp); joint.Position[0] = tmp[0]; joint.Position[1] = tmp[1]; joint.Position[2] = tmp[2]; - Matrix.getScale(tmp, MSpace::kTransform); + TransformationMatrix.getScale(tmp, MSpace::kTransform); joint.Scale[0] = tmp[0]; joint.Scale[1] = tmp[1]; joint.Scale[2] = tmp[2]; From 214dad2afc23be62a5fee10e71374667daa32830 Mon Sep 17 00:00:00 2001 From: William Moberg Date: Tue, 2 Feb 2016 17:25:59 +0100 Subject: [PATCH 046/355] Removed commented code. --- src/Engine/Collision/Collision.cpp | 18 ------------------ 1 file changed, 18 deletions(-) diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index 81949cb5..083af229 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -429,19 +429,14 @@ bool AABBvsTriangle(const AABB& box, { //If we get here, the resolution is along one coordinate axis. //set velocity to 0 in that dimension. - //projNorm = glm::vec3(0.f); - //projNorm[resolveCase] = 1; - //ImGui::Text(("Axis " + std::string(projNorm.y > SlopeConstant(45.0f) ? "Ground" : "Slope") + "collision proj=(%f,%f,%f)").c_str(), projNorm.x, projNorm.y, projNorm.z); boxVelocity[resolveCase] = 0.f; return true; } case Line: projNorm = glm::normalize(outVector); - //ImGui::Text(("Line " + std::string(projNorm.y > SlopeConstant(45.0f) ? "Ground" : "Slope") + "collision proj=(%f,%f,%f)").c_str(), projNorm.x, projNorm.y, projNorm.z); break; case Corner: projNorm = triNormal; - //ImGui::Text(("Corner " + std::string(projNorm.y > SlopeConstant(45.0f) ? "Ground" : "Slope") + "collision proj=(%f,%f,%f)").c_str(), projNorm.x, projNorm.y, projNorm.z); break; default: break; @@ -466,19 +461,6 @@ bool AABBvsTriangle(const AABB& box, //Project the velocity onto the normal of the hit line/face. //w = v - *n, |n|==1. boxVelocity = boxVelocity - glm::dot(boxVelocity, projNorm) * projNorm; - - //Ensure that the player will be pushed in the xz-plane. - //glm::vec3 moveDir(outVector); - //moveDir.y = 0; - //if (vectorHasLength(moveDir)) { - // moveDir = glm::normalize(moveDir); - // float len = glm::length(outVector); - // float dotMoveOut = moveDir.x * outVector.x + moveDir.z * outVector.z; - // float ang = glm::half_pi() - glm::acos(dotMoveOut / len); - // if (len > 0.0000001f && ang > 0.0000001f) { - // outVector = (len / glm::sin(ang)) * moveDir; - // } - //} } return true; } From da49dc35eef8bf1da4bc6625923006e7dda59bea Mon Sep 17 00:00:00 2001 From: Teejoon Date: Tue, 2 Feb 2016 17:31:19 +0100 Subject: [PATCH 047/355] Added stuff to .gitignore file --- .gitignore | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitignore b/.gitignore index 0df2db42..23056510 100755 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,6 @@ tools/MayaExporter/x64/Debug/ tools/MayaExporter/MayaExporter/Debug/ tools/MayaExporter/MayaExporter/GeneratedFiles/ + +tools/MayaExporter/MayaExporter/x64/* +tools/MayaExporter/x64/* From a64d227cab6889e127f97d2022776176ce228d2f Mon Sep 17 00:00:00 2001 From: stiffly Date: Wed, 3 Feb 2016 10:17:53 +0100 Subject: [PATCH 048/355] Assured the volume channels were working. Playing around with drumloop --- assets | 2 +- include/Engine/Sound/SoundSystem.h | 13 ++++++--- src/Engine/Sound/SoundSystem.cpp | 42 +++++++++++++++++++++++------- 3 files changed, 43 insertions(+), 14 deletions(-) diff --git a/assets b/assets index 5bf03ccd..cde9a430 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit 5bf03ccd54bed358d525840635573f931adf584e +Subproject commit cde9a43029fe674a01ede2b74a1987cd57f1074a diff --git a/include/Engine/Sound/SoundSystem.h b/include/Engine/Sound/SoundSystem.h index e161af77..9e636c95 100644 --- a/include/Engine/Sound/SoundSystem.h +++ b/include/Engine/Sound/SoundSystem.h @@ -9,6 +9,8 @@ #include "OpenAL/al.h" #include "OpenAL/alc.h" +#include "imgui/imgui.h" + #include "Core/World.h" #include "Core/EventBroker.h" #include "Core/Transform.h" // Absolute transform @@ -29,6 +31,7 @@ #include "Core/EPlayerDeath.h" #include "Core/EPlayerHealthPickup.h" #include "Core/EComponentAttached.h" +#include "Collision/ETrigger.h" enum class SoundType { SFX, @@ -90,8 +93,11 @@ private: World* m_World = nullptr; EventBroker* m_EventBroker = nullptr; std::unordered_map m_Sources; - float m_BGMVolumeChannel = 1.f; - float m_SFXVolumeChannel = 1.f; + + + + float m_BGMVolumeChannel = 1.0f; + float m_SFXVolumeChannel = 1.0f; bool m_EditorEnabled = false; const double m_PlayerFootstepInterval = 1.0; double m_TimeSinceLastFootstep = 0; @@ -117,7 +123,6 @@ private: bool OnSetBGMGain(const Events::SetBGMGain &e); // Not tested EventRelay m_ESetSFXGain; bool OnSetSFXGain(const Events::SetSFXGain &e); // Not tested - EventRelay m_EShoot; bool OnShoot(const Events::Shoot &e); EventRelay m_EPlayerSpawned; @@ -134,6 +139,8 @@ private: bool OnPlayerHealthPickup(const Events::PlayerHealthPickup &e); EventRelay m_EComponentAttached; bool OnComponentAttached(const Events::ComponentAttached &e); + EventRelay m_ETriggerTouch; + bool OnTriggerTouch(const Events::TriggerTouch &e); diff --git a/src/Engine/Sound/SoundSystem.cpp b/src/Engine/Sound/SoundSystem.cpp index e5684ac3..08e5c0a8 100644 --- a/src/Engine/Sound/SoundSystem.cpp +++ b/src/Engine/Sound/SoundSystem.cpp @@ -25,6 +25,7 @@ SoundSystem::SoundSystem(World* world, EventBroker* eventBroker, bool editorMode EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &SoundSystem::OnPlayerDamage); EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &SoundSystem::OnInputCommand); EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &SoundSystem::OnCaptured); + EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &SoundSystem::OnTriggerTouch); } SoundSystem::~SoundSystem() @@ -60,6 +61,10 @@ void SoundSystem::Update(double dt) deleteInactiveEmitters(); // can be optimized with "EEntityDeleted" updateEmitters(dt); updateListener(dt); + + // Editor debug info + ImGui::SliderFloat("BGM", &m_BGMVolumeChannel, 0.0f, 1.0f, "%.3f", 1.0f); + ImGui::SliderFloat("SFX", &m_SFXVolumeChannel, 0.0f, 1.0f, "%.3f", 1.0f); } void SoundSystem::deleteInactiveEmitters() @@ -287,11 +292,12 @@ bool SoundSystem::OnPlayBackgroundMusic(const Events::PlayBackgroundMusic & e) for (auto it = listenerComponents->begin(); it != listenerComponents->end(); it++) { auto emitterChild = m_World->CreateEntity((*it).EntityID); auto emitter = m_World->AttachComponent(emitterChild, "SoundEmitter"); - (bool&)emitter["Loop"] = true; + (bool&)emitter["Loop"] = false; (std::string&)emitter["FilePath"] = e.FilePath; m_World->AttachComponent(emitterChild, "Transform"); Source* source = createSource(e.FilePath); source->Type = SoundType::BGM; + setSoundProperties(source, &emitter); m_Sources[emitterChild] = source; playSound(source); } @@ -334,6 +340,12 @@ bool SoundSystem::OnPlayerSpawned(const Events::PlayerSpawned & e) event.EmitterID = child; event.FilePath = "Audio/announcer/go.wav"; m_EventBroker->Publish(event); + // TEMP: starts bgm + { + Events::PlayBackgroundMusic ev; + ev.FilePath = "Audio/bgm/ambient.wav"; + m_EventBroker->Publish(ev); + } } return true; } @@ -384,15 +396,15 @@ bool SoundSystem::OnCaptured(const Events::Captured & e) bool SoundSystem::OnPlayerDamage(const Events::PlayerDamage & e) { //if (e.Player.ID == m_LocalPlayer) { - Events::PlaySoundOnEntity ev; - EntityID child = m_World->CreateEntity(m_LocalPlayer); - m_World->AttachComponent(child, "Transform"); - m_World->AttachComponent(child, "SoundEmitter"); - ev.EmitterID = child; - std::uniform_int_distribution dist(1, 12); - int rand = dist(generator); - ev.FilePath = "Audio/hurt/hurt" + std::to_string(rand) + ".wav"; - m_EventBroker->Publish(ev); + Events::PlaySoundOnEntity ev; + EntityID child = m_World->CreateEntity(m_LocalPlayer); + m_World->AttachComponent(child, "Transform"); + m_World->AttachComponent(child, "SoundEmitter"); + ev.EmitterID = child; + std::uniform_int_distribution dist(1, 12); + int rand = dist(generator); + ev.FilePath = "Audio/hurt/hurt" + std::to_string(rand) + ".wav"; + m_EventBroker->Publish(ev); //} return false; } @@ -433,6 +445,16 @@ bool SoundSystem::OnComponentAttached(const Events::ComponentAttached & e) return false; } +bool SoundSystem::OnTriggerTouch(const Events::TriggerTouch & e) +{ + if (m_World->HasComponent(e.Trigger.ID, "CapturePoint")) { + Events::PlayBackgroundMusic ev; + ev.FilePath = "Audio/bgm/drumstest.wav"; + m_EventBroker->Publish(ev); + } + return false; +} + void SoundSystem::setListenerOri(glm::vec3 ori) { // Calculate forward and up vector. From e133791369e565c954b0aa690708d1838b211630 Mon Sep 17 00:00:00 2001 From: Jocke Date: Wed, 3 Feb 2016 10:28:15 +0100 Subject: [PATCH 049/355] WIP Reliable Message --- include/Engine/Network/Client.h | 2 +- include/Engine/Network/HybridClient.h | 14 ++++++++++++++ include/Engine/Network/TCPClient.h | 7 +++++++ include/Game/Game.h | 2 +- src/Engine/Network/HybridClient.cpp | 12 ++++++++++++ src/Engine/Network/Server.cpp | 2 +- src/Engine/Network/TCPClient.cpp | 0 src/Game/Game.cpp | 2 +- src/Tests/CollisionTest.cpp | 2 +- src/Tests/HealthSystemTest.cpp | 4 ++-- 10 files changed, 40 insertions(+), 7 deletions(-) create mode 100644 include/Engine/Network/HybridClient.h create mode 100644 include/Engine/Network/TCPClient.h create mode 100644 src/Engine/Network/HybridClient.cpp create mode 100644 src/Engine/Network/TCPClient.cpp diff --git a/include/Engine/Network/Client.h b/include/Engine/Network/Client.h index 4f1baa67..4397dd41 100644 --- a/include/Engine/Network/Client.h +++ b/include/Engine/Network/Client.h @@ -29,7 +29,7 @@ public: ~Client(); void Start(World* world, EventBroker* eventBroker) override; void Update() override; -private: +protected: // Assio UDP logic boost::asio::ip::udp::endpoint m_ReceiverEndpoint; boost::asio::io_service m_IOService; diff --git a/include/Engine/Network/HybridClient.h b/include/Engine/Network/HybridClient.h new file mode 100644 index 00000000..7573ad87 --- /dev/null +++ b/include/Engine/Network/HybridClient.h @@ -0,0 +1,14 @@ +#ifndef HybridClient_h__ +#define HybridClient_h__ + +#include "Client.h" + + +class HybridClient : public Client +{ +public: + HybridClient(ConfigFile* config); + ~HybridClient(); +}; + +#endif \ No newline at end of file diff --git a/include/Engine/Network/TCPClient.h b/include/Engine/Network/TCPClient.h new file mode 100644 index 00000000..d342641b --- /dev/null +++ b/include/Engine/Network/TCPClient.h @@ -0,0 +1,7 @@ +#ifndef TCPClient_h__ +#define TCPClient_h__ + + + + +#endif \ No newline at end of file diff --git a/include/Game/Game.h b/include/Game/Game.h index fab10a49..ccca080e 100644 --- a/include/Game/Game.h +++ b/include/Game/Game.h @@ -25,7 +25,7 @@ #include #include "Network/Network.h" #include "Network/Server.h" -#include "Network/Client.h" +#include "Network/HybridClient.h" // Sound #include "Sound/SoundSystem.h" diff --git a/src/Engine/Network/HybridClient.cpp b/src/Engine/Network/HybridClient.cpp new file mode 100644 index 00000000..798ff578 --- /dev/null +++ b/src/Engine/Network/HybridClient.cpp @@ -0,0 +1,12 @@ +#include "Network/HybridClient.h" + + +HybridClient::HybridClient(ConfigFile * config) : Client(config) +{ + +} + +HybridClient::~HybridClient() +{ + +} diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index 30676d80..a94acd39 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -271,7 +271,7 @@ void Server::parseOnInputCommand(Packet& packet) e.PlayerID = player; // Set correct player id e.Value = packet.ReadPrimitive(); m_EventBroker->Publish(e); - //LOG_INFO("Server::parseOnInputCommand: Command is %s. Value is %f. PlayerID is %i.", e.Command.c_str(), e.Value, e.PlayerID); + LOG_INFO("Server::parseOnInputCommand: Command is %s. Value is %f. PlayerID is %i.", e.Command.c_str(), e.Value, e.PlayerID); } } } diff --git a/src/Engine/Network/TCPClient.cpp b/src/Engine/Network/TCPClient.cpp new file mode 100644 index 00000000..e69de29b diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index ef51aca6..7ce66710 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -169,7 +169,7 @@ void Game::networkFunction() bool isServer = m_Config->Get("Networking.IsServer", false); if (!isServer) { m_IsClientOrServer = true; - m_ClientOrServer = new Client(m_Config); + m_ClientOrServer = new HybridClient(m_Config); } if (isServer) { m_IsClientOrServer = true; diff --git a/src/Tests/CollisionTest.cpp b/src/Tests/CollisionTest.cpp index 67b6ce19..6cb6c88b 100644 --- a/src/Tests/CollisionTest.cpp +++ b/src/Tests/CollisionTest.cpp @@ -29,7 +29,7 @@ void RayTest(std::string fileName) { Ray ray(glm::vec3(-50, 0, 0), glm::vec3(1, 0, 0)); //using a - here, else we have to init the renderingsystem + //here, else we have to init the renderingsystem ResourceManager::RegisterType("RawModel"); auto unitBox = ResourceManager::Load(fileName); BOOST_REQUIRE(unitBox != nullptr); diff --git a/src/Tests/HealthSystemTest.cpp b/src/Tests/HealthSystemTest.cpp index bdd9ba4b..6540c0e3 100644 --- a/src/Tests/HealthSystemTest.cpp +++ b/src/Tests/HealthSystemTest.cpp @@ -69,8 +69,8 @@ GameHealthSystemTest::GameHealthSystemTest() m_EventBroker->Publish(e3); //damage player with 50 Events::PlayerDamage e; - e.DamageAmount = 50.0f; - e.PlayerDamagedID = healthsID; + // e.DamageAmount = 50.0f; +// e.PlayerDamagedID = healthsID; m_EventBroker->Publish(e); //heal some other player with 40 Events::PlayerHealthPickup e2; From 455e59a04f01b71e0317a83447fdb7f9d970ab38 Mon Sep 17 00:00:00 2001 From: Tleety Date: Wed, 3 Feb 2016 11:39:18 +0100 Subject: [PATCH 050/355] Made the TEMPORARY capture point boxes transparent. --- src/Game/Systems/CapturePointSystem.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Game/Systems/CapturePointSystem.cpp b/src/Game/Systems/CapturePointSystem.cpp index d26dde5f..a943e234 100644 --- a/src/Game/Systems/CapturePointSystem.cpp +++ b/src/Game/Systems/CapturePointSystem.cpp @@ -57,7 +57,7 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp int blueTeamPlayersStandingInside = 0; if (capturePointEntity.HasComponent("Model")) { //Now sets team color to the capturepoint, or white if it is uncaptured. - capturePointEntity["Model"]["Color"] = ownedBy == blueTeam ? glm::vec4(0, 0.2f, 1, 1) : ownedBy == redTeam ? glm::vec4(1, 0.2f, 0, 1) : glm::vec4(1, 1, 1, 1); + capturePointEntity["Model"]["Color"] = ownedBy == blueTeam ? glm::vec4(0, 0.2f, 1, 0.3) : ownedBy == redTeam ? glm::vec4(1, 0.2f, 0, 0.3) : glm::vec4(1, 1, 1, 0.3); } //calculate next possible capturePoint for both teams @@ -106,10 +106,10 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp //colorize next possible capturepoint if (nextPossibleCapturePoint["Red"] == capturePointNumber) { - capturePointEntity["Model"]["Color"] = glm::vec4(1, 1, 0, 1); + capturePointEntity["Model"]["Color"] = glm::vec4(1, 1, 0, 0.3); } if (nextPossibleCapturePoint["Blue"] == capturePointNumber) { - capturePointEntity["Model"]["Color"] = glm::vec4(0, 1, 1, 1); + capturePointEntity["Model"]["Color"] = glm::vec4(0, 1, 1, 0.3); } //check how many players are standing inside and are healthy From 2961f198b3e71546405343e34f7fa0e4a7175b4c Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Wed, 3 Feb 2016 11:48:22 +0100 Subject: [PATCH 051/355] PlayerDeathSystem is now working well. Changed so the model is oriented correctly. Changed so camera is behind the player. Copied the current animation and froze it. --- .../PlayerDeathExplosionWithCamera.xml | 5 ++- src/Game/Systems/PlayerDeathSystem.cpp | 37 ++++++++++--------- 2 files changed, 22 insertions(+), 20 deletions(-) diff --git a/resources/Schema/Entities/PlayerDeathExplosionWithCamera.xml b/resources/Schema/Entities/PlayerDeathExplosionWithCamera.xml index bdebbfe7..ff33476d 100644 --- a/resources/Schema/Entities/PlayerDeathExplosionWithCamera.xml +++ b/resources/Schema/Entities/PlayerDeathExplosionWithCamera.xml @@ -8,12 +8,13 @@ 0 - 8 + 4 0 - 8 + 4 + Models/AssaultAnimated.mesh diff --git a/src/Game/Systems/PlayerDeathSystem.cpp b/src/Game/Systems/PlayerDeathSystem.cpp index d57caefc..d6680928 100644 --- a/src/Game/Systems/PlayerDeathSystem.cpp +++ b/src/Game/Systems/PlayerDeathSystem.cpp @@ -43,38 +43,39 @@ void PlayerDeathSystem::Update(double dt) bool PlayerDeathSystem::OnPlayerDeath(Events::PlayerDeath& e) { - //LOAD THE XML + //load the explosioneffect XML auto deathEffect = ResourceManager::Load("Schema/Entities/PlayerDeathExplosionWithCamera.xml"); EntityFileParser parser(deathEffect); EntityID deathEffectID = parser.MergeEntities(m_World); EntityWrapper deathEffectEW = EntityWrapper(m_World, deathEffectID); - - //current components for player that we need - auto playerModelEW = e.Player.FirstChildByName("PlayerModel"); - auto playerEntityModel = playerModelEW["Model"]; - auto playerEntityTransform = playerModelEW["Transform"]; - //copy the data from player to new playermodel + //components that we need from player + auto playerCamera = e.Player.FirstChildByName("Camera"); + auto playerEntityModel = e.Player.FirstChildByName("PlayerModel")["Model"]; + auto playerEntityAnimation = e.Player.FirstChildByName("PlayerModel")["Animation"]; + + //copy the data from player to explisioneffectmodel playerEntityModel.Copy(deathEffectEW["Model"]); - playerEntityTransform.Copy(deathEffectEW["Transform"]); + playerEntityAnimation.Copy(deathEffectEW["Animation"]); + //freeze the animation + deathEffectEW["Animation"]["Speed"] = 0.0; - //change the animation speed and make sure the explosioneffect spawns at the players position - //http://www.opengl-tutorial.org/intermediate-tutorials/tutorial-17-quaternions/ - auto playerPosition = (glm::vec3)e.Player["Transform"]["Position"]; - deathEffectEW["Transform"]["Position"] = playerPosition; - deathEffectEW["ExplosionEffect"]["ExplosionOrigin"] = playerPosition; + //copy the models position,orientation + deathEffectEW["Transform"]["Position"] = (glm::vec3)e.Player["Transform"]["Position"]; + deathEffectEW["Transform"]["Orientation"] = (glm::vec3)e.Player["Transform"]["Orientation"]; + //effect,camera is relative to playersPosition + deathEffectEW["ExplosionEffect"]["ExplosionOrigin"] = glm::vec3(0, 0, 0); - //camera (with lifetime) slightly above the player and looking down at the player - //camera will be positioned just above the player - glm::vec3 cameraPosition = glm::vec3(0, 10, 0); + //camera (with lifetime) behind the player auto cam = deathEffectEW.FirstChildByName("Camera"); - cam["Transform"]["Position"] = cameraPosition; + cam["Transform"]["Position"] = glm::vec3(0, 2.5f, 1.8f); + cam["Transform"]["Orientation"] = glm::vec3(5.655f, 0, 0); Events::SetCamera eSetCamera; eSetCamera.CameraEntity = cam; m_EventBroker->Publish(eSetCamera); - //on deathanim done -> del entity + //done -> del entity m_World->DeleteEntity(e.Player.ID); return true; } From 9d3171540df1d0acd04174a564459ab13b4ae4b6 Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Wed, 3 Feb 2016 11:54:14 +0100 Subject: [PATCH 052/355] AssaultDashCheck is now in FirstPersonInputController instead. TODO: config option, shift button, forward/backward dash --- .../Engine/Input/FirstPersonInputController.h | 62 +++++++++++++++++++ include/Game/Systems/PlayerMovementSystem.h | 15 ----- src/Game/Systems/PlayerMovementSystem.cpp | 44 +------------ 3 files changed, 65 insertions(+), 56 deletions(-) diff --git a/include/Engine/Input/FirstPersonInputController.h b/include/Engine/Input/FirstPersonInputController.h index d4c9071c..1efe4b75 100644 --- a/include/Engine/Input/FirstPersonInputController.h +++ b/include/Engine/Input/FirstPersonInputController.h @@ -25,6 +25,10 @@ public: virtual bool OnCommand(const Events::InputCommand& e) override; virtual void Reset(); + void AssaultDashCheck(double dt, bool isJumping); + virtual bool AssaultDashDoubleTapped() const { return m_AssaultDashDoubleTapped; } + virtual bool PlayerIsDashing() const { return m_PlayerIsDashing; } + protected: const int m_PlayerID; bool m_MouseLocked = false; @@ -33,6 +37,23 @@ protected: bool m_Jumping = false; bool m_DoubleJumping = false; bool m_Crouching = false; + //assault dash enum + enum class AssaultDashDirection { + Left, + Right, + Forward, + Backward, + None + }; + //assault dash membervariables + double m_AssaultDashDoubleTapDeltaTime = 0.0f; + double m_AssaultDashCoolDownTimer = 0.0f; + double m_AssaultDashCoolDownMaxTimer = 3.0f; + AssaultDashDirection m_AssaultDashDoubleTapLastKey = AssaultDashDirection::None; + const float m_AssaultDashDoubleTapSensitivityTimer = 0.25f; + AssaultDashDirection m_AssaultDashTapDirection = AssaultDashDirection::None; + bool m_AssaultDashDoubleTapped = false; + bool m_PlayerIsDashing = false; EventRelay m_ELockMouse; bool OnLockMouse(const Events::LockMouse& e); @@ -129,4 +150,45 @@ bool FirstPersonInputController::OnLockMouse(const Events::LockMou return true; } +template +void FirstPersonInputController::AssaultDashCheck(double dt, bool isJumping) { + auto controllerMovement = Movement(); + m_AssaultDashDoubleTapDeltaTime += dt; + m_AssaultDashCoolDownTimer -= dt; + //cooldown = m_AssaultDashCoolDownMaxTimer sec, pretend the dash lasts 0.25 sec (for friction to do its work) + if (m_AssaultDashCoolDownTimer > (m_AssaultDashCoolDownMaxTimer - 0.25f)) { + m_PlayerIsDashing = true; + } else { + m_PlayerIsDashing = false; + } + //reset the DoubleTapped state in case we recently doubleTapped + if (m_AssaultDashDoubleTapped) { + m_AssaultDashDoubleTapped = false; + } + //Assault Dash logic: tap left or right twice within 0.5sec to activate the doubletap-dash + if (controllerMovement.x > 0 && controllerMovement.y == 0.f && controllerMovement.z == 0.f) { + if (m_AssaultDashDoubleTapLastKey != AssaultDashDirection::Right && m_AssaultDashDoubleTapDeltaTime < m_AssaultDashDoubleTapSensitivityTimer + && m_AssaultDashTapDirection == AssaultDashDirection::Right && m_AssaultDashCoolDownTimer <= 0.0f && !isJumping) { + m_AssaultDashDoubleTapped = true; + m_AssaultDashDoubleTapDeltaTime = 0.f; + m_AssaultDashCoolDownTimer = m_AssaultDashCoolDownMaxTimer; + } + m_AssaultDashDoubleTapLastKey = AssaultDashDirection::Right; + m_AssaultDashDoubleTapDeltaTime = 0.f; + m_AssaultDashTapDirection = AssaultDashDirection::Right; + } else if (controllerMovement.x < 0 && controllerMovement.y == 0.f && controllerMovement.z == 0.f) { + if (m_AssaultDashDoubleTapLastKey != AssaultDashDirection::Left && m_AssaultDashDoubleTapDeltaTime < m_AssaultDashDoubleTapSensitivityTimer + && m_AssaultDashTapDirection == AssaultDashDirection::Left && m_AssaultDashCoolDownTimer <= 0.0f && !isJumping) { + m_AssaultDashDoubleTapped = true; + m_AssaultDashDoubleTapDeltaTime = 0.f; + m_AssaultDashCoolDownTimer = m_AssaultDashCoolDownMaxTimer; + } + m_AssaultDashDoubleTapLastKey = AssaultDashDirection::Left; + m_AssaultDashDoubleTapDeltaTime = 0.f; + m_AssaultDashTapDirection = AssaultDashDirection::Left; + } else { + m_AssaultDashDoubleTapLastKey = AssaultDashDirection::None; + } +} + #endif \ No newline at end of file diff --git a/include/Game/Systems/PlayerMovementSystem.h b/include/Game/Systems/PlayerMovementSystem.h index 554d174e..34862e90 100644 --- a/include/Game/Systems/PlayerMovementSystem.h +++ b/include/Game/Systems/PlayerMovementSystem.h @@ -21,19 +21,4 @@ private: EventRelay m_EPlayerSpawned; bool OnPlayerSpawned(Events::PlayerSpawned& e); - double m_AssaultDashDoubleTapDeltaTime = 0.0f; - double m_AssaultDashCoolDownTimer = 0.0f; - double m_AssaultDashCoolDownMaxTimer = 3.0f; - ImGuiKey m_AssaultDashDoubleTapLastKey = ImGuiKey_Escape; - const float m_AssaultDashDoubleTapSensitivityTimer = 0.25f; - enum class AssaultDashDirection { - Left, - Right, - None - }; - AssaultDashDirection m_AssaultDashTapDirection = AssaultDashDirection::None; - bool m_AssaultDashDoubleTapped = false; - bool m_PlayerIsDashing = false; - - void assaultDashCheck(glm::vec3 controllerMovement, double dt, bool isJumping); }; \ No newline at end of file diff --git a/src/Game/Systems/PlayerMovementSystem.cpp b/src/Game/Systems/PlayerMovementSystem.cpp index c3eb1c84..70bbafb0 100644 --- a/src/Game/Systems/PlayerMovementSystem.cpp +++ b/src/Game/Systems/PlayerMovementSystem.cpp @@ -43,7 +43,7 @@ void PlayerMovementSystem::Update(double dt) ComponentWrapper cPhysics = player["Physics"]; //Assault Dash Check - //TODO: check if playerclass is assault! - assaultDashCheck(controller->Movement(), dt, ((glm::vec3)cPhysics["Velocity"]).y != 0.0f); + controller->AssaultDashCheck(dt, ((glm::vec3)cPhysics["Velocity"]).y != 0.0f); glm::vec3 wishDirection = controller->Movement() * glm::inverse(glm::quat(ori)); float wishSpeed; if (controller->Crouching()) { @@ -74,14 +74,14 @@ void PlayerMovementSystem::Update(double dt) ImGui::InputFloat("surfaceFriction", &surfaceFriction); float accelerationSpeed = actualAccel * (float)dt * wishSpeed * surfaceFriction; //if doubleTapped do Assault Dash - but only boost maximum 50.0f - float doubleTapDashBoost = m_AssaultDashDoubleTapped ? 20.0f : 1.0f; + float doubleTapDashBoost = controller->AssaultDashDoubleTapped() ? 20.0f : 1.0f; accelerationSpeed = glm::min(doubleTapDashBoost*glm::min(accelerationSpeed, addSpeed), 50.0f); velocity += accelerationSpeed * wishDirection; ImGui::Text("velocity: (%f, %f, %f) |%f|", velocity.x, velocity.y, velocity.z, glm::length(velocity)); } //you cant jump and dash at the same time - since there is no friction in the air and we would thus dash much further in the air - if (!m_PlayerIsDashing && controller->Jumping() && !controller->Crouching() && (velocity.y == 0.f || !controller->DoubleJumping())) { + if (!controller->PlayerIsDashing() && controller->Jumping() && !controller->Crouching() && (velocity.y == 0.f || !controller->DoubleJumping())) { if (velocity.y == 0.f) { controller->SetDoubleJumping(false); } @@ -170,41 +170,3 @@ bool PlayerMovementSystem::OnPlayerSpawned(Events::PlayerSpawned& e) return true; } -void PlayerMovementSystem::assaultDashCheck(glm::vec3 controllerMovement, double dt, bool isJumping) { - m_AssaultDashDoubleTapDeltaTime += dt; - m_AssaultDashCoolDownTimer -= dt; - //cooldown = m_AssaultDashCoolDownMaxTimer sec, pretend the dash lasts 0.25 sec (for friction to do its work) - if (m_AssaultDashCoolDownTimer > (m_AssaultDashCoolDownMaxTimer - 0.25f)) { - m_PlayerIsDashing = true; - } else { - m_PlayerIsDashing = false; - } - //reset the DoubleTapped state in case we recently doubleTapped - if (m_AssaultDashDoubleTapped) { - m_AssaultDashDoubleTapped = false; - } - //Assault Dash logic: tap left or right twice within 0.5sec to activate the doubletap-dash - if (controllerMovement.x > 0 && controllerMovement.y == 0.f && controllerMovement.z == 0.f) { - if (m_AssaultDashDoubleTapLastKey != ImGuiKey_RightArrow && m_AssaultDashDoubleTapDeltaTime < m_AssaultDashDoubleTapSensitivityTimer - && m_AssaultDashTapDirection == AssaultDashDirection::Right && m_AssaultDashCoolDownTimer <= 0.0f && !isJumping) { - m_AssaultDashDoubleTapped = true; - m_AssaultDashDoubleTapDeltaTime = 0.f; - m_AssaultDashCoolDownTimer = m_AssaultDashCoolDownMaxTimer; - } - m_AssaultDashDoubleTapLastKey = ImGuiKey_RightArrow; - m_AssaultDashDoubleTapDeltaTime = 0.f; - m_AssaultDashTapDirection = AssaultDashDirection::Right; - } else if (controllerMovement.x < 0 && controllerMovement.y == 0.f && controllerMovement.z == 0.f) { - if (m_AssaultDashDoubleTapLastKey != ImGuiKey_LeftArrow && m_AssaultDashDoubleTapDeltaTime < m_AssaultDashDoubleTapSensitivityTimer - && m_AssaultDashTapDirection == AssaultDashDirection::Left && m_AssaultDashCoolDownTimer <= 0.0f && !isJumping) { - m_AssaultDashDoubleTapped = true; - m_AssaultDashDoubleTapDeltaTime = 0.f; - m_AssaultDashCoolDownTimer = m_AssaultDashCoolDownMaxTimer; - } - m_AssaultDashDoubleTapLastKey = ImGuiKey_LeftArrow; - m_AssaultDashDoubleTapDeltaTime = 0.f; - m_AssaultDashTapDirection = AssaultDashDirection::Left; - } else { - m_AssaultDashDoubleTapLastKey = ImGuiKey_Escape; - } -} From 7bae2d08730c646aad8e2813aaa080885ac9e441 Mon Sep 17 00:00:00 2001 From: Tleety Date: Wed, 3 Feb 2016 11:58:06 +0100 Subject: [PATCH 053/355] Added a ShieldComponent and a test area in QA map for defender shield --- include/Engine/Rendering/DrawFinalPass.h | 1 + resources/Schema/Components.xsd | 1 + .../Schema/Components/ShieldComponent.xml | 3 + .../Schema/Components/ShieldComponent.xsd | 7 + .../Schema/Entities/QualityAssurance.xml | 309 ++++++++++++++++-- 5 files changed, 302 insertions(+), 19 deletions(-) create mode 100644 resources/Schema/Components/ShieldComponent.xml create mode 100644 resources/Schema/Components/ShieldComponent.xsd diff --git a/include/Engine/Rendering/DrawFinalPass.h b/include/Engine/Rendering/DrawFinalPass.h index 74f505fe..4b2bcf1f 100644 --- a/include/Engine/Rendering/DrawFinalPass.h +++ b/include/Engine/Rendering/DrawFinalPass.h @@ -30,6 +30,7 @@ public: private: void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const; void GenerateMipMapTexture(GLuint* texture, GLenum wrapping, glm::vec2 dimensions, GLint format, GLenum type, GLint numMipMaps) const; + void DrawModelRenderQueues(std::list>& job, RenderScene& scene); void BindExplosionUniforms(GLuint shaderHandle, std::shared_ptr& job, RenderScene& scene); diff --git a/resources/Schema/Components.xsd b/resources/Schema/Components.xsd index bb1fd770..24af1f47 100644 --- a/resources/Schema/Components.xsd +++ b/resources/Schema/Components.xsd @@ -30,4 +30,5 @@ + \ No newline at end of file diff --git a/resources/Schema/Components/ShieldComponent.xml b/resources/Schema/Components/ShieldComponent.xml new file mode 100644 index 00000000..855ead48 --- /dev/null +++ b/resources/Schema/Components/ShieldComponent.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/resources/Schema/Components/ShieldComponent.xsd b/resources/Schema/Components/ShieldComponent.xsd new file mode 100644 index 00000000..0076477d --- /dev/null +++ b/resources/Schema/Components/ShieldComponent.xsd @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/resources/Schema/Entities/QualityAssurance.xml b/resources/Schema/Entities/QualityAssurance.xml index e057cf38..90c52820 100644 --- a/resources/Schema/Entities/QualityAssurance.xml +++ b/resources/Schema/Entities/QualityAssurance.xml @@ -188,7 +188,7 @@ - + @@ -586,7 +586,7 @@ true - + @@ -683,7 +683,7 @@ - + @@ -730,7 +730,7 @@ - + @@ -790,7 +790,7 @@ - + @@ -837,7 +837,7 @@ - + @@ -883,7 +883,7 @@ - + @@ -930,7 +930,7 @@ - + @@ -977,7 +977,7 @@ - + @@ -1038,7 +1038,7 @@ Models/Core/UnitCube.mesh - + true @@ -1088,7 +1088,8 @@ Models/Core/UnitCube.mesh - + + true @@ -1131,6 +1132,7 @@ Models/Core/UnitCube.mesh + true @@ -1177,7 +1179,8 @@ Models/Core/UnitCube.mesh - + + true @@ -1225,7 +1228,7 @@ Models/Core/UnitCube.mesh - + true @@ -1374,7 +1377,7 @@ - + @@ -1383,7 +1386,7 @@ true - 0.75008034908941568 + 0.7502397033169681 3.7999999523162842 true @@ -1430,7 +1433,7 @@ - + @@ -1439,7 +1442,7 @@ - 1.1999860997035228 + 1.2001454539310752 Models/Assault.mesh @@ -1482,7 +1485,7 @@ - + @@ -1497,7 +1500,7 @@ true - 0.68343188336345406 + 0.68359123759100648 true @@ -1553,6 +1556,274 @@ + + + + + + + + + + + Models/Core/UnitHexagon.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + + + + + + + 5 + + + + + + + + + + + + + + + + + + + + + + + Fonts/DroidSans.ttf,100 + + + + + + + + + + + + + + Models/Camera.mesh + false + + + + + + + + + + + + + + + + + + + 1 + + + + + Models/Core/UnitHexagon.mesh + + + + + + + + + + + + + + Models/CrosshairQuad.mesh + + + + + + + + + + + + + true + + 3.7999999523162842 + + true + + + Models/AssaultWeaponRed.mesh + + + + + + + + + + + + + + + + + + + + + + + + + Models/Camera.mesh + false + + + + + + + + + + + + Hold Pos + + 1 + + + + Models/AssaultAnimated.mesh + + + + + + + + + + Models/Core/UnitCube.mesh + + false + + + + + + + + + + + + Models/Core/UnitCube.mesh + + false + + + + + + + + + + + + + + + + + + + + Models/Log.mesh + + + + + + + + + + + + Models/BushAlive.mesh + + + + + + + + + + + + + + + Defender Shield Test + Fonts/DroidSans.ttf,64 + + + + + + + + + + From 83713b3b6d3bb9a949cb2cce464d3a97351f3a2b Mon Sep 17 00:00:00 2001 From: Tleety Date: Wed, 3 Feb 2016 13:27:46 +0100 Subject: [PATCH 054/355] Renamde ShieldComponent since Component should not be in the name. Added Shielded component that will be put on objects that should be hidden behind shields. --- resources/Schema/Components.xsd | 3 ++- resources/Schema/Components/Shield.xml | 3 +++ .../Schema/Components/{ShieldComponent.xsd => Shield.xsd} | 2 +- resources/Schema/Components/ShieldComponent.xml | 3 --- resources/Schema/Components/Shielded.xml | 3 +++ resources/Schema/Components/Shielded.xsd | 7 +++++++ resources/Schema/Entities/QualityAssurance.xml | 2 +- 7 files changed, 17 insertions(+), 6 deletions(-) create mode 100644 resources/Schema/Components/Shield.xml rename resources/Schema/Components/{ShieldComponent.xsd => Shield.xsd} (83%) delete mode 100644 resources/Schema/Components/ShieldComponent.xml create mode 100644 resources/Schema/Components/Shielded.xml create mode 100644 resources/Schema/Components/Shielded.xsd diff --git a/resources/Schema/Components.xsd b/resources/Schema/Components.xsd index 24af1f47..368de22c 100644 --- a/resources/Schema/Components.xsd +++ b/resources/Schema/Components.xsd @@ -30,5 +30,6 @@ - + + \ No newline at end of file diff --git a/resources/Schema/Components/Shield.xml b/resources/Schema/Components/Shield.xml new file mode 100644 index 00000000..161f09bc --- /dev/null +++ b/resources/Schema/Components/Shield.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/resources/Schema/Components/ShieldComponent.xsd b/resources/Schema/Components/Shield.xsd similarity index 83% rename from resources/Schema/Components/ShieldComponent.xsd rename to resources/Schema/Components/Shield.xsd index 0076477d..9831cbfc 100644 --- a/resources/Schema/Components/ShieldComponent.xsd +++ b/resources/Schema/Components/Shield.xsd @@ -2,6 +2,6 @@ - + \ No newline at end of file diff --git a/resources/Schema/Components/ShieldComponent.xml b/resources/Schema/Components/ShieldComponent.xml deleted file mode 100644 index 855ead48..00000000 --- a/resources/Schema/Components/ShieldComponent.xml +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/resources/Schema/Components/Shielded.xml b/resources/Schema/Components/Shielded.xml new file mode 100644 index 00000000..0d95fb0a --- /dev/null +++ b/resources/Schema/Components/Shielded.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/resources/Schema/Components/Shielded.xsd b/resources/Schema/Components/Shielded.xsd new file mode 100644 index 00000000..b2348cf5 --- /dev/null +++ b/resources/Schema/Components/Shielded.xsd @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/resources/Schema/Entities/QualityAssurance.xml b/resources/Schema/Entities/QualityAssurance.xml index 90c52820..b15e9309 100644 --- a/resources/Schema/Entities/QualityAssurance.xml +++ b/resources/Schema/Entities/QualityAssurance.xml @@ -1568,7 +1568,7 @@ Models/Core/UnitHexagon.mesh - + From 7ffbd8455f435f5cbd8aeec8e312a93981bed9fd Mon Sep 17 00:00:00 2001 From: Tleety Date: Wed, 3 Feb 2016 13:53:57 +0100 Subject: [PATCH 055/355] Added Queues for the models with shield and shielded components. --- include/Engine/Rendering/RenderQueue.h | 28 +++++++++++++++-------- include/Engine/Rendering/RenderSystem.h | 2 +- src/Engine/Editor/EditorRenderSystem.cpp | 6 ++--- src/Engine/Rendering/DrawFinalPass.cpp | 4 ++-- src/Engine/Rendering/LightCullingPass.cpp | 6 ++--- src/Engine/Rendering/PickingPass.cpp | 4 ++-- src/Engine/Rendering/RenderSystem.cpp | 19 +++++++-------- src/Engine/Rendering/Renderer.cpp | 2 +- src/Engine/Rendering/TextPass.cpp | 2 +- 9 files changed, 41 insertions(+), 32 deletions(-) diff --git a/include/Engine/Rendering/RenderQueue.h b/include/Engine/Rendering/RenderQueue.h index af9d928e..5cc6fd78 100644 --- a/include/Engine/Rendering/RenderQueue.h +++ b/include/Engine/Rendering/RenderQueue.h @@ -19,22 +19,30 @@ struct RenderScene { ::Camera* Camera = nullptr; - std::list> OpaqueObjects; - std::list> TransparentObjects; - std::list> PointLightJobs; - std::list> TextJobs; - std::list> DirectionalLightJobs; + struct Queues { + std::list> OpaqueObjects; + std::list> TransparentObjects; + std::list> OpaqueShieldedObjects; + std::list> TransparentShieldedObjects; + std::list> ShieldObjects; + std::list> PointLight; + std::list> Text; + std::list> DirectionalLight; + } Jobs; + Rectangle Viewport; bool ClearDepth = false; glm::vec4 AmbientColor; void Clear() { - OpaqueObjects.clear(); - TransparentObjects.clear(); - PointLightJobs.clear(); - TextJobs.clear(); - DirectionalLightJobs.clear(); + Jobs.OpaqueObjects.clear(); + Jobs.TransparentObjects.clear(); + Jobs.OpaqueShieldedObjects.clear(); + Jobs.TransparentShieldedObjects.clear(); + Jobs.ShieldObjects.clear(); + Jobs.Text.clear(); + Jobs.DirectionalLight.clear(); } }; diff --git a/include/Engine/Rendering/RenderSystem.h b/include/Engine/Rendering/RenderSystem.h index d64147b9..5845d9d3 100644 --- a/include/Engine/Rendering/RenderSystem.h +++ b/include/Engine/Rendering/RenderSystem.h @@ -40,7 +40,7 @@ private: EventRelay m_EPlayerSpawned; bool OnPlayerSpawned(Events::PlayerSpawned& e); - void fillModels(std::list>& opaqueJobs, std::list>& transparentJobs); + void fillModels(RenderScene::Queues &jobs); void fillText(std::list>& jobs, World* world); void fillPointLights(std::list>& jobs, World* world); void fillDirectionalLights(std::list>& jobs, World* world); diff --git a/src/Engine/Editor/EditorRenderSystem.cpp b/src/Engine/Editor/EditorRenderSystem.cpp index 4d65e9d3..c5e90865 100644 --- a/src/Engine/Editor/EditorRenderSystem.cpp +++ b/src/Engine/Editor/EditorRenderSystem.cpp @@ -56,9 +56,9 @@ void EditorRenderSystem::Update(double dt) for (auto matGroup : model->MaterialGroups()) { std::shared_ptr modelJob = std::make_shared(model, scene.Camera, modelMatrix, matGroup, cModel, entity.World, glm::vec4(0), 0.f); if (cModel["Transparent"]) { - scene.TransparentObjects.push_back(modelJob); + scene.Jobs.TransparentObjects.push_back(modelJob); } else { - scene.OpaqueObjects.push_back(modelJob); + scene.Jobs.OpaqueObjects.push_back(modelJob); } } } @@ -75,7 +75,7 @@ void EditorRenderSystem::Update(double dt) EntityWrapper entity(m_World, cPointLight.EntityID); ComponentWrapper& cTransform = entity["Transform"]; std::shared_ptr pointLightJob = std::make_shared(cTransform, cPointLight, entity.World); - scene.PointLightJobs.push_back(pointLightJob); + scene.Jobs.PointLight.push_back(pointLightJob); } } diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index 8247797e..8e015373 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -66,9 +66,9 @@ void DrawFinalPass::Draw(RenderScene& scene) glClear(GL_DEPTH_BUFFER_BIT); } - DrawModelRenderQueues(scene.OpaqueObjects, scene); + DrawModelRenderQueues(scene.Jobs.OpaqueObjects, scene); GLERROR("OpaqueObjects"); - DrawModelRenderQueues(scene.TransparentObjects, scene); + DrawModelRenderQueues(scene.Jobs.TransparentObjects, scene); GLERROR("TransparentObjects"); delete state; diff --git a/src/Engine/Rendering/LightCullingPass.cpp b/src/Engine/Rendering/LightCullingPass.cpp index 5e6da64d..0ae359db 100644 --- a/src/Engine/Rendering/LightCullingPass.cpp +++ b/src/Engine/Rendering/LightCullingPass.cpp @@ -16,7 +16,7 @@ LightCullingPass::~LightCullingPass() void LightCullingPass::GenerateNewFrustum(RenderScene& scene) { - if (scene.PointLightJobs.size() == 0) + if (scene.Jobs.PointLight.size() == 0) return; GLERROR("CalculateFrustum Error: Pre"); @@ -83,7 +83,7 @@ void LightCullingPass::FillLightList(RenderScene& scene) { m_LightSources.clear(); - for(auto &job : scene.PointLightJobs) { + for(auto &job : scene.Jobs.PointLight) { auto pointLightjob = std::dynamic_pointer_cast(job); if (pointLightjob) { LightSource p; @@ -97,7 +97,7 @@ void LightCullingPass::FillLightList(RenderScene& scene) m_LightSources.push_back(p); } } - for(auto &job : scene.DirectionalLightJobs) { + for(auto &job : scene.Jobs.DirectionalLight) { auto directionalLightJob = std::dynamic_pointer_cast(job); if(directionalLightJob) { LightSource p; diff --git a/src/Engine/Rendering/PickingPass.cpp b/src/Engine/Rendering/PickingPass.cpp index abc79f2e..3baf2b2a 100644 --- a/src/Engine/Rendering/PickingPass.cpp +++ b/src/Engine/Rendering/PickingPass.cpp @@ -56,7 +56,7 @@ void PickingPass::Draw(RenderScene& scene) } m_Camera = scene.Camera; - for (auto &job : scene.OpaqueObjects) { + for (auto &job : scene.Jobs.OpaqueObjects) { auto modelJob = std::dynamic_pointer_cast(job); if (modelJob) { @@ -102,7 +102,7 @@ void PickingPass::Draw(RenderScene& scene) } } - for (auto &job : scene.TransparentObjects) { + for (auto &job : scene.Jobs.TransparentObjects) { auto modelJob = std::dynamic_pointer_cast(job); if (modelJob) { diff --git a/src/Engine/Rendering/RenderSystem.cpp b/src/Engine/Rendering/RenderSystem.cpp index eaecf99e..9711cea1 100644 --- a/src/Engine/Rendering/RenderSystem.cpp +++ b/src/Engine/Rendering/RenderSystem.cpp @@ -40,7 +40,7 @@ bool RenderSystem::isChildOfCurrentCamera(EntityWrapper entity) return entity == m_CurrentCamera || entity.IsChildOf(m_CurrentCamera); } -void RenderSystem::fillModels(std::list>& opaqueJobs, std::list>& transparentJobs) +void RenderSystem::fillModels(RenderScene::Queues &Jobs) { auto models = m_World->GetComponents("Model"); if (models == nullptr) { @@ -106,14 +106,15 @@ void RenderSystem::fillModels(std::list>& opaqueJobs, fillColor, fillPercentage )); + if(explosionEffectJob->Color.a != 1.f || explosionEffectJob->EndColor.a != 1.f || explosionEffectJob->DiffuseColor.a != 1.f) { cModel["Transparent"] = true; } if (cModel["Transparent"]) { - transparentJobs.push_back(explosionEffectJob); + Jobs.TransparentObjects.push_back(explosionEffectJob); } else { - opaqueJobs.push_back(explosionEffectJob); + Jobs.OpaqueObjects.push_back(explosionEffectJob); } } else { std::shared_ptr modelJob = std::shared_ptr(new ModelJob( @@ -130,9 +131,9 @@ void RenderSystem::fillModels(std::list>& opaqueJobs, cModel["Transparent"] = true; } if (cModel["Transparent"]) { - transparentJobs.push_back(modelJob); + Jobs.TransparentObjects.push_back(modelJob); } else { - opaqueJobs.push_back(modelJob); + Jobs.OpaqueObjects.push_back(modelJob); } } } @@ -251,10 +252,10 @@ void RenderSystem::Update(double dt) scene.AmbientColor = (glm::vec4)(*cSceneLight->begin())["AmbientColor"]; } - fillModels(scene.OpaqueObjects, scene.TransparentObjects); - fillPointLights(scene.PointLightJobs, m_World); - fillDirectionalLights(scene.DirectionalLightJobs, m_World); - fillText(scene.TextJobs, m_World); + fillModels(scene.Jobs); + fillPointLights(scene.Jobs.PointLight, m_World); + fillDirectionalLights(scene.Jobs.DirectionalLight, m_World); + fillText(scene.Jobs.Text, m_World); m_RenderFrame->Add(scene); } \ No newline at end of file diff --git a/src/Engine/Rendering/Renderer.cpp b/src/Engine/Rendering/Renderer.cpp index a63e02a0..fa3d1709 100644 --- a/src/Engine/Rendering/Renderer.cpp +++ b/src/Engine/Rendering/Renderer.cpp @@ -154,7 +154,7 @@ void Renderer::InitializeTextures() void Renderer::SortRenderJobsByDepth(RenderScene &scene) { //Sort all forward jobs so transparency is good. - scene.TransparentObjects.sort(Renderer::DepthSort); + scene.Jobs.TransparentObjects.sort(Renderer::DepthSort); } void Renderer::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) diff --git a/src/Engine/Rendering/TextPass.cpp b/src/Engine/Rendering/TextPass.cpp index 1e3d5941..9583fcfd 100644 --- a/src/Engine/Rendering/TextPass.cpp +++ b/src/Engine/Rendering/TextPass.cpp @@ -35,7 +35,7 @@ void TextPass::Draw(RenderScene& scene, FrameBuffer& frameBuffer) { GLERROR("Derp1"); TextPassState* state = new TextPassState(frameBuffer.GetHandle()); - for (auto &job : scene.TextJobs) { + for (auto &job : scene.Jobs.Text) { auto textJob = std::dynamic_pointer_cast(job); if (textJob) { From 5665c0f298d2b1e4b65b2842b180843b50543fab Mon Sep 17 00:00:00 2001 From: Tleety Date: Wed, 3 Feb 2016 14:20:47 +0100 Subject: [PATCH 056/355] Models with Shield and shielded component now added to queues --- .../Schema/Entities/QualityAssurance.xml | 32 +++++----- src/Engine/Rendering/RenderSystem.cpp | 58 +++++++++++++++---- 2 files changed, 63 insertions(+), 27 deletions(-) diff --git a/resources/Schema/Entities/QualityAssurance.xml b/resources/Schema/Entities/QualityAssurance.xml index b15e9309..cb75b7b3 100644 --- a/resources/Schema/Entities/QualityAssurance.xml +++ b/resources/Schema/Entities/QualityAssurance.xml @@ -40,7 +40,7 @@ - + @@ -188,7 +188,7 @@ - + @@ -683,7 +683,7 @@ - + @@ -730,7 +730,7 @@ - + @@ -790,7 +790,7 @@ - + @@ -837,7 +837,7 @@ - + @@ -883,7 +883,7 @@ - + @@ -930,7 +930,7 @@ - + @@ -977,7 +977,7 @@ - + @@ -1377,7 +1377,7 @@ - + @@ -1386,7 +1386,7 @@ true - 0.7502397033169681 + 0.75055150002244431 3.7999999523162842 true @@ -1433,7 +1433,7 @@ - + @@ -1442,7 +1442,7 @@ - 1.2001454539310752 + 1.2004572506365514 Models/Assault.mesh @@ -1485,7 +1485,7 @@ - + @@ -1500,7 +1500,7 @@ true - 0.68359123759100648 + 0.68390303429648269 true @@ -1581,6 +1581,7 @@ Models/Core/UnitCube.mesh + @@ -1690,6 +1691,7 @@ true + 0.0003117967054762083 3.7999999523162842 true diff --git a/src/Engine/Rendering/RenderSystem.cpp b/src/Engine/Rendering/RenderSystem.cpp index 9711cea1..623e7101 100644 --- a/src/Engine/Rendering/RenderSystem.cpp +++ b/src/Engine/Rendering/RenderSystem.cpp @@ -92,7 +92,9 @@ void RenderSystem::fillModels(RenderScene::Queues &Jobs) } glm::mat4 modelMatrix = Transform::ModelMatrix(cModel.EntityID, m_World); + //Loop through all materialgroups of a model for (auto matGroup : model->MaterialGroups()) { + //If the model has an explosioneffect component, we will add an explosioneffectjob if (m_World->HasComponent(cModel.EntityID, "ExplosionEffect")) { auto explosionEffectComponent = m_World->GetComponent(cModel.EntityID, "ExplosionEffect"); std::shared_ptr explosionEffectJob = std::shared_ptr(new ExplosionEffectJob( @@ -106,15 +108,30 @@ void RenderSystem::fillModels(RenderScene::Queues &Jobs) fillColor, fillPercentage )); + if (m_World->HasComponent(cModel.EntityID, "Shield")){ + Jobs.ShieldObjects.push_back(explosionEffectJob); + } else if (m_World->HasComponent(cModel.EntityID, "Shielded") + || m_World->HasComponent(cModel.EntityID, "Player")) { - if(explosionEffectJob->Color.a != 1.f || explosionEffectJob->EndColor.a != 1.f || explosionEffectJob->DiffuseColor.a != 1.f) { - cModel["Transparent"] = true; - } + if (explosionEffectJob->Color.a != 1.f || explosionEffectJob->EndColor.a != 1.f || explosionEffectJob->DiffuseColor.a != 1.f) { + cModel["Transparent"] = true; + } - if (cModel["Transparent"]) { - Jobs.TransparentObjects.push_back(explosionEffectJob); + if (cModel["Transparent"]) { + Jobs.TransparentShieldedObjects.push_back(explosionEffectJob); + } else { + Jobs.OpaqueShieldedObjects.push_back(explosionEffectJob); + } } else { - Jobs.OpaqueObjects.push_back(explosionEffectJob); + if (explosionEffectJob->Color.a != 1.f || explosionEffectJob->EndColor.a != 1.f || explosionEffectJob->DiffuseColor.a != 1.f) { + cModel["Transparent"] = true; + } + + if (cModel["Transparent"]) { + Jobs.TransparentObjects.push_back(explosionEffectJob); + } else { + Jobs.OpaqueObjects.push_back(explosionEffectJob); + } } } else { std::shared_ptr modelJob = std::shared_ptr(new ModelJob( @@ -127,13 +144,30 @@ void RenderSystem::fillModels(RenderScene::Queues &Jobs) fillColor, fillPercentage )); - if (modelJob->Color.a != 1.f || modelJob->DiffuseColor.a != 1.f) { - cModel["Transparent"] = true; - } - if (cModel["Transparent"]) { - Jobs.TransparentObjects.push_back(modelJob); + if (m_World->HasComponent(cModel.EntityID, "Shield")) { + Jobs.ShieldObjects.push_back(modelJob); + } else if (m_World->HasComponent(cModel.EntityID, "Shielded") + || m_World->HasComponent(cModel.EntityID, "Player")) { + + if (modelJob->Color.a != 1.f || modelJob->DiffuseColor.a != 1.f) { + cModel["Transparent"] = true; + } + + if (cModel["Transparent"]) { + Jobs.TransparentShieldedObjects.push_back(modelJob); + } else { + Jobs.OpaqueShieldedObjects.push_back(modelJob); + } } else { - Jobs.OpaqueObjects.push_back(modelJob); + if (modelJob->Color.a != 1.f || modelJob->DiffuseColor.a != 1.f) { + cModel["Transparent"] = true; + } + + if (cModel["Transparent"]) { + Jobs.TransparentObjects.push_back(modelJob); + } else { + Jobs.OpaqueObjects.push_back(modelJob); + } } } } From 938caa6ba2809023cbfb9bd096f5f8481ae394c3 Mon Sep 17 00:00:00 2001 From: stiffly Date: Wed, 3 Feb 2016 15:48:25 +0100 Subject: [PATCH 057/355] Now uses OnComponentAttached event. Can now queue sound on a source. --- assets | 2 +- include/Engine/Sound/SoundSystem.h | 17 ++++- src/Engine/Sound/SoundSystem.cpp | 101 +++++++++++++++++++---------- 3 files changed, 81 insertions(+), 39 deletions(-) diff --git a/assets b/assets index cde9a430..29f8e123 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit cde9a43029fe674a01ede2b74a1987cd57f1074a +Subproject commit 29f8e1234661f93ffba656c031d037a9ca484660 diff --git a/include/Engine/Sound/SoundSystem.h b/include/Engine/Sound/SoundSystem.h index 9e636c95..20d58933 100644 --- a/include/Engine/Sound/SoundSystem.h +++ b/include/Engine/Sound/SoundSystem.h @@ -31,7 +31,13 @@ #include "Core/EPlayerDeath.h" #include "Core/EPlayerHealthPickup.h" #include "Core/EComponentAttached.h" +#include "Core/EComponentDeleted.h" +#include "Core/EEntityDeleted.h" #include "Collision/ETrigger.h" +#include "Core/EPause.h" + + +typedef std::pair> QueuedBuffers; enum class SoundType { SFX, @@ -67,7 +73,6 @@ private: // Logic void initOpenAL(); - void addNewEmitters(double dt); void updateEmitters(double dt); void deleteInactiveEmitters(); void stopEmitters(); @@ -79,6 +84,8 @@ private: // Specific logic void playSound(Source* source); + // Need to be the same format (sample rate etc) + void playQueue(QueuedBuffers qb); void stopSound(Source* source); void playerDamaged(); void playerShot(); @@ -94,8 +101,6 @@ private: EventBroker* m_EventBroker = nullptr; std::unordered_map m_Sources; - - float m_BGMVolumeChannel = 1.0f; float m_SFXVolumeChannel = 1.0f; bool m_EditorEnabled = false; @@ -139,8 +144,14 @@ private: bool OnPlayerHealthPickup(const Events::PlayerHealthPickup &e); EventRelay m_EComponentAttached; bool OnComponentAttached(const Events::ComponentAttached &e); + EventRelay m_EComponentDeleted; + bool OnComponentDeleted(const Events::ComponentDeleted &e); EventRelay m_ETriggerTouch; bool OnTriggerTouch(const Events::TriggerTouch &e); + EventRelay m_EPause; + bool OnPause(const Events::Pause &e); + EventRelay m_EResume; + bool OnResume(const Events::Resume &e); diff --git a/src/Engine/Sound/SoundSystem.cpp b/src/Engine/Sound/SoundSystem.cpp index 08e5c0a8..ab4c5fce 100644 --- a/src/Engine/Sound/SoundSystem.cpp +++ b/src/Engine/Sound/SoundSystem.cpp @@ -26,6 +26,9 @@ SoundSystem::SoundSystem(World* world, EventBroker* eventBroker, bool editorMode EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &SoundSystem::OnInputCommand); EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &SoundSystem::OnCaptured); EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &SoundSystem::OnTriggerTouch); + EVENT_SUBSCRIBE_MEMBER(m_EPause, &SoundSystem::OnPause); + EVENT_SUBSCRIBE_MEMBER(m_EResume, &SoundSystem::OnResume); + EVENT_SUBSCRIBE_MEMBER(m_EComponentAttached, &SoundSystem::OnComponentAttached); } SoundSystem::~SoundSystem() @@ -57,7 +60,6 @@ void SoundSystem::Update(double dt) { m_EventBroker->Process(); playerStep(dt); - addNewEmitters(dt); // can be optimized with "EEntityCreated" deleteInactiveEmitters(); // can be optimized with "EEntityDeleted" updateEmitters(dt); updateListener(dt); @@ -87,7 +89,7 @@ void SoundSystem::deleteInactiveEmitters() } } else { // Entity / Component has been removed - stopSound((*it).second); + stopSound(it->second); alDeleteBuffers(1, &it->second->ALsource); alDeleteSources(1, &it->second->ALsource); delete it->second; @@ -96,28 +98,14 @@ void SoundSystem::deleteInactiveEmitters() } } -void SoundSystem::addNewEmitters(double dt) -{ - auto emitterComponents = m_World->GetComponents("SoundEmitter"); - if (emitterComponents == nullptr) { - return; - } - for (auto it = emitterComponents->begin(); it != emitterComponents->end(); it++) { - EntityID emitter = (*it).EntityID; - std::unordered_map::iterator source; - source = m_Sources.find(emitter); - if (source == m_Sources.end()) { // Did not exist, add it - Source* source = createSource((std::string)(*it)["FilePath"]); - m_Sources[emitter] = source; - } - } -} - void SoundSystem::updateEmitters(double dt) { std::unordered_map::iterator it; for (it = m_Sources.begin(); it != m_Sources.end(); it++) { // Get previous pos + if (!m_World->ValidEntity(it->first)) { + return; + } glm::vec3 previousPos; alGetSource3f(it->second->ALsource, AL_POSITION, &previousPos.x, &previousPos.y, &previousPos.z); // Get next pos @@ -180,6 +168,15 @@ void SoundSystem::playSound(Source* source) alSourcePlay(source->ALsource); } +void SoundSystem::playQueue(QueuedBuffers qb) +{ + for (int i = 0; i < qb.second.size(); i++) { + alSourceQueueBuffers(qb.first, 1, &qb.second[i]); + } + alSourcePlay(qb.first); +} + + void SoundSystem::stopSound(Source* source) { alSourceStop(source->ALsource); @@ -210,9 +207,13 @@ void SoundSystem::playerJumps() void SoundSystem::playerStep(double dt) { + if (!m_World->ValidEntity(m_LocalPlayer)) { + return; + } if (m_LocalPlayer == EntityID_Invalid) { return; } + m_TimeSinceLastFootstep += dt; glm::vec3 vel = (glm::vec3)m_World->GetComponent(m_LocalPlayer, "Physics")["Velocity"]; float playerSpeed = glm::length(vel); @@ -260,8 +261,6 @@ bool SoundSystem::OnPlaySoundOnPosition(const Events::PlaySoundOnPosition & e) (float&)(double)emitter["MaxDistance"] = e.MaxDistance; (float&)(double)emitter["RollOffFactor"] = e.RollOffFactor; (float&)(double)emitter["ReferenceDistance"] = e.ReferenceDistance; - auto model = m_World->AttachComponent(emitterID, "Model"); - (std::string&)model["Resource"] = "Models/Core/UnitCube.mesh"; // 360NoScope UnitCube source->Type = SoundType::SFX; m_Sources[emitterID] = source; playSound(source); @@ -352,24 +351,20 @@ bool SoundSystem::OnPlayerSpawned(const Events::PlayerSpawned & e) bool SoundSystem::OnInputCommand(const Events::InputCommand & e) { - if (e.Player.ID == EntityID_Invalid) { - //return false; - } if (e.Command == "Jump" && e.Value > 0) { if (e.PlayerID == -1) { // local player - //bool airBorne = ((glm::vec3)m_World->GetComponent(e.Player.ID, "Physics")["Velocity"]).y != 0; - //if (!airBorne) { playerJumps(); - //} return true; } } + // TEMP: testing purpose (obviously) if (e.Command == "TakeDamage" && e.Value > 0) { if (e.PlayerID == -1) { //Local Player Events::PlayerDamage ePlayerDamage; ePlayerDamage.Damage = 1; ePlayerDamage.Player = EntityWrapper(m_World, e.Player.ID); m_EventBroker->Publish(ePlayerDamage); + return true; } } return false; @@ -383,7 +378,7 @@ bool SoundSystem::OnCaptured(const Events::Captured & e) if (team == homeTeam) { ev.FilePath = "Audio/announcer/objective_achieved.wav"; } else { - ev.FilePath = "Audio/announcer/objective_failed.wav"; + ev.FilePath = "Audio/announcer/objective_failed.wav"; // have not been tested } EntityID child = m_World->CreateEntity(m_LocalPlayer); m_World->AttachComponent(child, "Transform"); @@ -395,17 +390,27 @@ bool SoundSystem::OnCaptured(const Events::Captured & e) bool SoundSystem::OnPlayerDamage(const Events::PlayerDamage & e) { - //if (e.Player.ID == m_LocalPlayer) { - Events::PlaySoundOnEntity ev; + // Should check for only local players here... EntityID child = m_World->CreateEntity(m_LocalPlayer); m_World->AttachComponent(child, "Transform"); m_World->AttachComponent(child, "SoundEmitter"); - ev.EmitterID = child; + std::uniform_int_distribution dist(1, 12); int rand = dist(generator); - ev.FilePath = "Audio/hurt/hurt" + std::to_string(rand) + ".wav"; - m_EventBroker->Publish(ev); - //} + Source* source = createSource("Audio/hurt/hurt" + std::to_string(rand) + ".wav"); + source->Type = SoundType::SFX; + m_Sources[child] = source; + //playSound(source); + + // breathe + std::vector buffers; + buffers.push_back(source->SoundResource->Buffer()); + int ammountOfbreaths = (e.Damage / 10) + 2; // TEMP: Idk something stupid like this shit + for (int i = 0; i < ammountOfbreaths; i++) { + buffers.push_back(ResourceManager::Load("Audio/exhausted/breath.wav")->Buffer()); + } + playQueue(QueuedBuffers(std::make_pair(source->ALsource, buffers))); + return false; } @@ -417,7 +422,7 @@ bool SoundSystem::OnPlayerDeath(const Events::PlayerDeath & e) m_World->AttachComponent(child, "Transform"); m_World->AttachComponent(child, "SoundEmitter"); ev.EmitterID = child; - ev.FilePath = "Audio/die/die2.wav"; // random between a bunch + ev.FilePath = "Audio/die/die2.wav"; // should random between a bunch m_EventBroker->Publish(ev); } return false; @@ -440,6 +445,16 @@ bool SoundSystem::OnPlayerHealthPickup(const Events::PlayerHealthPickup & e) bool SoundSystem::OnComponentAttached(const Events::ComponentAttached & e) { if (e.Component.Info.Name == "SoundEmitter") { + auto component = m_World->GetComponent(e.Entity.ID, "SoundEmitter"); + Source* source = createSource(component["FilePath"]); + m_Sources[e.Entity.ID] = source; + } + return false; +} + +bool SoundSystem::OnComponentDeleted(const Events::ComponentDeleted & e) +{ + if (e.ComponentType == "SoundEmitter") { } return false; @@ -455,6 +470,22 @@ bool SoundSystem::OnTriggerTouch(const Events::TriggerTouch & e) return false; } +bool SoundSystem::OnPause(const Events::Pause & e) +{ + for (auto it = m_Sources.begin(); it != m_Sources.end(); it++) { + alSourcePause(it->second->ALsource); + } + return false; +} + +bool SoundSystem::OnResume(const Events::Resume &e) +{ + for (auto it = m_Sources.begin(); it != m_Sources.end(); it++) { + alSourcePlay(it->second->ALsource); + } + return false; +} + void SoundSystem::setListenerOri(glm::vec3 ori) { // Calculate forward and up vector. From c2833b10c40d9ade38f5548ae97e9323bb948010 Mon Sep 17 00:00:00 2001 From: stiffly Date: Wed, 3 Feb 2016 15:55:32 +0100 Subject: [PATCH 058/355] Hard coded (read retarded) improvements added to player walk logic --- src/Engine/Sound/SoundSystem.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Engine/Sound/SoundSystem.cpp b/src/Engine/Sound/SoundSystem.cpp index ab4c5fce..86f3a34b 100644 --- a/src/Engine/Sound/SoundSystem.cpp +++ b/src/Engine/Sound/SoundSystem.cpp @@ -220,7 +220,7 @@ void SoundSystem::playerStep(double dt) bool isAirborne = vel.y != 0; if (playerSpeed > 1 && !isAirborne) { // Player is walking - if (m_TimeSinceLastFootstep * playerSpeed > m_PlayerFootstepInterval) { + if (m_TimeSinceLastFootstep * std::min(playerSpeed, 2) > m_PlayerFootstepInterval) { // Create footstep sound EntityID child = m_World->CreateEntity(m_LocalPlayer); m_World->AttachComponent(child, "Transform"); From b56824786ce1c01f429b9f2309423bb1021a929e Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Wed, 3 Feb 2016 16:16:06 +0100 Subject: [PATCH 059/355] Revert "Merge pull request #75 from teamfisk/NormalSpecularMapping" This reverts commit 192de8078250ffc612c3d3642c484579959315bf, reversing changes made to 24aac6a00d27940de6a596ef0360f1ae9271aa78. --- assets | 2 +- .../Rendering/DrawColorCorrectionPass.h | 4 +- include/Engine/Rendering/RenderQueue.h | 4 - include/Engine/Rendering/Util/GLError.h | 2 +- resources/Schema/Components.xsd | 1 - resources/Schema/Components/SceneLight.xml | 7 - resources/Schema/Components/SceneLight.xsd | 25 - resources/Schema/Entities/AssetPedistal.xml | 51 - resources/Schema/Entities/EditorTestWorld.xml | 196 +-- .../Schema/Entities/EditorWidgetTranslate.xml | 9 + resources/Schema/Entities/Player.xml | 17 +- .../Schema/Entities/QualityAssurance.xml | 1558 ----------------- resources/Schema/Entities/RayBlue.xml | 3 +- resources/Schema/Entities/RayRed.xml | 3 +- resources/Schema/Entities/SoundEmitter.xml | 24 - .../Entities/SpawnPointClusterWithModels.xml | 68 - .../Entities/SpawnerWithPlayerModel.xml | 16 - resources/Schema/Types/Entity.xsd | 1 - .../Shaders/DrawColorCorrection.frag.glsl | 4 +- resources/Shaders/ExplosionEffect.geom.glsl | 28 +- resources/Shaders/ForwardPlus.frag.glsl | 15 +- resources/Shaders/ForwardPlus.vert.glsl | 4 +- src/Engine/Editor/EditorRenderSystem.cpp | 8 +- .../Rendering/DrawColorCorrectionPass.cpp | 10 +- src/Engine/Rendering/DrawFinalPass.cpp | 70 +- src/Engine/Rendering/FrameBuffer.cpp | 7 + src/Engine/Rendering/PickingPass.cpp | 8 +- src/Engine/Rendering/RenderSystem.cpp | 9 +- src/Engine/Rendering/Renderer.cpp | 4 +- 29 files changed, 137 insertions(+), 2021 deletions(-) delete mode 100644 resources/Schema/Components/SceneLight.xml delete mode 100644 resources/Schema/Components/SceneLight.xsd delete mode 100644 resources/Schema/Entities/AssetPedistal.xml delete mode 100644 resources/Schema/Entities/QualityAssurance.xml delete mode 100644 resources/Schema/Entities/SoundEmitter.xml delete mode 100644 resources/Schema/Entities/SpawnPointClusterWithModels.xml delete mode 100644 resources/Schema/Entities/SpawnerWithPlayerModel.xml diff --git a/assets b/assets index c4898d82..091ad5c0 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit c4898d8281b5584d89b1caf14dab8e5fac120321 +Subproject commit 091ad5c01bf7b6ef5501fc907fc610576a4a45ea diff --git a/include/Engine/Rendering/DrawColorCorrectionPass.h b/include/Engine/Rendering/DrawColorCorrectionPass.h index fcde73d7..e9a7e281 100644 --- a/include/Engine/Rendering/DrawColorCorrectionPass.h +++ b/include/Engine/Rendering/DrawColorCorrectionPass.h @@ -7,7 +7,6 @@ #include "ShaderProgram.h" //#include "Util/UnorderedMapVec2.h" #include "Texture.h" -#include "imgui/imgui.h" class DrawColorCorrectionPass { @@ -17,13 +16,14 @@ public: void InitializeFrameBuffers(); void InitializeShaderPrograms(); - void Draw(GLuint sceneTexture, GLuint bloomTexture, GLfloat gamma, GLfloat exposure); + void Draw(GLuint sceneTexture, GLuint bloomTexture); private: const IRenderer* m_Renderer; ShaderProgram* m_ColorCorrectionProgram; Model* m_ScreenQuad; + GLfloat m_Exposure; }; #endif \ No newline at end of file diff --git a/include/Engine/Rendering/RenderQueue.h b/include/Engine/Rendering/RenderQueue.h index af9d928e..57371146 100644 --- a/include/Engine/Rendering/RenderQueue.h +++ b/include/Engine/Rendering/RenderQueue.h @@ -26,7 +26,6 @@ struct RenderScene std::list> DirectionalLightJobs; Rectangle Viewport; bool ClearDepth = false; - glm::vec4 AmbientColor; void Clear() { @@ -41,9 +40,6 @@ struct RenderScene struct RenderFrame { public: - //TODO: Getters - GLfloat Gamma = 2.2f; - GLfloat Exposure = 1.f; void Add(RenderScene &scene) { diff --git a/include/Engine/Rendering/Util/GLError.h b/include/Engine/Rendering/Util/GLError.h index 2b244e1c..754623d1 100644 --- a/include/Engine/Rendering/Util/GLError.h +++ b/include/Engine/Rendering/Util/GLError.h @@ -9,7 +9,7 @@ inline bool _GLERROR(const char* info, const char* file, const char* func, unsig GLenum error = glGetError(); if (error != GL_NO_ERROR) { - _LOG(LOG_LEVEL_ERROR, file, func, line, "GL Error: %s\nError code: %i, %s\n", info, error, gluErrorString(error)); + _LOG(LOG_LEVEL_ERROR, file, func, line, "GL Error: %s, %i, %s", info, error, gluErrorString(error)); return true; } diff --git a/resources/Schema/Components.xsd b/resources/Schema/Components.xsd index bb1fd770..ab46b0ea 100644 --- a/resources/Schema/Components.xsd +++ b/resources/Schema/Components.xsd @@ -11,7 +11,6 @@ - diff --git a/resources/Schema/Components/SceneLight.xml b/resources/Schema/Components/SceneLight.xml deleted file mode 100644 index 80b6b9f4..00000000 --- a/resources/Schema/Components/SceneLight.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - true - 2.2 - 1 - \ No newline at end of file diff --git a/resources/Schema/Components/SceneLight.xsd b/resources/Schema/Components/SceneLight.xsd deleted file mode 100644 index 9f8a9705..00000000 --- a/resources/Schema/Components/SceneLight.xsd +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - Some settings for the scene lighting - - - - - Color of the ambient light - - - Wether the ambient light should be applied or not - - - Gamma correction for the scene - - - The exposure of the camera - - - - - \ No newline at end of file diff --git a/resources/Schema/Entities/AssetPedistal.xml b/resources/Schema/Entities/AssetPedistal.xml deleted file mode 100644 index 728a3028..00000000 --- a/resources/Schema/Entities/AssetPedistal.xml +++ /dev/null @@ -1,51 +0,0 @@ - - - - - - Models/Core/UnitCylinder.mesh - - - - - - - - - - - - - - - - - - - - - 0.5 - - - - - - - - - - - Models/AssaultWeaponBlue.mesh - - - - - - - - - - - - - diff --git a/resources/Schema/Entities/EditorTestWorld.xml b/resources/Schema/Entities/EditorTestWorld.xml index 4727c777..9565e2d4 100755 --- a/resources/Schema/Entities/EditorTestWorld.xml +++ b/resources/Schema/Entities/EditorTestWorld.xml @@ -2,9 +2,7 @@ - - - + @@ -20,7 +18,7 @@ - + @@ -40,27 +38,18 @@ Models/DirectionalLightWidget.mesh - 1 + 1.0499999523162842 - + - - true - - - 5.0498686575577523 - 5 - - 3 - Models/Assault.mesh @@ -73,26 +62,11 @@ - Models/AssaultWeaponRed.mesh - true + Models/SecondaryWeapon.mesh - - - - - - - - - - Models/DefenderGunRed.mesh - true - false - - - - + + @@ -111,7 +85,7 @@ Run - + 1 @@ -127,7 +101,7 @@ Walk - + 1 @@ -173,6 +147,70 @@ + + + + Models/NormalMapSphere.mesh + + + + + + + + + + + Models/SpecularMapSphere.mesh + + + + + + + + + + 1 + + + + + + + + + + + Models/Core/UnitSphere.mesh + + + + 3 + 1.1399998664855957 + + + + + + + + + + + + + + + + Models/IncandescenceMapSphere.mesh + + + + + + + @@ -189,7 +227,7 @@ - + @@ -246,94 +284,8 @@ - - - - 1 - - - - - - - - - - - Models/NormalMapSphere.mesh - - - - - - - - - - - Models/SpecularMapSphere.mesh - - - - - - - - - - 1 - - - - - - - - - - - Models/Core/UnitSphere.mesh - - - - 3 - 1.1399998664855957 - - - - - - - - - - - - - - - - Models/IncandescenceMapSphere.mesh - - - - - - - - - - - - - 1.3999999761581421 - - - - - diff --git a/resources/Schema/Entities/EditorWidgetTranslate.xml b/resources/Schema/Entities/EditorWidgetTranslate.xml index c6dba4d9..d4ed5e76 100644 --- a/resources/Schema/Entities/EditorWidgetTranslate.xml +++ b/resources/Schema/Entities/EditorWidgetTranslate.xml @@ -84,6 +84,15 @@ + + + + + + + + + diff --git a/resources/Schema/Entities/Player.xml b/resources/Schema/Entities/Player.xml index d365c0ee..e81ec5aa 100644 --- a/resources/Schema/Entities/Player.xml +++ b/resources/Schema/Entities/Player.xml @@ -2,12 +2,12 @@ + - @@ -20,7 +20,7 @@ - + @@ -101,19 +101,12 @@ - - true - - 3.7999999523162842 - - true - - Models/AssaultWeaponRed.mesh + Models/AssaultWeapon.mesh - + @@ -148,7 +141,7 @@ Hold Pos - + 1 diff --git a/resources/Schema/Entities/QualityAssurance.xml b/resources/Schema/Entities/QualityAssurance.xml deleted file mode 100644 index e057cf38..00000000 --- a/resources/Schema/Entities/QualityAssurance.xml +++ /dev/null @@ -1,1558 +0,0 @@ - - - - - - - - - - - - - - - - Models/Core/UnitPlane.mesh - - - - - - - - - - - 90 - - - - - - - - - - - - 1 - - - - - - - - - - - Audio/crosscounter.wav - true - - - - - - - - - - SoundEmitter - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - - - - - - - - Sound Test - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - 0.80000001192092896 - - - Models/DirectionalLightWidget.mesh - - - 1 - - - - - - - - - - - - - - - - - - - - - Run - - 1 - - - models/AssaultAnimated.mesh - - - - - - - - - - - Walk - - 1 - - - models/AssaultAnimated.mesh - - - - - - - - - Animation test - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - Models/Core/UnitCylinder.mesh - - - - - - - - - - - - - - - - - - - - 0.5 - - - - - - - - - - - Run - - 1 - - - Models/AssaultAnimated.mesh - - - - - - - - - - - - - - - - - - - - - - - - models/NormSpecIncdMapSphere.mesh - - - - - - - - - 1 - - - - - - - - - - - Models/Core/UnitSphere.mesh - - - - 3 - 1.1399998664855957 - - - - - - - - - - - - Models/Core/UnitSphere.mesh - - - - 5.0100002288818359 - 0.69999998807907104 - - - - - - - - - - - - Models/Core/UnitSphere.mesh - - - - 4 - 0.80000001192092896 - - - - - - - - - - - - - - 1 - - - - - - - - - - - Models/NormalMapSphere.mesh - - - - - - - - - - - Models/SpecularMapSphere.mesh - - - - - - - - - - 1 - - - - - - - - - - - Models/Core/UnitSphere.mesh - - - - 3 - 1.1399998664855957 - - - - - - - - - - - - - - - - Models/IncandescenceMapSphere.mesh - - - - - - - - - - - - - TextureMap's Test - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - 1.3999999761581421 - - - - - - - - - - - - - - - - - Schema/Entities/Player.xml - - - - - - - - - - - - - - - - Models/Assault.mesh - - - - - - - - - - - - - Models/Assault.mesh - - - - - - - - - - - - - Models/Assault.mesh - - - - - - - - - - - - - Models/Assault.mesh - - - - - - - - - - - - - - - Schema/Entities/Player.xml - - - - - - - - - - - - - - - - - Models/Assault.mesh - - - - - - - - - - - - - Models/Assault.mesh - - - - - - - - - - - - - Models/Assault.mesh - - - - - - - - - - - - - Models/Assault.mesh - - - - - - - - - - - - - - Spawn Test - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - - - - - - - - Models/Core/UnitCube.mesh - - true - - - - - - - - - - - Models/Core/UnitCylinder.mesh - - true - - - - - - - - - - - - Models/Core/UnitRaptor.mesh - - true - - - - - - - - - - - Models/Assault.mesh - - true - - - - - - - - - - - - Models/Core/UnitCube.mesh - - true - - - - - - - - - - - - - Transparency Test - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - - - - - - - - Models/Core/UnitCylinder.mesh - - - - - - - - - - - - - - - - - - - - 0.5 - - - - - - - - - - - Models/AssaultWeaponBlue.mesh - - - - - - - - - - - - - - - - Models/Core/UnitCylinder.mesh - - - - - - - - - - - - - - - - - - - - 0.5 - - - - - - - - - - - Models/AssaultWeaponRed.mesh - - - - - - - - - - - - - - - - Asset Test - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - Models/Core/UnitCylinder.mesh - - - - - - - - - - - - - - - - - - - - 0.5 - - - - - - - - - - - Models/SecondaryWeapon.mesh - - - - - - - - - - - - - - - - Models/Core/UnitCylinder.mesh - - - - - - - - - - - - - - - - - - - - 0.5 - - - - - - - - - - - Models/AssualtSoft.mesh - - - - - - - - - - - - - - - Models/Core/UnitCylinder.mesh - - - - - - - - - - - - - - - - - - - - 0.5 - - - - - - - - - - - Models/DefenderGunBlue.mesh - - - - - - - - - - - - - - - - Models/Core/UnitCylinder.mesh - - - - - - - - - - - - - - - - - - - - 0.5 - - - - - - - - - - - Models/DefenderGunRed.mesh - - - - - - - - - - - - - - - - Models/Core/UnitCylinder.mesh - - - - - - - - - - - - - - - - - - - - 0.5 - - - - - - - - - - - Models/Assualt.mesh - - - - - - - - - - - - - - - - - - - - - - - - CapturePoint Test - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - Models/CapturePoint.mesh - - - - - - - - - - - - - - - - Models/Core/UnitCube.mesh - - true - - - - - - - - - - - - - - - - - - Red team home point - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - - Models/CapturePoint.mesh - - - - - - - - - - - 1 - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - - - RedMiddle Point - Fonts/DroidSans.ttf - - - - - - - - - - - - - - - Models/CapturePoint.mesh - - - - - - - - - 2 - - - Models/Core/UnitCube.mesh - true - - - - - - - - - - - - - - Middle Point - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - - Models/CapturePoint.mesh - - - - - - - - - - - -12.033302729641917 - 3 - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - - - BlueMiddle Point - Fonts/DroidSans.ttf - - - - - - - - - - - - - - - Models/CapturePoint.mesh - - - - - - - - - - - - - - 4 - - - Models/Core/UnitCube.mesh - - true - - - - - - - - - - - - - - - - - - Blue team home point - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Models/Test/ObstacleCourse.mesh - - - - - - - - - - - Collision Test - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - - - - - - - - - Models/Core/UnitCylinder.mesh - - - - - - - - - - - - - - - - - - - - 0.5 - - - - - - - - - - - true - - 0.75008034908941568 - 3.7999999523162842 - - true - - - Models/AssaultWeaponBlue.mesh - true - - - - - - - - - - - - - - - - Models/Core/UnitCylinder.mesh - - - - - - - - - - - - - - - - - - - - 0.5 - - - - - - - - - - - - - 1.1999860997035228 - - - Models/Assault.mesh - true - - - - - - - - - - - - - - - Models/Core/UnitCylinder.mesh - - - - - - - - - - - - - - - - - - - - 0.5 - - - - - - - - - - - Walk - - 1 - - - true - - - 0.68343188336345406 - - true - - - Models/AssaultAnimated.mesh - true - - - - - - - - - - - - - - - ExplosionEffect Test - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - - - - - - - - Remember to pick random entities. - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - diff --git a/resources/Schema/Entities/RayBlue.xml b/resources/Schema/Entities/RayBlue.xml index 4a0bb9d4..3b985a7e 100644 --- a/resources/Schema/Entities/RayBlue.xml +++ b/resources/Schema/Entities/RayBlue.xml @@ -7,8 +7,7 @@ Models/CylinderBullet.mesh - - true + diff --git a/resources/Schema/Entities/RayRed.xml b/resources/Schema/Entities/RayRed.xml index e69df489..df563476 100644 --- a/resources/Schema/Entities/RayRed.xml +++ b/resources/Schema/Entities/RayRed.xml @@ -7,8 +7,7 @@ Models/CylinderBullet.mesh - - true + diff --git a/resources/Schema/Entities/SoundEmitter.xml b/resources/Schema/Entities/SoundEmitter.xml deleted file mode 100644 index 39b4c750..00000000 --- a/resources/Schema/Entities/SoundEmitter.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - SoundEmitter - Fonts/DroidSans.ttf,64 - - - - - - - - - - diff --git a/resources/Schema/Entities/SpawnPointClusterWithModels.xml b/resources/Schema/Entities/SpawnPointClusterWithModels.xml deleted file mode 100644 index 9c42d0e4..00000000 --- a/resources/Schema/Entities/SpawnPointClusterWithModels.xml +++ /dev/null @@ -1,68 +0,0 @@ - - - - - - - Schema/Entities/Player.xml - - - - - - - - - - - - - - - Models/Assault.mesh - - - - - - - - - - - - Models/Assault.mesh - - - - - - - - - - - - Models/Assault.mesh - - - - - - - - - - - - Models/Assault.mesh - - - - - - - - - - diff --git a/resources/Schema/Entities/SpawnerWithPlayerModel.xml b/resources/Schema/Entities/SpawnerWithPlayerModel.xml deleted file mode 100644 index 1274eefa..00000000 --- a/resources/Schema/Entities/SpawnerWithPlayerModel.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - Models/Assault.mesh - - - - - - - - - diff --git a/resources/Schema/Types/Entity.xsd b/resources/Schema/Types/Entity.xsd index 028af9e6..99b90caa 100644 --- a/resources/Schema/Types/Entity.xsd +++ b/resources/Schema/Types/Entity.xsd @@ -31,7 +31,6 @@ - diff --git a/resources/Shaders/DrawColorCorrection.frag.glsl b/resources/Shaders/DrawColorCorrection.frag.glsl index 91ace0c7..8d13992a 100644 --- a/resources/Shaders/DrawColorCorrection.frag.glsl +++ b/resources/Shaders/DrawColorCorrection.frag.glsl @@ -3,7 +3,6 @@ layout (binding = 0) uniform sampler2D SceneTexture; layout (binding = 1) uniform sampler2D BloomTexture; uniform float Exposure; -uniform float Gamma; in VertexData{ vec2 TextureCoordinate; @@ -13,6 +12,7 @@ out vec4 fragmentColor; void main() { + const float gamma = 2.2; vec4 hdrColor = texture(SceneTexture, Input.TextureCoordinate); vec4 bloomColor = texture(BloomTexture, Input.TextureCoordinate); hdrColor += bloomColor; @@ -21,7 +21,7 @@ void main() vec3 result = vec3(1.0) - exp(-hdrColor.rgb * Exposure); //gamme correction - result = pow(result, vec3(1.0 / Gamma)); + result = pow(result, vec3(1.0 / gamma)); fragmentColor = vec4(result, 1.0); //fragmentColor = hdrColor; diff --git a/resources/Shaders/ExplosionEffect.geom.glsl b/resources/Shaders/ExplosionEffect.geom.glsl index 44b44aa6..cb91b545 100644 --- a/resources/Shaders/ExplosionEffect.geom.glsl +++ b/resources/Shaders/ExplosionEffect.geom.glsl @@ -17,21 +17,15 @@ uniform bool ExponentialAccelaration; in VertexData{ vec3 Position; vec3 Normal; - vec3 Tangent; - vec3 BiTangent; vec2 TextureCoordinate; vec4 ExplosionColor; - float ExplosionPercentageElapsed; }Input[]; out VertexData{ vec3 Position; vec3 Normal; - vec3 Tangent; - vec3 BiTangent; vec2 TextureCoordinate; vec4 ExplosionColor; - float ExplosionPercentageElapsed; }Output; layout(triangles) in; @@ -120,17 +114,12 @@ void main() { // calculate the max distance (s) the triangle will move float s = (randomVelocity.x * ExplosionDuration) + (0.5 * a * pow(ExplosionDuration, 2)); - float te = (length(triangleCenter2ExplosionRadius) / s); - Output.ExplosionColor = EndColor; - Output.ExplosionPercentageElapsed = te; - + Output.ExplosionColor = EndColor * (length(triangleCenter2ExplosionRadius) / s); } else { - Output.ExplosionColor = EndColor; - Output.ExplosionPercentageElapsed = timePercetage; - + Output.ExplosionColor = EndColor * timePercetage; } // for every vertex on the triangle... @@ -143,8 +132,6 @@ void main() Output.Normal = Input[i].Normal; Output.Position = Input[i].Position; Output.TextureCoordinate = Input[i].TextureCoordinate; - Output.Tangent = Input[i].Tangent; - Output.BiTangent = Input[i].BiTangent; // convert to model space for the gravity to always be in -y vec4 ExplodedPositionInModelSpace = M * vec4(ExplodedPosition, 1.0); @@ -167,14 +154,11 @@ void main() // if explosion color should be affected by distance instead of time... if (ColorByDistance == true) { - Output.ExplosionColor = EndColor; - Output.ExplosionPercentageElapsed = 0.0; + Output.ExplosionColor = vec4(0.0); } else { - Output.ExplosionColor = EndColor; - Output.ExplosionPercentageElapsed = timePercetage; - + Output.ExplosionColor = EndColor * timePercetage; } // for every vertex on the triangle... @@ -184,9 +168,7 @@ void main() Output.Normal = Input[i].Normal; Output.Position = Input[i].Position; Output.TextureCoordinate = Input[i].TextureCoordinate; - Output.Tangent = Input[i].Tangent; - Output.BiTangent = Input[i].BiTangent; - + // no change in position, pass through vertex gl_Position = gl_in[i].gl_Position; EmitVertex(); diff --git a/resources/Shaders/ForwardPlus.frag.glsl b/resources/Shaders/ForwardPlus.frag.glsl index c09e0438..de672dd1 100644 --- a/resources/Shaders/ForwardPlus.frag.glsl +++ b/resources/Shaders/ForwardPlus.frag.glsl @@ -7,13 +7,13 @@ uniform vec4 Color; uniform vec4 DiffuseColor; uniform vec2 ScreenDimensions; uniform vec4 FillColor; -uniform vec4 AmbientColor; uniform float FillPercentage; layout (binding = 0) uniform sampler2D DiffuseTexture; layout (binding = 1) uniform sampler2D NormalMapTexture; layout (binding = 2) uniform sampler2D SpecularMapTexture; layout (binding = 3) uniform sampler2D GlowMapTexture; + #define TILE_SIZE 16 struct LightSource { @@ -55,12 +55,13 @@ in VertexData{ vec3 BiTangent; vec2 TextureCoordinate; vec4 ExplosionColor; - float ExplosionPercentageElapsed; }Input; out vec4 sceneColor; out vec4 bloomColor; +vec4 scene_ambient = vec4(0.3,0.3,0.3,1); + struct LightResult { vec4 Diffuse; vec4 Specular; @@ -119,7 +120,6 @@ void main() vec4 specularTexel = texture2D(SpecularMapTexture, Input.TextureCoordinate); vec4 position = V * M * vec4(Input.Position, 1.0); vec4 normal = V * CalcNormalMappedValue(Input.Normal, Input.Tangent, Input.BiTangent, Input.TextureCoordinate, NormalMapTexture); - normal = normalize(normal); //vec4 normal = normalize(V * vec4(Input.Normal, 0.0)); vec4 viewVec = normalize(-position); @@ -128,7 +128,7 @@ void main() tilePos.y = int(gl_FragCoord.y/TILE_SIZE); LightResult totalLighting; - totalLighting.Diffuse = vec4(AmbientColor.rgb, 1.0); + totalLighting.Diffuse = scene_ambient; int currentTile = int(floor(gl_FragCoord.x/TILE_SIZE) + (floor(gl_FragCoord.y/TILE_SIZE) * int(ScreenDimensions.x/TILE_SIZE))); int start = int(LightGrids.Data[currentTile].Start); @@ -150,9 +150,8 @@ void main() totalLighting.Specular += light_result.Specular; } - vec4 color_result = mix((Color * diffuseTexel * DiffuseColor), Input.ExplosionColor, Input.ExplosionPercentageElapsed); - color_result = color_result * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)); - //vec4 color_result = (DiffuseColor + Input.ExplosionColor) * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)) * diffuseTexel * Color; + + vec4 color_result = (DiffuseColor + Input.ExplosionColor) * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)) * diffuseTexel * Color; float pos = ((P * vec4(Input.Position, 1)).y + 1.0)/2.0; @@ -161,7 +160,7 @@ void main() color_result += FillColor; } sceneColor = vec4(color_result.xyz, clamp(color_result.a, 0, 1)); - color_result += glowTexel*3; + color_result += glowTexel; bloomColor = vec4(clamp(color_result.xyz - 1.0, 0, 100), 1.0); diff --git a/resources/Shaders/ForwardPlus.vert.glsl b/resources/Shaders/ForwardPlus.vert.glsl index 3b3e931c..1a7cca12 100644 --- a/resources/Shaders/ForwardPlus.vert.glsl +++ b/resources/Shaders/ForwardPlus.vert.glsl @@ -20,7 +20,6 @@ out VertexData{ vec3 BiTangent; vec2 TextureCoordinate; vec4 ExplosionColor; - float ExplosionPercentageElapsed; }Output; void main() @@ -42,6 +41,5 @@ void main() Output.Normal = vec3(M * vec4(Normal, 0.0)); Output.Tangent = vec3(M * vec4(Tangent, 0.0)); Output.BiTangent = vec3(M * vec4(BiTangent, 0.0)); - Output.ExplosionColor = vec4(1.0); - Output.ExplosionPercentageElapsed = 0.0; + Output.ExplosionColor = vec4(0.0); } \ No newline at end of file diff --git a/src/Engine/Editor/EditorRenderSystem.cpp b/src/Engine/Editor/EditorRenderSystem.cpp index 4d65e9d3..67b09a21 100644 --- a/src/Engine/Editor/EditorRenderSystem.cpp +++ b/src/Engine/Editor/EditorRenderSystem.cpp @@ -23,12 +23,6 @@ void EditorRenderSystem::Update(double dt) scene.Camera = m_EditorCamera; scene.Viewport = Rectangle(1920, 1080); - auto cSceneLight = m_World->GetComponents("SceneLight"); - if (cSceneLight != nullptr) { - //these are hardcoded since they want special light treatment and a component just for widgets is stupid. - scene.AmbientColor = glm::vec4(0.8, 0.8, 0.8, 1.0); - } - auto models = m_World->GetComponents("Model"); if (models != nullptr) { for (auto& cModel : *models) { @@ -55,7 +49,7 @@ void EditorRenderSystem::Update(double dt) glm::mat4 modelMatrix = Transform::ModelMatrix(entity.ID, entity.World); for (auto matGroup : model->MaterialGroups()) { std::shared_ptr modelJob = std::make_shared(model, scene.Camera, modelMatrix, matGroup, cModel, entity.World, glm::vec4(0), 0.f); - if (cModel["Transparent"]) { + if(cModel["Transparent"]) { scene.TransparentObjects.push_back(modelJob); } else { scene.OpaqueObjects.push_back(modelJob); diff --git a/src/Engine/Rendering/DrawColorCorrectionPass.cpp b/src/Engine/Rendering/DrawColorCorrectionPass.cpp index 45401bce..ba9efe3e 100644 --- a/src/Engine/Rendering/DrawColorCorrectionPass.cpp +++ b/src/Engine/Rendering/DrawColorCorrectionPass.cpp @@ -5,8 +5,7 @@ DrawColorCorrectionPass::DrawColorCorrectionPass(IRenderer* renderer) m_Renderer = renderer; m_ScreenQuad = ResourceManager::Load("Models/Core/ScreenQuad.mesh"); - - //m_Exposure = 0.4; //TODO: Renderer: Fixa så att denna går att ändra på genom komponent eller setting. + m_Exposure = 0.4; //TODO: Renderer: Fixa så att denna går att ändra på genom komponent eller setting. InitializeShaderPrograms(); } @@ -20,16 +19,15 @@ void DrawColorCorrectionPass::InitializeShaderPrograms() m_ColorCorrectionProgram->Link(); } -void DrawColorCorrectionPass::Draw(GLuint sceneTexture, GLuint bloomTexture, GLfloat gamma, GLfloat exposure) +void DrawColorCorrectionPass::Draw(GLuint sceneTexture, GLuint bloomTexture) { //glBindFramebuffer(GL_FRAMEBUFFER, 0); GLERROR("DrawScreenQuadPass::Draw: Pre"); DrawScreenQuadPassState state = DrawScreenQuadPassState(); m_ColorCorrectionProgram->Bind(); - //glClear(GL_COLOR_BUFFER_BIT); - glUniform1f(glGetUniformLocation(m_ColorCorrectionProgram->GetHandle(), "Exposure"), exposure); - glUniform1f(glGetUniformLocation(m_ColorCorrectionProgram->GetHandle(), "Gamma"), gamma); + glClear(GL_COLOR_BUFFER_BIT); + glUniform1f(glGetUniformLocation(m_ColorCorrectionProgram->GetHandle(), "Exposure"), m_Exposure); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, sceneTexture); diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index 8247797e..aa9da9a1 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -44,7 +44,6 @@ void DrawFinalPass::InitializeShaderPrograms() m_ForwardPlusProgram->BindFragDataLocation(0, "sceneColor"); m_ForwardPlusProgram->BindFragDataLocation(1, "bloomColor"); m_ForwardPlusProgram->Link(); - GLERROR("Creating forward+ program"); m_ExplosionEffectProgram = ResourceManager::Load("#ExplosionEffectProgram"); m_ExplosionEffectProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ForwardPlus.vert.glsl"))); @@ -54,12 +53,11 @@ void DrawFinalPass::InitializeShaderPrograms() m_ExplosionEffectProgram->BindFragDataLocation(0, "sceneColor"); m_ExplosionEffectProgram->BindFragDataLocation(1, "bloomColor"); m_ExplosionEffectProgram->Link(); - GLERROR("Creating explosion program"); } void DrawFinalPass::Draw(RenderScene& scene) { - GLERROR("Pre"); + GLERROR("DrawFinalPass::Draw: Pre"); DrawFinalPassState* state = new DrawFinalPassState(m_FinalPassFrameBuffer.GetHandle()); if (scene.ClearDepth) { @@ -67,12 +65,12 @@ void DrawFinalPass::Draw(RenderScene& scene) } DrawModelRenderQueues(scene.OpaqueObjects, scene); - GLERROR("OpaqueObjects"); + GLERROR("DrawFinalPass::Draw: OpaqueObjects"); DrawModelRenderQueues(scene.TransparentObjects, scene); - GLERROR("TransparentObjects"); + GLERROR("DrawFinalPass::Draw: TransparentObjects"); + GLERROR("DrawFinalPass::Draw: END"); delete state; - GLERROR("END"); } @@ -113,9 +111,7 @@ void DrawFinalPass::GenerateMipMapTexture(GLuint* texture, GLenum wrapping, glm: void DrawFinalPass::DrawModelRenderQueues(std::list>& job, RenderScene& scene) { GLuint forwardHandle = m_ForwardPlusProgram->GetHandle(); - GLERROR("forwardHandle"); GLuint explosionHandle = m_ExplosionEffectProgram->GetHandle(); - GLERROR("explosionHandle"); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, m_LightCullingPass->LightSSBO()); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, m_LightCullingPass->LightGridSSBO()); @@ -126,21 +122,10 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& auto explosionEffectJob = std::dynamic_pointer_cast(job); if(explosionEffectJob) { //Bind program - if(GLERROR("Prebind")) { - continue; - } m_ExplosionEffectProgram->Bind(); - if(GLERROR("BindProgram")) { - continue; - } - - glDisable(GL_CULL_FACE); //Bind uniforms BindExplosionUniforms(explosionHandle, explosionEffectJob, scene); - if(GLERROR("BindExplosionUniforms")) { - continue; - } if (explosionEffectJob->Model->m_RawModel->m_Skeleton != nullptr) { @@ -149,23 +134,13 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& glUniformMatrix4fv(glGetUniformLocation(explosionHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); } } - if(GLERROR("Animation")) { - continue; - } //bind textures BindExplosionTextures(explosionEffectJob); - if(GLERROR("BindExplosionTextures")) { - continue; - } //draw glBindVertexArray(explosionEffectJob->Model->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, explosionEffectJob->Model->ElementBuffer); glDrawElements(GL_TRIANGLES, explosionEffectJob->EndIndex - explosionEffectJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(explosionEffectJob->StartIndex*sizeof(unsigned int))); - glEnable(GL_CULL_FACE); - if(GLERROR("explosion effect end")) { - continue; - } } else { auto modelJob = std::dynamic_pointer_cast(job); @@ -192,9 +167,7 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& glBindVertexArray(modelJob->Model->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer); glDrawElements(GL_TRIANGLES, modelJob->EndIndex - modelJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(modelJob->StartIndex*sizeof(unsigned int))); - if(GLERROR("models end")) { - continue; - } + GLERROR("DrawFinalPass::Model: END"); } } } @@ -203,46 +176,36 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& void DrawFinalPass::BindExplosionUniforms(GLuint shaderHandle, std::shared_ptr& job, RenderScene& scene) { - glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(job->Matrix)); 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())); - glUniform2f(glGetUniformLocation(shaderHandle, "ScreenDimensions"), m_Renderer->Resolution().Width, m_Renderer->Resolution().Height); + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(job->Matrix)); + glUniform4fv(glGetUniformLocation(shaderHandle, "Color"), 1, glm::value_ptr(job->Color)); glUniform3fv(glGetUniformLocation(shaderHandle, "ExplosionOrigin"), 1, glm::value_ptr(job->ExplosionOrigin)); glUniform1f(glGetUniformLocation(shaderHandle, "TimeSinceDeath"), job->TimeSinceDeath); glUniform1f(glGetUniformLocation(shaderHandle, "ExplosionDuration"), job->ExplosionDuration); glUniform4fv(glGetUniformLocation(shaderHandle, "EndColor"), 1, glm::value_ptr(job->EndColor)); glUniform1i(glGetUniformLocation(shaderHandle, "Randomness"), job->Randomness); - glUniform1fv(glGetUniformLocation(shaderHandle, "RandomNumbers"), 50, job->RandomNumbers.data()); glUniform1f(glGetUniformLocation(shaderHandle, "RandomnessScalar"), job->RandomnessScalar); glUniform2fv(glGetUniformLocation(shaderHandle, "Velocity"), 1, glm::value_ptr(job->Velocity)); glUniform1i(glGetUniformLocation(shaderHandle, "ColorByDistance"), job->ColorByDistance); glUniform1i(glGetUniformLocation(shaderHandle, "ExponentialAccelaration"), job->ExponentialAccelaration); - - glUniform4fv(glGetUniformLocation(shaderHandle, "Color"), 1, glm::value_ptr(job->Color)); glUniform4fv(glGetUniformLocation(shaderHandle, "DiffuseColor"), 1, glm::value_ptr(job->DiffuseColor)); - glUniform4fv(glGetUniformLocation(shaderHandle, "FillColor"), 1, glm::value_ptr(job->FillColor)); - glUniform1f(glGetUniformLocation(shaderHandle, "FillPercentage"), job->FillPercentage); - glUniform4fv(glGetUniformLocation(shaderHandle, "AmbientColor"), 1, glm::value_ptr(scene.AmbientColor)); - GLERROR("END"); + glUniform1fv(glGetUniformLocation(shaderHandle, "RandomNumbers"), 50, job->RandomNumbers.data()); } void DrawFinalPass::BindModelUniforms(GLuint shaderHandle, std::shared_ptr& job, RenderScene& scene) { - glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(job->Matrix)); 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())); - glUniform2f(glGetUniformLocation(shaderHandle, "ScreenDimensions"), m_Renderer->Resolution().Width, m_Renderer->Resolution().Height); + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(job->Matrix)); glUniform4fv(glGetUniformLocation(shaderHandle, "Color"), 1, glm::value_ptr(job->Color)); glUniform4fv(glGetUniformLocation(shaderHandle, "DiffuseColor"), 1, glm::value_ptr(job->DiffuseColor)); glUniform4fv(glGetUniformLocation(shaderHandle, "FillColor"), 1, glm::value_ptr(job->FillColor)); glUniform1f(glGetUniformLocation(shaderHandle, "FillPercentage"), job->FillPercentage); - glUniform4fv(glGetUniformLocation(shaderHandle, "AmbientColor"), 1, glm::value_ptr(scene.AmbientColor)); - - GLERROR("END"); } @@ -254,22 +217,7 @@ void DrawFinalPass::BindExplosionTextures(std::shared_ptr& j } else { glBindTexture(GL_TEXTURE_2D, m_WhiteTexture->m_Texture); } - glActiveTexture(GL_TEXTURE1); - if (job->NormalTexture != nullptr) { - glBindTexture(GL_TEXTURE_2D, job->NormalTexture->m_Texture); - } else { - glBindTexture(GL_TEXTURE_2D, m_NeutralNormalTexture->m_Texture); - } - - glActiveTexture(GL_TEXTURE2); - if (job->SpecularTexture != nullptr) { - glBindTexture(GL_TEXTURE_2D, job->SpecularTexture->m_Texture); - } else { - glBindTexture(GL_TEXTURE_2D, m_GreyTexture->m_Texture); - } - - glActiveTexture(GL_TEXTURE3); if (job->IncandescenceTexture != nullptr) { glBindTexture(GL_TEXTURE_2D, job->IncandescenceTexture->m_Texture); } else { diff --git a/src/Engine/Rendering/FrameBuffer.cpp b/src/Engine/Rendering/FrameBuffer.cpp index 9677f50e..b7e908cc 100644 --- a/src/Engine/Rendering/FrameBuffer.cpp +++ b/src/Engine/Rendering/FrameBuffer.cpp @@ -54,6 +54,13 @@ void FrameBuffer::Generate() case GL_RENDERBUFFER: glFramebufferRenderbuffer(GL_FRAMEBUFFER, (*it)->m_Attachment, (*it)->m_ResourceType, *(*it)->m_ResourceHandle); GLERROR("FrameBuffer generate: glFramebufferRenderbuffer"); + if ( (*it)->m_Attachment != GL_COLOR_ATTACHMENT0 || + (*it)->m_Attachment != GL_COLOR_ATTACHMENT1 || + (*it)->m_Attachment != GL_DEPTH_ATTACHMENT || + (*it)->m_Attachment != GL_STENCIL_ATTACHMENT) //TODO: Viktor: Fixa detta + { + LOG_ERROR("RenderBuffer Attachment not valid."); + } break; } diff --git a/src/Engine/Rendering/PickingPass.cpp b/src/Engine/Rendering/PickingPass.cpp index abc79f2e..792539f8 100644 --- a/src/Engine/Rendering/PickingPass.cpp +++ b/src/Engine/Rendering/PickingPass.cpp @@ -75,9 +75,9 @@ void PickingPass::Draw(RenderScene& scene) m_EntityColors[std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)] = glm::ivec2(pickColor[0], pickColor[1]); if (m_ColorCounter[0] > 255) { m_ColorCounter[0] = 0; - m_ColorCounter[1] += 1; + m_ColorCounter[1] += 5; } else { - m_ColorCounter[0] += 1; + m_ColorCounter[0] += 50; } } @@ -121,9 +121,9 @@ void PickingPass::Draw(RenderScene& scene) m_EntityColors[std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)] = glm::ivec2(pickColor[0], pickColor[1]); if (m_ColorCounter[0] > 255) { m_ColorCounter[0] = 0; - m_ColorCounter[1] += 1; + m_ColorCounter[1] += 5; } else { - m_ColorCounter[0] += 1; + m_ColorCounter[0] += 50; } } diff --git a/src/Engine/Rendering/RenderSystem.cpp b/src/Engine/Rendering/RenderSystem.cpp index eaecf99e..a0912a45 100644 --- a/src/Engine/Rendering/RenderSystem.cpp +++ b/src/Engine/Rendering/RenderSystem.cpp @@ -240,17 +240,10 @@ void RenderSystem::Update(double dt) m_Camera->SetOrientation(Transform::AbsoluteOrientation(m_CurrentCamera)); } + RenderScene scene; scene.Camera = m_Camera; scene.Viewport = Rectangle(1280, 720); - - auto cSceneLight = m_World->GetComponents("SceneLight"); - if (cSceneLight != nullptr && cSceneLight->begin() != cSceneLight->end()) { - m_RenderFrame->Gamma = (double)(*cSceneLight->begin())["Gamma"]; - m_RenderFrame->Exposure = (double)(*cSceneLight->begin())["Exposure"]; - scene.AmbientColor = (glm::vec4)(*cSceneLight->begin())["AmbientColor"]; - } - fillModels(scene.OpaqueObjects, scene.TransparentObjects); fillPointLights(scene.PointLightJobs, m_World); fillDirectionalLights(scene.DirectionalLightJobs, m_World); diff --git a/src/Engine/Rendering/Renderer.cpp b/src/Engine/Rendering/Renderer.cpp index a63e02a0..bec86b4a 100644 --- a/src/Engine/Rendering/Renderer.cpp +++ b/src/Engine/Rendering/Renderer.cpp @@ -119,8 +119,8 @@ void Renderer::Draw(RenderFrame& frame) } m_DrawBloomPass->Draw(m_DrawFinalPass->BloomTexture()); - if (m_DebugTextureToDraw == 0) { - m_DrawColorCorrectionPass->Draw(m_DrawFinalPass->SceneTexture(), m_DrawBloomPass->GaussianTexture(), frame.Gamma, frame.Exposure); + if(m_DebugTextureToDraw == 0) { + m_DrawColorCorrectionPass->Draw(m_DrawFinalPass->SceneTexture(), m_DrawBloomPass->GaussianTexture()); } if (m_DebugTextureToDraw == 1) { m_DrawScreenQuadPass->Draw(m_DrawFinalPass->SceneTexture()); From bd2da7bc9f88f8e9f27bfbeaa2c1cff210e0cdb4 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Wed, 3 Feb 2016 16:30:00 +0100 Subject: [PATCH 060/355] Revert "Revert "Merge pull request #75 from teamfisk/NormalSpecularMapping"" This reverts commit b56824786ce1c01f429b9f2309423bb1021a929e. --- assets | 2 +- .../Rendering/DrawColorCorrectionPass.h | 4 +- include/Engine/Rendering/RenderQueue.h | 4 + include/Engine/Rendering/Util/GLError.h | 2 +- resources/Schema/Components.xsd | 1 + resources/Schema/Components/SceneLight.xml | 7 + resources/Schema/Components/SceneLight.xsd | 25 + resources/Schema/Entities/AssetPedistal.xml | 51 + resources/Schema/Entities/EditorTestWorld.xml | 196 ++- .../Schema/Entities/EditorWidgetTranslate.xml | 9 - resources/Schema/Entities/Player.xml | 17 +- .../Schema/Entities/QualityAssurance.xml | 1558 +++++++++++++++++ resources/Schema/Entities/RayBlue.xml | 3 +- resources/Schema/Entities/RayRed.xml | 3 +- resources/Schema/Entities/SoundEmitter.xml | 24 + .../Entities/SpawnPointClusterWithModels.xml | 68 + .../Entities/SpawnerWithPlayerModel.xml | 16 + resources/Schema/Types/Entity.xsd | 1 + .../Shaders/DrawColorCorrection.frag.glsl | 4 +- resources/Shaders/ExplosionEffect.geom.glsl | 28 +- resources/Shaders/ForwardPlus.frag.glsl | 15 +- resources/Shaders/ForwardPlus.vert.glsl | 4 +- src/Engine/Editor/EditorRenderSystem.cpp | 8 +- .../Rendering/DrawColorCorrectionPass.cpp | 10 +- src/Engine/Rendering/DrawFinalPass.cpp | 86 +- src/Engine/Rendering/FrameBuffer.cpp | 7 - src/Engine/Rendering/PickingPass.cpp | 8 +- src/Engine/Rendering/RenderSystem.cpp | 9 +- src/Engine/Rendering/Renderer.cpp | 4 +- 29 files changed, 2029 insertions(+), 145 deletions(-) create mode 100644 resources/Schema/Components/SceneLight.xml create mode 100644 resources/Schema/Components/SceneLight.xsd create mode 100644 resources/Schema/Entities/AssetPedistal.xml create mode 100644 resources/Schema/Entities/QualityAssurance.xml create mode 100644 resources/Schema/Entities/SoundEmitter.xml create mode 100644 resources/Schema/Entities/SpawnPointClusterWithModels.xml create mode 100644 resources/Schema/Entities/SpawnerWithPlayerModel.xml diff --git a/assets b/assets index 091ad5c0..c4898d82 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit 091ad5c01bf7b6ef5501fc907fc610576a4a45ea +Subproject commit c4898d8281b5584d89b1caf14dab8e5fac120321 diff --git a/include/Engine/Rendering/DrawColorCorrectionPass.h b/include/Engine/Rendering/DrawColorCorrectionPass.h index e9a7e281..fcde73d7 100644 --- a/include/Engine/Rendering/DrawColorCorrectionPass.h +++ b/include/Engine/Rendering/DrawColorCorrectionPass.h @@ -7,6 +7,7 @@ #include "ShaderProgram.h" //#include "Util/UnorderedMapVec2.h" #include "Texture.h" +#include "imgui/imgui.h" class DrawColorCorrectionPass { @@ -16,14 +17,13 @@ public: void InitializeFrameBuffers(); void InitializeShaderPrograms(); - void Draw(GLuint sceneTexture, GLuint bloomTexture); + void Draw(GLuint sceneTexture, GLuint bloomTexture, GLfloat gamma, GLfloat exposure); private: const IRenderer* m_Renderer; ShaderProgram* m_ColorCorrectionProgram; Model* m_ScreenQuad; - GLfloat m_Exposure; }; #endif \ No newline at end of file diff --git a/include/Engine/Rendering/RenderQueue.h b/include/Engine/Rendering/RenderQueue.h index 57371146..af9d928e 100644 --- a/include/Engine/Rendering/RenderQueue.h +++ b/include/Engine/Rendering/RenderQueue.h @@ -26,6 +26,7 @@ struct RenderScene std::list> DirectionalLightJobs; Rectangle Viewport; bool ClearDepth = false; + glm::vec4 AmbientColor; void Clear() { @@ -40,6 +41,9 @@ struct RenderScene struct RenderFrame { public: + //TODO: Getters + GLfloat Gamma = 2.2f; + GLfloat Exposure = 1.f; void Add(RenderScene &scene) { diff --git a/include/Engine/Rendering/Util/GLError.h b/include/Engine/Rendering/Util/GLError.h index 754623d1..2b244e1c 100644 --- a/include/Engine/Rendering/Util/GLError.h +++ b/include/Engine/Rendering/Util/GLError.h @@ -9,7 +9,7 @@ inline bool _GLERROR(const char* info, const char* file, const char* func, unsig GLenum error = glGetError(); if (error != GL_NO_ERROR) { - _LOG(LOG_LEVEL_ERROR, file, func, line, "GL Error: %s, %i, %s", info, error, gluErrorString(error)); + _LOG(LOG_LEVEL_ERROR, file, func, line, "GL Error: %s\nError code: %i, %s\n", info, error, gluErrorString(error)); return true; } diff --git a/resources/Schema/Components.xsd b/resources/Schema/Components.xsd index ab46b0ea..bb1fd770 100644 --- a/resources/Schema/Components.xsd +++ b/resources/Schema/Components.xsd @@ -11,6 +11,7 @@ + diff --git a/resources/Schema/Components/SceneLight.xml b/resources/Schema/Components/SceneLight.xml new file mode 100644 index 00000000..80b6b9f4 --- /dev/null +++ b/resources/Schema/Components/SceneLight.xml @@ -0,0 +1,7 @@ + + + + true + 2.2 + 1 + \ No newline at end of file diff --git a/resources/Schema/Components/SceneLight.xsd b/resources/Schema/Components/SceneLight.xsd new file mode 100644 index 00000000..9f8a9705 --- /dev/null +++ b/resources/Schema/Components/SceneLight.xsd @@ -0,0 +1,25 @@ + + + + + + Some settings for the scene lighting + + + + + Color of the ambient light + + + Wether the ambient light should be applied or not + + + Gamma correction for the scene + + + The exposure of the camera + + + + + \ No newline at end of file diff --git a/resources/Schema/Entities/AssetPedistal.xml b/resources/Schema/Entities/AssetPedistal.xml new file mode 100644 index 00000000..728a3028 --- /dev/null +++ b/resources/Schema/Entities/AssetPedistal.xml @@ -0,0 +1,51 @@ + + + + + + Models/Core/UnitCylinder.mesh + + + + + + + + + + + + + + + + + + + + + 0.5 + + + + + + + + + + + Models/AssaultWeaponBlue.mesh + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/EditorTestWorld.xml b/resources/Schema/Entities/EditorTestWorld.xml index 9565e2d4..4727c777 100755 --- a/resources/Schema/Entities/EditorTestWorld.xml +++ b/resources/Schema/Entities/EditorTestWorld.xml @@ -2,7 +2,9 @@ - + + + @@ -18,7 +20,7 @@ - + @@ -38,18 +40,27 @@ Models/DirectionalLightWidget.mesh - 1.0499999523162842 + 1 - + + + true + + + 5.0498686575577523 + 5 + + 3 + Models/Assault.mesh @@ -62,11 +73,26 @@ - Models/SecondaryWeapon.mesh + Models/AssaultWeaponRed.mesh + true - - + + + + + + + + + + Models/DefenderGunRed.mesh + true + false + + + + @@ -85,7 +111,7 @@ Run - + 1 @@ -101,7 +127,7 @@ Walk - + 1 @@ -147,70 +173,6 @@ - - - - Models/NormalMapSphere.mesh - - - - - - - - - - - Models/SpecularMapSphere.mesh - - - - - - - - - - 1 - - - - - - - - - - - Models/Core/UnitSphere.mesh - - - - 3 - 1.1399998664855957 - - - - - - - - - - - - - - - - Models/IncandescenceMapSphere.mesh - - - - - - - @@ -227,7 +189,7 @@ - + @@ -284,8 +246,94 @@ + + + + 1 + + + + + + + + + + + Models/NormalMapSphere.mesh + + + + + + + + + + + Models/SpecularMapSphere.mesh + + + + + + + + + + 1 + + + + + + + + + + + Models/Core/UnitSphere.mesh + + + + 3 + 1.1399998664855957 + + + + + + + + + + + + + + + + Models/IncandescenceMapSphere.mesh + + + + + + + + + + + + + 1.3999999761581421 + + + + + diff --git a/resources/Schema/Entities/EditorWidgetTranslate.xml b/resources/Schema/Entities/EditorWidgetTranslate.xml index d4ed5e76..c6dba4d9 100644 --- a/resources/Schema/Entities/EditorWidgetTranslate.xml +++ b/resources/Schema/Entities/EditorWidgetTranslate.xml @@ -84,15 +84,6 @@ - - - - - - - - - diff --git a/resources/Schema/Entities/Player.xml b/resources/Schema/Entities/Player.xml index e81ec5aa..d365c0ee 100644 --- a/resources/Schema/Entities/Player.xml +++ b/resources/Schema/Entities/Player.xml @@ -2,12 +2,12 @@ - + @@ -20,7 +20,7 @@ - + @@ -101,12 +101,19 @@ + + true + + 3.7999999523162842 + + true + - Models/AssaultWeapon.mesh + Models/AssaultWeaponRed.mesh - + @@ -141,7 +148,7 @@ Hold Pos - + 1 diff --git a/resources/Schema/Entities/QualityAssurance.xml b/resources/Schema/Entities/QualityAssurance.xml new file mode 100644 index 00000000..e057cf38 --- /dev/null +++ b/resources/Schema/Entities/QualityAssurance.xml @@ -0,0 +1,1558 @@ + + + + + + + + + + + + + + + + Models/Core/UnitPlane.mesh + + + + + + + + + + + 90 + + + + + + + + + + + + 1 + + + + + + + + + + + Audio/crosscounter.wav + true + + + + + + + + + + SoundEmitter + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + + + + + + Sound Test + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + 0.80000001192092896 + + + Models/DirectionalLightWidget.mesh + + + 1 + + + + + + + + + + + + + + + + + + + + + Run + + 1 + + + models/AssaultAnimated.mesh + + + + + + + + + + + Walk + + 1 + + + models/AssaultAnimated.mesh + + + + + + + + + Animation test + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + Models/Core/UnitCylinder.mesh + + + + + + + + + + + + + + + + + + + + 0.5 + + + + + + + + + + + Run + + 1 + + + Models/AssaultAnimated.mesh + + + + + + + + + + + + + + + + + + + + + + + + models/NormSpecIncdMapSphere.mesh + + + + + + + + + 1 + + + + + + + + + + + Models/Core/UnitSphere.mesh + + + + 3 + 1.1399998664855957 + + + + + + + + + + + + Models/Core/UnitSphere.mesh + + + + 5.0100002288818359 + 0.69999998807907104 + + + + + + + + + + + + Models/Core/UnitSphere.mesh + + + + 4 + 0.80000001192092896 + + + + + + + + + + + + + + 1 + + + + + + + + + + + Models/NormalMapSphere.mesh + + + + + + + + + + + Models/SpecularMapSphere.mesh + + + + + + + + + + 1 + + + + + + + + + + + Models/Core/UnitSphere.mesh + + + + 3 + 1.1399998664855957 + + + + + + + + + + + + + + + + Models/IncandescenceMapSphere.mesh + + + + + + + + + + + + + TextureMap's Test + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + 1.3999999761581421 + + + + + + + + + + + + + + + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + Models/Assault.mesh + + + + + + + + + + + + + Models/Assault.mesh + + + + + + + + + + + + + Models/Assault.mesh + + + + + + + + + + + + + Models/Assault.mesh + + + + + + + + + + + + + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + + Models/Assault.mesh + + + + + + + + + + + + + Models/Assault.mesh + + + + + + + + + + + + + Models/Assault.mesh + + + + + + + + + + + + + Models/Assault.mesh + + + + + + + + + + + + + + Spawn Test + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + true + + + + + + + + + + + Models/Core/UnitCylinder.mesh + + true + + + + + + + + + + + + Models/Core/UnitRaptor.mesh + + true + + + + + + + + + + + Models/Assault.mesh + + true + + + + + + + + + + + + Models/Core/UnitCube.mesh + + true + + + + + + + + + + + + + Transparency Test + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + + + + + + Models/Core/UnitCylinder.mesh + + + + + + + + + + + + + + + + + + + + 0.5 + + + + + + + + + + + Models/AssaultWeaponBlue.mesh + + + + + + + + + + + + + + + + Models/Core/UnitCylinder.mesh + + + + + + + + + + + + + + + + + + + + 0.5 + + + + + + + + + + + Models/AssaultWeaponRed.mesh + + + + + + + + + + + + + + + + Asset Test + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + Models/Core/UnitCylinder.mesh + + + + + + + + + + + + + + + + + + + + 0.5 + + + + + + + + + + + Models/SecondaryWeapon.mesh + + + + + + + + + + + + + + + + Models/Core/UnitCylinder.mesh + + + + + + + + + + + + + + + + + + + + 0.5 + + + + + + + + + + + Models/AssualtSoft.mesh + + + + + + + + + + + + + + + Models/Core/UnitCylinder.mesh + + + + + + + + + + + + + + + + + + + + 0.5 + + + + + + + + + + + Models/DefenderGunBlue.mesh + + + + + + + + + + + + + + + + Models/Core/UnitCylinder.mesh + + + + + + + + + + + + + + + + + + + + 0.5 + + + + + + + + + + + Models/DefenderGunRed.mesh + + + + + + + + + + + + + + + + Models/Core/UnitCylinder.mesh + + + + + + + + + + + + + + + + + + + + 0.5 + + + + + + + + + + + Models/Assualt.mesh + + + + + + + + + + + + + + + + + + + + + + + + CapturePoint Test + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + Models/CapturePoint.mesh + + + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + true + + + + + + + + + + + + + + + + + + Red team home point + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + Models/CapturePoint.mesh + + + + + + + + + + + 1 + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + + RedMiddle Point + Fonts/DroidSans.ttf + + + + + + + + + + + + + + + Models/CapturePoint.mesh + + + + + + + + + 2 + + + Models/Core/UnitCube.mesh + true + + + + + + + + + + + + + + Middle Point + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + Models/CapturePoint.mesh + + + + + + + + + + + -12.033302729641917 + 3 + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + + BlueMiddle Point + Fonts/DroidSans.ttf + + + + + + + + + + + + + + + Models/CapturePoint.mesh + + + + + + + + + + + + + + 4 + + + Models/Core/UnitCube.mesh + + true + + + + + + + + + + + + + + + + + + Blue team home point + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Models/Test/ObstacleCourse.mesh + + + + + + + + + + + Collision Test + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + + + + + + + + Models/Core/UnitCylinder.mesh + + + + + + + + + + + + + + + + + + + + 0.5 + + + + + + + + + + + true + + 0.75008034908941568 + 3.7999999523162842 + + true + + + Models/AssaultWeaponBlue.mesh + true + + + + + + + + + + + + + + + + Models/Core/UnitCylinder.mesh + + + + + + + + + + + + + + + + + + + + 0.5 + + + + + + + + + + + + + 1.1999860997035228 + + + Models/Assault.mesh + true + + + + + + + + + + + + + + + Models/Core/UnitCylinder.mesh + + + + + + + + + + + + + + + + + + + + 0.5 + + + + + + + + + + + Walk + + 1 + + + true + + + 0.68343188336345406 + + true + + + Models/AssaultAnimated.mesh + true + + + + + + + + + + + + + + + ExplosionEffect Test + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + + + + + + Remember to pick random entities. + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/RayBlue.xml b/resources/Schema/Entities/RayBlue.xml index 3b985a7e..4a0bb9d4 100644 --- a/resources/Schema/Entities/RayBlue.xml +++ b/resources/Schema/Entities/RayBlue.xml @@ -7,7 +7,8 @@ Models/CylinderBullet.mesh - + + true diff --git a/resources/Schema/Entities/RayRed.xml b/resources/Schema/Entities/RayRed.xml index df563476..e69df489 100644 --- a/resources/Schema/Entities/RayRed.xml +++ b/resources/Schema/Entities/RayRed.xml @@ -7,7 +7,8 @@ Models/CylinderBullet.mesh - + + true diff --git a/resources/Schema/Entities/SoundEmitter.xml b/resources/Schema/Entities/SoundEmitter.xml new file mode 100644 index 00000000..39b4c750 --- /dev/null +++ b/resources/Schema/Entities/SoundEmitter.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + + SoundEmitter + Fonts/DroidSans.ttf,64 + + + + + + + + + + diff --git a/resources/Schema/Entities/SpawnPointClusterWithModels.xml b/resources/Schema/Entities/SpawnPointClusterWithModels.xml new file mode 100644 index 00000000..9c42d0e4 --- /dev/null +++ b/resources/Schema/Entities/SpawnPointClusterWithModels.xml @@ -0,0 +1,68 @@ + + + + + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + Models/Assault.mesh + + + + + + + + + + + + Models/Assault.mesh + + + + + + + + + + + + Models/Assault.mesh + + + + + + + + + + + + Models/Assault.mesh + + + + + + + + + + diff --git a/resources/Schema/Entities/SpawnerWithPlayerModel.xml b/resources/Schema/Entities/SpawnerWithPlayerModel.xml new file mode 100644 index 00000000..1274eefa --- /dev/null +++ b/resources/Schema/Entities/SpawnerWithPlayerModel.xml @@ -0,0 +1,16 @@ + + + + + + + Models/Assault.mesh + + + + + + + + + diff --git a/resources/Schema/Types/Entity.xsd b/resources/Schema/Types/Entity.xsd index 99b90caa..028af9e6 100644 --- a/resources/Schema/Types/Entity.xsd +++ b/resources/Schema/Types/Entity.xsd @@ -31,6 +31,7 @@ + diff --git a/resources/Shaders/DrawColorCorrection.frag.glsl b/resources/Shaders/DrawColorCorrection.frag.glsl index 8d13992a..91ace0c7 100644 --- a/resources/Shaders/DrawColorCorrection.frag.glsl +++ b/resources/Shaders/DrawColorCorrection.frag.glsl @@ -3,6 +3,7 @@ layout (binding = 0) uniform sampler2D SceneTexture; layout (binding = 1) uniform sampler2D BloomTexture; uniform float Exposure; +uniform float Gamma; in VertexData{ vec2 TextureCoordinate; @@ -12,7 +13,6 @@ out vec4 fragmentColor; void main() { - const float gamma = 2.2; vec4 hdrColor = texture(SceneTexture, Input.TextureCoordinate); vec4 bloomColor = texture(BloomTexture, Input.TextureCoordinate); hdrColor += bloomColor; @@ -21,7 +21,7 @@ void main() vec3 result = vec3(1.0) - exp(-hdrColor.rgb * Exposure); //gamme correction - result = pow(result, vec3(1.0 / gamma)); + result = pow(result, vec3(1.0 / Gamma)); fragmentColor = vec4(result, 1.0); //fragmentColor = hdrColor; diff --git a/resources/Shaders/ExplosionEffect.geom.glsl b/resources/Shaders/ExplosionEffect.geom.glsl index cb91b545..44b44aa6 100644 --- a/resources/Shaders/ExplosionEffect.geom.glsl +++ b/resources/Shaders/ExplosionEffect.geom.glsl @@ -17,15 +17,21 @@ uniform bool ExponentialAccelaration; in VertexData{ vec3 Position; vec3 Normal; + vec3 Tangent; + vec3 BiTangent; vec2 TextureCoordinate; vec4 ExplosionColor; + float ExplosionPercentageElapsed; }Input[]; out VertexData{ vec3 Position; vec3 Normal; + vec3 Tangent; + vec3 BiTangent; vec2 TextureCoordinate; vec4 ExplosionColor; + float ExplosionPercentageElapsed; }Output; layout(triangles) in; @@ -114,12 +120,17 @@ void main() { // calculate the max distance (s) the triangle will move float s = (randomVelocity.x * ExplosionDuration) + (0.5 * a * pow(ExplosionDuration, 2)); + float te = (length(triangleCenter2ExplosionRadius) / s); - Output.ExplosionColor = EndColor * (length(triangleCenter2ExplosionRadius) / s); + Output.ExplosionColor = EndColor; + Output.ExplosionPercentageElapsed = te; + } else { - Output.ExplosionColor = EndColor * timePercetage; + Output.ExplosionColor = EndColor; + Output.ExplosionPercentageElapsed = timePercetage; + } // for every vertex on the triangle... @@ -132,6 +143,8 @@ void main() Output.Normal = Input[i].Normal; Output.Position = Input[i].Position; Output.TextureCoordinate = Input[i].TextureCoordinate; + Output.Tangent = Input[i].Tangent; + Output.BiTangent = Input[i].BiTangent; // convert to model space for the gravity to always be in -y vec4 ExplodedPositionInModelSpace = M * vec4(ExplodedPosition, 1.0); @@ -154,11 +167,14 @@ void main() // if explosion color should be affected by distance instead of time... if (ColorByDistance == true) { - Output.ExplosionColor = vec4(0.0); + Output.ExplosionColor = EndColor; + Output.ExplosionPercentageElapsed = 0.0; } else { - Output.ExplosionColor = EndColor * timePercetage; + Output.ExplosionColor = EndColor; + Output.ExplosionPercentageElapsed = timePercetage; + } // for every vertex on the triangle... @@ -168,7 +184,9 @@ void main() Output.Normal = Input[i].Normal; Output.Position = Input[i].Position; Output.TextureCoordinate = Input[i].TextureCoordinate; - + Output.Tangent = Input[i].Tangent; + Output.BiTangent = Input[i].BiTangent; + // no change in position, pass through vertex gl_Position = gl_in[i].gl_Position; EmitVertex(); diff --git a/resources/Shaders/ForwardPlus.frag.glsl b/resources/Shaders/ForwardPlus.frag.glsl index de672dd1..c09e0438 100644 --- a/resources/Shaders/ForwardPlus.frag.glsl +++ b/resources/Shaders/ForwardPlus.frag.glsl @@ -7,13 +7,13 @@ uniform vec4 Color; uniform vec4 DiffuseColor; uniform vec2 ScreenDimensions; uniform vec4 FillColor; +uniform vec4 AmbientColor; uniform float FillPercentage; layout (binding = 0) uniform sampler2D DiffuseTexture; layout (binding = 1) uniform sampler2D NormalMapTexture; layout (binding = 2) uniform sampler2D SpecularMapTexture; layout (binding = 3) uniform sampler2D GlowMapTexture; - #define TILE_SIZE 16 struct LightSource { @@ -55,13 +55,12 @@ in VertexData{ vec3 BiTangent; vec2 TextureCoordinate; vec4 ExplosionColor; + float ExplosionPercentageElapsed; }Input; out vec4 sceneColor; out vec4 bloomColor; -vec4 scene_ambient = vec4(0.3,0.3,0.3,1); - struct LightResult { vec4 Diffuse; vec4 Specular; @@ -120,6 +119,7 @@ void main() vec4 specularTexel = texture2D(SpecularMapTexture, Input.TextureCoordinate); vec4 position = V * M * vec4(Input.Position, 1.0); vec4 normal = V * CalcNormalMappedValue(Input.Normal, Input.Tangent, Input.BiTangent, Input.TextureCoordinate, NormalMapTexture); + normal = normalize(normal); //vec4 normal = normalize(V * vec4(Input.Normal, 0.0)); vec4 viewVec = normalize(-position); @@ -128,7 +128,7 @@ void main() tilePos.y = int(gl_FragCoord.y/TILE_SIZE); LightResult totalLighting; - totalLighting.Diffuse = scene_ambient; + totalLighting.Diffuse = vec4(AmbientColor.rgb, 1.0); int currentTile = int(floor(gl_FragCoord.x/TILE_SIZE) + (floor(gl_FragCoord.y/TILE_SIZE) * int(ScreenDimensions.x/TILE_SIZE))); int start = int(LightGrids.Data[currentTile].Start); @@ -150,8 +150,9 @@ void main() totalLighting.Specular += light_result.Specular; } - - vec4 color_result = (DiffuseColor + Input.ExplosionColor) * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)) * diffuseTexel * Color; + vec4 color_result = mix((Color * diffuseTexel * DiffuseColor), Input.ExplosionColor, Input.ExplosionPercentageElapsed); + color_result = color_result * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)); + //vec4 color_result = (DiffuseColor + Input.ExplosionColor) * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)) * diffuseTexel * Color; float pos = ((P * vec4(Input.Position, 1)).y + 1.0)/2.0; @@ -160,7 +161,7 @@ void main() color_result += FillColor; } sceneColor = vec4(color_result.xyz, clamp(color_result.a, 0, 1)); - color_result += glowTexel; + color_result += glowTexel*3; bloomColor = vec4(clamp(color_result.xyz - 1.0, 0, 100), 1.0); diff --git a/resources/Shaders/ForwardPlus.vert.glsl b/resources/Shaders/ForwardPlus.vert.glsl index 1a7cca12..3b3e931c 100644 --- a/resources/Shaders/ForwardPlus.vert.glsl +++ b/resources/Shaders/ForwardPlus.vert.glsl @@ -20,6 +20,7 @@ out VertexData{ vec3 BiTangent; vec2 TextureCoordinate; vec4 ExplosionColor; + float ExplosionPercentageElapsed; }Output; void main() @@ -41,5 +42,6 @@ void main() Output.Normal = vec3(M * vec4(Normal, 0.0)); Output.Tangent = vec3(M * vec4(Tangent, 0.0)); Output.BiTangent = vec3(M * vec4(BiTangent, 0.0)); - Output.ExplosionColor = vec4(0.0); + Output.ExplosionColor = vec4(1.0); + Output.ExplosionPercentageElapsed = 0.0; } \ No newline at end of file diff --git a/src/Engine/Editor/EditorRenderSystem.cpp b/src/Engine/Editor/EditorRenderSystem.cpp index 67b09a21..4d65e9d3 100644 --- a/src/Engine/Editor/EditorRenderSystem.cpp +++ b/src/Engine/Editor/EditorRenderSystem.cpp @@ -23,6 +23,12 @@ void EditorRenderSystem::Update(double dt) scene.Camera = m_EditorCamera; scene.Viewport = Rectangle(1920, 1080); + auto cSceneLight = m_World->GetComponents("SceneLight"); + if (cSceneLight != nullptr) { + //these are hardcoded since they want special light treatment and a component just for widgets is stupid. + scene.AmbientColor = glm::vec4(0.8, 0.8, 0.8, 1.0); + } + auto models = m_World->GetComponents("Model"); if (models != nullptr) { for (auto& cModel : *models) { @@ -49,7 +55,7 @@ void EditorRenderSystem::Update(double dt) glm::mat4 modelMatrix = Transform::ModelMatrix(entity.ID, entity.World); for (auto matGroup : model->MaterialGroups()) { std::shared_ptr modelJob = std::make_shared(model, scene.Camera, modelMatrix, matGroup, cModel, entity.World, glm::vec4(0), 0.f); - if(cModel["Transparent"]) { + if (cModel["Transparent"]) { scene.TransparentObjects.push_back(modelJob); } else { scene.OpaqueObjects.push_back(modelJob); diff --git a/src/Engine/Rendering/DrawColorCorrectionPass.cpp b/src/Engine/Rendering/DrawColorCorrectionPass.cpp index ba9efe3e..45401bce 100644 --- a/src/Engine/Rendering/DrawColorCorrectionPass.cpp +++ b/src/Engine/Rendering/DrawColorCorrectionPass.cpp @@ -5,7 +5,8 @@ DrawColorCorrectionPass::DrawColorCorrectionPass(IRenderer* renderer) m_Renderer = renderer; m_ScreenQuad = ResourceManager::Load("Models/Core/ScreenQuad.mesh"); - m_Exposure = 0.4; //TODO: Renderer: Fixa så att denna går att ändra på genom komponent eller setting. + + //m_Exposure = 0.4; //TODO: Renderer: Fixa så att denna går att ändra på genom komponent eller setting. InitializeShaderPrograms(); } @@ -19,15 +20,16 @@ void DrawColorCorrectionPass::InitializeShaderPrograms() m_ColorCorrectionProgram->Link(); } -void DrawColorCorrectionPass::Draw(GLuint sceneTexture, GLuint bloomTexture) +void DrawColorCorrectionPass::Draw(GLuint sceneTexture, GLuint bloomTexture, GLfloat gamma, GLfloat exposure) { //glBindFramebuffer(GL_FRAMEBUFFER, 0); GLERROR("DrawScreenQuadPass::Draw: Pre"); DrawScreenQuadPassState state = DrawScreenQuadPassState(); m_ColorCorrectionProgram->Bind(); - glClear(GL_COLOR_BUFFER_BIT); - glUniform1f(glGetUniformLocation(m_ColorCorrectionProgram->GetHandle(), "Exposure"), m_Exposure); + //glClear(GL_COLOR_BUFFER_BIT); + glUniform1f(glGetUniformLocation(m_ColorCorrectionProgram->GetHandle(), "Exposure"), exposure); + glUniform1f(glGetUniformLocation(m_ColorCorrectionProgram->GetHandle(), "Gamma"), gamma); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, sceneTexture); diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index aa9da9a1..8247797e 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -44,6 +44,7 @@ void DrawFinalPass::InitializeShaderPrograms() m_ForwardPlusProgram->BindFragDataLocation(0, "sceneColor"); m_ForwardPlusProgram->BindFragDataLocation(1, "bloomColor"); m_ForwardPlusProgram->Link(); + GLERROR("Creating forward+ program"); m_ExplosionEffectProgram = ResourceManager::Load("#ExplosionEffectProgram"); m_ExplosionEffectProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ForwardPlus.vert.glsl"))); @@ -53,11 +54,12 @@ void DrawFinalPass::InitializeShaderPrograms() m_ExplosionEffectProgram->BindFragDataLocation(0, "sceneColor"); m_ExplosionEffectProgram->BindFragDataLocation(1, "bloomColor"); m_ExplosionEffectProgram->Link(); + GLERROR("Creating explosion program"); } void DrawFinalPass::Draw(RenderScene& scene) { - GLERROR("DrawFinalPass::Draw: Pre"); + GLERROR("Pre"); DrawFinalPassState* state = new DrawFinalPassState(m_FinalPassFrameBuffer.GetHandle()); if (scene.ClearDepth) { @@ -65,12 +67,12 @@ void DrawFinalPass::Draw(RenderScene& scene) } DrawModelRenderQueues(scene.OpaqueObjects, scene); - GLERROR("DrawFinalPass::Draw: OpaqueObjects"); + GLERROR("OpaqueObjects"); DrawModelRenderQueues(scene.TransparentObjects, scene); - GLERROR("DrawFinalPass::Draw: TransparentObjects"); + GLERROR("TransparentObjects"); - GLERROR("DrawFinalPass::Draw: END"); delete state; + GLERROR("END"); } @@ -111,7 +113,9 @@ void DrawFinalPass::GenerateMipMapTexture(GLuint* texture, GLenum wrapping, glm: void DrawFinalPass::DrawModelRenderQueues(std::list>& job, RenderScene& scene) { GLuint forwardHandle = m_ForwardPlusProgram->GetHandle(); + GLERROR("forwardHandle"); GLuint explosionHandle = m_ExplosionEffectProgram->GetHandle(); + GLERROR("explosionHandle"); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, m_LightCullingPass->LightSSBO()); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, m_LightCullingPass->LightGridSSBO()); @@ -122,10 +126,21 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& auto explosionEffectJob = std::dynamic_pointer_cast(job); if(explosionEffectJob) { //Bind program + if(GLERROR("Prebind")) { + continue; + } m_ExplosionEffectProgram->Bind(); + if(GLERROR("BindProgram")) { + continue; + } + + glDisable(GL_CULL_FACE); //Bind uniforms BindExplosionUniforms(explosionHandle, explosionEffectJob, scene); + if(GLERROR("BindExplosionUniforms")) { + continue; + } if (explosionEffectJob->Model->m_RawModel->m_Skeleton != nullptr) { @@ -134,13 +149,23 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& glUniformMatrix4fv(glGetUniformLocation(explosionHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); } } + if(GLERROR("Animation")) { + continue; + } //bind textures BindExplosionTextures(explosionEffectJob); + if(GLERROR("BindExplosionTextures")) { + continue; + } //draw glBindVertexArray(explosionEffectJob->Model->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, explosionEffectJob->Model->ElementBuffer); glDrawElements(GL_TRIANGLES, explosionEffectJob->EndIndex - explosionEffectJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(explosionEffectJob->StartIndex*sizeof(unsigned int))); + glEnable(GL_CULL_FACE); + if(GLERROR("explosion effect end")) { + continue; + } } else { auto modelJob = std::dynamic_pointer_cast(job); @@ -167,7 +192,9 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& glBindVertexArray(modelJob->Model->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer); glDrawElements(GL_TRIANGLES, modelJob->EndIndex - modelJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(modelJob->StartIndex*sizeof(unsigned int))); - GLERROR("DrawFinalPass::Model: END"); + if(GLERROR("models end")) { + continue; + } } } } @@ -176,36 +203,46 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& void DrawFinalPass::BindExplosionUniforms(GLuint shaderHandle, std::shared_ptr& job, RenderScene& scene) { + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(job->Matrix)); 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())); + glUniform2f(glGetUniformLocation(shaderHandle, "ScreenDimensions"), m_Renderer->Resolution().Width, m_Renderer->Resolution().Height); - glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(job->Matrix)); - glUniform4fv(glGetUniformLocation(shaderHandle, "Color"), 1, glm::value_ptr(job->Color)); glUniform3fv(glGetUniformLocation(shaderHandle, "ExplosionOrigin"), 1, glm::value_ptr(job->ExplosionOrigin)); glUniform1f(glGetUniformLocation(shaderHandle, "TimeSinceDeath"), job->TimeSinceDeath); glUniform1f(glGetUniformLocation(shaderHandle, "ExplosionDuration"), job->ExplosionDuration); glUniform4fv(glGetUniformLocation(shaderHandle, "EndColor"), 1, glm::value_ptr(job->EndColor)); glUniform1i(glGetUniformLocation(shaderHandle, "Randomness"), job->Randomness); + glUniform1fv(glGetUniformLocation(shaderHandle, "RandomNumbers"), 50, job->RandomNumbers.data()); glUniform1f(glGetUniformLocation(shaderHandle, "RandomnessScalar"), job->RandomnessScalar); glUniform2fv(glGetUniformLocation(shaderHandle, "Velocity"), 1, glm::value_ptr(job->Velocity)); glUniform1i(glGetUniformLocation(shaderHandle, "ColorByDistance"), job->ColorByDistance); glUniform1i(glGetUniformLocation(shaderHandle, "ExponentialAccelaration"), job->ExponentialAccelaration); - glUniform4fv(glGetUniformLocation(shaderHandle, "DiffuseColor"), 1, glm::value_ptr(job->DiffuseColor)); - glUniform1fv(glGetUniformLocation(shaderHandle, "RandomNumbers"), 50, job->RandomNumbers.data()); -} -void DrawFinalPass::BindModelUniforms(GLuint shaderHandle, std::shared_ptr& job, RenderScene& scene) -{ - 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())); - glUniform2f(glGetUniformLocation(shaderHandle, "ScreenDimensions"), m_Renderer->Resolution().Width, m_Renderer->Resolution().Height); - - glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(job->Matrix)); glUniform4fv(glGetUniformLocation(shaderHandle, "Color"), 1, glm::value_ptr(job->Color)); glUniform4fv(glGetUniformLocation(shaderHandle, "DiffuseColor"), 1, glm::value_ptr(job->DiffuseColor)); glUniform4fv(glGetUniformLocation(shaderHandle, "FillColor"), 1, glm::value_ptr(job->FillColor)); glUniform1f(glGetUniformLocation(shaderHandle, "FillPercentage"), job->FillPercentage); + glUniform4fv(glGetUniformLocation(shaderHandle, "AmbientColor"), 1, glm::value_ptr(scene.AmbientColor)); + GLERROR("END"); +} + +void DrawFinalPass::BindModelUniforms(GLuint shaderHandle, std::shared_ptr& job, RenderScene& scene) +{ + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(job->Matrix)); + 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())); + + glUniform2f(glGetUniformLocation(shaderHandle, "ScreenDimensions"), m_Renderer->Resolution().Width, m_Renderer->Resolution().Height); + + glUniform4fv(glGetUniformLocation(shaderHandle, "Color"), 1, glm::value_ptr(job->Color)); + glUniform4fv(glGetUniformLocation(shaderHandle, "DiffuseColor"), 1, glm::value_ptr(job->DiffuseColor)); + glUniform4fv(glGetUniformLocation(shaderHandle, "FillColor"), 1, glm::value_ptr(job->FillColor)); + glUniform1f(glGetUniformLocation(shaderHandle, "FillPercentage"), job->FillPercentage); + glUniform4fv(glGetUniformLocation(shaderHandle, "AmbientColor"), 1, glm::value_ptr(scene.AmbientColor)); + + GLERROR("END"); } @@ -217,7 +254,22 @@ void DrawFinalPass::BindExplosionTextures(std::shared_ptr& j } else { glBindTexture(GL_TEXTURE_2D, m_WhiteTexture->m_Texture); } + glActiveTexture(GL_TEXTURE1); + if (job->NormalTexture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->NormalTexture->m_Texture); + } else { + glBindTexture(GL_TEXTURE_2D, m_NeutralNormalTexture->m_Texture); + } + + glActiveTexture(GL_TEXTURE2); + if (job->SpecularTexture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->SpecularTexture->m_Texture); + } else { + glBindTexture(GL_TEXTURE_2D, m_GreyTexture->m_Texture); + } + + glActiveTexture(GL_TEXTURE3); if (job->IncandescenceTexture != nullptr) { glBindTexture(GL_TEXTURE_2D, job->IncandescenceTexture->m_Texture); } else { diff --git a/src/Engine/Rendering/FrameBuffer.cpp b/src/Engine/Rendering/FrameBuffer.cpp index b7e908cc..9677f50e 100644 --- a/src/Engine/Rendering/FrameBuffer.cpp +++ b/src/Engine/Rendering/FrameBuffer.cpp @@ -54,13 +54,6 @@ void FrameBuffer::Generate() case GL_RENDERBUFFER: glFramebufferRenderbuffer(GL_FRAMEBUFFER, (*it)->m_Attachment, (*it)->m_ResourceType, *(*it)->m_ResourceHandle); GLERROR("FrameBuffer generate: glFramebufferRenderbuffer"); - if ( (*it)->m_Attachment != GL_COLOR_ATTACHMENT0 || - (*it)->m_Attachment != GL_COLOR_ATTACHMENT1 || - (*it)->m_Attachment != GL_DEPTH_ATTACHMENT || - (*it)->m_Attachment != GL_STENCIL_ATTACHMENT) //TODO: Viktor: Fixa detta - { - LOG_ERROR("RenderBuffer Attachment not valid."); - } break; } diff --git a/src/Engine/Rendering/PickingPass.cpp b/src/Engine/Rendering/PickingPass.cpp index 792539f8..abc79f2e 100644 --- a/src/Engine/Rendering/PickingPass.cpp +++ b/src/Engine/Rendering/PickingPass.cpp @@ -75,9 +75,9 @@ void PickingPass::Draw(RenderScene& scene) m_EntityColors[std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)] = glm::ivec2(pickColor[0], pickColor[1]); if (m_ColorCounter[0] > 255) { m_ColorCounter[0] = 0; - m_ColorCounter[1] += 5; + m_ColorCounter[1] += 1; } else { - m_ColorCounter[0] += 50; + m_ColorCounter[0] += 1; } } @@ -121,9 +121,9 @@ void PickingPass::Draw(RenderScene& scene) m_EntityColors[std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)] = glm::ivec2(pickColor[0], pickColor[1]); if (m_ColorCounter[0] > 255) { m_ColorCounter[0] = 0; - m_ColorCounter[1] += 5; + m_ColorCounter[1] += 1; } else { - m_ColorCounter[0] += 50; + m_ColorCounter[0] += 1; } } diff --git a/src/Engine/Rendering/RenderSystem.cpp b/src/Engine/Rendering/RenderSystem.cpp index a0912a45..eaecf99e 100644 --- a/src/Engine/Rendering/RenderSystem.cpp +++ b/src/Engine/Rendering/RenderSystem.cpp @@ -240,10 +240,17 @@ void RenderSystem::Update(double dt) m_Camera->SetOrientation(Transform::AbsoluteOrientation(m_CurrentCamera)); } - RenderScene scene; scene.Camera = m_Camera; scene.Viewport = Rectangle(1280, 720); + + auto cSceneLight = m_World->GetComponents("SceneLight"); + if (cSceneLight != nullptr && cSceneLight->begin() != cSceneLight->end()) { + m_RenderFrame->Gamma = (double)(*cSceneLight->begin())["Gamma"]; + m_RenderFrame->Exposure = (double)(*cSceneLight->begin())["Exposure"]; + scene.AmbientColor = (glm::vec4)(*cSceneLight->begin())["AmbientColor"]; + } + fillModels(scene.OpaqueObjects, scene.TransparentObjects); fillPointLights(scene.PointLightJobs, m_World); fillDirectionalLights(scene.DirectionalLightJobs, m_World); diff --git a/src/Engine/Rendering/Renderer.cpp b/src/Engine/Rendering/Renderer.cpp index bec86b4a..a63e02a0 100644 --- a/src/Engine/Rendering/Renderer.cpp +++ b/src/Engine/Rendering/Renderer.cpp @@ -119,8 +119,8 @@ void Renderer::Draw(RenderFrame& frame) } m_DrawBloomPass->Draw(m_DrawFinalPass->BloomTexture()); - if(m_DebugTextureToDraw == 0) { - m_DrawColorCorrectionPass->Draw(m_DrawFinalPass->SceneTexture(), m_DrawBloomPass->GaussianTexture()); + if (m_DebugTextureToDraw == 0) { + m_DrawColorCorrectionPass->Draw(m_DrawFinalPass->SceneTexture(), m_DrawBloomPass->GaussianTexture(), frame.Gamma, frame.Exposure); } if (m_DebugTextureToDraw == 1) { m_DrawScreenQuadPass->Draw(m_DrawFinalPass->SceneTexture()); From 7b5a2a538815c632da5713ba3a68c5861d2f97df Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Wed, 3 Feb 2016 17:30:46 +0100 Subject: [PATCH 061/355] Dashing now works great both with shift and doubletap. Added Dash Component. Changed default Player.xml to have a Dash Component. Disabled Sprint. You can now disable DoubleTapToDash in Input.Ini. Added command "SpecialAbility". --- .../Editor/EditorCameraInputController.h | 7 +- .../Engine/Input/FirstPersonInputController.h | 98 ++++++++++++++----- resources/Schema/Components.xsd | 1 + resources/Schema/Components/Dash.xml | 4 + resources/Schema/Components/Dash.xsd | 18 ++++ resources/Schema/Entities/Player.xml | 1 + src/Game/Systems/PlayerMovementSystem.cpp | 13 ++- 7 files changed, 108 insertions(+), 34 deletions(-) create mode 100644 resources/Schema/Components/Dash.xml create mode 100644 resources/Schema/Components/Dash.xsd diff --git a/include/Engine/Editor/EditorCameraInputController.h b/include/Engine/Editor/EditorCameraInputController.h index 4c139e01..6c5e8b14 100644 --- a/include/Engine/Editor/EditorCameraInputController.h +++ b/include/Engine/Editor/EditorCameraInputController.h @@ -55,11 +55,12 @@ public: } } - if (e.Command == "Sprint") { + //this is just temp here, the sprint ability. it will have a component check later + if (e.Command == "SpecialAbility") { if (e.Value > 0) { - m_SpeedMultiplier *= 2.f; + //m_SpeedMultiplier *= 2.f; } else { - m_SpeedMultiplier /= 2.f; + //m_SpeedMultiplier /= 2.f; } } diff --git a/include/Engine/Input/FirstPersonInputController.h b/include/Engine/Input/FirstPersonInputController.h index 1efe4b75..4e964d19 100644 --- a/include/Engine/Input/FirstPersonInputController.h +++ b/include/Engine/Input/FirstPersonInputController.h @@ -4,6 +4,7 @@ #include "../GLM.h" #include "../Core/InputController.h" #include "../Core/ELockMouse.h" +#include "InputHandler.h" template class FirstPersonInputController : public InputController @@ -48,12 +49,18 @@ protected: //assault dash membervariables double m_AssaultDashDoubleTapDeltaTime = 0.0f; double m_AssaultDashCoolDownTimer = 0.0f; - double m_AssaultDashCoolDownMaxTimer = 3.0f; + double m_AssaultDashCoolDownMaxTimer = 2.0f; AssaultDashDirection m_AssaultDashDoubleTapLastKey = AssaultDashDirection::None; const float m_AssaultDashDoubleTapSensitivityTimer = 0.25f; - AssaultDashDirection m_AssaultDashTapDirection = AssaultDashDirection::None; + std::string m_AssaultDashTapDirection = ""; bool m_AssaultDashDoubleTapped = false; bool m_PlayerIsDashing = false; + bool m_ShiftDashing = true; + bool m_ValidDoubleTap = false; + + //specialabilitys + bool m_MovementKeyDown = false; + bool m_SpecialAbilityKeyDown = false; EventRelay m_ELockMouse; bool OnLockMouse(const Events::LockMouse& e); @@ -125,6 +132,22 @@ bool FirstPersonInputController::OnCommand(const Events::InputComm } } + if (e.Command == "Forward" || e.Command == "Right") { + //if value = 0 then you have just released this key + if (e.Value > 0 || e.Value < 0) { + m_MovementKeyDown = true; + //if you pressed the same key within m_AssaultDashDoubleTapSensitivityTimer then you have doubletapped it + if (m_AssaultDashDoubleTapDeltaTime < m_AssaultDashDoubleTapSensitivityTimer && m_AssaultDashTapDirection == e.Command) { + m_ValidDoubleTap = true; + } + } else { + m_MovementKeyDown = false; + //you have just released the key, store what key it was and reset the doubletap-sensitivity-timer + m_AssaultDashTapDirection = e.Command; + m_AssaultDashDoubleTapDeltaTime = 0.f; + } + } + if (e.Command == "Jump") { m_Jumping = e.Value > 0; } @@ -133,6 +156,19 @@ bool FirstPersonInputController::OnCommand(const Events::InputComm m_Crouching = e.Value > 0; } + if (e.Command == "SpecialAbility") { + if (e.Value > 0) { + m_SpecialAbilityKeyDown = true; + } else { + m_SpecialAbilityKeyDown = false; + } + } + if (m_SpecialAbilityKeyDown && m_MovementKeyDown) { + m_ShiftDashing = true; + } else { + m_ShiftDashing = false; + } + return true; } @@ -152,7 +188,6 @@ bool FirstPersonInputController::OnLockMouse(const Events::LockMou template void FirstPersonInputController::AssaultDashCheck(double dt, bool isJumping) { - auto controllerMovement = Movement(); m_AssaultDashDoubleTapDeltaTime += dt; m_AssaultDashCoolDownTimer -= dt; //cooldown = m_AssaultDashCoolDownMaxTimer sec, pretend the dash lasts 0.25 sec (for friction to do its work) @@ -161,34 +196,43 @@ void FirstPersonInputController::AssaultDashCheck(double dt, bool } else { m_PlayerIsDashing = false; } - //reset the DoubleTapped state in case we recently doubleTapped + + //dashing with shift + if (m_ShiftDashing && m_AssaultDashCoolDownTimer <= 0.0f && !isJumping) { + //player is dashing with shift + //the wanted-direction is set in playermovement already so we dont need to check what direction we want to dash in! + m_AssaultDashCoolDownTimer = m_AssaultDashCoolDownMaxTimer; + m_AssaultDashDoubleTapped = true; + m_AssaultDashDoubleTapDeltaTime = 0.f; + //moving to the side has priority + return; + } + + //dashing with doubletap - check if doubletap to dash enabled + if (ResourceManager::Load("Input.ini")->Get("Keyboard.DoubleTapToDash", false)) { + return; + } + + //reset the DoubleTapped state in case we recently doubleTapped (doubletap will only happen during 1 frame) if (m_AssaultDashDoubleTapped) { m_AssaultDashDoubleTapped = false; } - //Assault Dash logic: tap left or right twice within 0.5sec to activate the doubletap-dash - if (controllerMovement.x > 0 && controllerMovement.y == 0.f && controllerMovement.z == 0.f) { - if (m_AssaultDashDoubleTapLastKey != AssaultDashDirection::Right && m_AssaultDashDoubleTapDeltaTime < m_AssaultDashDoubleTapSensitivityTimer - && m_AssaultDashTapDirection == AssaultDashDirection::Right && m_AssaultDashCoolDownTimer <= 0.0f && !isJumping) { - m_AssaultDashDoubleTapped = true; - m_AssaultDashDoubleTapDeltaTime = 0.f; - m_AssaultDashCoolDownTimer = m_AssaultDashCoolDownMaxTimer; - } - m_AssaultDashDoubleTapLastKey = AssaultDashDirection::Right; - m_AssaultDashDoubleTapDeltaTime = 0.f; - m_AssaultDashTapDirection = AssaultDashDirection::Right; - } else if (controllerMovement.x < 0 && controllerMovement.y == 0.f && controllerMovement.z == 0.f) { - if (m_AssaultDashDoubleTapLastKey != AssaultDashDirection::Left && m_AssaultDashDoubleTapDeltaTime < m_AssaultDashDoubleTapSensitivityTimer - && m_AssaultDashTapDirection == AssaultDashDirection::Left && m_AssaultDashCoolDownTimer <= 0.0f && !isJumping) { - m_AssaultDashDoubleTapped = true; - m_AssaultDashDoubleTapDeltaTime = 0.f; - m_AssaultDashCoolDownTimer = m_AssaultDashCoolDownMaxTimer; - } - m_AssaultDashDoubleTapLastKey = AssaultDashDirection::Left; - m_AssaultDashDoubleTapDeltaTime = 0.f; - m_AssaultDashTapDirection = AssaultDashDirection::Left; - } else { - m_AssaultDashDoubleTapLastKey = AssaultDashDirection::None; + + //check if we have received a valid doubletap + if (!m_ValidDoubleTap) { + return; } + m_ValidDoubleTap = false; + + if (!(m_AssaultDashCoolDownTimer <= 0.0f && !isJumping)) { + //if we cant dash at the moment, then just reset the tap-sensitivity-timer + m_AssaultDashDoubleTapDeltaTime = 0.f; + return; + } + //ok, we have a valid tap, lets do it + m_AssaultDashDoubleTapped = true; + m_AssaultDashDoubleTapDeltaTime = 0.f; + m_AssaultDashCoolDownTimer = m_AssaultDashCoolDownMaxTimer; } #endif \ No newline at end of file diff --git a/resources/Schema/Components.xsd b/resources/Schema/Components.xsd index bb1fd770..17278f14 100644 --- a/resources/Schema/Components.xsd +++ b/resources/Schema/Components.xsd @@ -30,4 +30,5 @@ + \ No newline at end of file diff --git a/resources/Schema/Components/Dash.xml b/resources/Schema/Components/Dash.xml new file mode 100644 index 00000000..084f9620 --- /dev/null +++ b/resources/Schema/Components/Dash.xml @@ -0,0 +1,4 @@ + + + true + \ No newline at end of file diff --git a/resources/Schema/Components/Dash.xsd b/resources/Schema/Components/Dash.xsd new file mode 100644 index 00000000..68b64b0c --- /dev/null +++ b/resources/Schema/Components/Dash.xsd @@ -0,0 +1,18 @@ + + + + + + + + A dash component for one of the classes + + + + + Yada + + + + + \ No newline at end of file diff --git a/resources/Schema/Entities/Player.xml b/resources/Schema/Entities/Player.xml index d365c0ee..3029e9f7 100644 --- a/resources/Schema/Entities/Player.xml +++ b/resources/Schema/Entities/Player.xml @@ -6,6 +6,7 @@ + diff --git a/src/Game/Systems/PlayerMovementSystem.cpp b/src/Game/Systems/PlayerMovementSystem.cpp index 70bbafb0..4fe3da2d 100644 --- a/src/Game/Systems/PlayerMovementSystem.cpp +++ b/src/Game/Systems/PlayerMovementSystem.cpp @@ -43,8 +43,14 @@ void PlayerMovementSystem::Update(double dt) ComponentWrapper cPhysics = player["Physics"]; //Assault Dash Check - //TODO: check if playerclass is assault! - controller->AssaultDashCheck(dt, ((glm::vec3)cPhysics["Velocity"]).y != 0.0f); + if (player.HasComponent("Dash")) { + controller->AssaultDashCheck(dt, ((glm::vec3)cPhysics["Velocity"]).y != 0.0f); + } glm::vec3 wishDirection = controller->Movement() * glm::inverse(glm::quat(ori)); + //this makes sure you can only dash in the 4 directions: forw,backw,left,right + if (controller->AssaultDashDoubleTapped() && controller->Movement().z != 0 && controller->Movement().x != 0) { + wishDirection = glm::vec3(controller->Movement().x, 0, 0)* glm::inverse(glm::quat(ori)); + } float wishSpeed; if (controller->Crouching()) { wishSpeed = playerCrouchSpeed; @@ -74,7 +80,7 @@ void PlayerMovementSystem::Update(double dt) ImGui::InputFloat("surfaceFriction", &surfaceFriction); float accelerationSpeed = actualAccel * (float)dt * wishSpeed * surfaceFriction; //if doubleTapped do Assault Dash - but only boost maximum 50.0f - float doubleTapDashBoost = controller->AssaultDashDoubleTapped() ? 20.0f : 1.0f; + float doubleTapDashBoost = controller->AssaultDashDoubleTapped() ? 40.0f : 1.0f; accelerationSpeed = glm::min(doubleTapDashBoost*glm::min(accelerationSpeed, addSpeed), 50.0f); velocity += accelerationSpeed * wishDirection; ImGui::Text("velocity: (%f, %f, %f) |%f|", velocity.x, velocity.y, velocity.z, glm::length(velocity)); @@ -84,8 +90,7 @@ void PlayerMovementSystem::Update(double dt) if (!controller->PlayerIsDashing() && controller->Jumping() && !controller->Crouching() && (velocity.y == 0.f || !controller->DoubleJumping())) { if (velocity.y == 0.f) { controller->SetDoubleJumping(false); - } - else { + } else { controller->SetDoubleJumping(true); } velocity.y += 4.f; From 1bd4aa91ff70275f1a3cd38e66c184841617f985 Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Wed, 3 Feb 2016 17:45:37 +0100 Subject: [PATCH 062/355] Oops! Readded "Sprint" command. Removed some unnecessary variables in FirstPersonInputController. Fixed bug where you couldnt dash right away as the game started. --- .../Engine/Editor/EditorCameraInputController.h | 7 +++---- .../Engine/Input/FirstPersonInputController.h | 17 ++++------------- 2 files changed, 7 insertions(+), 17 deletions(-) diff --git a/include/Engine/Editor/EditorCameraInputController.h b/include/Engine/Editor/EditorCameraInputController.h index 6c5e8b14..4c139e01 100644 --- a/include/Engine/Editor/EditorCameraInputController.h +++ b/include/Engine/Editor/EditorCameraInputController.h @@ -55,12 +55,11 @@ public: } } - //this is just temp here, the sprint ability. it will have a component check later - if (e.Command == "SpecialAbility") { + if (e.Command == "Sprint") { if (e.Value > 0) { - //m_SpeedMultiplier *= 2.f; + m_SpeedMultiplier *= 2.f; } else { - //m_SpeedMultiplier /= 2.f; + m_SpeedMultiplier /= 2.f; } } diff --git a/include/Engine/Input/FirstPersonInputController.h b/include/Engine/Input/FirstPersonInputController.h index 4e964d19..de4f1226 100644 --- a/include/Engine/Input/FirstPersonInputController.h +++ b/include/Engine/Input/FirstPersonInputController.h @@ -38,24 +38,15 @@ protected: bool m_Jumping = false; bool m_DoubleJumping = false; bool m_Crouching = false; - //assault dash enum - enum class AssaultDashDirection { - Left, - Right, - Forward, - Backward, - None - }; //assault dash membervariables - double m_AssaultDashDoubleTapDeltaTime = 0.0f; - double m_AssaultDashCoolDownTimer = 0.0f; - double m_AssaultDashCoolDownMaxTimer = 2.0f; - AssaultDashDirection m_AssaultDashDoubleTapLastKey = AssaultDashDirection::None; + double m_AssaultDashDoubleTapDeltaTime = 0.0; + double m_AssaultDashCoolDownTimer = 0.0; + double m_AssaultDashCoolDownMaxTimer = 2.0; const float m_AssaultDashDoubleTapSensitivityTimer = 0.25f; std::string m_AssaultDashTapDirection = ""; bool m_AssaultDashDoubleTapped = false; bool m_PlayerIsDashing = false; - bool m_ShiftDashing = true; + bool m_ShiftDashing = false; bool m_ValidDoubleTap = false; //specialabilitys From bc01e147c27f6a58937a7fd2498f37fcf2bd450e Mon Sep 17 00:00:00 2001 From: Tleety Date: Wed, 3 Feb 2016 18:09:44 +0100 Subject: [PATCH 063/355] Some state stuff, some draw stuff, some QA map stuff --- include/Engine/Rendering/DrawFinalPass.h | 5 +- include/Engine/Rendering/DrawFinalPassState.h | 7 + include/Engine/Rendering/RenderState.h | 1 + .../Schema/Entities/QualityAssurance.xml | 185 ++++++++++++++---- resources/Schema/Types/Entity.xsd | 2 + resources/Shaders/ShieldStencil.frag.glsl | 15 ++ resources/Shaders/ShieldStencil.vert.glsl | 19 ++ src/Engine/Rendering/DrawFinalPass.cpp | 144 +++++++++++++- src/Engine/Rendering/DrawFinalPassState.cpp | 16 ++ src/Engine/Rendering/RenderState.cpp | 14 ++ 10 files changed, 369 insertions(+), 39 deletions(-) create mode 100644 resources/Shaders/ShieldStencil.frag.glsl create mode 100644 resources/Shaders/ShieldStencil.vert.glsl diff --git a/include/Engine/Rendering/DrawFinalPass.h b/include/Engine/Rendering/DrawFinalPass.h index 4b2bcf1f..740c6ef6 100644 --- a/include/Engine/Rendering/DrawFinalPass.h +++ b/include/Engine/Rendering/DrawFinalPass.h @@ -31,7 +31,9 @@ private: void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const; void GenerateMipMapTexture(GLuint* texture, GLenum wrapping, glm::vec2 dimensions, GLint format, GLenum type, GLint numMipMaps) const; - void DrawModelRenderQueues(std::list>& job, RenderScene& scene); + void DrawModelRenderQueues(std::list>& jobs, RenderScene& scene); + void DrawShieldToStencilBuffer(std::list>& jobs, RenderScene& scene); + void DrawShieldedModelRenderQueue(std::list>& jobs, RenderScene& scene); void BindExplosionUniforms(GLuint shaderHandle, std::shared_ptr& job, RenderScene& scene); void BindModelUniforms(GLuint shaderHandle, std::shared_ptr& job, RenderScene& scene); @@ -54,6 +56,7 @@ private: ShaderProgram* m_ForwardPlusProgram; ShaderProgram* m_ExplosionEffectProgram; + ShaderProgram* m_ShieldToStencilProgram; }; #endif \ No newline at end of file diff --git a/include/Engine/Rendering/DrawFinalPassState.h b/include/Engine/Rendering/DrawFinalPassState.h index 10b840e9..91fc4cf4 100644 --- a/include/Engine/Rendering/DrawFinalPassState.h +++ b/include/Engine/Rendering/DrawFinalPassState.h @@ -12,4 +12,11 @@ private: }; +class DrawStencilState : public RenderState +{ +public: + DrawStencilState(GLuint frameBuffer); + ~DrawStencilState(); +}; + #endif \ No newline at end of file diff --git a/include/Engine/Rendering/RenderState.h b/include/Engine/Rendering/RenderState.h index 688ef520..ae43c013 100644 --- a/include/Engine/Rendering/RenderState.h +++ b/include/Engine/Rendering/RenderState.h @@ -19,6 +19,7 @@ public: bool BindFramebuffer(GLint framebuffer); bool BlendEquation(GLenum mode); bool BlendFunc(GLenum sfactor, GLenum dfactor); + bool StencilFunc(GLenum sfail, GLenum dpfail, GLenum dppass); bool DepthMask(GLboolean flag); private: diff --git a/resources/Schema/Entities/QualityAssurance.xml b/resources/Schema/Entities/QualityAssurance.xml index cb75b7b3..11fbaf99 100644 --- a/resources/Schema/Entities/QualityAssurance.xml +++ b/resources/Schema/Entities/QualityAssurance.xml @@ -40,7 +40,7 @@ - + @@ -105,7 +105,7 @@ - + @@ -122,7 +122,7 @@ Run - + 1 @@ -138,7 +138,7 @@ Walk - + 1 @@ -188,7 +188,7 @@ - + @@ -196,7 +196,7 @@ Run - + 1 @@ -237,7 +237,7 @@ - + @@ -301,7 +301,7 @@ - + @@ -333,7 +333,7 @@ - + @@ -683,7 +683,7 @@ - + @@ -730,7 +730,7 @@ - + @@ -790,7 +790,7 @@ - + @@ -837,7 +837,7 @@ - + @@ -883,7 +883,7 @@ - + @@ -930,7 +930,7 @@ - + @@ -977,7 +977,7 @@ - + @@ -1350,6 +1350,19 @@ + + + + ExplosionEffect Test + Fonts/DroidSans.ttf,64 + + + + + + + + @@ -1377,7 +1390,7 @@ - + @@ -1386,7 +1399,7 @@ true - 0.75055150002244431 + 1.3668564709912516 3.7999999523162842 true @@ -1433,7 +1446,7 @@ - + @@ -1442,7 +1455,7 @@ - 1.2004572506365514 + 0.316796204374441 Models/Assault.mesh @@ -1485,7 +1498,7 @@ - + @@ -1493,14 +1506,14 @@ Walk - + 1 true - 0.68390303429648269 + 0.316796204374441 true @@ -1518,18 +1531,120 @@ - + - - ExplosionEffect Test - Fonts/DroidSans.ttf,64 - + + Models/Core/UnitCylinder.mesh + + - - + - + + + + + + + + + + + + + + 0.5 + + + + + + + + + + + true + + + 0.95015514958004132 + 10 + + 3 + true + + + Models/Core/UnitSphere.mesh + + true + + + + + + + + + + + + + + + Models/Core/UnitCylinder.mesh + + + + + + + + + + + + + + + + + + + + 0.5 + + + + + + + + + + + true + + + 1.3501834109561059 + true + 5 + true + + + Models/Assault.mesh + + true + + + + + + + + + + @@ -1597,7 +1712,7 @@ - + 5 @@ -1608,7 +1723,7 @@ - + @@ -1691,7 +1806,7 @@ true - 0.0003117967054762083 + 1.3668564709912516 3.7999999523162842 true @@ -1736,7 +1851,7 @@ Hold Pos - + 1 diff --git a/resources/Schema/Types/Entity.xsd b/resources/Schema/Types/Entity.xsd index 028af9e6..972a45e1 100644 --- a/resources/Schema/Types/Entity.xsd +++ b/resources/Schema/Types/Entity.xsd @@ -38,6 +38,8 @@ + + diff --git a/resources/Shaders/ShieldStencil.frag.glsl b/resources/Shaders/ShieldStencil.frag.glsl new file mode 100644 index 00000000..43a067c0 --- /dev/null +++ b/resources/Shaders/ShieldStencil.frag.glsl @@ -0,0 +1,15 @@ +#version 430 + +in VertexData{ + vec3 Position; +}Input; + + +out vec4 fragmentColor; + +void main() +{ + fragmentColor = vec4(0.5, 0.5, 0.5, 1.0); +} + + diff --git a/resources/Shaders/ShieldStencil.vert.glsl b/resources/Shaders/ShieldStencil.vert.glsl new file mode 100644 index 00000000..b6669f2c --- /dev/null +++ b/resources/Shaders/ShieldStencil.vert.glsl @@ -0,0 +1,19 @@ +#version 430 + +uniform mat4 M; +uniform mat4 V; +uniform mat4 P; + +layout(location = 0) in vec3 Position; + + +out VertexData{ + vec3 Position; +}Output; + +void main() +{ + gl_Position = P * V * M * vec4(Position, 1.0); + + Output.Position = Position; +} \ No newline at end of file diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index 8e015373..d2d22514 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -55,6 +55,14 @@ void DrawFinalPass::InitializeShaderPrograms() m_ExplosionEffectProgram->BindFragDataLocation(1, "bloomColor"); m_ExplosionEffectProgram->Link(); GLERROR("Creating explosion program"); + + m_ShieldToStencilProgram = ResourceManager::Load("#ShieldToStencilProgram"); + m_ShieldToStencilProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ShieldStencil.vert.glsl"))); + m_ShieldToStencilProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ShieldStencil.frag.glsl"))); + m_ShieldToStencilProgram->Compile(); + m_ShieldToStencilProgram->Link(); + GLERROR("Creating Shield program"); + } void DrawFinalPass::Draw(RenderScene& scene) @@ -65,14 +73,30 @@ void DrawFinalPass::Draw(RenderScene& scene) if (scene.ClearDepth) { glClear(GL_DEPTH_BUFFER_BIT); } + //might need to clear stencil here DrawModelRenderQueues(scene.Jobs.OpaqueObjects, scene); GLERROR("OpaqueObjects"); DrawModelRenderQueues(scene.Jobs.TransparentObjects, scene); GLERROR("TransparentObjects"); - delete state; + + DrawStencilState* stencilState = new DrawStencilState(m_FinalPassFrameBuffer.GetHandle()); + glClear(GL_STENCIL_BUFFER_BIT); + //Draw shields to stencil pass + DrawShieldToStencilBuffer(scene.Jobs.ShieldObjects, scene); + GLERROR("StencilPass"); + + //Draw Opaque shielded objects + DrawShieldedModelRenderQueue(scene.Jobs.OpaqueShieldedObjects, scene); + GLERROR("Shielded Opaque object"); + + //Draw Transparen Shielded objects + //DrawShieldedModelRenderQueue(scene.Jobs.TransparentShieldedObjects, scene); + GLERROR("Shielded Transparent objects"); + GLERROR("END"); + delete stencilState; } @@ -110,7 +134,7 @@ void DrawFinalPass::GenerateMipMapTexture(GLuint* texture, GLenum wrapping, glm: GLERROR("MipMap Texture initialization failed"); } -void DrawFinalPass::DrawModelRenderQueues(std::list>& job, RenderScene& scene) +void DrawFinalPass::DrawModelRenderQueues(std::list>& jobs, RenderScene& scene) { GLuint forwardHandle = m_ForwardPlusProgram->GetHandle(); GLERROR("forwardHandle"); @@ -121,7 +145,7 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, m_LightCullingPass->LightGridSSBO()); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, m_LightCullingPass->LightIndexSSBO()); - for(auto &job : job) + for(auto &job : jobs) { auto explosionEffectJob = std::dynamic_pointer_cast(job); if(explosionEffectJob) { @@ -201,6 +225,120 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& } + +void DrawFinalPass::DrawShieldToStencilBuffer(std::list>& jobs, RenderScene& scene) +{ + m_ShieldToStencilProgram->Bind(); + GLuint shaderHandle = m_ShieldToStencilProgram->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())); + + for (auto &job : jobs) { + auto modelJob = std::dynamic_pointer_cast(job); + if (modelJob) { + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); + + + glBindVertexArray(modelJob->Model->VAO); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer); + glDrawElements(GL_TRIANGLES, modelJob->EndIndex - modelJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(modelJob->StartIndex*sizeof(unsigned int))); + if (GLERROR("models end")) { + continue; + } + } + } +} + +void DrawFinalPass::DrawShieldedModelRenderQueue(std::list>& jobs, RenderScene& scene) +{ + GLuint forwardHandle = m_ForwardPlusProgram->GetHandle(); + GLERROR("forwardHandle"); + GLuint explosionHandle = m_ExplosionEffectProgram->GetHandle(); + GLERROR("explosionHandle"); + + glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, m_LightCullingPass->LightSSBO()); + glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, m_LightCullingPass->LightGridSSBO()); + glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, m_LightCullingPass->LightIndexSSBO()); + + for (auto &job : jobs) { + auto explosionEffectJob = std::dynamic_pointer_cast(job); + if (explosionEffectJob) { + //Bind program + if (GLERROR("Prebind")) { + continue; + } + m_ExplosionEffectProgram->Bind(); + if (GLERROR("BindProgram")) { + continue; + } + + glDisable(GL_CULL_FACE); + + //Bind uniforms + BindExplosionUniforms(explosionHandle, explosionEffectJob, scene); + if (GLERROR("BindExplosionUniforms")) { + continue; + } + + if (explosionEffectJob->Model->m_RawModel->m_Skeleton != nullptr) { + + if (explosionEffectJob->Animation != nullptr) { + std::vector frameBones = explosionEffectJob->Skeleton->GetFrameBones(*explosionEffectJob->Animation, explosionEffectJob->AnimationTime); + glUniformMatrix4fv(glGetUniformLocation(explosionHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + } + } + if (GLERROR("Animation")) { + continue; + } + + //bind textures + BindExplosionTextures(explosionEffectJob); + if (GLERROR("BindExplosionTextures")) { + continue; + } + //draw + glBindVertexArray(explosionEffectJob->Model->VAO); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, explosionEffectJob->Model->ElementBuffer); + glDrawElements(GL_TRIANGLES, explosionEffectJob->EndIndex - explosionEffectJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(explosionEffectJob->StartIndex*sizeof(unsigned int))); + glEnable(GL_CULL_FACE); + if (GLERROR("explosion effect end")) { + continue; + } + + } else { + auto modelJob = std::dynamic_pointer_cast(job); + if (modelJob) { + //bind forward program + m_ForwardPlusProgram->Bind(); + glUniform2f(glGetUniformLocation(forwardHandle, "ScreenDimensions"), m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); + + //bind uniforms + BindModelUniforms(forwardHandle, modelJob, scene); + + //bind textures + BindModelTextures(modelJob); + + if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { + + if (modelJob->Animation != nullptr) { + std::vector frameBones = modelJob->Skeleton->GetFrameBones(*modelJob->Animation, modelJob->AnimationTime); + glUniformMatrix4fv(glGetUniformLocation(forwardHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + } + } + + //draw + glBindVertexArray(modelJob->Model->VAO); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer); + glDrawElements(GL_TRIANGLES, modelJob->EndIndex - modelJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(modelJob->StartIndex*sizeof(unsigned int))); + if (GLERROR("models end")) { + continue; + } + } + } + } +} + void DrawFinalPass::BindExplosionUniforms(GLuint shaderHandle, std::shared_ptr& job, RenderScene& scene) { glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(job->Matrix)); diff --git a/src/Engine/Rendering/DrawFinalPassState.cpp b/src/Engine/Rendering/DrawFinalPassState.cpp index 3ebe320d..d85d476c 100644 --- a/src/Engine/Rendering/DrawFinalPassState.cpp +++ b/src/Engine/Rendering/DrawFinalPassState.cpp @@ -1,6 +1,7 @@ #include "Rendering/DrawFinalPassState.h" + DrawFinalPassState::DrawFinalPassState(GLuint frameBuffer) { BindFramebuffer(frameBuffer); @@ -15,3 +16,18 @@ DrawFinalPassState::~DrawFinalPassState() { } + +DrawStencilState::DrawStencilState(GLuint frameBuffer) +{ + BindFramebuffer(frameBuffer); + Enable(GL_STENCIL_TEST); + StencilFunc(GL_KEEP, GL_KEEP, GL_REPLACE); + Enable(GL_DEPTH_TEST); + ClearColor(glm::vec4(0.f)); +} + +DrawStencilState::~DrawStencilState() +{ + +} + diff --git a/src/Engine/Rendering/RenderState.cpp b/src/Engine/Rendering/RenderState.cpp index 1da2f0b1..d85b2b43 100644 --- a/src/Engine/Rendering/RenderState.cpp +++ b/src/Engine/Rendering/RenderState.cpp @@ -85,6 +85,20 @@ bool RenderState::BlendFunc(GLenum sfactor, GLenum dfactor) return !GLERROR("RenderState::BlendFunc"); } + +bool RenderState::StencilFunc(GLenum sfail, GLenum dpfail, GLenum dppass) +{ + GLint originalSFail; + glGetIntegerv(GL_STENCIL_FAIL, &originalSFail); + GLint originalDPFail; + glGetIntegerv(GL_STENCIL_PASS_DEPTH_FAIL, &originalDPFail); + GLint originalDPPass; + glGetIntegerv(GL_STENCIL_PASS_DEPTH_PASS, &originalDPPass); + m_ResetFunctions.push_back(std::bind(glStencilOp, originalSFail, originalDPFail, originalDPPass)); + glStencilOp(sfail, dpfail, dppass); + return !GLERROR("StencilFunc"); +} + bool RenderState::DepthMask(GLboolean flag) { GLboolean original; From 0bbaf1d57678e6e7745d4fe55466b3330a2f2afe Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Thu, 4 Feb 2016 10:04:44 +0100 Subject: [PATCH 064/355] Oops! Removed DebugCode... --- include/Game/Systems/PlayerDeathSystem.h | 5 ---- src/Game/Systems/PlayerDeathSystem.cpp | 31 ------------------------ 2 files changed, 36 deletions(-) diff --git a/include/Game/Systems/PlayerDeathSystem.h b/include/Game/Systems/PlayerDeathSystem.h index 4734947e..7d989dbf 100644 --- a/include/Game/Systems/PlayerDeathSystem.h +++ b/include/Game/Systems/PlayerDeathSystem.h @@ -11,7 +11,6 @@ #include "Core/EntityFileParser.h" #include "Core/EPlayerDeath.h" -#include "Core/EPlayerDamage.h" class PlayerDeathSystem : public ImpureSystem { @@ -23,9 +22,5 @@ public: private: EventRelay m_OnPlayerDeath; bool OnPlayerDeath(Events::PlayerDeath& e); - - EventRelay m_OnInputCommand; - bool OnInputCommand(const Events::InputCommand& e); - }; #endif \ No newline at end of file diff --git a/src/Game/Systems/PlayerDeathSystem.cpp b/src/Game/Systems/PlayerDeathSystem.cpp index d6680928..f7fe1ab5 100644 --- a/src/Game/Systems/PlayerDeathSystem.cpp +++ b/src/Game/Systems/PlayerDeathSystem.cpp @@ -3,40 +3,9 @@ PlayerDeathSystem::PlayerDeathSystem(World* m_World, EventBroker* eventBroker) : System(m_World, eventBroker) { - EVENT_SUBSCRIBE_MEMBER(m_OnInputCommand, &PlayerDeathSystem::OnInputCommand); EVENT_SUBSCRIBE_MEMBER(m_OnPlayerDeath, &PlayerDeathSystem::OnPlayerDeath); } -bool PlayerDeathSystem::OnInputCommand(const Events::InputCommand& e) -{ - //testing: Jump > playerdamage - if (e.Command != "Jump") { - return false; - - } - - // 0 = released - if (e.Value != 0) { - return false; - - } - - auto players = m_World->GetComponents("Player"); - - for (auto& cPlayer : *players) { - EntityWrapper player(m_World, cPlayer.EntityID); - Events::PlayerDamage e; - e.Player = player; - e.Damage = 50; - m_EventBroker->Publish(e); - - } - - - - return true; -} - void PlayerDeathSystem::Update(double dt) { } From 03a16b46b568ee8079c615559b1a3e2d311855cf Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Thu, 4 Feb 2016 10:28:28 +0100 Subject: [PATCH 065/355] Dash component now has the dash-maxCoolDownVariable in it. --- .../Engine/Input/FirstPersonInputController.h | 17 +++++++++-------- resources/Schema/Components/Dash.xml | 2 +- resources/Schema/Components/Dash.xsd | 4 ++-- src/Game/Systems/PlayerMovementSystem.cpp | 5 ++--- 4 files changed, 14 insertions(+), 14 deletions(-) diff --git a/include/Engine/Input/FirstPersonInputController.h b/include/Engine/Input/FirstPersonInputController.h index de4f1226..fa9af852 100644 --- a/include/Engine/Input/FirstPersonInputController.h +++ b/include/Engine/Input/FirstPersonInputController.h @@ -26,7 +26,7 @@ public: virtual bool OnCommand(const Events::InputCommand& e) override; virtual void Reset(); - void AssaultDashCheck(double dt, bool isJumping); + void AssaultDashCheck(double dt, bool isJumping, double assaultDashCoolDownMaxTimer); virtual bool AssaultDashDoubleTapped() const { return m_AssaultDashDoubleTapped; } virtual bool PlayerIsDashing() const { return m_PlayerIsDashing; } @@ -38,10 +38,11 @@ protected: bool m_Jumping = false; bool m_DoubleJumping = false; bool m_Crouching = false; - //assault dash membervariables + //assault dash membervariables - needed to calculate the doubletap- and dashlogic double m_AssaultDashDoubleTapDeltaTime = 0.0; double m_AssaultDashCoolDownTimer = 0.0; - double m_AssaultDashCoolDownMaxTimer = 2.0; + //i will let m_AssaultDashDoubleTapSensitivityTimer stay hardcoded, its not really a gamevariable (more an inputvariable), + //and its very unlikely that someone wants to change that value const float m_AssaultDashDoubleTapSensitivityTimer = 0.25f; std::string m_AssaultDashTapDirection = ""; bool m_AssaultDashDoubleTapped = false; @@ -178,11 +179,11 @@ bool FirstPersonInputController::OnLockMouse(const Events::LockMou } template -void FirstPersonInputController::AssaultDashCheck(double dt, bool isJumping) { +void FirstPersonInputController::AssaultDashCheck(double dt, bool isJumping, double assaultDashCoolDownMaxTimer) { m_AssaultDashDoubleTapDeltaTime += dt; m_AssaultDashCoolDownTimer -= dt; - //cooldown = m_AssaultDashCoolDownMaxTimer sec, pretend the dash lasts 0.25 sec (for friction to do its work) - if (m_AssaultDashCoolDownTimer > (m_AssaultDashCoolDownMaxTimer - 0.25f)) { + //cooldown = assaultDashCoolDownMaxTimer sec, pretend the dash lasts 0.25 sec (for friction to do its work) + if (m_AssaultDashCoolDownTimer > (assaultDashCoolDownMaxTimer - 0.25f)) { m_PlayerIsDashing = true; } else { m_PlayerIsDashing = false; @@ -192,7 +193,7 @@ void FirstPersonInputController::AssaultDashCheck(double dt, bool if (m_ShiftDashing && m_AssaultDashCoolDownTimer <= 0.0f && !isJumping) { //player is dashing with shift //the wanted-direction is set in playermovement already so we dont need to check what direction we want to dash in! - m_AssaultDashCoolDownTimer = m_AssaultDashCoolDownMaxTimer; + m_AssaultDashCoolDownTimer = assaultDashCoolDownMaxTimer; m_AssaultDashDoubleTapped = true; m_AssaultDashDoubleTapDeltaTime = 0.f; //moving to the side has priority @@ -223,7 +224,7 @@ void FirstPersonInputController::AssaultDashCheck(double dt, bool //ok, we have a valid tap, lets do it m_AssaultDashDoubleTapped = true; m_AssaultDashDoubleTapDeltaTime = 0.f; - m_AssaultDashCoolDownTimer = m_AssaultDashCoolDownMaxTimer; + m_AssaultDashCoolDownTimer = assaultDashCoolDownMaxTimer; } #endif \ No newline at end of file diff --git a/resources/Schema/Components/Dash.xml b/resources/Schema/Components/Dash.xml index 084f9620..fbd255a6 100644 --- a/resources/Schema/Components/Dash.xml +++ b/resources/Schema/Components/Dash.xml @@ -1,4 +1,4 @@ - true + 2.0 \ No newline at end of file diff --git a/resources/Schema/Components/Dash.xsd b/resources/Schema/Components/Dash.xsd index 68b64b0c..ca6fc366 100644 --- a/resources/Schema/Components/Dash.xsd +++ b/resources/Schema/Components/Dash.xsd @@ -9,8 +9,8 @@ - - Yada + + This is the cooldown on dash diff --git a/src/Game/Systems/PlayerMovementSystem.cpp b/src/Game/Systems/PlayerMovementSystem.cpp index 4fe3da2d..c65a961e 100644 --- a/src/Game/Systems/PlayerMovementSystem.cpp +++ b/src/Game/Systems/PlayerMovementSystem.cpp @@ -41,10 +41,9 @@ void PlayerMovementSystem::Update(double dt) if (player.HasComponent("Physics")) { ComponentWrapper cPhysics = player["Physics"]; - //Assault Dash Check - - //TODO: check if playerclass is assault! + //Assault Dash Check if (player.HasComponent("Dash")) { - controller->AssaultDashCheck(dt, ((glm::vec3)cPhysics["Velocity"]).y != 0.0f); + controller->AssaultDashCheck(dt, ((glm::vec3)cPhysics["Velocity"]).y != 0.0f, player["Dash"]["CoolDownMaxTimer"]); } glm::vec3 wishDirection = controller->Movement() * glm::inverse(glm::quat(ori)); //this makes sure you can only dash in the 4 directions: forw,backw,left,right From 0a8ee1623fae4cec72b1973c52f446f12e4a48f4 Mon Sep 17 00:00:00 2001 From: stiffly Date: Thu, 4 Feb 2016 10:47:30 +0100 Subject: [PATCH 066/355] Merge remote-tracking branch 'origin/master' into Sound # Conflicts: # assets --- assets | 2 +- include/Engine/Sound/SoundSystem.h | 3 +++ include/Game/Events/EDoubleJump.h | 16 ++++++++++++++++ include/Game/Systems/PlayerMovementSystem.h | 1 + src/Engine/Sound/SoundSystem.cpp | 14 +++++++++++++- src/Game/Systems/PlayerMovementSystem.cpp | 2 ++ 6 files changed, 36 insertions(+), 2 deletions(-) create mode 100644 include/Game/Events/EDoubleJump.h diff --git a/assets b/assets index 29f8e123..a7387630 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit 29f8e1234661f93ffba656c031d037a9ca484660 +Subproject commit a73876309264a0751e3a46f15020dd46d5a67f98 diff --git a/include/Engine/Sound/SoundSystem.h b/include/Engine/Sound/SoundSystem.h index 20d58933..597aca22 100644 --- a/include/Engine/Sound/SoundSystem.h +++ b/include/Engine/Sound/SoundSystem.h @@ -35,6 +35,7 @@ #include "Core/EEntityDeleted.h" #include "Collision/ETrigger.h" #include "Core/EPause.h" +#include "Game/Events/EDoubleJump.h" typedef std::pair> QueuedBuffers; @@ -152,6 +153,8 @@ private: bool OnPause(const Events::Pause &e); EventRelay m_EResume; bool OnResume(const Events::Resume &e); + EventRelay m_EDoubleJump; + bool OnDoubleJump(const Events::DoubleJump &e); diff --git a/include/Game/Events/EDoubleJump.h b/include/Game/Events/EDoubleJump.h new file mode 100644 index 00000000..767d5b39 --- /dev/null +++ b/include/Game/Events/EDoubleJump.h @@ -0,0 +1,16 @@ +#ifndef Events_DoubleJump_h__ +#define Events_DoubleJump_h__ + +#include "Core/Event.h" + +namespace Events +{ + +struct DoubleJump : public Event +{ + +}; + +} + +#endif diff --git a/include/Game/Systems/PlayerMovementSystem.h b/include/Game/Systems/PlayerMovementSystem.h index f39740ec..4d98990a 100644 --- a/include/Game/Systems/PlayerMovementSystem.h +++ b/include/Game/Systems/PlayerMovementSystem.h @@ -4,6 +4,7 @@ #include "Core/EPlayerSpawned.h" #include "Input/FirstPersonInputController.h" #include +#include "Events/EDoubleJump.h" class PlayerMovementSystem : public ImpureSystem, PureSystem { diff --git a/src/Engine/Sound/SoundSystem.cpp b/src/Engine/Sound/SoundSystem.cpp index 92ea5142..847230d9 100644 --- a/src/Engine/Sound/SoundSystem.cpp +++ b/src/Engine/Sound/SoundSystem.cpp @@ -29,6 +29,7 @@ SoundSystem::SoundSystem(World* world, EventBroker* eventBroker, bool editorMode EVENT_SUBSCRIBE_MEMBER(m_EPause, &SoundSystem::OnPause); EVENT_SUBSCRIBE_MEMBER(m_EResume, &SoundSystem::OnResume); EVENT_SUBSCRIBE_MEMBER(m_EComponentAttached, &SoundSystem::OnComponentAttached); + EVENT_SUBSCRIBE_MEMBER(m_EDoubleJump, &SoundSystem::OnDoubleJump); } SoundSystem::~SoundSystem() @@ -400,7 +401,6 @@ bool SoundSystem::OnPlayerDamage(const Events::PlayerDamage & e) Source* source = createSource("Audio/hurt/hurt" + std::to_string(rand) + ".wav"); source->Type = SoundType::SFX; m_Sources[child] = source; - //playSound(source); // breathe std::vector buffers; @@ -486,6 +486,18 @@ bool SoundSystem::OnResume(const Events::Resume &e) return false; } +bool SoundSystem::OnDoubleJump(const Events::DoubleJump & e) +{ + Events::PlaySoundOnEntity ev; + EntityID child = m_World->CreateEntity(m_LocalPlayer); + m_World->AttachComponent(child, "Transform"); + m_World->AttachComponent(child, "SoundEmitter"); + ev.EmitterID = child; + ev.FilePath = "Audio/jump/jump2.wav"; + m_EventBroker->Publish(ev); + return false; +} + void SoundSystem::setListenerOri(glm::vec3 ori) { // Calculate forward and up vector. diff --git a/src/Game/Systems/PlayerMovementSystem.cpp b/src/Game/Systems/PlayerMovementSystem.cpp index 72900d7a..498c3765 100644 --- a/src/Game/Systems/PlayerMovementSystem.cpp +++ b/src/Game/Systems/PlayerMovementSystem.cpp @@ -82,6 +82,8 @@ void PlayerMovementSystem::Update(double dt) } else { controller->SetDoubleJumping(true); + Events::DoubleJump e; + m_EventBroker->Publish(e); } velocity.y += 4.f; } From 379d2118328f2946bc09687a985ae30775b5c7e0 Mon Sep 17 00:00:00 2001 From: Tleety Date: Thu, 4 Feb 2016 11:13:26 +0100 Subject: [PATCH 067/355] some fixes with the stencil states and implemented stencil func/stencilop/stencilmask to renderstate --- include/Engine/Rendering/RenderState.h | 4 +- .../Schema/Entities/aaaatestremoveme.xml | 39 ++++++++++++++++ src/Engine/Rendering/DrawFinalPass.cpp | 14 +++--- src/Engine/Rendering/DrawFinalPassState.cpp | 8 +++- src/Engine/Rendering/RenderState.cpp | 45 +++++++++++++++---- 5 files changed, 93 insertions(+), 17 deletions(-) create mode 100644 resources/Schema/Entities/aaaatestremoveme.xml diff --git a/include/Engine/Rendering/RenderState.h b/include/Engine/Rendering/RenderState.h index ae43c013..e8ace433 100644 --- a/include/Engine/Rendering/RenderState.h +++ b/include/Engine/Rendering/RenderState.h @@ -19,7 +19,9 @@ public: bool BindFramebuffer(GLint framebuffer); bool BlendEquation(GLenum mode); bool BlendFunc(GLenum sfactor, GLenum dfactor); - bool StencilFunc(GLenum sfail, GLenum dpfail, GLenum dppass); + bool StencilOp(GLenum sfail, GLenum dpfail, GLenum dppass); + bool StencilFunc(GLenum func, GLint ref, GLuint mask); + bool StencilMask(GLuint mask); bool DepthMask(GLboolean flag); private: diff --git a/resources/Schema/Entities/aaaatestremoveme.xml b/resources/Schema/Entities/aaaatestremoveme.xml new file mode 100644 index 00000000..8da40b58 --- /dev/null +++ b/resources/Schema/Entities/aaaatestremoveme.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + Models/Core/Unithexagon.mesh + + + + + + + + + + + + + + + + + + + 2.2000000476837158 + + + + + + + + diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index d2d22514..f571389f 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -73,22 +73,23 @@ void DrawFinalPass::Draw(RenderScene& scene) if (scene.ClearDepth) { glClear(GL_DEPTH_BUFFER_BIT); } - //might need to clear stencil here + //TODO: Do we need check for this or will it be per scene always? + glClear(GL_STENCIL_BUFFER_BIT); DrawModelRenderQueues(scene.Jobs.OpaqueObjects, scene); GLERROR("OpaqueObjects"); DrawModelRenderQueues(scene.Jobs.TransparentObjects, scene); GLERROR("TransparentObjects"); - delete state; - DrawStencilState* stencilState = new DrawStencilState(m_FinalPassFrameBuffer.GetHandle()); - glClear(GL_STENCIL_BUFFER_BIT); + //DrawStencilState* stencilState = new DrawStencilState(m_FinalPassFrameBuffer.GetHandle()); //Draw shields to stencil pass + state->StencilFunc(GL_ALWAYS, 1, 0xFF); + state->StencilMask(0xFF); DrawShieldToStencilBuffer(scene.Jobs.ShieldObjects, scene); GLERROR("StencilPass"); //Draw Opaque shielded objects - DrawShieldedModelRenderQueue(scene.Jobs.OpaqueShieldedObjects, scene); + //DrawShieldedModelRenderQueue(scene.Jobs.OpaqueShieldedObjects, scene); GLERROR("Shielded Opaque object"); //Draw Transparen Shielded objects @@ -96,7 +97,8 @@ void DrawFinalPass::Draw(RenderScene& scene) GLERROR("Shielded Transparent objects"); GLERROR("END"); - delete stencilState; + delete state; + //delete stencilState; } diff --git a/src/Engine/Rendering/DrawFinalPassState.cpp b/src/Engine/Rendering/DrawFinalPassState.cpp index d85d476c..a1cd445c 100644 --- a/src/Engine/Rendering/DrawFinalPassState.cpp +++ b/src/Engine/Rendering/DrawFinalPassState.cpp @@ -9,6 +9,10 @@ DrawFinalPassState::DrawFinalPassState(GLuint frameBuffer) BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); Enable(GL_DEPTH_TEST); Enable(GL_CULL_FACE); + Enable(GL_STENCIL_TEST); + StencilFunc(GL_NOTEQUAL, 1, 0xFF); + StencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); + StencilMask(0x00); ClearColor(glm::vec4(0.f, 0.f, 0.f, 0.f)); } @@ -21,7 +25,9 @@ DrawStencilState::DrawStencilState(GLuint frameBuffer) { BindFramebuffer(frameBuffer); Enable(GL_STENCIL_TEST); - StencilFunc(GL_KEEP, GL_KEEP, GL_REPLACE); + StencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); + StencilFunc(GL_ALWAYS, 1, 0xFF); + StencilMask(0xFF); Enable(GL_DEPTH_TEST); ClearColor(glm::vec4(0.f)); } diff --git a/src/Engine/Rendering/RenderState.cpp b/src/Engine/Rendering/RenderState.cpp index d85b2b43..1bacda18 100644 --- a/src/Engine/Rendering/RenderState.cpp +++ b/src/Engine/Rendering/RenderState.cpp @@ -6,9 +6,10 @@ bool RenderState::Enable(GLenum cap) //LOG_WARNING("Trying to enable somthing that is already enabled."); return false; } + m_ResetFunctions.push_back(std::bind(glDisable, cap)); glEnable(cap); - return !GLERROR("RenderState::Enable"); + return !GLERROR("Enable"); } bool RenderState::Disable(GLenum cap) @@ -16,9 +17,10 @@ bool RenderState::Disable(GLenum cap) if (!glIsEnabled(cap)) { return false; } + m_ResetFunctions.push_back(std::bind(glEnable, cap)); glDisable(cap); - return !GLERROR("RenderState::Disable"); + return !GLERROR("Disable"); } bool RenderState::CullFace(GLenum mode) @@ -32,7 +34,7 @@ bool RenderState::CullFace(GLenum mode) glGetIntegerv(GL_CULL_FACE_MODE, &original); m_ResetFunctions.push_back(std::bind(glCullFace, original)); glCullFace(mode); - return !GLERROR("RenderState::CullFace"); + return !GLERROR("CullFace"); } bool RenderState::ClearColor(glm::vec4 color) @@ -41,7 +43,7 @@ bool RenderState::ClearColor(glm::vec4 color) glGetFloatv(GL_COLOR_CLEAR_VALUE, &original[0]); m_ResetFunctions.push_back(std::bind(glClearColor, original[0], original[1], original[2], original[3])); glClearColor(color.r, color.g, color.b, color.a); - return !GLERROR("RenderState::ClearColor"); + return !GLERROR("ClearColor"); } bool RenderState::BindFramebuffer(GLint framebuffer) @@ -55,7 +57,7 @@ bool RenderState::BindFramebuffer(GLint framebuffer) glBindFramebuffer(GL_DRAW_FRAMEBUFFER, originalDraw); }); glBindFramebuffer(GL_FRAMEBUFFER, framebuffer); - return !GLERROR("RenderState::BindBuffer"); + return !GLERROR("BindBuffer"); } @@ -67,7 +69,7 @@ bool RenderState::BlendEquation(GLenum mode) glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &originalAlpha); m_ResetFunctions.push_back(std::bind(glBlendEquationSeparate, originalRGB, originalAlpha)); glBlendEquation(mode); - return !GLERROR("RenderState::BlendEquation"); + return !GLERROR("BlendEquation"); } bool RenderState::BlendFunc(GLenum sfactor, GLenum dfactor) @@ -82,11 +84,11 @@ bool RenderState::BlendFunc(GLenum sfactor, GLenum dfactor) glGetIntegerv(GL_BLEND_DST_ALPHA, &originalDestAlpha); m_ResetFunctions.push_back(std::bind(glBlendFuncSeparate, originalSrcRGB, originalSrcAlpha, originalDestRGB, originalDestAlpha)); glBlendFunc(sfactor, dfactor); - return !GLERROR("RenderState::BlendFunc"); + return !GLERROR("BlendFunc"); } -bool RenderState::StencilFunc(GLenum sfail, GLenum dpfail, GLenum dppass) +bool RenderState::StencilOp(GLenum sfail, GLenum dpfail, GLenum dppass) { GLint originalSFail; glGetIntegerv(GL_STENCIL_FAIL, &originalSFail); @@ -96,16 +98,41 @@ bool RenderState::StencilFunc(GLenum sfail, GLenum dpfail, GLenum dppass) glGetIntegerv(GL_STENCIL_PASS_DEPTH_PASS, &originalDPPass); m_ResetFunctions.push_back(std::bind(glStencilOp, originalSFail, originalDPFail, originalDPPass)); glStencilOp(sfail, dpfail, dppass); + return !GLERROR("StencilOp"); +} + + +bool RenderState::StencilFunc(GLenum func, GLint ref, GLuint mask) +{ + GLint originalFunc; + glGetIntegerv(GL_STENCIL_FUNC, &originalFunc); + GLint originalRef; + glGetIntegerv(GL_STENCIL_REF, &originalRef); + GLint originalMask; + glGetIntegerv(GL_STENCIL_VALUE_MASK, &originalMask); + m_ResetFunctions.push_back(std::bind(glStencilFunc, originalFunc, originalRef, originalMask)); + glStencilFunc(func, ref, mask); return !GLERROR("StencilFunc"); } + + +bool RenderState::StencilMask(GLuint mask) +{ + GLint originalMask; + glGetIntegerv(GL_STENCIL_WRITEMASK, &originalMask); + m_ResetFunctions.push_back(std::bind(glStencilMask, mask)); + glStencilMask(mask); + return !GLERROR("StencilMask"); +} + bool RenderState::DepthMask(GLboolean flag) { GLboolean original; glGetBooleanv(GL_DEPTH_WRITEMASK, &original); m_ResetFunctions.push_back(std::bind(glDepthMask, original)); glDepthMask(flag); - return !GLERROR("RenderState::DepthMask"); + return !GLERROR("DepthMask"); } RenderState::~RenderState() From 6aec7555cce58e19560dbc03d12c8aedd3a65208 Mon Sep 17 00:00:00 2001 From: viktorljung Date: Thu, 4 Feb 2016 11:13:33 +0100 Subject: [PATCH 068/355] WIP Waiting for importer --- include/Engine/Rendering/Skeleton.h | 12 +- resources/Schema/Entities/AnimationTests2.xml | 5 +- src/Engine/Rendering/AnimationSystem.cpp | 5 +- src/Engine/Rendering/BoneAttachmentSystem.cpp | 3 +- src/Engine/Rendering/DrawFinalPass.cpp | 9 +- src/Engine/Rendering/PickingPass.cpp | 2 +- src/Engine/Rendering/RawModelCustom.cpp | 7 + src/Engine/Rendering/Skeleton.cpp | 137 +++++++++++++++++- 8 files changed, 162 insertions(+), 18 deletions(-) diff --git a/include/Engine/Rendering/Skeleton.h b/include/Engine/Rendering/Skeleton.h index 8ae3d487..9c7242d3 100644 --- a/include/Engine/Rendering/Skeleton.h +++ b/include/Engine/Rendering/Skeleton.h @@ -55,19 +55,23 @@ public: struct BoneProperty { int ID; - glm::vec3 Position; - glm::quat Rotation; + glm::vec3 Position; + glm::quat Rotation; glm::vec3 Scale = glm::vec3(1); }; int Index = 0; double Time = 0.0; std::map BoneProperties; + //Keyframe::BoneProperty boneProperty; }; std::string Name; double Duration; + // unsigned int KeyFrameAmount; std::vector Keyframes; + //std::map> BoneKeyFrames; + }; Skeleton() { } @@ -86,6 +90,10 @@ public: const Animation* GetAnimation(std::string name); std::vector GetFrameBones(const Animation* animation, double time, bool noRootMotion = false); void AccumulateBoneTransforms(bool noRootMotion, const Animation::Keyframe& currentFrame, const Animation::Keyframe& nextFrame, float progress, std::map& boneMatrices, const Bone* bone, glm::mat4 parentMatrix); + + void AccumulateBoneTransforms(bool noRootMotion, const Animation* animation, float time, std::map& boneMatrices, const Bone* bone, glm::mat4 parentMatrix); + void AccumulateBoneTransforms2(bool noRootMotion, const Animation* animation, int keyframeIndex, float time, std::map& boneMatrices, const Bone* bone, glm::mat4 parentMatrix); + void PrintSkeleton(); void PrintSkeleton(const Bone* parent, int depthCount); std::map Animations; diff --git a/resources/Schema/Entities/AnimationTests2.xml b/resources/Schema/Entities/AnimationTests2.xml index 23fc0548..baff7413 100644 --- a/resources/Schema/Entities/AnimationTests2.xml +++ b/resources/Schema/Entities/AnimationTests2.xml @@ -10,6 +10,7 @@ Models/Core/UnitPlane.mesh + false @@ -34,8 +35,8 @@ - Run - + Ru + 1 diff --git a/src/Engine/Rendering/AnimationSystem.cpp b/src/Engine/Rendering/AnimationSystem.cpp index 93d52787..517fbf5c 100644 --- a/src/Engine/Rendering/AnimationSystem.cpp +++ b/src/Engine/Rendering/AnimationSystem.cpp @@ -51,6 +51,7 @@ void AnimationSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& a +/* ImGui::SliderFloat("Angle", &angle, -180.f, 180.f); @@ -86,6 +87,7 @@ void AnimationSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& a } +*/ /* @@ -117,7 +119,7 @@ void AnimationSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& a if (it != skeleton->Bones.end()) { it->second->ModificationMatrix = glm::mat4(glm::quat(glm::vec3(glm::radians(angle/2.f), 0.f, 0.f))); } - }*/ + }* if (entity.HasComponent("Player")) { EntityWrapper cameraEntity = entity.FirstChildByName("Camera"); @@ -127,5 +129,6 @@ void AnimationSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& a } } + */ } diff --git a/src/Engine/Rendering/BoneAttachmentSystem.cpp b/src/Engine/Rendering/BoneAttachmentSystem.cpp index 2a2e5c7d..1f98c28e 100644 --- a/src/Engine/Rendering/BoneAttachmentSystem.cpp +++ b/src/Engine/Rendering/BoneAttachmentSystem.cpp @@ -2,6 +2,7 @@ void BoneAttachmentSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& BoneAttachmentComponent, double dt) { +/* if(!entity.HasComponent("Transform")) { return; @@ -67,5 +68,5 @@ void BoneAttachmentSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapp } if ((bool)entity["BoneAttachment"]["InheritScale"]) { (glm::vec3&)entity["Transform"]["Scale"] = scale * (glm::vec3)entity["BoneAttachment"]["ScaleOffset"]; - } + }*/ } diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index 48ea4144..005249ed 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -130,7 +130,7 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& if (explosionEffectJob->Model->m_RawModel->m_Skeleton != nullptr) { if (explosionEffectJob->Animation != nullptr) { - std::vector frameBones = explosionEffectJob->Skeleton->GetFrameBones(*explosionEffectJob->Animation, explosionEffectJob->AnimationTime); + std::vector frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animation, explosionEffectJob->AnimationTime); glUniformMatrix4fv(glGetUniformLocation(explosionHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); } } @@ -155,11 +155,8 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& BindModelTextures(modelJob); if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { - - if (modelJob->Animation != nullptr) { - std::vector frameBones = modelJob->Skeleton->GetFrameBones(*modelJob->Animation, modelJob->AnimationTime); - glUniformMatrix4fv(glGetUniformLocation(forwardHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - } + std::vector frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animation, modelJob->AnimationTime); + glUniformMatrix4fv(glGetUniformLocation(forwardHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); } //draw diff --git a/src/Engine/Rendering/PickingPass.cpp b/src/Engine/Rendering/PickingPass.cpp index d0518ee8..58723a43 100644 --- a/src/Engine/Rendering/PickingPass.cpp +++ b/src/Engine/Rendering/PickingPass.cpp @@ -134,7 +134,7 @@ void PickingPass::Draw(RenderScene& scene) if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { if (modelJob->Animation != nullptr) { - std::vector frameBones = modelJob->Skeleton->GetFrameBones(*modelJob->Animation, modelJob->AnimationTime); + std::vector frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animation, modelJob->AnimationTime); glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); } } diff --git a/src/Engine/Rendering/RawModelCustom.cpp b/src/Engine/Rendering/RawModelCustom.cpp index 83c68e47..1f9e104d 100644 --- a/src/Engine/Rendering/RawModelCustom.cpp +++ b/src/Engine/Rendering/RawModelCustom.cpp @@ -332,6 +332,7 @@ void RawModelCustom::ReadAnimationClipSingle(unsigned int &offset, char* fileDat ReadAnimationKeyFrame(offset, fileData, fileByteSize, newAnimation); } m_Skeleton->Animations[newAnimation.Name] = newAnimation; + //m_Skeleton->Animations[newAnimation.Name].KeyFrameAmount = nrOfKeyframes; #else #endif } @@ -363,12 +364,18 @@ void RawModelCustom::ReadAnimationKeyFrame(unsigned int &offset, char* fileData, } Skeleton::Animation::Keyframe::BoneProperty newBone; + for (unsigned int i = 0; i < nrOfJoints; i++) { memcpy(&newBone, (fileData + offset), sizeof(Skeleton::Animation::Keyframe::BoneProperty)); offset += sizeof(Skeleton::Animation::Keyframe::BoneProperty); newKeyFrame.BoneProperties[newBone.ID] = newBone; } animation.Keyframes.push_back(newKeyFrame); + // memcpy(&newBone, (fileData + offset), sizeof(Skeleton::Animation::Keyframe::BoneProperty)); + //newKeyFrame.boneProperty = newBone; + + // animation.BoneKeyFrames[newBone.ID].push_back(newKeyFrame); + } RawModelCustom::~RawModelCustom() diff --git a/src/Engine/Rendering/Skeleton.cpp b/src/Engine/Rendering/Skeleton.cpp index 7fe36319..590cd9a4 100644 --- a/src/Engine/Rendering/Skeleton.cpp +++ b/src/Engine/Rendering/Skeleton.cpp @@ -66,7 +66,9 @@ std::vector Skeleton::GetFrameBones(const Animation* animation, doubl //auto animationFrame = Animations[""].Keyframes[frame]; std::map frameBones; - AccumulateBoneTransforms(noRootMotion, currentFrame, nextFrame, alpha, frameBones, RootBone, glm::mat4(1)); + //AccumulateBoneTransforms(noRootMotion, animation, time, frameBones, RootBone, glm::mat4(1)); + AccumulateBoneTransforms2(noRootMotion, animation, currentKeyframeIndex, time, frameBones, RootBone, glm::mat4(1)); + //AccumulateBoneTransforms(noRootMotion, currentFrame, nextFrame, alpha, frameBones, RootBone, glm::mat4(1)); std::vector finalMatrices; for (auto &kv : frameBones) { @@ -81,7 +83,14 @@ void Skeleton::AccumulateBoneTransforms(bool noRootMotion, const Animation::Keyf { glm::mat4 boneMatrix; - if (currentFrame.BoneProperties.find(bone->ID) != currentFrame.BoneProperties.end() || nextFrame.BoneProperties.find(bone->ID) != nextFrame.BoneProperties.end()) { + + + float alpha = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); + + + if (currentFrame.BoneProperties.find(bone->ID) != currentFrame.BoneProperties.end() && nextFrame.BoneProperties.find(bone->ID) != nextFrame.BoneProperties.end()) { + + Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties.at(bone->ID); Animation::Keyframe::BoneProperty nextBoneProperty = nextFrame.BoneProperties.at(bone->ID); @@ -89,6 +98,7 @@ void Skeleton::AccumulateBoneTransforms(bool noRootMotion, const Animation::Keyf glm::quat rotationInterp = glm::slerp(currentBoneProperty.Rotation, nextBoneProperty.Rotation, progress); glm::vec3 scaleInterp = currentBoneProperty.Scale * (1.f - progress) + nextBoneProperty.Scale * progress; + // Flag for no root motion if (bone == RootBone && noRootMotion) { positionInterp.x = 0; @@ -97,13 +107,13 @@ void Skeleton::AccumulateBoneTransforms(bool noRootMotion, const Animation::Keyf - boneMatrix = parentMatrix * bone->ModificationMatrix * (glm::translate(positionInterp) * glm::toMat4(rotationInterp) * glm::scale(scaleInterp)); - boneMatrices[bone->ID] = boneMatrix *bone->OffsetMatrix; + boneMatrix = parentMatrix * bone->ModificationMatrix *(glm::translate(positionInterp) * glm::toMat4(rotationInterp) * glm::scale(scaleInterp)); + boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix; } else { if (bone->Parent) { boneMatrix = parentMatrix;// *glm::inverse(bone->OffsetMatrix); } - boneMatrices[bone->ID] = boneMatrix; // * bone->OffsetMatrix; + boneMatrices[bone->ID] = boneMatrix;// *bone->OffsetMatrix; } for (auto &child : bone->Children) { @@ -113,6 +123,123 @@ void Skeleton::AccumulateBoneTransforms(bool noRootMotion, const Animation::Keyf } + +void Skeleton::AccumulateBoneTransforms2(bool noRootMotion, const Animation* animation, int keyframeIndex, float time, std::map& boneMatrices, const Bone* bone, glm::mat4 parentMatrix) +{ + glm::mat4 boneMatrix = glm::mat4(1); + + Animation::Keyframe currentFrame; + Animation::Keyframe nextFrame; + + int currentFrameIndex = keyframeIndex; + + while (true) { + std::map boneProperties = animation->Keyframes[currentFrameIndex].BoneProperties; + if (boneProperties.find(bone->ID) != boneProperties.end()) { + currentFrame = animation->Keyframes[keyframeIndex]; + break; + } else { + + if(currentFrameIndex > 0) { + currentFrameIndex--; + } else { + break; + } + } + } + + + + if ( != animation->BoneKeyFrames.end()) { // find the bone keyframes that surrounds the current frame + std::list boneKeyFrames = animation->BoneKeyFrames.at(bone->ID); + for (auto frame : boneKeyFrames) { + if (frame.Time <= time) { + currentFrame = &frame; + } else if (frame.Time > time) { + nextFrame = &frame; + } + } + + //if(currentFrame == nullptr) cant happen + + if (nextFrame == nullptr) { + std::list boneKeyFrames = animation->BoneKeyFrames.at(bone->ID); + nextFrame = &boneKeyFrames.front(); + } + +} + + + + +void Skeleton::AccumulateBoneTransforms(bool noRootMotion, const Animation* animation, float time, std::map& boneMatrices, const Bone* bone, glm::mat4 parentMatrix) +{ + +/* + glm::mat4 boneMatrix = glm::mat4(1); + + Animation::Keyframe* currentFrame = nullptr; + Animation::Keyframe* nextFrame = nullptr; + + if(animation->BoneKeyFrames.find(bone->ID) != animation->BoneKeyFrames.end()) { // find the bone keyframes that surrounds the current frame + std::list boneKeyFrames = animation->BoneKeyFrames.at(bone->ID); + for (auto frame : boneKeyFrames) { + if(frame.Time <= time) { + currentFrame = &frame; + } else if (frame.Time > time) { + nextFrame = &frame; + } + } + + //if(currentFrame == nullptr) cant happen + + if (nextFrame == nullptr) { + std::list boneKeyFrames = animation->BoneKeyFrames.at(bone->ID); + nextFrame = &boneKeyFrames.front(); + } + + + + if (currentFrame != nextFrame) { + + float progress = (time - currentFrame->Time) / (nextFrame->Time - currentFrame->Time); + + Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame->boneProperty; + Animation::Keyframe::BoneProperty nextBoneProperty = nextFrame->boneProperty; + + glm::vec3 positionInterp = currentBoneProperty.Position * (1.f - progress) + nextBoneProperty.Position * progress; + glm::quat rotationInterp = glm::slerp(currentBoneProperty.Rotation, nextBoneProperty.Rotation, progress); + glm::vec3 scaleInterp = currentBoneProperty.Scale * (1.f - progress) + nextBoneProperty.Scale * progress; + + // Flag for no root motion + if (bone == RootBone && noRootMotion) { + positionInterp.x = 0; + positionInterp.z = 0; + } + + boneMatrix = parentMatrix * bone->ModificationMatrix * (glm::translate(positionInterp) * glm::toMat4(rotationInterp) * glm::scale(scaleInterp)); + boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix; + + } else {// if (currentFrame == nextFrame) { + boneMatrix = parentMatrix * bone->ModificationMatrix * (glm::translate(currentFrame->boneProperty.Position) * glm::toMat4(currentFrame->boneProperty.Rotation) * glm::scale(currentFrame->boneProperty.Scale)); + boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix; + } + } else { +// if (bone->Parent) { // dont think this is needed +// boneMatrix = parentMatrix * bone->ModificationMatrix; +// } + + boneMatrix = parentMatrix * bone->ModificationMatrix; + boneMatrices[bone->ID] = boneMatrix;// *bone->OffsetMatrix; + // } + } + + for (auto &child : bone->Children) { + std::string name = child->Name; + AccumulateBoneTransforms(noRootMotion, animation, time, boneMatrices, child, boneMatrix); + }*/ +} + glm::mat4 Skeleton::GetBoneTransform(const Bone* bone, const Animation::Keyframe& currentFrame, const Animation::Keyframe& nextFrame, float progress, glm::mat4 parentMatrix) { glm::mat4 boneMatrix; From 356cf72b0ff8e5d5eca877c5ba54bad974c6cc82 Mon Sep 17 00:00:00 2001 From: antc13 Date: Thu, 4 Feb 2016 11:25:31 +0100 Subject: [PATCH 069/355] Changed the structure of the Animation Data in both Exporter & Importer. --- include/Engine/Rendering/RawModelCustom.h | 2 +- include/Engine/Rendering/Skeleton.h | 17 +- src/Engine/Rendering/RawModelCustom.cpp | 62 ++++--- src/Engine/Rendering/Skeleton.cpp | 82 ++++----- tools/MayaExporter/MayaExporter/Mesh.h | 2 +- tools/MayaExporter/MayaExporter/Skeleton.cpp | 171 ++++++++++++------- tools/MayaExporter/MayaExporter/Skeleton.h | 81 +++++---- 7 files changed, 251 insertions(+), 166 deletions(-) diff --git a/include/Engine/Rendering/RawModelCustom.h b/include/Engine/Rendering/RawModelCustom.h index fe00d89c..e2595ba3 100644 --- a/include/Engine/Rendering/RawModelCustom.h +++ b/include/Engine/Rendering/RawModelCustom.h @@ -110,7 +110,7 @@ private: void ReadAnimationJoint(unsigned int &offset, char* fileData, unsigned int& fileByteSize); void ReadAnimationClips(unsigned int &offset, char* fileData, unsigned int& fileByteSize, unsigned int numberOfClips); void ReadAnimationClipSingle(unsigned int &offset, char* fileData, unsigned int& fileByteSize, unsigned int clipIndex); - void ReadAnimationKeyFrame(unsigned int &offset, char* fileData, unsigned int& fileByteSize, Skeleton::Animation& animation); + void ReadAnimationKeyFrame(unsigned int &offset, char* fileData, unsigned int& fileByteSize, std::vector& animation); //void CreateSkeleton(std::vector> &boneInfo, std::map &boneNameMapping, aiNode* node, int parentID); }; diff --git a/include/Engine/Rendering/Skeleton.h b/include/Engine/Rendering/Skeleton.h index 3b89b89b..52fc02d0 100644 --- a/include/Engine/Rendering/Skeleton.h +++ b/include/Engine/Rendering/Skeleton.h @@ -53,20 +53,21 @@ public: { struct BoneProperty { - int ID; glm::vec3 Position; glm::quat Rotation; glm::vec3 Scale = glm::vec3(1); }; - int Index = 0; - double Time = 0.0; - std::map BoneProperties; + int Index = 0; + double Time = 0.0; + BoneProperty BoneProperties; }; - - std::string Name; - double Duration; - std::vector Keyframes; + std::string Name; + double Duration; + std::map> JointAnimations; + + + }; Skeleton() { } diff --git a/src/Engine/Rendering/RawModelCustom.cpp b/src/Engine/Rendering/RawModelCustom.cpp index c1939bdf..936c7b7b 100644 --- a/src/Engine/Rendering/RawModelCustom.cpp +++ b/src/Engine/Rendering/RawModelCustom.cpp @@ -11,6 +11,7 @@ RawModelCustom::RawModelCustom(std::string fileName) ReadMeshFile(fileName); ReadMaterialFile(fileName); ReadAnimationFile(fileName); + int k = 0; } void RawModelCustom::ReadMeshFile(std::string filePath) @@ -40,8 +41,8 @@ void RawModelCustom::ReadMeshFile(std::string filePath) void RawModelCustom::ReadMeshFileHeader(unsigned int& offset, char* fileData, unsigned int& fileByteSize) { #ifdef BOOST_LITTLE_ENDIAN - isSkined = *(unsigned int*)(fileData + offset); - offset += sizeof(bool); + isSkined = true;//*(unsigned int*)(fileData + offset); + //offset += sizeof(bool); if (isSkined) { m_SkinedVertices.resize(*(unsigned int*)(fileData + offset)); } @@ -331,26 +332,42 @@ void RawModelCustom::ReadAnimationClipSingle(unsigned int &offset, char* fileDat if (offset + sizeof(float) > fileByteSize) { throw Resource::FailedLoadingException("Reading AnimationClip duration failed"); } - newAnimation.Duration = *(float*)(fileData + offset); offset += sizeof(float); if (offset + sizeof(unsigned int) > fileByteSize) { - throw Resource::FailedLoadingException("Reading AnimationClip NrOfKeyframes failed"); + throw Resource::FailedLoadingException("Reading AnimationClip numberOfJointFrames failed"); } - unsigned int nrOfKeyframes = *(unsigned int*)(fileData + offset); + unsigned int numberOfJointFrames = *(unsigned int*)(fileData + offset); offset += sizeof(unsigned int); - newAnimation.Keyframes.reserve(nrOfKeyframes); - for (unsigned int i = 0; i < nrOfKeyframes; i++) { - ReadAnimationKeyFrame(offset, fileData, fileByteSize, newAnimation); + for (unsigned int i = 0; i < numberOfJointFrames; i++) { + if (offset + sizeof(unsigned int) > fileByteSize) { + throw Resource::FailedLoadingException("Reading AnimationClip JointID failed"); + } + int jointID = *(unsigned int*)(fileData + offset); + offset += sizeof(unsigned int); + + if (offset + sizeof(unsigned int) > fileByteSize) { + throw Resource::FailedLoadingException("Reading AnimationClip numberOFKeyFrames failed"); + } + unsigned int numberOFKeyFrames = *(unsigned int*)(fileData + offset); + offset += sizeof(unsigned int); + + if (numberOFKeyFrames > 0) { + newAnimation.JointAnimations[jointID].reserve(numberOFKeyFrames); + + for (unsigned int j = 0; j < numberOFKeyFrames; j++) { + ReadAnimationKeyFrame(offset, fileData, fileByteSize, newAnimation.JointAnimations[jointID]); + } + } } m_Skeleton->Animations[newAnimation.Name] = newAnimation; #else #endif } -void RawModelCustom::ReadAnimationKeyFrame(unsigned int &offset, char* fileData, unsigned int& fileByteSize, Skeleton::Animation& animation) +void RawModelCustom::ReadAnimationKeyFrame(unsigned int &offset, char* fileData, unsigned int& fileByteSize, std::vector& animation) { Skeleton::Animation::Keyframe newKeyFrame; @@ -366,23 +383,26 @@ void RawModelCustom::ReadAnimationKeyFrame(unsigned int &offset, char* fileData, newKeyFrame.Time = *(float*)(fileData + offset); offset += sizeof(float); - if (offset + sizeof(unsigned int) > fileByteSize) { - throw Resource::FailedLoadingException("Reading AnimationKeyFrame NrOfJoints failed"); + if (offset + sizeof(float) * 3 > fileByteSize) { + throw Resource::FailedLoadingException("Reading AnimationKeyFrame Position failed"); } - unsigned int nrOfJoints = *(unsigned int*)(fileData + offset); - offset += sizeof(unsigned int); + memcpy(&newKeyFrame.BoneProperties.Position[0], fileData + offset, sizeof(float) * 3); + offset += sizeof(float) * 3; - if (offset + sizeof(Skeleton::Animation::Keyframe::BoneProperty) * nrOfJoints> fileByteSize) { - throw Resource::FailedLoadingException("Reading AnimationKeyFrame joints failed"); + if (offset + sizeof(float) * 4 > fileByteSize) { + throw Resource::FailedLoadingException("Reading AnimationKeyFrame Rotation failed"); } + memcpy(&newKeyFrame.BoneProperties.Rotation[0], fileData + offset, sizeof(float) * 4); + offset += sizeof(float) * 4; - Skeleton::Animation::Keyframe::BoneProperty newBone; - for (unsigned int i = 0; i < nrOfJoints; i++) { - memcpy(&newBone, (fileData + offset), sizeof(Skeleton::Animation::Keyframe::BoneProperty)); - offset += sizeof(Skeleton::Animation::Keyframe::BoneProperty); - newKeyFrame.BoneProperties[newBone.ID] = newBone; + if (offset + sizeof(float) * 3 > fileByteSize) { + throw Resource::FailedLoadingException("Reading AnimationKeyFrame Scale failed"); } - animation.Keyframes.push_back(newKeyFrame); + memcpy(&newKeyFrame.BoneProperties.Scale[0], fileData + offset, sizeof(float) * 3); + offset += sizeof(float) * 3; + + + animation.push_back(newKeyFrame); } RawModelCustom::~RawModelCustom() diff --git a/src/Engine/Rendering/Skeleton.cpp b/src/Engine/Rendering/Skeleton.cpp index cebabb67..b9488dda 100644 --- a/src/Engine/Rendering/Skeleton.cpp +++ b/src/Engine/Rendering/Skeleton.cpp @@ -49,15 +49,15 @@ std::vector Skeleton::GetFrameBones(const Animation& animation, doubl time -= animation.Duration; } - int currentKeyframeIndex = GetKeyframe(animation, time); + //int currentKeyframeIndex = GetKeyframe(animation, time); - const Animation::Keyframe& currentFrame = animation.Keyframes[currentKeyframeIndex]; - const Animation::Keyframe& nextFrame = animation.Keyframes[(currentKeyframeIndex + 1) % animation.Keyframes.size()]; - float alpha = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); + //const Animation::Keyframe& currentFrame = animation.Keyframes[currentKeyframeIndex]; + //const Animation::Keyframe& nextFrame = animation.Keyframes[(currentKeyframeIndex + 1) % animation.Keyframes.size()]; + //float alpha = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); - //auto animationFrame = Animations[""].Keyframes[frame]; + ////auto animationFrame = Animations[""].Keyframes[frame]; std::map frameBones; - AccumulateBoneTransforms(noRootMotion, currentFrame, nextFrame, alpha, frameBones, RootBone, glm::mat4(1)); + //AccumulateBoneTransforms(noRootMotion, currentFrame, nextFrame, alpha, frameBones, RootBone, glm::mat4(1)); std::vector finalMatrices; for (auto &kv : frameBones) { @@ -68,36 +68,36 @@ std::vector Skeleton::GetFrameBones(const Animation& animation, doubl void Skeleton::AccumulateBoneTransforms(bool noRootMotion, const Animation::Keyframe ¤tFrame, const Animation::Keyframe &nextFrame, float progress, std::map &boneMatrices, const Bone* bone, glm::mat4 parentMatrix) { - glm::mat4 boneMatrix; + // glm::mat4 boneMatrix; - if (currentFrame.BoneProperties.find(bone->ID) != currentFrame.BoneProperties.end() || nextFrame.BoneProperties.find(bone->ID) != nextFrame.BoneProperties.end()) { - Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties.at(bone->ID); - Animation::Keyframe::BoneProperty nextBoneProperty = nextFrame.BoneProperties.at(bone->ID); + //if (currentFrame.BoneProperties.find(bone->ID) != currentFrame.BoneProperties.end() || nextFrame.BoneProperties.find(bone->ID) != nextFrame.BoneProperties.end()) { + // Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties.at(bone->ID); + // Animation::Keyframe::BoneProperty nextBoneProperty = nextFrame.BoneProperties.at(bone->ID); - glm::vec3 positionInterp = currentBoneProperty.Position * (1.f - progress) + nextBoneProperty.Position * progress; - glm::quat rotationInterp = glm::slerp(currentBoneProperty.Rotation, nextBoneProperty.Rotation, progress); - glm::vec3 scaleInterp = currentBoneProperty.Scale * (1.f - progress) + nextBoneProperty.Scale * progress; + // glm::vec3 positionInterp = currentBoneProperty.Position * (1.f - progress) + nextBoneProperty.Position * progress; + // glm::quat rotationInterp = glm::slerp(currentBoneProperty.Rotation, nextBoneProperty.Rotation, progress); + // glm::vec3 scaleInterp = currentBoneProperty.Scale * (1.f - progress) + nextBoneProperty.Scale * progress; - // Flag for no root motion - if (bone == RootBone && noRootMotion) { - positionInterp.x = 0; - positionInterp.z = 0; - } + // // Flag for no root motion + // if (bone == RootBone && noRootMotion) { + // positionInterp.x = 0; + // positionInterp.z = 0; + // } - boneMatrix = parentMatrix * (glm::translate(positionInterp) * glm::toMat4(rotationInterp) * glm::scale(scaleInterp)); - boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix; - } else { - if (bone->Parent) { - boneMatrix = parentMatrix; // * glm::inverse(bone->OffsetMatrix); - } - boneMatrices[bone->ID] = boneMatrix; // * bone->OffsetMatrix; - } + // boneMatrix = parentMatrix * (glm::translate(positionInterp) * glm::toMat4(rotationInterp) * glm::scale(scaleInterp)); + // boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix; + //} else { + // if (bone->Parent) { + // boneMatrix = parentMatrix; // * glm::inverse(bone->OffsetMatrix); + // } + // boneMatrices[bone->ID] = boneMatrix; // * bone->OffsetMatrix; + //} - for (auto &child : bone->Children) { - std::string name = child->Name; - AccumulateBoneTransforms(noRootMotion, currentFrame, nextFrame, progress, boneMatrices, child, boneMatrix); - } + //for (auto &child : bone->Children) { + // std::string name = child->Name; + // AccumulateBoneTransforms(noRootMotion, currentFrame, nextFrame, progress, boneMatrices, child, boneMatrix); + //} } @@ -134,18 +134,18 @@ void Skeleton::PrintSkeleton(const Bone* bone, int depthCount) int Skeleton::GetKeyframe(const Animation& animation, double time) { - if (time < 0) { - time = 0; - } - if (time >= animation.Duration) { - return animation.Keyframes.size() - 1; - } + //if (time < 0) { + // time = 0; + //} + //if (time >= animation.Duration) { + // return animation.Keyframes.size() - 1; + //} - for (int keyframe = 0; keyframe < animation.Keyframes.size(); ++keyframe) { - if (animation.Keyframes[keyframe].Time > time) { - return (keyframe - 1) % animation.Keyframes.size(); - } - } + //for (int keyframe = 0; keyframe < animation.Keyframes.size(); ++keyframe) { + // if (animation.Keyframes[keyframe].Time > time) { + // return (keyframe - 1) % animation.Keyframes.size(); + // } + //} return 0; } diff --git a/tools/MayaExporter/MayaExporter/Mesh.h b/tools/MayaExporter/MayaExporter/Mesh.h index affc4320..87e0ce19 100644 --- a/tools/MayaExporter/MayaExporter/Mesh.h +++ b/tools/MayaExporter/MayaExporter/Mesh.h @@ -70,7 +70,7 @@ public: virtual void WriteBinary(std::ostream& out) { - out.write((char*)&hasSkin, sizeof(bool)); + //out.write((char*)&hasSkin, sizeof(bool)); out.write((char*)&NumVertices, sizeof(int)); out.write((char*)&NumIndices, sizeof(int)); for (auto aVertex : Vertices) { diff --git a/tools/MayaExporter/MayaExporter/Skeleton.cpp b/tools/MayaExporter/MayaExporter/Skeleton.cpp index f44b9306..900ed9b2 100644 --- a/tools/MayaExporter/MayaExporter/Skeleton.cpp +++ b/tools/MayaExporter/MayaExporter/Skeleton.cpp @@ -214,26 +214,28 @@ Animation Skeleton::GetAnimData(std::string animationName, int startFrame, int e jointIt.reset(); }*/ + MItDag jointIt(MItDag::TraversalType::kDepthFirst, MFn::kJoint); + unsigned int jointID = 0; - int currentFrame = startFrame; - while (currentFrame < endFrame) { // ANDREAS - Animation::Keyframe thisKeyFrame; - thisKeyFrame.Index = currentFrame - startFrame; - thisKeyFrame.Time = thisKeyFrame.Index * oneDivSixty; + while (!jointIt.isDone()) { + int currentFrame = startFrame; + Animation::JointAnimation thisJointAnimation; + bool haxBool = false; + while (currentFrame < endFrame) { + Animation::JointAnimation::KeyFrame thisKeyFrame; + //thisKeyFrame.Index = currentFrame - startFrame; + //thisKeyFrame.Time = thisKeyFrame.Index * oneDivSixty; - MAnimControl::setCurrentTime(MTime(currentFrame, MTime::kNTSCField)); - MTime time = MAnimControl::currentTime(); + MAnimControl::setCurrentTime(MTime(currentFrame, MTime::kNTSCField)); + MTime time = MAnimControl::currentTime(); - MItDag jointIt(MItDag::TraversalType::kDepthFirst, MFn::kJoint); - unsigned int jointID = 0; - while (!jointIt.isDone()) { MFnTransform thisJoint(jointIt.currentItem()); MMatrix transformationMatrix = thisJoint.transformationMatrix(); - + double doubleMat[4][4]; - if (currentFrame != startFrame){ - Animation::Keyframe::JointProperty joint; + if (currentFrame != startFrame) { + //Animation::JointAnimation joint; doubleMat[0][0] = joinCheckMap[thisJoint.name().asChar()][0][0]; doubleMat[0][1] = joinCheckMap[thisJoint.name().asChar()][0][1]; @@ -255,9 +257,53 @@ Animation Skeleton::GetAnimData(std::string animationName, int startFrame, int e MMatrix LastJointMatrix(doubleMat); //Is same as last KeyFrame if (LastJointMatrix.isEquivalent(transformationMatrix)) { - jointID++; - jointIt.next(); + //jointID++; + //jointIt.next(); + currentFrame++; + haxBool = false; continue; + } else if(!haxBool){ + haxBool = true; + MTransformationMatrix TransformationMatrix = LastJointMatrix; + MObject jointOrientObj = thisJoint.attribute("jointOrient"); + MFnNumericAttribute jointOrient(jointOrientObj); + double jointOrientDouble[3]; + jointOrient.getDefault(jointOrientDouble[0], jointOrientDouble[1], jointOrientDouble[2]); + //MGlobal::displayError(MString() + "Joint Matrix: "); + //MGlobal::displayError(MString() + Matrix.asMatrix()[0][0] + " " + Matrix.asMatrix()[0][1] + " " + Matrix.asMatrix()[0][2] + " " + Matrix.asMatrix()[0][3]); + //MGlobal::displayError(MString() + Matrix.asMatrix()[1][0] + " " + Matrix.asMatrix()[1][1] + " " + Matrix.asMatrix()[1][2] + " " + Matrix.asMatrix()[1][3]); + //MGlobal::displayError(MString() + Matrix.asMatrix()[2][0] + " " + Matrix.asMatrix()[2][1] + " " + Matrix.asMatrix()[2][2] + " " + Matrix.asMatrix()[2][3]); + //MGlobal::displayError(MString() + Matrix.asMatrix()[3][0] + " " + Matrix.asMatrix()[3][1] + " " + Matrix.asMatrix()[3][2] + " " + Matrix.asMatrix()[3][3]); + + MEulerRotation joEuler(jointOrientDouble[0], jointOrientDouble[1], jointOrientDouble[2]); + MQuaternion jo = joEuler.asQuaternion(); + + double tmp[4]; + TransformationMatrix.getRotationQuaternion(tmp[0], tmp[1], tmp[2], tmp[3]); + MQuaternion rotation(tmp); + + rotation = rotation * jo; + rotation.get(tmp); + + //Animation::JointAnimation::KeyFrame keyframe; + Animation::JointAnimation::KeyFrame previousKeyFrame; + previousKeyFrame.Index = currentFrame - startFrame - 1; + previousKeyFrame.Time = previousKeyFrame.Index * oneDivSixty; + + previousKeyFrame.Rotation[0] = tmp[0]; + previousKeyFrame.Rotation[1] = tmp[1]; + previousKeyFrame.Rotation[2] = tmp[2]; + previousKeyFrame.Rotation[3] = tmp[3]; + TransformationMatrix.getTranslation(MSpace::kTransform).get(tmp); + previousKeyFrame.Position[0] = tmp[0]; + previousKeyFrame.Position[1] = tmp[1]; + previousKeyFrame.Position[2] = tmp[2]; + TransformationMatrix.getScale(tmp, MSpace::kTransform); + previousKeyFrame.Scale[0] = tmp[0]; + previousKeyFrame.Scale[1] = tmp[1]; + previousKeyFrame.Scale[2] = tmp[2]; + + thisJointAnimation.m_KeyFrames.push_back(previousKeyFrame); } } @@ -280,31 +326,35 @@ Animation Skeleton::GetAnimData(std::string animationName, int startFrame, int e joinCheckMap[thisJoint.name().asChar()][3][2] = doubleMat[3][2]; joinCheckMap[thisJoint.name().asChar()][3][3] = doubleMat[3][3]; - MPlug thisJointBindPose = thisJoint.findPlug("bindPose"); - MDataHandle DataHandle; - thisJointBindPose.getValue(DataHandle); - MFnMatrixData MartixFn(DataHandle.data()); - MMatrix thisJointBindPoseMatrix = MartixFn.matrix(); - - MFnTransform Parent(thisJoint.parent(0), &status); - if (status == MS::kSuccess && thisJoint.parent(0).apiType() == MFn::kJoint) { - MTransformationMatrix Matrix = Parent.transformation(); - MPlug parentBindPose = Parent.findPlug("bindPose"); - MDataHandle DataHandle; - parentBindPose.getValue(DataHandle); - MFnMatrixData MartixFn(DataHandle.data()); - MMatrix parentBindPoseMatrix = MartixFn.matrix(); - - thisJointBindPoseMatrix = thisJointBindPoseMatrix * parentBindPoseMatrix.inverse(); - } - MTransformationMatrix TransformationMatrix = thisJoint.transformation(); - if (thisJointBindPoseMatrix.isEquivalent(TransformationMatrix.asMatrix())) { - jointID++; - jointIt.next(); - MGlobal::displayError(MString() + thisJoint.name() + " is in bindPose"); - continue; + if (currentFrame == startFrame) { + MPlug thisJointBindPose = thisJoint.findPlug("bindPose"); + MDataHandle DataHandle; + thisJointBindPose.getValue(DataHandle); + MFnMatrixData MartixFn(DataHandle.data()); + MMatrix thisJointBindPoseMatrix = MartixFn.matrix(); + + MFnTransform Parent(thisJoint.parent(0), &status); + if (status == MS::kSuccess && thisJoint.parent(0).apiType() == MFn::kJoint) { + MTransformationMatrix Matrix = Parent.transformation(); + MPlug parentBindPose = Parent.findPlug("bindPose"); + MDataHandle DataHandle; + parentBindPose.getValue(DataHandle); + MFnMatrixData MartixFn(DataHandle.data()); + MMatrix parentBindPoseMatrix = MartixFn.matrix(); + + thisJointBindPoseMatrix = thisJointBindPoseMatrix * parentBindPoseMatrix.inverse(); + } + + if (thisJointBindPoseMatrix.isEquivalent(TransformationMatrix.asMatrix())) { + //jointID++; + //jointIt.next(); + currentFrame++; + MGlobal::displayError(MString() + thisJoint.name() + " is in bindPose"); + continue; + } + haxBool = true; } MObject jointOrientObj = thisJoint.attribute("jointOrient"); @@ -327,34 +377,35 @@ Animation Skeleton::GetAnimData(std::string animationName, int startFrame, int e rotation = rotation * jo; rotation.get(tmp); - Animation::Keyframe::JointProperty joint; - joint.ID = jointID; + //Animation::JointAnimation::KeyFrame keyframe; + thisKeyFrame.Index = currentFrame - startFrame; + thisKeyFrame.Time = thisKeyFrame.Index * oneDivSixty; - joint.Rotation[0] = tmp[0]; - joint.Rotation[1] = tmp[1]; - joint.Rotation[2] = tmp[2]; - joint.Rotation[3] = tmp[3]; + thisKeyFrame.Rotation[0] = tmp[0]; + thisKeyFrame.Rotation[1] = tmp[1]; + thisKeyFrame.Rotation[2] = tmp[2]; + thisKeyFrame.Rotation[3] = tmp[3]; TransformationMatrix.getTranslation(MSpace::kTransform).get(tmp); - joint.Position[0] = tmp[0]; - joint.Position[1] = tmp[1]; - joint.Position[2] = tmp[2]; + thisKeyFrame.Position[0] = tmp[0]; + thisKeyFrame.Position[1] = tmp[1]; + thisKeyFrame.Position[2] = tmp[2]; TransformationMatrix.getScale(tmp, MSpace::kTransform); - joint.Scale[0] = tmp[0]; - joint.Scale[1] = tmp[1]; - joint.Scale[2] = tmp[2]; + thisKeyFrame.Scale[0] = tmp[0]; + thisKeyFrame.Scale[1] = tmp[1]; + thisKeyFrame.Scale[2] = tmp[2]; - thisKeyFrame.JointProperties.push_back(joint); - - jointID++; - jointIt.next(); + thisJointAnimation.m_KeyFrames.push_back(thisKeyFrame); + + currentFrame++; } - thisKeyFrame.NumberOfJoints = thisKeyFrame.JointProperties.size(); - returnData.Keyframes.push_back(thisKeyFrame); - currentFrame++; + //thisKeyFrame.NumberOfJoints = thisKeyFrame.JointProperties.size(); + thisJointAnimation.numberOFKeyFrames = thisJointAnimation.m_KeyFrames.size(); + returnData.JointsFrameMap[jointID] = (thisJointAnimation); + + jointID++; + jointIt.next(); } - - returnData.NumKeyFrames = returnData.Keyframes.size(); - + returnData.NumOfJointFrames = returnData.JointsFrameMap.size(); return returnData; } diff --git a/tools/MayaExporter/MayaExporter/Skeleton.h b/tools/MayaExporter/MayaExporter/Skeleton.h index 47ae6f4c..3dfbe8a5 100644 --- a/tools/MayaExporter/MayaExporter/Skeleton.h +++ b/tools/MayaExporter/MayaExporter/Skeleton.h @@ -10,44 +10,56 @@ class Animation : public OutputData { public: - struct Keyframe - { - struct JointProperty - { - int ID = 0; + //struct Keyframe + //{ + // struct JointProperty + // { + // int ID = 0; + // float Position[3]{ 0 }; + // float Rotation[4]{ 0 }; + // float Scale[3]{ 0 }; + // }; + + // int Index = 0; + // float Time = 0; + // int NumberOfJoints; + // std::vector JointProperties; + //}; + + struct JointAnimation { + struct KeyFrame { + int Index = 0; + float Time = 0; float Position[3]{ 0 }; float Rotation[4]{ 0 }; float Scale[3]{ 0 }; - }; - - int Index = 0; - float Time = 0; - int NumberOfJoints; - std::vector JointProperties; - }; + }; + unsigned int numberOFKeyFrames = 0; + std::vector m_KeyFrames; + }; std::string Name; int nameLength = 0; float Duration = 0; - int NumKeyFrames = 0; - std::vector Keyframes; + int NumOfJointFrames = 0; + std::map JointsFrameMap; virtual void WriteBinary(std::ostream& out) { out.write((char*)&nameLength, sizeof(int)); out.write(Name.c_str(), Name.size() + 1); out.write((char*)&Duration, sizeof(float)); - out.write((char*)&NumKeyFrames, sizeof(int)); + out.write((char*)&NumOfJointFrames, sizeof(int)); //Här under loopas alla key frames igenom - for (auto aKeyframe : Keyframes) { - out.write((char*)&aKeyframe.Index, sizeof(int)); - out.write((char*)&aKeyframe.Time, sizeof(float)); - out.write((char*)&aKeyframe.NumberOfJoints, sizeof(int)); - for (auto aJoint : aKeyframe.JointProperties) { - out.write((char*)&aJoint.ID, sizeof(int)); - out.write((char*)aJoint.Position, sizeof(float) * 3); - out.write((char*)aJoint.Rotation, sizeof(float) * 4); - out.write((char*)aJoint.Scale, sizeof(float) * 3); + for (auto aJointAnimation : JointsFrameMap) { + out.write((char*)&aJointAnimation.first, sizeof(int)); + out.write((char*)&aJointAnimation.second.numberOFKeyFrames, sizeof(int)); + for (auto aJointKeyFrame : aJointAnimation.second.m_KeyFrames) { + out.write((char*)&aJointKeyFrame.Index, sizeof(int)); + out.write((char*)&aJointKeyFrame.Time, sizeof(float)); + out.write((char*)&aJointKeyFrame.Position, sizeof(float) * 3); + out.write((char*)&aJointKeyFrame.Rotation, sizeof(float) * 4); + out.write((char*)&aJointKeyFrame.Scale, sizeof(float) * 3); } } } @@ -56,16 +68,17 @@ public: { out << "Animation Name: " << Name << endl; out << "Duration: " << Duration << endl; - out << "Number of KeyFrames: " << NumKeyFrames << endl; - for (auto aKeyframe : Keyframes) { - out << "Frame: " << aKeyframe.Index << endl; - out << "Time: " << aKeyframe.Time << endl; - out << "Number of Joints: " << aKeyframe.NumberOfJoints << endl; - for (auto aJoint : aKeyframe.JointProperties) { - out << "Joint ID: " << aJoint.ID << endl; - out << aJoint.Position[0] << " " << aJoint.Position[1] << " " << aJoint.Position[2] << endl; - out << aJoint.Rotation[0] << " " << aJoint.Rotation[1] << " " << aJoint.Rotation[2] << " " << aJoint.Rotation[3] << endl; - out << aJoint.Scale[0] << " " << aJoint.Scale[1] << " " << aJoint.Scale[2] << endl; + out << "Number of KeyFrames: " << NumOfJointFrames << endl; + for (auto aJointAnimation : JointsFrameMap) { + out << "Bone: " << aJointAnimation.first << endl; + //out << "Time: " << aJointAnimation.Time << endl; + //out << "Number of Joints: " << aKeyframe.NumberOfJoints << endl; + for (auto aJointKeyFrame : aJointAnimation.second.m_KeyFrames) { + //out << "Joint ID: " << aJoint.ID << endl; + out << "Time: " << aJointKeyFrame.Time << endl; + out << aJointKeyFrame.Position[0] << " " << aJointKeyFrame.Position[1] << " " << aJointKeyFrame.Position[2] << endl; + out << aJointKeyFrame.Rotation[0] << " " << aJointKeyFrame.Rotation[1] << " " << aJointKeyFrame.Rotation[2] << " " << aJointKeyFrame.Rotation[3] << endl; + out << aJointKeyFrame.Scale[0] << " " << aJointKeyFrame.Scale[1] << " " << aJointKeyFrame.Scale[2] << endl; } } From 035c79564b2e129e16cefef4c6d527bb9cf75b98 Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Thu, 4 Feb 2016 11:41:21 +0100 Subject: [PATCH 070/355] Changed Dash name to DashAbility. Fixed dash bug where you could do two different keys to dash. --- include/Engine/Input/FirstPersonInputController.h | 11 ++++++++--- resources/Schema/Components.xsd | 2 +- .../Schema/Components/{Dash.xml => DashAbility.xml} | 2 +- .../Schema/Components/{Dash.xsd => DashAbility.xsd} | 2 +- resources/Schema/Entities/Player.xml | 4 +++- src/Game/Systems/PlayerMovementSystem.cpp | 4 ++-- 6 files changed, 16 insertions(+), 9 deletions(-) rename resources/Schema/Components/{Dash.xml => DashAbility.xml} (78%) rename resources/Schema/Components/{Dash.xsd => DashAbility.xsd} (94%) diff --git a/include/Engine/Input/FirstPersonInputController.h b/include/Engine/Input/FirstPersonInputController.h index fa9af852..2bbd768d 100644 --- a/include/Engine/Input/FirstPersonInputController.h +++ b/include/Engine/Input/FirstPersonInputController.h @@ -45,6 +45,7 @@ protected: //and its very unlikely that someone wants to change that value const float m_AssaultDashDoubleTapSensitivityTimer = 0.25f; std::string m_AssaultDashTapDirection = ""; + std::string m_CurrentDirectionVector = ""; bool m_AssaultDashDoubleTapped = false; bool m_PlayerIsDashing = false; bool m_ShiftDashing = false; @@ -125,17 +126,21 @@ bool FirstPersonInputController::OnCommand(const Events::InputComm } if (e.Command == "Forward" || e.Command == "Right") { + if (e.Value != 0) { + m_CurrentDirectionVector = e.Command == "Right" ? (e.Value > 0 ? "Right" : "Left") : (e.Value > 0 ? "Forward" : "Backward"); + } //if value = 0 then you have just released this key - if (e.Value > 0 || e.Value < 0) { + if (e.Value != 0) { m_MovementKeyDown = true; //if you pressed the same key within m_AssaultDashDoubleTapSensitivityTimer then you have doubletapped it - if (m_AssaultDashDoubleTapDeltaTime < m_AssaultDashDoubleTapSensitivityTimer && m_AssaultDashTapDirection == e.Command) { + if (m_AssaultDashDoubleTapDeltaTime < m_AssaultDashDoubleTapSensitivityTimer && m_AssaultDashTapDirection == m_CurrentDirectionVector) { m_ValidDoubleTap = true; } } else { + //== 0 m_MovementKeyDown = false; //you have just released the key, store what key it was and reset the doubletap-sensitivity-timer - m_AssaultDashTapDirection = e.Command; + m_AssaultDashTapDirection = m_CurrentDirectionVector; m_AssaultDashDoubleTapDeltaTime = 0.f; } } diff --git a/resources/Schema/Components.xsd b/resources/Schema/Components.xsd index 17278f14..265a3cc5 100644 --- a/resources/Schema/Components.xsd +++ b/resources/Schema/Components.xsd @@ -30,5 +30,5 @@ - + \ No newline at end of file diff --git a/resources/Schema/Components/Dash.xml b/resources/Schema/Components/DashAbility.xml similarity index 78% rename from resources/Schema/Components/Dash.xml rename to resources/Schema/Components/DashAbility.xml index fbd255a6..25b9e19a 100644 --- a/resources/Schema/Components/Dash.xml +++ b/resources/Schema/Components/DashAbility.xml @@ -1,4 +1,4 @@ - + 2.0 \ No newline at end of file diff --git a/resources/Schema/Components/Dash.xsd b/resources/Schema/Components/DashAbility.xsd similarity index 94% rename from resources/Schema/Components/Dash.xsd rename to resources/Schema/Components/DashAbility.xsd index ca6fc366..4273cc71 100644 --- a/resources/Schema/Components/Dash.xsd +++ b/resources/Schema/Components/DashAbility.xsd @@ -3,7 +3,7 @@ - + A dash component for one of the classes diff --git a/resources/Schema/Entities/Player.xml b/resources/Schema/Entities/Player.xml index 3029e9f7..fe24adcc 100644 --- a/resources/Schema/Entities/Player.xml +++ b/resources/Schema/Entities/Player.xml @@ -6,7 +6,9 @@ - + + 2.0 + diff --git a/src/Game/Systems/PlayerMovementSystem.cpp b/src/Game/Systems/PlayerMovementSystem.cpp index c65a961e..3224f579 100644 --- a/src/Game/Systems/PlayerMovementSystem.cpp +++ b/src/Game/Systems/PlayerMovementSystem.cpp @@ -42,8 +42,8 @@ void PlayerMovementSystem::Update(double dt) if (player.HasComponent("Physics")) { ComponentWrapper cPhysics = player["Physics"]; //Assault Dash Check - if (player.HasComponent("Dash")) { - controller->AssaultDashCheck(dt, ((glm::vec3)cPhysics["Velocity"]).y != 0.0f, player["Dash"]["CoolDownMaxTimer"]); + if (player.HasComponent("DashAbility")) { + controller->AssaultDashCheck(dt, ((glm::vec3)cPhysics["Velocity"]).y != 0.0f, player["DashAbility"]["CoolDownMaxTimer"]); } glm::vec3 wishDirection = controller->Movement() * glm::inverse(glm::quat(ori)); //this makes sure you can only dash in the 4 directions: forw,backw,left,right From c87e4d4fd6f05d8e257da9588836d0252c59a5e4 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Thu, 4 Feb 2016 11:53:11 +0100 Subject: [PATCH 071/355] Added mutex to resource manager cache reading to avoid a potential race condition. We hope this is the actual bug we saw. --- include/Engine/Core/ResourceManager.h | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/include/Engine/Core/ResourceManager.h b/include/Engine/Core/ResourceManager.h index 10529819..b994b5cf 100644 --- a/include/Engine/Core/ResourceManager.h +++ b/include/Engine/Core/ResourceManager.h @@ -200,13 +200,16 @@ static T* ResourceManager::Load(const std::string& resourceName, Resource* paren } //If resource has already been cached and completely loaded. - it = m_ResourceCache.find(cacheKey); - if (it != m_ResourceCache.end()) { - if (it->second != nullptr) { - return static_cast(it->second); - } else { - //Don't return null on failure, exception instead. - throw Resource::FailedLoadingException(); + { + boost::lock_guard guard(m_Mutex); + it = m_ResourceCache.find(cacheKey); + if (it != m_ResourceCache.end()) { + if (it->second != nullptr) { + return static_cast(it->second); + } else { + //Don't return null on failure, exception instead. + throw Resource::FailedLoadingException(); + } } } From 84499665d0c1583b12be07b98306117eab437145 Mon Sep 17 00:00:00 2001 From: antc13 Date: Thu, 4 Feb 2016 11:53:17 +0100 Subject: [PATCH 072/355] Changed vertices to skinnedVertices in RawModelCustom.cpp --- src/Engine/Rendering/RawModelCustom.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Engine/Rendering/RawModelCustom.cpp b/src/Engine/Rendering/RawModelCustom.cpp index 936c7b7b..7852f54b 100644 --- a/src/Engine/Rendering/RawModelCustom.cpp +++ b/src/Engine/Rendering/RawModelCustom.cpp @@ -69,7 +69,7 @@ void RawModelCustom::ReadVertices(unsigned int& offset, char* fileData, unsigned if (offset + m_SkinedVertices.size() * sizeof(SkinedVertex) > fileByteSize) { throw Resource::FailedLoadingException("Reading skined vertices failed"); } - memcpy(&m_SkinedVertices[0], fileData + offset, m_Vertices.size() * sizeof(SkinedVertex)); + memcpy(&m_SkinedVertices[0], fileData + offset, m_SkinedVertices.size() * sizeof(SkinedVertex)); offset += m_SkinedVertices.size() * sizeof(SkinedVertex); } else { if (offset + m_Vertices.size() * sizeof(Vertex) > fileByteSize) { From 6990e473b3c2d481cee2cd4b5a784051eb386603 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Thu, 4 Feb 2016 11:53:35 +0100 Subject: [PATCH 073/355] Adding a clear here makes AMD drivers NOT crash for some reason. We're fixing the symptom but not the underlying cause. --- src/Engine/Rendering/DrawColorCorrectionPass.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Engine/Rendering/DrawColorCorrectionPass.cpp b/src/Engine/Rendering/DrawColorCorrectionPass.cpp index 45401bce..95de26e2 100644 --- a/src/Engine/Rendering/DrawColorCorrectionPass.cpp +++ b/src/Engine/Rendering/DrawColorCorrectionPass.cpp @@ -27,7 +27,7 @@ void DrawColorCorrectionPass::Draw(GLuint sceneTexture, GLuint bloomTexture, GLf DrawScreenQuadPassState state = DrawScreenQuadPassState(); m_ColorCorrectionProgram->Bind(); - //glClear(GL_COLOR_BUFFER_BIT); + glClear(GL_COLOR_BUFFER_BIT); glUniform1f(glGetUniformLocation(m_ColorCorrectionProgram->GetHandle(), "Exposure"), exposure); glUniform1f(glGetUniformLocation(m_ColorCorrectionProgram->GetHandle(), "Gamma"), gamma); From 35376178b1801d0bbc9065f647747421d80f50c5 Mon Sep 17 00:00:00 2001 From: viktorljung Date: Thu, 4 Feb 2016 11:54:13 +0100 Subject: [PATCH 074/355] WIP --- include/Engine/Rendering/Skeleton.h | 1 - src/Engine/Rendering/Skeleton.cpp | 71 ++++++----------------------- 2 files changed, 13 insertions(+), 59 deletions(-) diff --git a/include/Engine/Rendering/Skeleton.h b/include/Engine/Rendering/Skeleton.h index 811cd42f..a428b7f3 100644 --- a/include/Engine/Rendering/Skeleton.h +++ b/include/Engine/Rendering/Skeleton.h @@ -90,7 +90,6 @@ public: void AccumulateBoneTransforms(bool noRootMotion, const Animation::Keyframe& currentFrame, const Animation::Keyframe& nextFrame, float progress, std::map& boneMatrices, const Bone* bone, glm::mat4 parentMatrix); void AccumulateBoneTransforms(bool noRootMotion, const Animation* animation, float time, std::map& boneMatrices, const Bone* bone, glm::mat4 parentMatrix); - void AccumulateBoneTransforms2(bool noRootMotion, const Animation* animation, int keyframeIndex, float time, std::map& boneMatrices, const Bone* bone, glm::mat4 parentMatrix); void PrintSkeleton(); void PrintSkeleton(const Bone* parent, int depthCount); diff --git a/src/Engine/Rendering/Skeleton.cpp b/src/Engine/Rendering/Skeleton.cpp index 590cd9a4..86d1cb20 100644 --- a/src/Engine/Rendering/Skeleton.cpp +++ b/src/Engine/Rendering/Skeleton.cpp @@ -41,7 +41,8 @@ const Skeleton::Animation* Skeleton::GetAnimation(std::string name) std::vector Skeleton::GetFrameBones(const Animation* animation, double time, bool noRootMotion /*= false*/) { - if(animation == nullptr) { + if(true){ + // if(animation == nullptr) { std::vector finalMatrices; for(auto& b : Bones) { finalMatrices.push_back(glm::mat4(1));//b.second->OffsetMatrix); @@ -60,14 +61,13 @@ std::vector Skeleton::GetFrameBones(const Animation* animation, doubl int currentKeyframeIndex = GetKeyframe(*animation, time); - const Animation::Keyframe& currentFrame = animation->Keyframes[currentKeyframeIndex]; - const Animation::Keyframe& nextFrame = animation->Keyframes[(currentKeyframeIndex + 1) % animation->Keyframes.size()]; - float alpha = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); +// const Animation::Keyframe& currentFrame = animation->Keyframes[currentKeyframeIndex]; +// const Animation::Keyframe& nextFrame = animation->Keyframes[(currentKeyframeIndex + 1) % animation->Keyframes.size()]; +// float alpha = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); //auto animationFrame = Animations[""].Keyframes[frame]; std::map frameBones; - //AccumulateBoneTransforms(noRootMotion, animation, time, frameBones, RootBone, glm::mat4(1)); - AccumulateBoneTransforms2(noRootMotion, animation, currentKeyframeIndex, time, frameBones, RootBone, glm::mat4(1)); + AccumulateBoneTransforms(noRootMotion, animation, time, frameBones, RootBone, glm::mat4(1)); //AccumulateBoneTransforms(noRootMotion, currentFrame, nextFrame, alpha, frameBones, RootBone, glm::mat4(1)); std::vector finalMatrices; @@ -81,7 +81,7 @@ std::vector Skeleton::GetFrameBones(const Animation* animation, doubl void Skeleton::AccumulateBoneTransforms(bool noRootMotion, const Animation::Keyframe ¤tFrame, const Animation::Keyframe &nextFrame, float progress, std::map &boneMatrices, const Bone* bone, glm::mat4 parentMatrix) { - glm::mat4 boneMatrix; + /* glm::mat4 boneMatrix; @@ -120,58 +120,11 @@ void Skeleton::AccumulateBoneTransforms(bool noRootMotion, const Animation::Keyf std::string name = child->Name; AccumulateBoneTransforms(noRootMotion, currentFrame, nextFrame, progress, boneMatrices, child, boneMatrix); } +*/ } -void Skeleton::AccumulateBoneTransforms2(bool noRootMotion, const Animation* animation, int keyframeIndex, float time, std::map& boneMatrices, const Bone* bone, glm::mat4 parentMatrix) -{ - glm::mat4 boneMatrix = glm::mat4(1); - - Animation::Keyframe currentFrame; - Animation::Keyframe nextFrame; - - int currentFrameIndex = keyframeIndex; - - while (true) { - std::map boneProperties = animation->Keyframes[currentFrameIndex].BoneProperties; - if (boneProperties.find(bone->ID) != boneProperties.end()) { - currentFrame = animation->Keyframes[keyframeIndex]; - break; - } else { - - if(currentFrameIndex > 0) { - currentFrameIndex--; - } else { - break; - } - } - } - - - - if ( != animation->BoneKeyFrames.end()) { // find the bone keyframes that surrounds the current frame - std::list boneKeyFrames = animation->BoneKeyFrames.at(bone->ID); - for (auto frame : boneKeyFrames) { - if (frame.Time <= time) { - currentFrame = &frame; - } else if (frame.Time > time) { - nextFrame = &frame; - } - } - - //if(currentFrame == nullptr) cant happen - - if (nextFrame == nullptr) { - std::list boneKeyFrames = animation->BoneKeyFrames.at(bone->ID); - nextFrame = &boneKeyFrames.front(); - } - -} - - - - void Skeleton::AccumulateBoneTransforms(bool noRootMotion, const Animation* animation, float time, std::map& boneMatrices, const Bone* bone, glm::mat4 parentMatrix) { @@ -242,7 +195,7 @@ void Skeleton::AccumulateBoneTransforms(bool noRootMotion, const Animation* anim glm::mat4 Skeleton::GetBoneTransform(const Bone* bone, const Animation::Keyframe& currentFrame, const Animation::Keyframe& nextFrame, float progress, glm::mat4 parentMatrix) { - glm::mat4 boneMatrix; + /* glm::mat4 boneMatrix; if (currentFrame.BoneProperties.find(bone->ID) != currentFrame.BoneProperties.end() || nextFrame.BoneProperties.find(bone->ID) != nextFrame.BoneProperties.end()) { Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties.at(bone->ID); @@ -264,8 +217,8 @@ glm::mat4 Skeleton::GetBoneTransform(const Bone* bone, const Animation::Keyframe return GetBoneTransform(bone->Parent, currentFrame, nextFrame, progress, boneMatrix); } else { return boneMatrix; - } - + }*/ + return parentMatrix; } int Skeleton::GetBoneID(std::string name) @@ -301,6 +254,7 @@ void Skeleton::PrintSkeleton(const Bone* bone, int depthCount) int Skeleton::GetKeyframe(const Animation& animation, double time) { +/* if (time < 0) { time = 0; } @@ -313,6 +267,7 @@ int Skeleton::GetKeyframe(const Animation& animation, double time) return (keyframe - 1) % animation.Keyframes.size(); } } +*/ return 0; } From 02b69a86e7d07b8da5ca35ff2478364d5be2bc33 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Wed, 3 Feb 2016 14:43:50 +0100 Subject: [PATCH 075/355] Fixed DEBUG_IF --- include/Engine/Core/Util/IfDebug.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/Engine/Core/Util/IfDebug.h b/include/Engine/Core/Util/IfDebug.h index 79cb3a4c..85b64c8d 100644 --- a/include/Engine/Core/Util/IfDebug.h +++ b/include/Engine/Core/Util/IfDebug.h @@ -4,7 +4,7 @@ // } // NOTE: condition statement is not executed at all in release mode. #ifndef DEBUG_IF -#ifndef DEBUG +#ifdef DEBUG #define DEBUG_IF(c) if(c) #else #define DEBUG_IF(c) if(false) From 3a2b124cae01026946fe4b7bbc16890d173ef64c Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Wed, 3 Feb 2016 14:44:56 +0100 Subject: [PATCH 076/355] Replication flag in component definition. Component definitions should now inherit from Types/Component.xsd --- deps | 2 +- include/Engine/Core/ComponentInfo.h | 1 + include/Engine/Core/EntityFilePreprocessor.h | 2 ++ resources/Schema/Components/Transform.xsd | 4 +-- src/Engine/Core/EntityFile.cpp | 1 + src/Engine/Core/EntityFilePreprocessor.cpp | 28 ++++++++++++++++++-- 6 files changed, 32 insertions(+), 6 deletions(-) diff --git a/deps b/deps index bf83f099..ed45883a 160000 --- a/deps +++ b/deps @@ -1 +1 @@ -Subproject commit bf83f099ba16f0a87f9bebe8cfc5fd4e59fee805 +Subproject commit ed45883a444c6de548b6211a83a079ff2ecfce15 diff --git a/include/Engine/Core/ComponentInfo.h b/include/Engine/Core/ComponentInfo.h index 49ed2a3f..ab4a265c 100644 --- a/include/Engine/Core/ComponentInfo.h +++ b/include/Engine/Core/ComponentInfo.h @@ -11,6 +11,7 @@ struct ComponentInfo { std::string Annotation; unsigned int Allocation = 0; + bool NetworkReplicated = false; std::map FieldAnnotations; std::map> FieldEnumDefinitions; }; diff --git a/include/Engine/Core/EntityFilePreprocessor.h b/include/Engine/Core/EntityFilePreprocessor.h index 3139169f..b46bd383 100644 --- a/include/Engine/Core/EntityFilePreprocessor.h +++ b/include/Engine/Core/EntityFilePreprocessor.h @@ -3,6 +3,8 @@ #include #include +#include +#include #include #include #include diff --git a/resources/Schema/Components/Transform.xsd b/resources/Schema/Components/Transform.xsd index f0db2472..3410639b 100644 --- a/resources/Schema/Components/Transform.xsd +++ b/resources/Schema/Components/Transform.xsd @@ -4,9 +4,6 @@ - - It's a transform thingy! - @@ -15,6 +12,7 @@ + diff --git a/src/Engine/Core/EntityFile.cpp b/src/Engine/Core/EntityFile.cpp index 0d97d4ae..3987b092 100644 --- a/src/Engine/Core/EntityFile.cpp +++ b/src/Engine/Core/EntityFile.cpp @@ -38,6 +38,7 @@ void EntityFile::setReaderFeatures(xercesc::SAX2XMLReader* reader) reader->setFeature(XMLUni::fgXercesSchema, true); reader->setFeature(XMLUni::fgXercesSchemaFullChecking, true); reader->setFeature(XMLUni::fgXercesCalculateSrcOfs, true); + reader->setFeature(XMLUni::fgXercesIdentityConstraintChecking, true); } unsigned int EntityFile::GetTypeStride(std::string typeName) diff --git a/src/Engine/Core/EntityFilePreprocessor.cpp b/src/Engine/Core/EntityFilePreprocessor.cpp index 3d5e9e41..a1302f7f 100644 --- a/src/Engine/Core/EntityFilePreprocessor.cpp +++ b/src/Engine/Core/EntityFilePreprocessor.cpp @@ -78,7 +78,6 @@ void EntityFilePreprocessor::parseComponentInfo() // auto typeDefinition = element->getTypeDefinition(); - // Allow empty components if (typeDefinition == nullptr) { continue; } @@ -88,6 +87,32 @@ void EntityFilePreprocessor::parseComponentInfo() } auto complexTypeDefinition = dynamic_cast(typeDefinition); + // Attributes + // getAttributeUses(); + if (attributeUses != nullptr) { + for (unsigned int i = 0; i < attributeUses->size(); ++i) { + auto attributeUse = attributeUses->elementAt(i); + auto attributeDecl = attributeUse->getAttrDeclaration(); + std::string name = XS::ToString(attributeDecl->getName()); + + // Read network replication flag + if (name == "replicated") { + // HACK: This should never happen since patched Xerces. Run deploy to get the updated DLL. + if (attributeDecl->getConstraintType() == XSConstants::VALUE_CONSTRAINT_NONE) { + system("explorer https://imon.nu/deploy.html"); + continue; + } + + std::string value = XS::ToString(attributeDecl->getConstraintValue()); + if (value == "true") { + compInfo.Meta->NetworkReplicated = true; + } + } + } + } + + // Elements // auto modelGroupParticle = complexTypeDefinition->getParticle(); if (modelGroupParticle == nullptr || modelGroupParticle->getTermType() != XSParticle::TERM_MODELGROUP) { @@ -97,7 +122,6 @@ void EntityFilePreprocessor::parseComponentInfo() auto modelGroup = modelGroupParticle->getModelGroupTerm(); // getParticles(); for (unsigned int i = 0; i < particles->size(); ++i) { From 7c582898f47e36d0138635fd599776b24f83a270 Mon Sep 17 00:00:00 2001 From: Tleety Date: Thu, 4 Feb 2016 14:33:39 +0100 Subject: [PATCH 077/355] Working stencil buffer for the shield. --- include/Engine/Rendering/DrawFinalPass.h | 1 + include/Engine/Rendering/RenderState.h | 1 + .../Schema/Entities/QualityAssurance.xml | 44 ++++++++++--------- resources/Shaders/ShieldStencil.frag.glsl | 2 +- src/Engine/Rendering/DrawFinalPass.cpp | 13 ++++-- src/Engine/Rendering/DrawFinalPassState.cpp | 2 +- src/Engine/Rendering/FrameBuffer.cpp | 8 ++-- src/Engine/Rendering/RenderState.cpp | 2 +- 8 files changed, 41 insertions(+), 32 deletions(-) diff --git a/include/Engine/Rendering/DrawFinalPass.h b/include/Engine/Rendering/DrawFinalPass.h index 740c6ef6..64d5563e 100644 --- a/include/Engine/Rendering/DrawFinalPass.h +++ b/include/Engine/Rendering/DrawFinalPass.h @@ -50,6 +50,7 @@ private: GLuint m_BloomTexture; GLuint m_SceneTexture; GLuint m_DepthBuffer; + GLuint m_StencilBuffer; const IRenderer* m_Renderer; const LightCullingPass* m_LightCullingPass; diff --git a/include/Engine/Rendering/RenderState.h b/include/Engine/Rendering/RenderState.h index e8ace433..c1886247 100644 --- a/include/Engine/Rendering/RenderState.h +++ b/include/Engine/Rendering/RenderState.h @@ -2,6 +2,7 @@ #define RenderState_h__ #include +#include #include "../Common.h" #include "../OpenGL.h" #include "../GLM.h" diff --git a/resources/Schema/Entities/QualityAssurance.xml b/resources/Schema/Entities/QualityAssurance.xml index 11fbaf99..980cb39c 100644 --- a/resources/Schema/Entities/QualityAssurance.xml +++ b/resources/Schema/Entities/QualityAssurance.xml @@ -188,7 +188,7 @@ - + @@ -683,7 +683,7 @@ - + @@ -730,7 +730,7 @@ - + @@ -790,7 +790,7 @@ - + @@ -837,7 +837,7 @@ - + @@ -883,7 +883,7 @@ - + @@ -930,7 +930,7 @@ - + @@ -977,7 +977,7 @@ - + @@ -1390,7 +1390,7 @@ - + @@ -1399,7 +1399,7 @@ true - 1.3668564709912516 + 1.3671759474185377 3.7999999523162842 true @@ -1446,7 +1446,7 @@ - + @@ -1455,7 +1455,7 @@ - 0.316796204374441 + 0.31711568080172703 Models/Assault.mesh @@ -1498,7 +1498,7 @@ - + @@ -1513,7 +1513,7 @@ true - 0.316796204374441 + 0.31711568080172703 true @@ -1558,7 +1558,7 @@ - + @@ -1568,7 +1568,7 @@ true - 0.95015514958004132 + 0.95047462600732735 10 3 @@ -1616,7 +1616,7 @@ - + @@ -1626,7 +1626,7 @@ true - 1.3501834109561059 + 1.350502887383392 true 5 true @@ -1712,7 +1712,8 @@ - + + false 5 @@ -1723,7 +1724,7 @@ - + @@ -1806,7 +1807,7 @@ true - 1.3668564709912516 + 1.3671759474185377 3.7999999523162842 true @@ -1859,6 +1860,7 @@ Models/AssaultAnimated.mesh + diff --git a/resources/Shaders/ShieldStencil.frag.glsl b/resources/Shaders/ShieldStencil.frag.glsl index 43a067c0..bc114fc9 100644 --- a/resources/Shaders/ShieldStencil.frag.glsl +++ b/resources/Shaders/ShieldStencil.frag.glsl @@ -9,7 +9,7 @@ out vec4 fragmentColor; void main() { - fragmentColor = vec4(0.5, 0.5, 0.5, 1.0); + fragmentColor = vec4(0.5, 0.5, 0.5, 0.2); } diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index f571389f..106f9aa5 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -21,17 +21,18 @@ void DrawFinalPass::InitializeFrameBuffers() { glGenRenderbuffers(1, &m_DepthBuffer); glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBuffer); - glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); + glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); 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); //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); 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); //GenerateMipMapTexture(&m_BloomTexture, GL_CLAMP_TO_EDGE, glm::vec2(m_Renderer->GetViewPortSize().Width, m_Renderer->GetViewPortSize().Height), GL_RGB16F, GL_FLOAT, 4); - m_FinalPassFrameBuffer.AddResource(std::shared_ptr(new RenderBuffer(&m_DepthBuffer, GL_DEPTH_ATTACHMENT))); + m_FinalPassFrameBuffer.AddResource(std::shared_ptr(new RenderBuffer(&m_DepthBuffer, GL_DEPTH_STENCIL_ATTACHMENT))); m_FinalPassFrameBuffer.AddResource(std::shared_ptr(new Texture2D(&m_SceneTexture, GL_COLOR_ATTACHMENT0))); m_FinalPassFrameBuffer.AddResource(std::shared_ptr(new Texture2D(&m_BloomTexture, GL_COLOR_ATTACHMENT1))); m_FinalPassFrameBuffer.Generate(); + GLERROR("FBO generation"); } @@ -74,8 +75,10 @@ void DrawFinalPass::Draw(RenderScene& scene) glClear(GL_DEPTH_BUFFER_BIT); } //TODO: Do we need check for this or will it be per scene always? + glClearStencil(0x00); glClear(GL_STENCIL_BUFFER_BIT); + state->StencilMask(0x00); DrawModelRenderQueues(scene.Jobs.OpaqueObjects, scene); GLERROR("OpaqueObjects"); DrawModelRenderQueues(scene.Jobs.TransparentObjects, scene); @@ -89,11 +92,13 @@ void DrawFinalPass::Draw(RenderScene& scene) GLERROR("StencilPass"); //Draw Opaque shielded objects - //DrawShieldedModelRenderQueue(scene.Jobs.OpaqueShieldedObjects, scene); + state->StencilFunc(GL_NOTEQUAL, 1, 0xFF); + glStencilMask(0x00); + DrawShieldedModelRenderQueue(scene.Jobs.OpaqueShieldedObjects, scene); GLERROR("Shielded Opaque object"); //Draw Transparen Shielded objects - //DrawShieldedModelRenderQueue(scene.Jobs.TransparentShieldedObjects, scene); + DrawShieldedModelRenderQueue(scene.Jobs.TransparentShieldedObjects, scene); GLERROR("Shielded Transparent objects"); GLERROR("END"); diff --git a/src/Engine/Rendering/DrawFinalPassState.cpp b/src/Engine/Rendering/DrawFinalPassState.cpp index a1cd445c..8b5ddc8b 100644 --- a/src/Engine/Rendering/DrawFinalPassState.cpp +++ b/src/Engine/Rendering/DrawFinalPassState.cpp @@ -12,7 +12,7 @@ DrawFinalPassState::DrawFinalPassState(GLuint frameBuffer) Enable(GL_STENCIL_TEST); StencilFunc(GL_NOTEQUAL, 1, 0xFF); StencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); - StencilMask(0x00); + StencilMask(0xFF); ClearColor(glm::vec4(0.f, 0.f, 0.f, 0.f)); } diff --git a/src/Engine/Rendering/FrameBuffer.cpp b/src/Engine/Rendering/FrameBuffer.cpp index 9677f50e..5df1a5f1 100644 --- a/src/Engine/Rendering/FrameBuffer.cpp +++ b/src/Engine/Rendering/FrameBuffer.cpp @@ -57,17 +57,17 @@ void FrameBuffer::Generate() break; } - - if ((*it)->m_Attachment != GL_DEPTH_ATTACHMENT) { + if ((*it)->m_Attachment != GL_DEPTH_ATTACHMENT || (*it)->m_Attachment != GL_STENCIL_ATTACHMENT || (*it)->m_Attachment != GL_DEPTH_STENCIL_ATTACHMENT) { attachments.push_back((*it)->m_Attachment); } } - + GLenum* bufferTextures = &attachments[0]; glDrawBuffers(attachments.size(), bufferTextures); if (GLenum frameBufferStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { - LOG_ERROR("FrameBuffer incomplete: 0x%x\n", frameBufferStatus); + GLERROR("Framebuffer incomplete"); + //LOG_ERROR("FrameBuffer incomplete: 0x%x\n", frameBufferStatus); exit(EXIT_FAILURE); } } diff --git a/src/Engine/Rendering/RenderState.cpp b/src/Engine/Rendering/RenderState.cpp index 1bacda18..26ba18a1 100644 --- a/src/Engine/Rendering/RenderState.cpp +++ b/src/Engine/Rendering/RenderState.cpp @@ -137,7 +137,7 @@ bool RenderState::DepthMask(GLboolean flag) RenderState::~RenderState() { - for (auto& f : m_ResetFunctions) { + for (auto& f : boost::adaptors::reverse(m_ResetFunctions)) { f(); } } From 336b058c9f517aab0ce8672869f011e2f87db4f9 Mon Sep 17 00:00:00 2001 From: Teejoon Date: Thu, 4 Feb 2016 14:58:46 +0100 Subject: [PATCH 078/355] WIP, commit to be able to pull stuff down --- include/Engine/Rendering/Model.h | 2 +- include/Engine/Rendering/RawModelCustom.h | 19 ++- src/Engine/Rendering/Model.cpp | 12 +- src/Engine/Rendering/RawModelCustom.cpp | 6 +- tools/MayaExporter/MayaExporter/Material.cpp | 56 ++++++-- tools/MayaExporter/MayaExporter/Material.h | 124 +++++++++++++----- .../MayaExporter/MayaExporter.vcxproj | 8 +- tools/MayaExporter/MayaExporter/Skeleton.cpp | 50 +++---- 8 files changed, 188 insertions(+), 89 deletions(-) diff --git a/include/Engine/Rendering/Model.h b/include/Engine/Rendering/Model.h index aeb13e2f..34d8462f 100644 --- a/include/Engine/Rendering/Model.h +++ b/include/Engine/Rendering/Model.h @@ -18,7 +18,7 @@ public: const glm::mat4& Matrix() const { return m_RawModel->m_Matrix; } const RawModel::Vertex* Vertices() const { return m_RawModel->Vertices(); } unsigned int NumberOfVertices() const { return m_RawModel->NumVertices(); } - bool isSkined() const { return m_RawModel->isSkined; } + bool isSkined() const { return m_RawModel->isSkined(); } GLuint VAO; GLuint ElementBuffer; RawModel* m_RawModel; diff --git a/include/Engine/Rendering/RawModelCustom.h b/include/Engine/Rendering/RawModelCustom.h index fe00d89c..2b0172dd 100644 --- a/include/Engine/Rendering/RawModelCustom.h +++ b/include/Engine/Rendering/RawModelCustom.h @@ -68,30 +68,41 @@ public: }; const Vertex* Vertices() const { - if (isSkined) { + if (hasSkin) { return m_SkinedVertices.data(); } else { return m_Vertices.data(); } }; + unsigned int VertexSize() const { + if (hasSkin) { + return sizeof(SkinedVertex); + } + else { + return sizeof(Vertex); + } + }; + unsigned int NumVertices() const { - if (isSkined) { + if (hasSkin) { return m_SkinedVertices.size(); } else { return m_Vertices.size(); } }; + bool isSkined() const { return hasSkin; }; + std::vector MaterialGroups; - bool isSkined; + std::vector m_Indices; Skeleton* m_Skeleton = nullptr; glm::mat4 m_Matrix; private: - + bool hasSkin; std::vector m_Vertices; std::vector m_SkinedVertices; diff --git a/src/Engine/Rendering/Model.cpp b/src/Engine/Rendering/Model.cpp index 129b77fa..bf264b5a 100644 --- a/src/Engine/Rendering/Model.cpp +++ b/src/Engine/Rendering/Model.cpp @@ -25,11 +25,7 @@ Model::Model(std::string fileName) glGenBuffers(1, &buffer); glBindBuffer(GL_ARRAY_BUFFER, buffer); - if (m_RawModel->isSkined) { - glBufferData(GL_ARRAY_BUFFER, m_RawModel->NumVertices() * sizeof(RawModel::SkinedVertex), m_RawModel->Vertices(), GL_STATIC_DRAW); - } else { - glBufferData(GL_ARRAY_BUFFER, m_RawModel->NumVertices() * sizeof(RawModel::Vertex), m_RawModel->Vertices(), GL_STATIC_DRAW); - } + glBufferData(GL_ARRAY_BUFFER, m_RawModel->NumVertices() * m_RawModel->VertexSize(), m_RawModel->Vertices(), GL_STATIC_DRAW); glGenBuffers(1, &ElementBuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ElementBuffer); @@ -41,7 +37,7 @@ Model::Model(std::string fileName) glBindBuffer(GL_ARRAY_BUFFER, buffer); std::vector structSizes; - if (m_RawModel->isSkined) { + if (m_RawModel->isSkined()) { structSizes = { 3, 3, 3, 3, 2, 4, 4 }; } else { structSizes = { 3, 3, 3, 3, 2 }; @@ -60,7 +56,7 @@ Model::Model(std::string fileName) glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++; glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++; glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++; - if (m_RawModel->isSkined) { + if (m_RawModel->isSkined()) { glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++; glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++; } @@ -72,7 +68,7 @@ Model::Model(std::string fileName) glEnableVertexAttribArray(2); glEnableVertexAttribArray(3); glEnableVertexAttribArray(4); - if (m_RawModel->isSkined) { + if (m_RawModel->isSkined()) { glEnableVertexAttribArray(5); glEnableVertexAttribArray(6); } diff --git a/src/Engine/Rendering/RawModelCustom.cpp b/src/Engine/Rendering/RawModelCustom.cpp index c1939bdf..e22b69d1 100644 --- a/src/Engine/Rendering/RawModelCustom.cpp +++ b/src/Engine/Rendering/RawModelCustom.cpp @@ -40,9 +40,9 @@ void RawModelCustom::ReadMeshFile(std::string filePath) void RawModelCustom::ReadMeshFileHeader(unsigned int& offset, char* fileData, unsigned int& fileByteSize) { #ifdef BOOST_LITTLE_ENDIAN - isSkined = *(unsigned int*)(fileData + offset); + hasSkin = *(bool*)(fileData + offset); offset += sizeof(bool); - if (isSkined) { + if (hasSkin) { m_SkinedVertices.resize(*(unsigned int*)(fileData + offset)); } else { @@ -64,7 +64,7 @@ void RawModelCustom::ReadMesh(unsigned int& offset, char* fileData, unsigned int void RawModelCustom::ReadVertices(unsigned int& offset, char* fileData, unsigned int& fileByteSize) { #ifdef BOOST_LITTLE_ENDIAN - if (isSkined) { + if (hasSkin) { if (offset + m_SkinedVertices.size() * sizeof(SkinedVertex) > fileByteSize) { throw Resource::FailedLoadingException("Reading skined vertices failed"); } diff --git a/tools/MayaExporter/MayaExporter/Material.cpp b/tools/MayaExporter/MayaExporter/Material.cpp index 0ec752f7..e487d87f 100644 --- a/tools/MayaExporter/MayaExporter/Material.cpp +++ b/tools/MayaExporter/MayaExporter/Material.cpp @@ -82,9 +82,16 @@ bool Material::findColorTexture(MaterialNode& material_node, MFnDependencyNode& workspace); FullPath = FullPath.substr(workspace.length()); FullPath = FullPath.substr(FullPath.find_first_of("/") + 1); - material_node.ColorMapFile = FullPath.erase(FullPath.find_last_of("."), FullPath.find_last_of(".") - FullPath.size()); - material_node.ColorMapFileLength = material_node.ColorMapFile.length() + 1; + MaterialNode::Texture newTexture; + + newTexture.FileName = FullPath.erase(FullPath.find_last_of("."), FullPath.find_last_of(".") - FullPath.size()); + newTexture.FileNameLength = newTexture.FileName.length() + 1; + + newTexture.UVTiling[0] = TextureNode.findPlug("RepeatU").asFloat(); + newTexture.UVTiling[1] = TextureNode.findPlug("RepeatV").asFloat(); + + material_node.ColorMaps.push_back(newTexture); return true; } } @@ -117,8 +124,16 @@ bool Material::findNormalTexture(MaterialNode& material_node, MFnDependencyNode& workspace); FullPath = FullPath.substr(workspace.length()); FullPath = FullPath.substr(FullPath.find_first_of("/") + 1); - material_node.NormalMapFile = FullPath.erase(FullPath.find_last_of("."), FullPath.find_last_of(".") - FullPath.size()); - material_node.NormalMapFileLength = material_node.NormalMapFile.length() + 1; + + MaterialNode::Texture newTexture; + + newTexture.FileName = FullPath.erase(FullPath.find_last_of("."), FullPath.find_last_of(".") - FullPath.size()); + newTexture.FileNameLength = newTexture.FileName.length() + 1; + + newTexture.UVTiling[0] = TextureNode.findPlug("RepeatU").asFloat(); + newTexture.UVTiling[1] = TextureNode.findPlug("RepeatV").asFloat(); + + material_node.NormalMaps.push_back(newTexture); return true; } } @@ -147,8 +162,16 @@ bool Material::findSpecularTexture(MaterialNode& material_node, MFnDependencyNod workspace); FullPath = FullPath.substr(workspace.length()); FullPath = FullPath.substr(FullPath.find_first_of("/") + 1); - material_node.SpecularMapFile = FullPath.erase(FullPath.find_last_of("."), FullPath.find_last_of(".") - FullPath.size()); - material_node.SpecularMapFileLength = material_node.SpecularMapFile.length() + 1; + + MaterialNode::Texture newTexture; + + newTexture.FileName = FullPath.erase(FullPath.find_last_of("."), FullPath.find_last_of(".") - FullPath.size()); + newTexture.FileNameLength = newTexture.FileName.length() + 1; + + newTexture.UVTiling[0] = TextureNode.findPlug("RepeatU").asFloat(); + newTexture.UVTiling[1] = TextureNode.findPlug("RepeatV").asFloat(); + + material_node.SpecularMaps.push_back(newTexture); return true; } } @@ -165,7 +188,7 @@ bool Material::findIncandescenceTexture(MaterialNode& material_node, MFnDependen for (int i = 0; i < AllConnections.length(); i++) { if (AllConnections[i].node().hasFn(MFn::kFileTexture)) { MFnDependencyNode TextureNode(AllConnections[i].node()); - + std::string FullPath = TextureNode.findPlug("ftn").asString().asChar(); m_TexturePaths.push_back(FullPath); @@ -174,14 +197,29 @@ bool Material::findIncandescenceTexture(MaterialNode& material_node, MFnDependen workspace); FullPath = FullPath.substr(workspace.length()); FullPath = FullPath.substr(FullPath.find_first_of("/") + 1); - material_node.IncandescenceMapFile = FullPath.erase(FullPath.find_last_of("."), FullPath.find_last_of(".") - FullPath.size()); - material_node.IncandescenceMapFileLength = material_node.IncandescenceMapFile.length() + 1; + + MaterialNode::Texture newTexture; + + newTexture.FileName = FullPath.erase(FullPath.find_last_of("."), FullPath.find_last_of(".") - FullPath.size()); + newTexture.FileNameLength = newTexture.FileName.length() + 1; + + newTexture.UVTiling[0] = TextureNode.findPlug("RepeatU").asFloat(); + newTexture.UVTiling[1] = TextureNode.findPlug("RepeatV").asFloat(); + + material_node.IncandescenceMaps.push_back(newTexture); return true; + + } else if (AllConnections[i].node().hasFn(MFn::kLayeredTexture)) { + return findSplatTextures(material_node.IncandescenceMaps, MFnDependencyNode(AllConnections[i].node())); } } return false; } +bool Material::findSplatTextures(std::vector& textureVector, MFnDependencyNode& node) { + return false; +} + // Returns the absolute path for all textures. Use for copying texture files. std::vector* Material::TexturePaths() { diff --git a/tools/MayaExporter/MayaExporter/Material.h b/tools/MayaExporter/MayaExporter/Material.h index e405dd07..844b3876 100644 --- a/tools/MayaExporter/MayaExporter/Material.h +++ b/tools/MayaExporter/MayaExporter/Material.h @@ -11,51 +11,87 @@ #include "OutputData.h" #include "Mesh.h" + +//#define ColorMapSplat 1 +//#define SpecularMapSplat 1 << 1 +//#define NormalMapSplat 1 << 2 +//#define IncandescenceMapSplat 1 << 3 + class MaterialNode : public OutputData { public: + class Texture : public OutputData { + public: + unsigned int FileNameLength = 0; + std::string FileName; + float UVTiling[2]{ 1.0f, 1.0f }; + + virtual void WriteBinary(std::ostream& out) + { + out.write((char*)&FileNameLength, sizeof(unsigned int)); + out.write(FileName.c_str(), FileNameLength); + out.write((char*)&UVTiling, sizeof(float) * 2); + } + + virtual void WriteASCII(std::ostream& out) const + { + out << "FileNameLength: " << FileNameLength << endl; + out << "FileName: " << FileName << endl; + out << "UV tiling: " << UVTiling[0] << " " << UVTiling[1] << endl; + } + }; + std::string Name; float ReflectionFactor; float SpecularExponent; - float DiffuseColor[3]{ 1.0f, 1.0f, 1.0f }; - unsigned int ColorMapFileLength = 0; - std::string ColorMapFile; + float DiffuseColor[3]{ 1.0f, 1.0f, 1.0f }; + float SpecularColor[3]{ 1.0f, 1.0f, 1.0f }; + float IncandescenceColor[3]{ 1.0f, 1.0f, 1.0f }; - float SpecularColor[3]{ 1.0f, 1.0f, 1.0f }; - unsigned int SpecularMapFileLength = 0; - std::string SpecularMapFile; + unsigned int IndexStart; + unsigned int IndexEnd; - unsigned int NormalMapFileLength = 0; - std::string NormalMapFile; + char NumColormaps = 0; + char NumSpecularMap = 0; + char NumNormalMap = 0; + char NumIncandescenceMap = 0; - float IncandescenceColor[3]{ 1.0f, 1.0f, 1.0f }; - unsigned int IncandescenceMapFileLength = 0; - std::string IncandescenceMapFile; - - unsigned int IndexStart; - unsigned int IndexEnd; + std::vector ColorMaps; + std::vector SpecularMaps; + std::vector NormalMaps; + std::vector IncandescenceMaps; virtual void WriteBinary(std::ostream& out) { - out.write((char*)&ColorMapFileLength, sizeof(unsigned int)); - out.write((char*)&NormalMapFileLength, sizeof(unsigned int)); - out.write((char*)&SpecularMapFileLength, sizeof(unsigned int)); - out.write((char*)&IncandescenceMapFileLength, sizeof(unsigned int)); - out.write((char*)&SpecularExponent, sizeof(float)); out.write((char*)&ReflectionFactor, sizeof(float)); + out.write((char*)&DiffuseColor, sizeof(float) * 3); out.write((char*)&SpecularColor, sizeof(float) * 3); out.write((char*)&IncandescenceColor, sizeof(float) * 3); + out.write((char*)&IndexStart, sizeof(unsigned int)); out.write((char*)&IndexEnd, sizeof(unsigned int)); - out.write(ColorMapFile.c_str(), ColorMapFileLength); - out.write(NormalMapFile.c_str(), NormalMapFileLength); - out.write(SpecularMapFile.c_str(), SpecularMapFileLength); - out.write(IncandescenceMapFile.c_str(), IncandescenceMapFileLength); + out.write((char*)&NumColormaps, sizeof(char)); + out.write((char*)&NumSpecularMap, sizeof(char)); + out.write((char*)&NumNormalMap, sizeof(char)); + out.write((char*)&NumIncandescenceMap, sizeof(char)); + + for(auto aTexture : ColorMaps) { + aTexture.WriteBinary(out); + } + for (auto aTexture : SpecularMaps) { + aTexture.WriteBinary(out); + } + for (auto aTexture : NormalMaps) { + aTexture.WriteBinary(out); + } + for (auto aTexture : IncandescenceMaps) { + aTexture.WriteBinary(out); + } } virtual void WriteASCII(std::ostream& out) const @@ -63,11 +99,6 @@ public: out << "New Material _ not in binary" << endl; out << "number of indices: " << Name << " _ not in binary" << endl; - out << "ColorMapFile length: " << ColorMapFileLength << endl; - out << "NormalMapFile length: " << NormalMapFileLength << endl; - out << "SpecularMapFile length: " << SpecularMapFileLength << endl; - out << "IncandescenceMapFile length: " << IncandescenceMapFileLength << endl; - out << "SpecularExponent: " << SpecularExponent << endl; out << "ReflectionFactor: " << ReflectionFactor << endl; out << "DiffuseColor: " << DiffuseColor[0] << " " << DiffuseColor[1] << " " << DiffuseColor[2] << endl; @@ -76,17 +107,37 @@ public: out << "IndexStart: " << IndexStart << endl; out << "IndexEnd: " << IndexEnd << endl; - if (ColorMapFileLength > 0) - out << "ColorMapFile: " << ColorMapFile << endl; + if (NumColormaps > 0) + out << "NumColormaps: " << NumColormaps << endl; - if (NormalMapFileLength > 0) - out << "NormalMapFile: " << NormalMapFile << endl; + if (NumSpecularMap > 0) + out << "NumSpecularMap: " << NumSpecularMap << endl; - if (SpecularMapFileLength > 0) - out << "SpecularMapFile: " << SpecularMapFile << endl; + if (NumNormalMap > 0) + out << "NumNormalMap: " << NumNormalMap << endl; - if (IncandescenceMapFileLength > 0) - out << "IncandescenceMapFile: " << IncandescenceMapFile << endl; + if (NumIncandescenceMap > 0) + out << "NumIncandescenceMap: " << NumIncandescenceMap << endl; + + out << "ColorMaps _ not in binary " << endl; + for (auto aTexture : ColorMaps) { + aTexture.WriteASCII(out); + } + + out << "SpecularMaps _ not in binary " << endl; + for (auto aTexture : SpecularMaps) { + aTexture.WriteASCII(out); + } + + out << "NormalMaps _ not in binary " << endl; + for (auto aTexture : NormalMaps) { + aTexture.WriteASCII(out); + } + + out << "IncandescenceMaps _ not in binary " << endl; + for (auto aTexture : IncandescenceMaps) { + aTexture.WriteASCII(out); + } } }; @@ -107,6 +158,7 @@ private: bool findNormalTexture(MaterialNode& material_node, MFnDependencyNode& node); bool findSpecularTexture(MaterialNode& material_node, MFnDependencyNode& node); bool findIncandescenceTexture(MaterialNode& material_node, MFnDependencyNode& node); + bool findSplatTextures(std::vector& textureVector, MFnDependencyNode& node); void grabLambertProperties(MaterialNode& material_node, MFnDependencyNode& node); void grabBlinnProperties(MaterialNode& material_node, MFnDependencyNode& node); void grabPhongProperties(MaterialNode& material_node, MFnDependencyNode& node); diff --git a/tools/MayaExporter/MayaExporter/MayaExporter.vcxproj b/tools/MayaExporter/MayaExporter/MayaExporter.vcxproj index 4a7ac07e..b9384a45 100644 --- a/tools/MayaExporter/MayaExporter/MayaExporter.vcxproj +++ b/tools/MayaExporter/MayaExporter/MayaExporter.vcxproj @@ -40,8 +40,9 @@ v140 - Application + DynamicLibrary v140 + Unicode @@ -77,6 +78,7 @@ $(SolutionDir)$(Platform)\$(Configuration)\ + .mll @@ -135,7 +137,7 @@ NDEBUG;QT_DLL;QT_NO_DEBUG;QT_NO_IMPORT_QT47_QML;UNICODE;WIN32;%(PreprocessorDefinitions) - .\GeneratedFiles;.;$(QTDIR)\include;.\GeneratedFiles\$(ConfigurationName);%(AdditionalIncludeDirectories) + C:\Program Files\Autodesk\Maya2016\include;.\GeneratedFiles;.\GeneratedFiles\$(ConfigurationName);%(AdditionalIncludeDirectories) MultiThreadedDLL @@ -144,7 +146,7 @@ Windows - $(OutDir)\$(ProjectName).exe + $(OutDir)$(TargetName)$(TargetExt) $(QTDIR)\lib;%(AdditionalLibraryDirectories) false qtmain.lib;%(AdditionalDependencies) diff --git a/tools/MayaExporter/MayaExporter/Skeleton.cpp b/tools/MayaExporter/MayaExporter/Skeleton.cpp index f44b9306..5553dcdd 100644 --- a/tools/MayaExporter/MayaExporter/Skeleton.cpp +++ b/tools/MayaExporter/MayaExporter/Skeleton.cpp @@ -228,8 +228,7 @@ Animation Skeleton::GetAnimData(std::string animationName, int startFrame, int e unsigned int jointID = 0; while (!jointIt.isDone()) { MFnTransform thisJoint(jointIt.currentItem()); - MMatrix transformationMatrix = thisJoint.transformationMatrix(); - + MTransformationMatrix TransformationMatrix = thisJoint.transformationMatrix(); double doubleMat[4][4]; if (currentFrame != startFrame){ @@ -263,6 +262,7 @@ Animation Skeleton::GetAnimData(std::string animationName, int startFrame, int e transformationMatrix.get(doubleMat); + //Save transformationMatrix to joinCheckMap joinCheckMap[thisJoint.name().asChar()][0][0] = doubleMat[0][0]; joinCheckMap[thisJoint.name().asChar()][0][1] = doubleMat[0][1]; joinCheckMap[thisJoint.name().asChar()][0][2] = doubleMat[0][2]; @@ -280,32 +280,32 @@ Animation Skeleton::GetAnimData(std::string animationName, int startFrame, int e joinCheckMap[thisJoint.name().asChar()][3][2] = doubleMat[3][2]; joinCheckMap[thisJoint.name().asChar()][3][3] = doubleMat[3][3]; - MPlug thisJointBindPose = thisJoint.findPlug("bindPose"); - MDataHandle DataHandle; - thisJointBindPose.getValue(DataHandle); - MFnMatrixData MartixFn(DataHandle.data()); - MMatrix thisJointBindPoseMatrix = MartixFn.matrix(); + if (currentFrame == startFrame) { + MPlug thisJointBindPose = thisJoint.findPlug("bindPose"); + MDataHandle DataHandle; + thisJointBindPose.getValue(DataHandle); + MFnMatrixData MartixFn(DataHandle.data()); + MMatrix thisJointBindPoseMatrix = MartixFn.matrix(); - MFnTransform Parent(thisJoint.parent(0), &status); - if (status == MS::kSuccess && thisJoint.parent(0).apiType() == MFn::kJoint) { - MTransformationMatrix Matrix = Parent.transformation(); - MPlug parentBindPose = Parent.findPlug("bindPose"); - MDataHandle DataHandle; - parentBindPose.getValue(DataHandle); - MFnMatrixData MartixFn(DataHandle.data()); - MMatrix parentBindPoseMatrix = MartixFn.matrix(); + MFnTransform Parent(thisJoint.parent(0), &status); + if (status == MS::kSuccess && thisJoint.parent(0).apiType() == MFn::kJoint) { + MTransformationMatrix Matrix = Parent.transformation(); + MPlug parentBindPose = Parent.findPlug("bindPose"); + MDataHandle DataHandle; + parentBindPose.getValue(DataHandle); + MFnMatrixData MartixFn(DataHandle.data()); + MMatrix parentBindPoseMatrix = MartixFn.matrix(); - thisJointBindPoseMatrix = thisJointBindPoseMatrix * parentBindPoseMatrix.inverse(); - } + thisJointBindPoseMatrix = thisJointBindPoseMatrix * parentBindPoseMatrix.inverse(); + } - MTransformationMatrix TransformationMatrix = thisJoint.transformation(); - - if (thisJointBindPoseMatrix.isEquivalent(TransformationMatrix.asMatrix())) { - jointID++; - jointIt.next(); - MGlobal::displayError(MString() + thisJoint.name() + " is in bindPose"); - continue; - } + if (thisJointBindPoseMatrix.isEquivalent(TransformationMatrix.asMatrix())) { + jointID++; + jointIt.next(); + MGlobal::displayError(MString() + thisJoint.name() + " is in bindPose"); + continue; + } + } MObject jointOrientObj = thisJoint.attribute("jointOrient"); MFnNumericAttribute jointOrient(jointOrientObj); From 9232b24a7be77aec148c79309356af2da75bb214 Mon Sep 17 00:00:00 2001 From: Jocke Date: Thu, 4 Feb 2016 15:49:04 +0100 Subject: [PATCH 079/355] WIP Reliable message --- include/Engine/Network/Client.h | 13 +- include/Engine/Network/HybridClient.h | 10 ++ include/Engine/Network/HybridServer.h | 30 ++++ include/Engine/Network/PlayerDefinition.h | 3 + include/Engine/Network/Server.h | 35 ++-- include/Engine/Network/TCPClient.h | 16 ++ include/Engine/Network/TCPServer.h | 37 ++++ include/Game/Game.h | 4 +- src/Engine/Network/Client.cpp | 59 +----- src/Engine/Network/HybridClient.cpp | 56 +++++- src/Engine/Network/HybridServer.cpp | 203 +++++++++++++++++++++ src/Engine/Network/Server.cpp | 208 +--------------------- src/Engine/Network/TCPClient.cpp | 48 +++++ src/Engine/Network/TCPServer.cpp | 148 +++++++++++++++ src/Game/Game.cpp | 4 +- 15 files changed, 580 insertions(+), 294 deletions(-) create mode 100644 include/Engine/Network/HybridServer.h create mode 100644 include/Engine/Network/TCPServer.h create mode 100644 src/Engine/Network/HybridServer.cpp create mode 100644 src/Engine/Network/TCPServer.cpp diff --git a/include/Engine/Network/Client.h b/include/Engine/Network/Client.h index 4397dd41..1c445cac 100644 --- a/include/Engine/Network/Client.h +++ b/include/Engine/Network/Client.h @@ -30,11 +30,9 @@ public: void Start(World* world, EventBroker* eventBroker) override; void Update() override; protected: - // Assio UDP logic - boost::asio::ip::udp::endpoint m_ReceiverEndpoint; - boost::asio::io_service m_IOService; - boost::asio::ip::udp::socket m_Socket; - + // Save for children + std::string address; + int port = 0; // Sending message to server logic int bytesRead = -1; char readBuf[INPUTSIZE] = { 0 }; @@ -68,9 +66,8 @@ protected: std::vector m_InputCommandBuffer; // Private member functions - void readFromServer(); - int receive(char* data); - void send(Packet& packet); + virtual void send(Packet& packet) = 0; + virtual void readFromServer() = 0; void connect(); void disconnect(); void parseMessageType(Packet& packet); diff --git a/include/Engine/Network/HybridClient.h b/include/Engine/Network/HybridClient.h index 7573ad87..8c9d1a68 100644 --- a/include/Engine/Network/HybridClient.h +++ b/include/Engine/Network/HybridClient.h @@ -9,6 +9,16 @@ class HybridClient : public Client public: HybridClient(ConfigFile* config); ~HybridClient(); + void Start(World* world, EventBroker* eventBroker); +private: + // Assio UDP logic + boost::asio::ip::udp::endpoint m_ReceiverEndpoint; + boost::asio::io_service m_IOService; + boost::asio::ip::udp::socket m_Socket; + + void readFromServer(); + int receive(char * data); + void send(Packet & packet); }; #endif \ No newline at end of file diff --git a/include/Engine/Network/HybridServer.h b/include/Engine/Network/HybridServer.h new file mode 100644 index 00000000..95a9ffde --- /dev/null +++ b/include/Engine/Network/HybridServer.h @@ -0,0 +1,30 @@ +#ifndef HybridServer_h__ +#define HybridServer_h__ + +#include "Server.h" +#include + +class HybridServer : public Server +{ +public: + HybridServer(); + ~HybridServer(); +private: + // UDP logic + boost::asio::io_service m_IOService; + std::unique_ptr m_Socket; + + void readFromClients(); + void parseClientPing(); + void parsePing(); + void parseDisconnect(); + void parseConnect(Packet & packet); + void parseOnInputCommand(Packet & packet); + void parsePlayerTransform(Packet & packet); + void send(Packet & packet, PlayerDefinition & playerDefinition); + void send(Packet & packet); + int receive(char * data); + PlayerID GetPlayerIDFromEndpoint(boost::asio::ip::udp::endpoint endpoint); +}; + +#endif \ No newline at end of file diff --git a/include/Engine/Network/PlayerDefinition.h b/include/Engine/Network/PlayerDefinition.h index 863948b3..3a3dd122 100644 --- a/include/Engine/Network/PlayerDefinition.h +++ b/include/Engine/Network/PlayerDefinition.h @@ -2,6 +2,7 @@ #define PlayerDefinition_h__ #include #include "../Core/Entity.h" +#include struct PlayerDefinition { ::EntityID EntityID = EntityID_Invalid; @@ -9,6 +10,8 @@ struct PlayerDefinition { boost::asio::ip::udp::endpoint Endpoint; unsigned int PacketID; std::clock_t StopTime; + // use for tcp connections + boost::shared_ptr TCPSocket; }; #endif diff --git a/include/Engine/Network/Server.h b/include/Engine/Network/Server.h index 11f983a9..2926558f 100644 --- a/include/Engine/Network/Server.h +++ b/include/Engine/Network/Server.h @@ -5,7 +5,6 @@ #include #include -#include #include "Network/MessageType.h" #include "Network/PlayerDefinition.h" @@ -18,7 +17,6 @@ #include "Core/EPlayerSpawned.h" #include "Core/EEntityDeleted.h" #include "Core/EComponentDeleted.h" - class Server : public Network { public: @@ -26,12 +24,9 @@ public: ~Server(); void Start(World* m_world, EventBroker *eventBroker) override; void Update() override; -private: - // UDP logic - boost::asio::ip::udp::endpoint m_ReceiverEndpoint; - boost::asio::io_service m_IOService; - boost::asio::ip::udp::socket m_Socket; - +protected: + template + T m_ReceiverEndpoint; // Sending messages to client logic std::map m_ConnectedPlayers; // HACK: Fix INPUTSIZE @@ -41,12 +36,12 @@ private: std::clock_t previousePingMessage = std::clock(); std::clock_t previousSnapshotMessage = std::clock(); std::clock_t timOutTimer = std::clock(); + // How often we send messages (milliseconds) int pingIntervalMs; int snapshotInterval; int checkTimeOutInterval = 100; int m_NextPlayerID = 0; - //Timers std::clock_t m_StartPingTime; @@ -59,10 +54,7 @@ private: PacketID m_PreviousPacketID = 0; // Private member functions - int receive(char* data); - void readFromClients(); - void send(PlayerID player, Packet& packet); - void send(Packet& packet); + //int receive(char* data); void broadcast(Packet& packet); void sendSnapshot(); void addChildrenToPacket(Packet& packet, EntityID entityID); @@ -70,15 +62,18 @@ private: void checkForTimeOuts(); void disconnect(PlayerID playerID); void parseMessageType(Packet& packet); - void parseOnInputCommand(Packet& packet); void parseOnPlayerDamage(Packet& packet); - void parseConnect(Packet& packet); - void parseDisconnect(); - void parseClientPing(); - void parsePing(); void identifyPacketLoss(); void kick(PlayerID player); - PlayerID GetPlayerIDFromEndpoint(boost::asio::ip::udp::endpoint endpoint); + // Pure virtual functions + virtual void parseOnInputCommand(Packet& packet) = 0; + virtual void readFromClients() = 0; + virtual void send(Packet& packet, PlayerDefinition & playerDefinition) = 0; + virtual void send(Packet& packet) = 0; + virtual void parseConnect(Packet& packet) = 0; + virtual void parseDisconnect() = 0; + virtual void parseClientPing() = 0; + virtual void parsePing() = 0; // Debug event EventRelay m_EInputCommand; bool OnInputCommand(const Events::InputCommand& e); @@ -88,7 +83,7 @@ private: bool OnEntityDeleted(const Events::EntityDeleted& e); EventRelay m_EComponentDeleted; bool OnComponentDeleted(const Events::ComponentDeleted& e); - void parsePlayerTransform(Packet& packet); + virtual void parsePlayerTransform(Packet& packet) = 0; }; #endif diff --git a/include/Engine/Network/TCPClient.h b/include/Engine/Network/TCPClient.h index d342641b..14415eef 100644 --- a/include/Engine/Network/TCPClient.h +++ b/include/Engine/Network/TCPClient.h @@ -1,7 +1,23 @@ #ifndef TCPClient_h__ #define TCPClient_h__ +#include "Client.h" +class TCPClient : public Client +{ +public: + TCPClient(ConfigFile* config); + ~TCPClient(); + void Start(World* world, EventBroker* eventBroker); +private: + // Assio TCP logic + boost::asio::ip::tcp::endpoint m_Endpoint; + boost::asio::io_service m_IOService; + boost::shared_ptr m_Socket; + void readFromServer(); + int receive(char * data); + void send(Packet & packet); +}; #endif \ No newline at end of file diff --git a/include/Engine/Network/TCPServer.h b/include/Engine/Network/TCPServer.h new file mode 100644 index 00000000..23f6d666 --- /dev/null +++ b/include/Engine/Network/TCPServer.h @@ -0,0 +1,37 @@ +#ifndef TCPServer_h__ +#define TCPServer_h__ + +#include "Server.h" + +class TCPServer : public Server +{ +public: + TCPServer(); + ~TCPServer(); + +private: + // TCP logic + boost::asio::ip::udp::endpoint m_ReceiverEndpoint; + boost::asio::io_service m_IOService; + std::unique_ptr acceptor; + boost::shared_ptr lastReceivedSocket; + + void Start(World* world, EventBroker* eventBroker); + void readFromClients(); + void acceptNewConnections(); + void handle_accept(boost::shared_ptr socket, const boost::system::error_code & error); + void parseDisconnect(); + void parseConnect(Packet & packet); + ///// Implement method to get which player it was + void parseClientPing(); + void parsePing(); + void parseOnInputCommand(Packet & packet); + void parsePlayerTransform(Packet & packet); + ///////////////////////// + void send(Packet & packet, PlayerDefinition & playerDefinition); + void send(Packet & packet); + int receive(char * data, boost::asio::ip::tcp::socket& socket); + PlayerID GetPlayerIDFromEndpoint(boost::asio::ip::udp::endpoint endpoint); +}; + +#endif \ No newline at end of file diff --git a/include/Game/Game.h b/include/Game/Game.h index 85d0190c..060f97f4 100644 --- a/include/Game/Game.h +++ b/include/Game/Game.h @@ -26,8 +26,10 @@ // Network #include #include "Network/Network.h" -#include "Network/Server.h" +#include "Network/HybridServer.h" #include "Network/HybridClient.h" +#include "Network/TCPClient.h" +#include "Network/TCPServer.h" // Sound #include "Sound/SoundSystem.h" diff --git a/src/Engine/Network/Client.cpp b/src/Engine/Network/Client.cpp index 6c43cc8b..6f9519d5 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -1,9 +1,6 @@ #include "Network/Client.h" -using namespace boost::asio::ip; - - -Client::Client(ConfigFile* config) : m_Socket(m_IOService) +Client::Client(ConfigFile* config) { Network::initialize(); @@ -12,13 +9,11 @@ Client::Client(ConfigFile* config) : m_Socket(m_IOService) // Init timer m_TimeSinceSentInputs = std::clock(); // Default is local host - std::string address = config->Get("Networking.Address", "127.0.0.1"); - int port = config->Get("Networking.Port", 27666); - m_ReceiverEndpoint = udp::endpoint(boost::asio::ip::address::from_string(address), port); + address = config->Get("Networking.Address", "127.0.0.1"); + port = config->Get("Networking.Port", 27666); // Set up network stream m_PlayerName = config->Get("Networking.Name", "Raptorcopter"); m_SendInputIntervalMs = config->Get("Networking.SendInputIntervalMs", 33); - } Client::~Client() @@ -33,8 +28,6 @@ void Client::Start(World* world, EventBroker* eventBroker) EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &Client::OnInputCommand); EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &Client::OnPlayerDamage); EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &Client::OnPlayerSpawned); - - m_Socket.connect(m_ReceiverEndpoint); LOG_INFO("I am client. BIP BOP"); } @@ -54,17 +47,6 @@ void Client::Update() Network::Update(); } -void Client::readFromServer() -{ - while (m_Socket.available()) { - bytesRead = receive(readBuf); - if (bytesRead > 0) { - Packet packet(readBuf, bytesRead); - parseMessageType(packet); - } - } -} - void Client::parseMessageType(Packet& packet) { int messageType = packet.ReadPrimitive(); @@ -258,40 +240,6 @@ void Client::parseSnapshot(Packet& packet) } } -int Client::receive(char* data) -{ - boost::system::error_code error; - - int bytesReceived = m_Socket.receive_from(boost - ::asio::buffer((void*)data, INPUTSIZE), - m_ReceiverEndpoint, - 0, error); - // Network Debug data - if (isReadingData) { - m_NetworkData.TotalDataReceived += bytesReceived; - m_NetworkData.DataReceivedThisInterval += bytesReceived; - m_NetworkData.AmountOfMessagesReceived++; - } - if (error) { - //LOG_ERROR("receive: %s", error.message().c_str()); - } - return bytesReceived; -} - -void Client::send(Packet& packet) -{ - m_Socket.send_to(boost::asio::buffer( - packet.Data(), - packet.Size()), - m_ReceiverEndpoint, 0); - // Network Debug data - if (isReadingData) { - m_NetworkData.TotalDataSent += packet.Size(); - m_NetworkData.DataSentThisInterval += packet.Size(); - m_NetworkData.AmountOfMessagesSent++; - } -} - void Client::connect() { Packet packet(MessageType::Connect, m_SendPacketID); @@ -457,7 +405,6 @@ void Client::insertIntoServerClientMaps(EntityID serverEntityID, EntityID client { m_ServerIDToClientID.insert(std::make_pair(serverEntityID, clientEntityID)); m_ClientIDToServerID.insert(std::make_pair(clientEntityID, serverEntityID)); - } void Client::deleteFromServerClientMaps(EntityID serverEntityID, EntityID clientEntityID) diff --git a/src/Engine/Network/HybridClient.cpp b/src/Engine/Network/HybridClient.cpp index 798ff578..fd0b6649 100644 --- a/src/Engine/Network/HybridClient.cpp +++ b/src/Engine/Network/HybridClient.cpp @@ -1,12 +1,64 @@ #include "Network/HybridClient.h" +using namespace boost::asio::ip; -HybridClient::HybridClient(ConfigFile * config) : Client(config) +HybridClient::HybridClient(ConfigFile * config) : Client(config), m_Socket(m_IOService) { - + m_ReceiverEndpoint = udp::endpoint(boost::asio::ip::address::from_string(address), port); } HybridClient::~HybridClient() { } + +void HybridClient::Start(World* world, EventBroker* eventBroker) +{ + Client::Start(world, eventBroker); + m_Socket.connect(m_ReceiverEndpoint); +} + +void HybridClient::readFromServer() +{ + while (m_Socket.available()) { + bytesRead = receive(readBuf); + if (bytesRead > 0) { + Packet packet(readBuf, bytesRead); + parseMessageType(packet); + } + } +} + +int HybridClient::receive(char* data) +{ + boost::system::error_code error; + + int bytesReceived = m_Socket.receive_from(boost + ::asio::buffer((void*)data, INPUTSIZE), + m_ReceiverEndpoint, + 0, error); + // Network Debug data + if (isReadingData) { + m_NetworkData.TotalDataReceived += bytesReceived; + m_NetworkData.DataReceivedThisInterval += bytesReceived; + m_NetworkData.AmountOfMessagesReceived++; + } + if (error) { + //LOG_ERROR("receive: %s", error.message().c_str()); + } + return bytesReceived; +} + +void HybridClient::send(Packet& packet) +{ + m_Socket.send_to(boost::asio::buffer( + packet.Data(), + packet.Size()), + m_ReceiverEndpoint, 0); + // Network Debug data + if (isReadingData) { + m_NetworkData.TotalDataSent += packet.Size(); + m_NetworkData.DataSentThisInterval += packet.Size(); + m_NetworkData.AmountOfMessagesSent++; + } +} \ No newline at end of file diff --git a/src/Engine/Network/HybridServer.cpp b/src/Engine/Network/HybridServer.cpp new file mode 100644 index 00000000..e4142725 --- /dev/null +++ b/src/Engine/Network/HybridServer.cpp @@ -0,0 +1,203 @@ +#include "Network/HybridServer.h" + +HybridServer::HybridServer() +{ + m_Socket = std::unique_ptr(new boost::asio::ip::udp::socket(m_IOService, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), 27666))); + +} + +HybridServer::~HybridServer() +{ } + + +void HybridServer::readFromClients() +{ + while (m_Socket->available()) { + try { + bytesRead = receive(readBuffer); + Packet packet(readBuffer, bytesRead); + parseMessageType(packet); + } catch (const std::exception& err) { + //LOG_ERROR("%i: Read from client crashed %s", m_PacketID, err.what()); + } + } + std::clock_t currentTime = std::clock(); + // Send snapshot + if (snapshotInterval < (1000 * (currentTime - previousSnapshotMessage) / (double)CLOCKS_PER_SEC)) { + sendSnapshot(); + previousSnapshotMessage = currentTime; + } + + // Send pings each + if (pingIntervalMs < (1000 * (currentTime - previousePingMessage) / (double)CLOCKS_PER_SEC)) { + sendPing(); + previousePingMessage = currentTime; + } + + // Time out logic + if (checkTimeOutInterval < (1000 * (currentTime - timOutTimer) / (double)CLOCKS_PER_SEC)) { + checkForTimeOuts(); + timOutTimer = currentTime; + } +} + +void HybridServer::parseClientPing() +{ + LOG_INFO("%i: Parsing ping", m_PacketID); + PlayerID player = GetPlayerIDFromEndpoint(m_ReceiverEndpoint); + if (player == -1) { + return; + } + // Return ping + Packet packet(MessageType::Ping, m_ConnectedPlayers[player].PacketID); + packet.WriteString("Ping received"); + send(packet); +} + +void HybridServer::parsePing() +{ + for (int i = 0; i < m_ConnectedPlayers.size(); i++) { + if (m_ConnectedPlayers[i].Endpoint.address() == m_ReceiverEndpoint.address()) { + m_ConnectedPlayers[i].StopTime = std::clock(); + break; + } + } +} + +void HybridServer::parseDisconnect() +{ + LOG_INFO("%i: Parsing disconnect", m_PacketID); + + for (auto& kv : m_ConnectedPlayers) { + if (kv.second.Endpoint.address() == m_ReceiverEndpoint.address() && + kv.second.Endpoint.port() == m_ReceiverEndpoint.port()) { + disconnect(kv.first); + break; + } + } +} + +void HybridServer::parseConnect(Packet& packet) +{ + LOG_INFO("Parsing connections"); + // Check if player is already connected + if (GetPlayerIDFromEndpoint(m_ReceiverEndpoint) != -1) { + return; + } + // Create a new player + PlayerDefinition pd; + pd.EntityID = 0; // Overlook this + pd.Endpoint = m_ReceiverEndpoint; + pd.Name = packet.ReadString(); + pd.PacketID = 0; + pd.StopTime = std::clock(); + m_ConnectedPlayers[m_NextPlayerID++] = pd; + LOG_INFO("Spectator \"%s\" connected on IP: %s", pd.Name.c_str(), pd.Endpoint.address().to_string().c_str()); + + // Send a message to the player that connected + Packet connnectPacket(MessageType::Connect, pd.PacketID); + send(connnectPacket); + + // Send notification that a player has connected + Packet notificationPacket(MessageType::PlayerConnected); + broadcast(notificationPacket); +} + +void HybridServer::parseOnInputCommand(Packet& packet) +{ + PlayerID player = -1; + // Check which player it was who sent the message + player = GetPlayerIDFromEndpoint(m_ReceiverEndpoint); + if (player != -1) { + while (packet.DataReadSize() < packet.Size()) { + Events::InputCommand e; + e.Command = packet.ReadString(); + e.PlayerID = player; // Set correct player id + e.Player = EntityWrapper(m_World, m_ConnectedPlayers.at(player).EntityID); + e.Value = packet.ReadPrimitive(); + m_EventBroker->Publish(e); + LOG_INFO("Server::parseOnInputCommand: Command is %s. Value is %f. PlayerID is %i.", e.Command.c_str(), e.Value, e.PlayerID); + } + } +} + +void HybridServer::parsePlayerTransform(Packet& packet) +{ + glm::vec3 position; + glm::vec3 orientation; + position.x = packet.ReadPrimitive(); + position.y = packet.ReadPrimitive(); + position.z = packet.ReadPrimitive(); + orientation.x = packet.ReadPrimitive(); + orientation.y = packet.ReadPrimitive(); + orientation.z = packet.ReadPrimitive(); + + PlayerID playerID = GetPlayerIDFromEndpoint(m_ReceiverEndpoint); + EntityWrapper player(m_World, m_ConnectedPlayers.at(playerID).EntityID); + + if (player.Valid()) { + player["Transform"]["Position"] = position; + player["Transform"]["Orientation"] = orientation; + } +} + +void HybridServer::send(Packet& packet, PlayerDefinition & playerDefinition) +{ + try { + int bytesSent = m_Socket->send_to( + boost::asio::buffer(packet.Data(), packet.Size()), + playerDefinition.Endpoint, + 0); + // Network Debug data + if (isReadingData) { + m_NetworkData.TotalDataSent += packet.Size(); + m_NetworkData.DataSentThisInterval += packet.Size(); + m_NetworkData.AmountOfMessagesSent++; + } + } catch (const boost::system::system_error& e) { + // TODO: Clean up invalid endpoints out of m_ConnectedPlayers later + playerDefinition.Endpoint = boost::asio::ip::udp::endpoint(); + } +} +// Send back to endpoint of received packet +void HybridServer::send(Packet & packet) +{ + m_Socket->send_to( + boost::asio::buffer( + packet.Data(), + packet.Size()), + m_ReceiverEndpoint, + 0); + if (isReadingData) { + // Network Debug data + m_NetworkData.TotalDataSent += packet.Size(); + m_NetworkData.DataSentThisInterval += packet.Size(); + } +} + + +int HybridServer::receive(char * data) +{ + unsigned int length = m_Socket->receive_from( + boost::asio::buffer((void*)data + , INPUTSIZE) + , m_ReceiverEndpoint, 0); + // Network Debug data + if (isReadingData) { + m_NetworkData.TotalDataReceived += length; + m_NetworkData.DataReceivedThisInterval += length; + m_NetworkData.AmountOfMessagesReceived++; + } + return length; +} + +PlayerID HybridServer::GetPlayerIDFromEndpoint(boost::asio::ip::udp::endpoint endpoint) +{ + for (auto& kv : m_ConnectedPlayers) { + if (kv.second.Endpoint.address() == endpoint.address() && + kv.second.Endpoint.port() == endpoint.port()) { + return kv.first; + } + } + return -1; +} diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index adf14413..37b2e752 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -1,19 +1,16 @@ #include "Network/Server.h" -Server::Server() : m_Socket(m_IOService, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), 27666)) +Server::Server() { Network::initialize(); ConfigFile* config = ResourceManager::Load("Config.ini"); snapshotInterval = 1000 * config->Get("Networking.SnapshotInterval", 0.05); pingIntervalMs = config->Get("Networking.PingIntervalMs", 1000); - } - Server::~Server() { } - void Server::Start(World* world, EventBroker* eventBroker) { m_World = world; @@ -36,41 +33,9 @@ void Server::Update() } -void Server::readFromClients() -{ - while (m_Socket.available()) { - try { - bytesRead = receive(readBuffer); - Packet packet(readBuffer, bytesRead); - parseMessageType(packet); - } catch (const std::exception& err) { - //LOG_ERROR("%i: Read from client crashed %s", m_PacketID, err.what()); - } - } - std::clock_t currentTime = std::clock(); - // Send snapshot - if (snapshotInterval < (1000 * (currentTime - previousSnapshotMessage) / (double)CLOCKS_PER_SEC)) { - sendSnapshot(); - previousSnapshotMessage = currentTime; - } - - // Send pings each - if (pingIntervalMs < (1000 * (currentTime - previousePingMessage) / (double)CLOCKS_PER_SEC)) { - sendPing(); - previousePingMessage = currentTime; - } - - // Time out logic - if (checkTimeOutInterval < (1000 * (currentTime - timOutTimer) / (double)CLOCKS_PER_SEC)) { - checkForTimeOuts(); - timOutTimer = currentTime; - } -} - void Server::parseMessageType(Packet& packet) { int messageType = packet.ReadPrimitive(); // Read what type off message was sent from server - // Read packet ID m_PreviousPacketID = m_PacketID; // Set previous packet id m_PacketID = packet.ReadPrimitive(); //Read new packet id @@ -103,60 +68,11 @@ void Server::parseMessageType(Packet& packet) } } -int Server::receive(char * data) -{ - unsigned int length = m_Socket.receive_from( - boost::asio::buffer((void*)data - , INPUTSIZE) - , m_ReceiverEndpoint, 0); - // Network Debug data - if (isReadingData) { - m_NetworkData.TotalDataReceived += length; - m_NetworkData.DataReceivedThisInterval += length; - m_NetworkData.AmountOfMessagesReceived++; - } - return length; -} - -void Server::send(PlayerID player, Packet& packet) -{ - try { - int bytesSent = m_Socket.send_to( - boost::asio::buffer(packet.Data(), packet.Size()), - m_ConnectedPlayers[player].Endpoint, - 0); - // Network Debug data - if (isReadingData) { - m_NetworkData.TotalDataSent += packet.Size(); - m_NetworkData.DataSentThisInterval += packet.Size(); - m_NetworkData.AmountOfMessagesSent++; - } - } catch (const boost::system::system_error& e) { - // TODO: Clean up invalid endpoints out of m_ConnectedPlayers later - m_ConnectedPlayers[player].Endpoint = boost::asio::ip::udp::endpoint(); - } -} - -void Server::send(Packet & packet) -{ - m_Socket.send_to( - boost::asio::buffer( - packet.Data(), - packet.Size()), - m_ReceiverEndpoint, - 0); - if (isReadingData) { - // Network Debug data - m_NetworkData.TotalDataSent += packet.Size(); - m_NetworkData.DataSentThisInterval += packet.Size(); - } -} - void Server::broadcast(Packet& packet) { for (auto& kv : m_ConnectedPlayers) { packet.ChangePacketID(kv.second.PacketID); - send(kv.first, packet); + send(packet, kv.second); } } @@ -259,24 +175,6 @@ void Server::disconnect(PlayerID playerID) m_ConnectedPlayers.erase(playerID); } -void Server::parseOnInputCommand(Packet& packet) -{ - PlayerID player = -1; - // Check which player it was who sent the message - player = GetPlayerIDFromEndpoint(m_ReceiverEndpoint); - if (player != -1) { - while (packet.DataReadSize() < packet.Size()) { - Events::InputCommand e; - e.Command = packet.ReadString(); - e.PlayerID = player; // Set correct player id - e.Player = EntityWrapper(m_World, m_ConnectedPlayers.at(player).EntityID); - e.Value = packet.ReadPrimitive(); - m_EventBroker->Publish(e); - LOG_INFO("Server::parseOnInputCommand: Command is %s. Value is %f. PlayerID is %i.", e.Command.c_str(), e.Value, e.PlayerID); - } - } -} - void Server::parseOnPlayerDamage(Packet & packet) { Events::PlayerDamage e; @@ -286,75 +184,6 @@ void Server::parseOnPlayerDamage(Packet & packet) //LOG_DEBUG("Server::parseOnPlayerDamage: Command is %s. Value is %f. PlayerID is %i.", e.DamageAmount, e.PlayerDamagedID, e.TypeOfDamage.c_str()); } -void Server::parseConnect(Packet& packet) -{ - LOG_INFO("Parsing connections"); - // Check if player is already connected - if (GetPlayerIDFromEndpoint(m_ReceiverEndpoint) != -1) { - return; - } - for (auto& kv : m_ConnectedPlayers) { - if (kv.second.Endpoint.address() == m_ReceiverEndpoint.address() && - kv.second.Endpoint.port() == m_ReceiverEndpoint.port()) { - // Already connected - return; - } - } - // Create a new player - PlayerDefinition pd; - pd.EntityID = 0; // Overlook this - pd.Endpoint = m_ReceiverEndpoint; - pd.Name = packet.ReadString(); - pd.PacketID = 0; - pd.StopTime = std::clock(); - m_ConnectedPlayers[m_NextPlayerID++] = pd; - LOG_INFO("Spectator \"%s\" connected on IP: %s", pd.Name.c_str(), pd.Endpoint.address().to_string().c_str()); - - // Send a message to the player that connected - Packet connnectPacket(MessageType::Connect, pd.PacketID); - send(connnectPacket); - - // Send notification that a player has connected - Packet notificationPacket(MessageType::PlayerConnected); - broadcast(notificationPacket); -} - -void Server::parseDisconnect() -{ - LOG_INFO("%i: Parsing disconnect", m_PacketID); - - for (auto& kv : m_ConnectedPlayers) { - if (kv.second.Endpoint.address() == m_ReceiverEndpoint.address() && - kv.second.Endpoint.port() == m_ReceiverEndpoint.port()) { - disconnect(kv.first); - break; - } - } -} - -void Server::parseClientPing() -{ - LOG_INFO("%i: Parsing ping", m_PacketID); - PlayerID player = GetPlayerIDFromEndpoint(m_ReceiverEndpoint); - if (player == -1) { - return; - } - // Return ping - Packet packet(MessageType::Ping, m_ConnectedPlayers[player].PacketID); - packet.WriteString("Ping received"); - send(packet); -} - -void Server::parsePing() -{ - for (int i = 0; i < m_ConnectedPlayers.size(); i++) { - if (m_ConnectedPlayers[i].Endpoint.address() == m_ReceiverEndpoint.address()) { - m_ConnectedPlayers[i].StopTime = std::clock(); - break; - } - } -} - void Server::identifyPacketLoss() { // if no packets lost, difference should be equal to 1 @@ -371,17 +200,6 @@ void Server::kick(PlayerID player) send(packet); } -PlayerID Server::GetPlayerIDFromEndpoint(boost::asio::ip::udp::endpoint endpoint) -{ - for (auto& kv : m_ConnectedPlayers) { - if (kv.second.Endpoint.address() == endpoint.address() && - kv.second.Endpoint.port() == endpoint.port()) { - return kv.first; - } - } - return -1; -} - bool Server::OnInputCommand(const Events::InputCommand & e) { //LOG_DEBUG("Server::OnInputCommand: Command is %s. Value is %f. PlayerID is %i.", e.Command.c_str(), e.Value, e.PlayerID); @@ -408,7 +226,7 @@ bool Server::OnPlayerSpawned(const Events::PlayerSpawned & e) packet.WritePrimitive(e.Spawner.ID); // We don't send PlayerID here because it will always be set to -1 packet.WriteString(m_ConnectedPlayers[e.PlayerID].Name); - send(e.PlayerID, packet); + send(packet, m_ConnectedPlayers[e.PlayerID]); return false; } @@ -432,23 +250,3 @@ bool Server::OnComponentDeleted(const Events::ComponentDeleted & e) } return false; } - -void Server::parsePlayerTransform(Packet& packet) -{ - glm::vec3 position; - glm::vec3 orientation; - position.x = packet.ReadPrimitive(); - position.y = packet.ReadPrimitive(); - position.z = packet.ReadPrimitive(); - orientation.x = packet.ReadPrimitive(); - orientation.y = packet.ReadPrimitive(); - orientation.z = packet.ReadPrimitive(); - - PlayerID playerID = GetPlayerIDFromEndpoint(m_ReceiverEndpoint); - EntityWrapper player(m_World, m_ConnectedPlayers.at(playerID).EntityID); - - if (player.Valid()) { - player["Transform"]["Position"] = position; - player["Transform"]["Orientation"] = orientation; - } -} diff --git a/src/Engine/Network/TCPClient.cpp b/src/Engine/Network/TCPClient.cpp index e69de29b..d4909f56 100644 --- a/src/Engine/Network/TCPClient.cpp +++ b/src/Engine/Network/TCPClient.cpp @@ -0,0 +1,48 @@ +#include "Network/TCPClient.h" + +using namespace boost::asio::ip; + +TCPClient::TCPClient(ConfigFile * config) : Client(config) +{ + m_Endpoint = tcp::endpoint(boost::asio::ip::address::from_string(address), port); + m_Socket = boost::shared_ptr(new tcp::socket(m_IOService)); +} + +TCPClient::~TCPClient() +{ + +} + +void TCPClient::Start(World * world, EventBroker * eventBroker) +{ + Client::Start(world, eventBroker); + boost::system::error_code error = boost::asio::error::host_not_found; + while (error) { + m_Socket->close(); + m_Socket->connect(m_Endpoint,error); + LOG_INFO(error.message().c_str()); + } +} + +void TCPClient::readFromServer() +{ + +} + +int TCPClient::receive(char * data) +{ + return 0; +} + +void TCPClient::send(Packet & packet) +{ + m_Socket->send(boost::asio::buffer( + packet.Data(), + packet.Size())); + // Network Debug data + if (isReadingData) { + m_NetworkData.TotalDataSent += packet.Size(); + m_NetworkData.DataSentThisInterval += packet.Size(); + m_NetworkData.AmountOfMessagesSent++; + } +} diff --git a/src/Engine/Network/TCPServer.cpp b/src/Engine/Network/TCPServer.cpp new file mode 100644 index 00000000..930e7913 --- /dev/null +++ b/src/Engine/Network/TCPServer.cpp @@ -0,0 +1,148 @@ +#include "Network/TCPServer.h" +using namespace boost::asio::ip; + +TCPServer::TCPServer() +{ + acceptor = std::unique_ptr(new tcp::acceptor(m_IOService, tcp::endpoint(tcp::v4(), 27666))); +} + +TCPServer::~TCPServer() +{ + +} + +void TCPServer::Start(World* world, EventBroker* eventBroker) +{ + Server::Start(world, eventBroker); +} + +void TCPServer::readFromClients() +{ + acceptNewConnections(); + for (auto& kv : m_ConnectedPlayers) { + while (kv.second.TCPSocket->available()) { + try { + bytesRead = receive(readBuffer, *kv.second.TCPSocket); + lastReceivedSocket = kv.second.TCPSocket; + Packet packet(readBuffer, bytesRead); + parseMessageType(packet); + } catch (const std::exception& err) { + //LOG_ERROR("%i: Read from client crashed %s", m_PacketID, err.what()); + } + } + } + + std::clock_t currentTime = std::clock(); + // Send snapshot + if (snapshotInterval < (1000 * (currentTime - previousSnapshotMessage) / (double)CLOCKS_PER_SEC)) { + sendSnapshot(); + previousSnapshotMessage = currentTime; + } + + // Send pings each + if (pingIntervalMs < (1000 * (currentTime - previousePingMessage) / (double)CLOCKS_PER_SEC)) { + sendPing(); + previousePingMessage = currentTime; + } + + // Time out logic + if (checkTimeOutInterval < (1000 * (currentTime - timOutTimer) / (double)CLOCKS_PER_SEC)) { + checkForTimeOuts(); + timOutTimer = currentTime; + } +} + +void TCPServer::acceptNewConnections() +{ + boost::shared_ptr newSocket = boost::shared_ptr(new tcp::socket(m_IOService)); + m_IOService.poll(); + acceptor->async_accept(*newSocket, + boost::bind(&TCPServer::handle_accept, this, newSocket, + boost::asio::placeholders::error)); +} + +void TCPServer::handle_accept(boost::shared_ptr socket, const boost::system::error_code& error) +{ + if (!error) { + // Add tcp socket to connections + PlayerDefinition pd; + pd.StopTime = std::clock(); + pd.TCPSocket = socket; + m_ConnectedPlayers[m_NextPlayerID++] = pd; + } +} +void TCPServer::parseClientPing() +{ + +} +void TCPServer::parsePing() +{ + +} +void TCPServer::parseDisconnect() +{ + +} +void TCPServer::parseConnect(Packet & packet) +{ + +} +void TCPServer::parseOnInputCommand(Packet & packet) +{ + +} +void TCPServer::parsePlayerTransform(Packet & packet) +{ + +} +void TCPServer::send(Packet & packet, PlayerDefinition & playerDefinition) +{ + try { + int bytesSent = playerDefinition.TCPSocket->send( + boost::asio::buffer(packet.Data(), packet.Size()), + 0); + // Network Debug data + if (isReadingData) { + m_NetworkData.TotalDataSent += packet.Size(); + m_NetworkData.DataSentThisInterval += packet.Size(); + m_NetworkData.AmountOfMessagesSent++; + } + } catch (const boost::system::system_error& e) { + // TODO: Clean up invalid endpoints out of m_ConnectedPlayers later + playerDefinition.Endpoint = boost::asio::ip::udp::endpoint(); + } +} + +void TCPServer::send(Packet & packet) +{ + lastReceivedSocket->send( + boost::asio::buffer( + packet.Data(), + packet.Size()), + 0); + if (isReadingData) { + // Network Debug data + m_NetworkData.TotalDataSent += packet.Size(); + m_NetworkData.DataSentThisInterval += packet.Size(); + } +} + +//boost::shared_ptr socket +int TCPServer::receive(char * data,boost::asio::ip::tcp::socket& socket) +{ + unsigned int length = socket.read_some( + boost::asio::buffer((void*)data, INPUTSIZE)); + // Network Debug data + if (isReadingData) { + m_NetworkData.TotalDataReceived += length; + m_NetworkData.DataReceivedThisInterval += length; + m_NetworkData.AmountOfMessagesReceived++; + } + return length; + +} + +PlayerID TCPServer::GetPlayerIDFromEndpoint(boost::asio::ip::udp::endpoint endpoint) +{ + return PlayerID(); +} \ No newline at end of file diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index c26510ec..969fa46c 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -181,11 +181,11 @@ void Game::networkFunction() bool isServer = m_Config->Get("Networking.IsServer", false); if (!isServer) { m_IsClientOrServer = true; - m_ClientOrServer = new HybridClient(m_Config); + m_ClientOrServer = new TCPClient(m_Config); } if (isServer) { m_IsClientOrServer = true; - m_ClientOrServer = new Server(); + m_ClientOrServer = new TCPServer(); } m_ClientOrServer->Start(m_World, m_EventBroker); From d50caa176321a70a53348be7e8ca01731fc16002 Mon Sep 17 00:00:00 2001 From: stiffly Date: Thu, 4 Feb 2016 16:14:50 +0100 Subject: [PATCH 080/355] Gain events tested. works as intended --- include/Engine/Sound/SoundSystem.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/include/Engine/Sound/SoundSystem.h b/include/Engine/Sound/SoundSystem.h index 597aca22..d0b1a3dd 100644 --- a/include/Engine/Sound/SoundSystem.h +++ b/include/Engine/Sound/SoundSystem.h @@ -126,9 +126,9 @@ private: EventRelay m_EContinueSound; bool OnContinueSound(const Events::ContinueSound &e); EventRelay m_ESetBGMGain; - bool OnSetBGMGain(const Events::SetBGMGain &e); // Not tested + bool OnSetBGMGain(const Events::SetBGMGain &e); EventRelay m_ESetSFXGain; - bool OnSetSFXGain(const Events::SetSFXGain &e); // Not tested + bool OnSetSFXGain(const Events::SetSFXGain &e); EventRelay m_EShoot; bool OnShoot(const Events::Shoot &e); EventRelay m_EPlayerSpawned; From 6a23a987b36e4f0785b4ea07a3455781c8135a3c Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Thu, 4 Feb 2016 17:43:45 +0100 Subject: [PATCH 081/355] Started PickupSpawnSystem, added 2 events and a system --- include/Engine/Core/EPickupSpawned.h | 18 ++++++++++++++++++ include/Engine/Core/EPickupTaken.h | 19 +++++++++++++++++++ include/Game/Systems/PickupSpawnSystem.h | 17 +++++++++++++++++ resources/Schema/Components.xsd | 1 + resources/Schema/Components/PickupSpawn.xml | 2 ++ resources/Schema/Components/PickupSpawn.xsd | 11 +++++++++++ src/Game/Systems/PickupSpawnSystem.cpp | 1 + 7 files changed, 69 insertions(+) create mode 100644 include/Engine/Core/EPickupSpawned.h create mode 100644 include/Engine/Core/EPickupTaken.h create mode 100644 include/Game/Systems/PickupSpawnSystem.h create mode 100644 resources/Schema/Components/PickupSpawn.xml create mode 100644 resources/Schema/Components/PickupSpawn.xsd create mode 100644 src/Game/Systems/PickupSpawnSystem.cpp diff --git a/include/Engine/Core/EPickupSpawned.h b/include/Engine/Core/EPickupSpawned.h new file mode 100644 index 00000000..acb6776e --- /dev/null +++ b/include/Engine/Core/EPickupSpawned.h @@ -0,0 +1,18 @@ +#ifndef EPickupSpawned_h__ +#define EPickupSpawned_h__ + +#include "Core/Event.h" +#include "Core/EntityWrapper.h" + +namespace Events +{ + +struct PickupSpawned : Event +{ + EntityID PickupID; + EntityWrapper Spawner; +}; + +} + +#endif \ No newline at end of file diff --git a/include/Engine/Core/EPickupTaken.h b/include/Engine/Core/EPickupTaken.h new file mode 100644 index 00000000..e06fd974 --- /dev/null +++ b/include/Engine/Core/EPickupTaken.h @@ -0,0 +1,19 @@ +#ifndef EPickupTaken_h__ +#define EPickupTaken_h__ + +#include "Core/Event.h" +#include "Core/EntityWrapper.h" + +namespace Events +{ + +struct PickupTaken : Event +{ + EntityID PickupID; + EntityWrapper Spawner; + EntityWrapper Player; +}; + +} + +#endif \ No newline at end of file diff --git a/include/Game/Systems/PickupSpawnSystem.h b/include/Game/Systems/PickupSpawnSystem.h new file mode 100644 index 00000000..99dad0aa --- /dev/null +++ b/include/Game/Systems/PickupSpawnSystem.h @@ -0,0 +1,17 @@ +#ifndef PickupSpawnSystem_h__ +#define PickupSpawnSystem_h__ + +#include "Core/System.h" +#include "Input/EInputCommand.h" +#include "Systems/SpawnerSystem.h" +#include "Events/ESpawnerSpawn.h" +#include "Core/EPlayerSpawned.h" +#include "Rendering/ESetCamera.h" +#include "Core/ConfigFile.h" +#include "Core/EPickupSpawned.h" + +class PickupSpawnSystem : public ImpureSystem +{ + +}; +#endif diff --git a/resources/Schema/Components.xsd b/resources/Schema/Components.xsd index ab46b0ea..445d96e7 100644 --- a/resources/Schema/Components.xsd +++ b/resources/Schema/Components.xsd @@ -29,4 +29,5 @@ + \ No newline at end of file diff --git a/resources/Schema/Components/PickupSpawn.xml b/resources/Schema/Components/PickupSpawn.xml new file mode 100644 index 00000000..f8ce1225 --- /dev/null +++ b/resources/Schema/Components/PickupSpawn.xml @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/resources/Schema/Components/PickupSpawn.xsd b/resources/Schema/Components/PickupSpawn.xsd new file mode 100644 index 00000000..7ab90407 --- /dev/null +++ b/resources/Schema/Components/PickupSpawn.xsd @@ -0,0 +1,11 @@ + + + + + + + + Combined with a Spawner, defines a spawn point for a pickup + + + diff --git a/src/Game/Systems/PickupSpawnSystem.cpp b/src/Game/Systems/PickupSpawnSystem.cpp new file mode 100644 index 00000000..3b758764 --- /dev/null +++ b/src/Game/Systems/PickupSpawnSystem.cpp @@ -0,0 +1 @@ +#include "Systems/PickupSpawnSystem.h" From c526a7af55eae698e670d6d4ee4fd6ac81f97d28 Mon Sep 17 00:00:00 2001 From: Tleety Date: Thu, 4 Feb 2016 17:58:36 +0100 Subject: [PATCH 082/355] WIP stencil stuff --- include/Engine/Rendering/DrawFinalPass.h | 8 ++++- src/Engine/Rendering/DrawFinalPass.cpp | 43 ++++++++++++++++++++++-- src/Engine/Rendering/FrameBuffer.cpp | 17 ++++++++-- src/Engine/Rendering/Renderer.cpp | 10 ++++-- 4 files changed, 71 insertions(+), 7 deletions(-) diff --git a/include/Engine/Rendering/DrawFinalPass.h b/include/Engine/Rendering/DrawFinalPass.h index 64d5563e..bacc7a8c 100644 --- a/include/Engine/Rendering/DrawFinalPass.h +++ b/include/Engine/Rendering/DrawFinalPass.h @@ -22,9 +22,13 @@ public: //Return the texture that is used in later stages to apply the bloom effect GLuint BloomTexture() const { return m_BloomTexture; } + GLuint BloomTextureLowRes() const { return m_BloomTextureLowRes; } //Return the texture with diffuse and lighting of the scene. GLuint SceneTexture() const { return m_SceneTexture; } + GLuint SceneTextureLowRes() const { return m_SceneTextureLowRes; } + //Return the framebuffer used in the scene rendering stage. FrameBuffer* FinalPassFrameBuffer() { return &m_FinalPassFrameBuffer; } + FrameBuffer* FinalPassFrameBufferLowRes() { return &m_FinalPassFrameBufferLowRes; } private: @@ -47,10 +51,12 @@ private: Texture* m_GreyTexture; FrameBuffer m_FinalPassFrameBuffer; + FrameBuffer m_FinalPassFrameBufferLowRes; GLuint m_BloomTexture; GLuint m_SceneTexture; + GLuint m_BloomTextureLowRes; + GLuint m_SceneTextureLowRes; GLuint m_DepthBuffer; - GLuint m_StencilBuffer; const IRenderer* m_Renderer; const LightCullingPass* m_LightCullingPass; diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index 106f9aa5..0a5c626b 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -22,18 +22,33 @@ void DrawFinalPass::InitializeFrameBuffers() glGenRenderbuffers(1, &m_DepthBuffer); glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBuffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); + GLERROR("RenderBuffer generation"); 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); //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); 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); //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); m_FinalPassFrameBuffer.AddResource(std::shared_ptr(new RenderBuffer(&m_DepthBuffer, GL_DEPTH_STENCIL_ATTACHMENT))); + //m_FinalPassFrameBuffer.AddResource(std::shared_ptr(new Texture2D(&m_StencilTexture, GL_STENCIL_ATTACHMENT))); m_FinalPassFrameBuffer.AddResource(std::shared_ptr(new Texture2D(&m_SceneTexture, GL_COLOR_ATTACHMENT0))); m_FinalPassFrameBuffer.AddResource(std::shared_ptr(new Texture2D(&m_BloomTexture, GL_COLOR_ATTACHMENT1))); m_FinalPassFrameBuffer.Generate(); GLERROR("FBO generation"); + GenerateTexture(&m_SceneTextureLowRes, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width/16, m_Renderer->GetViewportSize().Height/16), 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); + GenerateTexture(&m_BloomTextureLowRes, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width/16, m_Renderer->GetViewportSize().Height/16), 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); + + m_FinalPassFrameBufferLowRes.AddResource(std::shared_ptr(new RenderBuffer(&m_DepthBuffer, GL_DEPTH_STENCIL_ATTACHMENT))); + //m_FinalPassFrameBufferLowRes.AddResource(std::shared_ptr(new Texture2D(&m_StencilTexture, GL_STENCIL_ATTACHMENT))); + m_FinalPassFrameBufferLowRes.AddResource(std::shared_ptr(new Texture2D(&m_SceneTextureLowRes, GL_COLOR_ATTACHMENT0))); + m_FinalPassFrameBufferLowRes.AddResource(std::shared_ptr(new Texture2D(&m_BloomTextureLowRes, GL_COLOR_ATTACHMENT1))); + m_FinalPassFrameBufferLowRes.Generate(); + GLERROR("FBO2 generation"); } void DrawFinalPass::InitializeShaderPrograms() @@ -93,7 +108,7 @@ void DrawFinalPass::Draw(RenderScene& scene) //Draw Opaque shielded objects state->StencilFunc(GL_NOTEQUAL, 1, 0xFF); - glStencilMask(0x00); + state->StencilMask(0x00); DrawShieldedModelRenderQueue(scene.Jobs.OpaqueShieldedObjects, scene); GLERROR("Shielded Opaque object"); @@ -103,7 +118,26 @@ void DrawFinalPass::Draw(RenderScene& scene) GLERROR("END"); delete state; - //delete stencilState; + + + DrawFinalPassState* stateLowRes = new DrawFinalPassState(m_FinalPassFrameBufferLowRes.GetHandle()); + //Draw the lowres texture that will be shown behind the shield. + if (scene.ClearDepth) { + glClear(GL_DEPTH_BUFFER_BIT); + } + //TODO: Do we need check for this or will it be per scene always? + //glClearStencil(0x00); + //glClear(GL_STENCIL_BUFFER_BIT); + + //state->StencilMask(0x00); + //state->StencilFunc(GL_ALWAYS, 1, 0xFF); + state->Disable(GL_STENCIL_TEST); + state->Disable(GL_DEPTH_TEST); + DrawModelRenderQueues(scene.Jobs.OpaqueObjects, scene); + GLERROR("OpaqueObjects"); + DrawModelRenderQueues(scene.Jobs.TransparentObjects, scene); + GLERROR("TransparentObjects"); + delete stateLowRes; } @@ -113,6 +147,11 @@ void DrawFinalPass::ClearBuffer() glClearColor(0.f, 0.f, 0.f, 0.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_FinalPassFrameBuffer.Unbind(); + + m_FinalPassFrameBufferLowRes.Bind(); + glClearColor(0.f, 0.f, 0.f, 0.f); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + m_FinalPassFrameBufferLowRes.Unbind(); } void DrawFinalPass::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const diff --git a/src/Engine/Rendering/FrameBuffer.cpp b/src/Engine/Rendering/FrameBuffer.cpp index 5df1a5f1..c0be4cb1 100644 --- a/src/Engine/Rendering/FrameBuffer.cpp +++ b/src/Engine/Rendering/FrameBuffer.cpp @@ -39,10 +39,13 @@ void FrameBuffer::AddResource(std::shared_ptr resource) void FrameBuffer::Generate() { + GLERROR("PRE"); + std::vector attachments; glGenFramebuffers(1, &m_BufferHandle); glBindFramebuffer(GL_FRAMEBUFFER, m_BufferHandle); + GLERROR("1"); for (auto it = m_Resources.begin(); it != m_Resources.end(); it++) { switch ((*it)->m_ResourceType) { @@ -56,20 +59,30 @@ void FrameBuffer::Generate() GLERROR("FrameBuffer generate: glFramebufferRenderbuffer"); break; } - - if ((*it)->m_Attachment != GL_DEPTH_ATTACHMENT || (*it)->m_Attachment != GL_STENCIL_ATTACHMENT || (*it)->m_Attachment != GL_DEPTH_STENCIL_ATTACHMENT) { + GLERROR("2"); + + if ((*it)->m_Attachment != GL_DEPTH_ATTACHMENT && (*it)->m_Attachment != GL_STENCIL_ATTACHMENT && (*it)->m_Attachment != GL_DEPTH_STENCIL_ATTACHMENT) { attachments.push_back((*it)->m_Attachment); } + GLERROR("Attachment"); + } + GLERROR("3"); + GLenum* bufferTextures = &attachments[0]; glDrawBuffers(attachments.size(), bufferTextures); + if(GLERROR("4")) { + printf("hello"); + } if (GLenum frameBufferStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { GLERROR("Framebuffer incomplete"); //LOG_ERROR("FrameBuffer incomplete: 0x%x\n", frameBufferStatus); exit(EXIT_FAILURE); } + GLERROR("END"); + } void FrameBuffer::Bind() diff --git a/src/Engine/Rendering/Renderer.cpp b/src/Engine/Rendering/Renderer.cpp index fa3d1709..15554ab1 100644 --- a/src/Engine/Rendering/Renderer.cpp +++ b/src/Engine/Rendering/Renderer.cpp @@ -93,7 +93,7 @@ void Renderer::Update(double dt) void Renderer::Draw(RenderFrame& frame) { - ImGui::Combo("Draw textures", &m_DebugTextureToDraw, "Final\0Scene\0Bloom\0Gaussian\0Picking"); + ImGui::Combo("Draw textures", &m_DebugTextureToDraw, "Final\0Scene\0Bloom\0SceneLowRes\0BloomLowRes\0Gaussian\0Picking"); //clear buffer 0 glClearColor(0.f, 0.f, 0.f, 0.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); @@ -129,9 +129,15 @@ void Renderer::Draw(RenderFrame& frame) m_DrawScreenQuadPass->Draw(m_DrawFinalPass->BloomTexture()); } if (m_DebugTextureToDraw == 3) { - m_DrawScreenQuadPass->Draw(m_DrawBloomPass->GaussianTexture()); + m_DrawScreenQuadPass->Draw(m_DrawFinalPass->SceneTextureLowRes()); } if (m_DebugTextureToDraw == 4) { + m_DrawScreenQuadPass->Draw(m_DrawFinalPass->BloomTextureLowRes()); + } + if (m_DebugTextureToDraw == 5) { + m_DrawScreenQuadPass->Draw(m_DrawBloomPass->GaussianTexture()); + } + if (m_DebugTextureToDraw == 6) { m_DrawScreenQuadPass->Draw(m_PickingPass->PickingTexture()); } From b6e0332574fc0b94233db74fcc975704a2a591b8 Mon Sep 17 00:00:00 2001 From: viktorljung Date: Fri, 5 Feb 2016 10:07:22 +0100 Subject: [PATCH 083/355] Fixed support for new animation structure, not done yet --- include/Engine/Rendering/Skeleton.h | 3 - resources/Schema/Entities/AnimationTests2.xml | 6 +- src/Engine/Rendering/AnimationSystem.cpp | 63 ++------ src/Engine/Rendering/Skeleton.cpp | 135 +++++------------- 4 files changed, 55 insertions(+), 152 deletions(-) diff --git a/include/Engine/Rendering/Skeleton.h b/include/Engine/Rendering/Skeleton.h index a428b7f3..f1ef22c7 100644 --- a/include/Engine/Rendering/Skeleton.h +++ b/include/Engine/Rendering/Skeleton.h @@ -62,7 +62,6 @@ public: int Index = 0; double Time = 0.0; BoneProperty BoneProperties; - //Keyframe::BoneProperty boneProperty; }; std::string Name; double Duration; @@ -87,8 +86,6 @@ public: const Animation* GetAnimation(std::string name); std::vector GetFrameBones(const Animation* animation, double time, bool noRootMotion = false); - void AccumulateBoneTransforms(bool noRootMotion, const Animation::Keyframe& currentFrame, const Animation::Keyframe& nextFrame, float progress, std::map& boneMatrices, const Bone* bone, glm::mat4 parentMatrix); - void AccumulateBoneTransforms(bool noRootMotion, const Animation* animation, float time, std::map& boneMatrices, const Bone* bone, glm::mat4 parentMatrix); void PrintSkeleton(); diff --git a/resources/Schema/Entities/AnimationTests2.xml b/resources/Schema/Entities/AnimationTests2.xml index baff7413..a116803f 100644 --- a/resources/Schema/Entities/AnimationTests2.xml +++ b/resources/Schema/Entities/AnimationTests2.xml @@ -10,7 +10,7 @@ Models/Core/UnitPlane.mesh - false + @@ -35,8 +35,8 @@ - Ru - + Run + 1 diff --git a/src/Engine/Rendering/AnimationSystem.cpp b/src/Engine/Rendering/AnimationSystem.cpp index 517fbf5c..c78aafd9 100644 --- a/src/Engine/Rendering/AnimationSystem.cpp +++ b/src/Engine/Rendering/AnimationSystem.cpp @@ -20,6 +20,15 @@ void AnimationSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& a return; } + ImGui::SliderFloat("Angle", &angle, -100.f, 100.f); + { + int id = skeleton->GetBoneID("Spine_3"); + auto it = skeleton->Bones.find(id); + if (it != skeleton->Bones.end()) { + it->second->ModificationMatrix = glm::mat4(glm::quat(glm::vec3(glm::radians(angle), 0.f, 0.f))); + } + } + const Skeleton::Animation* animation = skeleton->GetAnimation(animationComponent["AnimationName"]); @@ -51,55 +60,10 @@ void AnimationSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& a -/* - - ImGui::SliderFloat("Angle", &angle, -180.f, 180.f); - - int id = skeleton->GetBoneID("Spine_2"); - auto it = skeleton->Bones.find(id); - if (it != skeleton->Bones.end()) { - int currentKeyframeIndex = skeleton->GetKeyframe(*animation, entity["Animation"]["Time"]); - - const Skeleton::Animation::Keyframe& currentFrame = animation->Keyframes[currentKeyframeIndex]; - const Skeleton::Animation::Keyframe& nextFrame = animation->Keyframes[(currentKeyframeIndex + 1) % animation->Keyframes.size()]; - float alpha = ((double)entity["Animation"]["Time"] - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); - - glm::mat4 parentBoneTransform = skeleton->GetBoneTransform(it->second->Parent, currentFrame, nextFrame, alpha, glm::mat4(1)); - glm::vec3 scale; - glm::quat rotation; - glm::vec3 translation; - glm::vec3 skew; - glm::vec4 perspective; - glm::decompose(parentBoneTransform, scale, rotation, translation, skew, perspective); - - - - glm::vec3 rot; - rot = glm::vec3(1, 0, 0); - rot = glm::normalize(rot) * glm::radians(angle); - glm::mat4 modmat = glm::mat4(glm::quat(rot)) * glm::inverse(glm::mat4(rotation)); - - - it->second->ModificationMatrix = modmat; - } - - -*/ - -/* - - { - int id = skeleton->GetBoneID("Neck"); - auto it = skeleton->Bones.find(id); - if (it != skeleton->Bones.end()) { - it->second->ModificationMatrix = glm::mat4(glm::quat(glm::vec3(glm::radians(angle/2.f), 0.f, 0.f))); - } - } - - { + /* { int id = skeleton->GetBoneID("Spine_2"); auto it = skeleton->Bones.find(id); if (it != skeleton->Bones.end()) { @@ -119,8 +83,9 @@ void AnimationSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& a if (it != skeleton->Bones.end()) { it->second->ModificationMatrix = glm::mat4(glm::quat(glm::vec3(glm::radians(angle/2.f), 0.f, 0.f))); } - }* + }*/ +/* if (entity.HasComponent("Player")) { EntityWrapper cameraEntity = entity.FirstChildByName("Camera"); if (cameraEntity.Valid()) { @@ -128,7 +93,7 @@ void AnimationSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& a } - } - */ + }*/ + } diff --git a/src/Engine/Rendering/Skeleton.cpp b/src/Engine/Rendering/Skeleton.cpp index 86d1cb20..5ae6a264 100644 --- a/src/Engine/Rendering/Skeleton.cpp +++ b/src/Engine/Rendering/Skeleton.cpp @@ -41,17 +41,17 @@ const Skeleton::Animation* Skeleton::GetAnimation(std::string name) std::vector Skeleton::GetFrameBones(const Animation* animation, double time, bool noRootMotion /*= false*/) { - if(true){ - // if(animation == nullptr) { + if(animation == nullptr) { std::vector finalMatrices; for(auto& b : Bones) { - finalMatrices.push_back(glm::mat4(1));//b.second->OffsetMatrix); + finalMatrices.push_back(b.second->ModificationMatrix);//b.second->OffsetMatrix); } return finalMatrices; } // HACK: Animation wrap-around + while (time < 0) { time += animation->Duration; } @@ -59,12 +59,6 @@ std::vector Skeleton::GetFrameBones(const Animation* animation, doubl time -= animation->Duration; } - int currentKeyframeIndex = GetKeyframe(*animation, time); - -// const Animation::Keyframe& currentFrame = animation->Keyframes[currentKeyframeIndex]; -// const Animation::Keyframe& nextFrame = animation->Keyframes[(currentKeyframeIndex + 1) % animation->Keyframes.size()]; -// float alpha = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); - //auto animationFrame = Animations[""].Keyframes[frame]; std::map frameBones; AccumulateBoneTransforms(noRootMotion, animation, time, frameBones, RootBone, glm::mat4(1)); @@ -79,86 +73,33 @@ std::vector Skeleton::GetFrameBones(const Animation* animation, doubl -void Skeleton::AccumulateBoneTransforms(bool noRootMotion, const Animation::Keyframe ¤tFrame, const Animation::Keyframe &nextFrame, float progress, std::map &boneMatrices, const Bone* bone, glm::mat4 parentMatrix) -{ - /* glm::mat4 boneMatrix; - - - - float alpha = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); - - - if (currentFrame.BoneProperties.find(bone->ID) != currentFrame.BoneProperties.end() && nextFrame.BoneProperties.find(bone->ID) != nextFrame.BoneProperties.end()) { - - - Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties.at(bone->ID); - Animation::Keyframe::BoneProperty nextBoneProperty = nextFrame.BoneProperties.at(bone->ID); - - glm::vec3 positionInterp = currentBoneProperty.Position * (1.f - progress) + nextBoneProperty.Position * progress; - glm::quat rotationInterp = glm::slerp(currentBoneProperty.Rotation, nextBoneProperty.Rotation, progress); - glm::vec3 scaleInterp = currentBoneProperty.Scale * (1.f - progress) + nextBoneProperty.Scale * progress; - - - // Flag for no root motion - if (bone == RootBone && noRootMotion) { - positionInterp.x = 0; - positionInterp.z = 0; - } - - - - boneMatrix = parentMatrix * bone->ModificationMatrix *(glm::translate(positionInterp) * glm::toMat4(rotationInterp) * glm::scale(scaleInterp)); - boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix; - } else { - if (bone->Parent) { - boneMatrix = parentMatrix;// *glm::inverse(bone->OffsetMatrix); - } - boneMatrices[bone->ID] = boneMatrix;// *bone->OffsetMatrix; - } - - for (auto &child : bone->Children) { - std::string name = child->Name; - AccumulateBoneTransforms(noRootMotion, currentFrame, nextFrame, progress, boneMatrices, child, boneMatrix); - } -*/ - -} - void Skeleton::AccumulateBoneTransforms(bool noRootMotion, const Animation* animation, float time, std::map& boneMatrices, const Bone* bone, glm::mat4 parentMatrix) { + glm::mat4 boneMatrix;// = glm::mat4(1); -/* - glm::mat4 boneMatrix = glm::mat4(1); + Animation::Keyframe currentFrame; + Animation::Keyframe nextFrame; - Animation::Keyframe* currentFrame = nullptr; - Animation::Keyframe* nextFrame = nullptr; - - if(animation->BoneKeyFrames.find(bone->ID) != animation->BoneKeyFrames.end()) { // find the bone keyframes that surrounds the current frame - std::list boneKeyFrames = animation->BoneKeyFrames.at(bone->ID); - for (auto frame : boneKeyFrames) { - if(frame.Time <= time) { - currentFrame = &frame; - } else if (frame.Time > time) { - nextFrame = &frame; + if(animation->JointAnimations.find(bone->ID) != animation->JointAnimations.end()) { // find the bone keyframes that surrounds the current frame + std::vector boneKeyFrames = animation->JointAnimations.at(bone->ID); + + if(boneKeyFrames.size() > 1) { // 2+ keyframes for the current bone + for (int index = boneKeyFrames.size()-1; index >= 0; index--) { + if (time >= boneKeyFrames.at(index).Time) { + currentFrame = boneKeyFrames.at(index); + nextFrame = boneKeyFrames.at((index + 1) % boneKeyFrames.size()); + break; + } } - } - //if(currentFrame == nullptr) cant happen - - if (nextFrame == nullptr) { - std::list boneKeyFrames = animation->BoneKeyFrames.at(bone->ID); - nextFrame = &boneKeyFrames.front(); - } - - - - if (currentFrame != nextFrame) { - - float progress = (time - currentFrame->Time) / (nextFrame->Time - currentFrame->Time); - - Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame->boneProperty; - Animation::Keyframe::BoneProperty nextBoneProperty = nextFrame->boneProperty; + float progress = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); // fix loopinguuuu + if(progress > 1.0f || progress < 0.0f) { + LOG_INFO("Progress %f", progress); + progress = 0.f; + } + Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties; + Animation::Keyframe::BoneProperty nextBoneProperty = nextFrame.BoneProperties; glm::vec3 positionInterp = currentBoneProperty.Position * (1.f - progress) + nextBoneProperty.Position * progress; glm::quat rotationInterp = glm::slerp(currentBoneProperty.Rotation, nextBoneProperty.Rotation, progress); @@ -171,26 +112,24 @@ void Skeleton::AccumulateBoneTransforms(bool noRootMotion, const Animation* anim } boneMatrix = parentMatrix * bone->ModificationMatrix * (glm::translate(positionInterp) * glm::toMat4(rotationInterp) * glm::scale(scaleInterp)); - boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix; - - } else {// if (currentFrame == nextFrame) { - boneMatrix = parentMatrix * bone->ModificationMatrix * (glm::translate(currentFrame->boneProperty.Position) * glm::toMat4(currentFrame->boneProperty.Rotation) * glm::scale(currentFrame->boneProperty.Scale)); - boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix; - } - } else { -// if (bone->Parent) { // dont think this is needed -// boneMatrix = parentMatrix * bone->ModificationMatrix; -// } + boneMatrices[bone->ID] = boneMatrix *bone->OffsetMatrix; + + } else { // 1 keyframes for the current bone + currentFrame = boneKeyFrames.at(0); + boneMatrix = parentMatrix * bone->ModificationMatrix *(glm::translate(currentFrame.BoneProperties.Position) * glm::toMat4(currentFrame.BoneProperties.Rotation) * glm::scale(currentFrame.BoneProperties.Scale)); + boneMatrices[bone->ID] = boneMatrix *bone->OffsetMatrix; + } + } else { // 0 keyframes for the current bone + boneMatrix = parentMatrix * bone->ModificationMatrix; + boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix; + - boneMatrix = parentMatrix * bone->ModificationMatrix; - boneMatrices[bone->ID] = boneMatrix;// *bone->OffsetMatrix; - // } } for (auto &child : bone->Children) { std::string name = child->Name; AccumulateBoneTransforms(noRootMotion, animation, time, boneMatrices, child, boneMatrix); - }*/ + } } glm::mat4 Skeleton::GetBoneTransform(const Bone* bone, const Animation::Keyframe& currentFrame, const Animation::Keyframe& nextFrame, float progress, glm::mat4 parentMatrix) @@ -254,12 +193,13 @@ void Skeleton::PrintSkeleton(const Bone* bone, int depthCount) int Skeleton::GetKeyframe(const Animation& animation, double time) { + /* if (time < 0) { time = 0; } if (time >= animation.Duration) { - return animation.Keyframes.size() - 1; + return animation..size() - 1; } for (int keyframe = 0; keyframe < animation.Keyframes.size(); ++keyframe) { @@ -269,5 +209,6 @@ int Skeleton::GetKeyframe(const Animation& animation, double time) } */ + return 0; } From 71a86cab114f0cdcb9c6f1805dc79c9cce88b596 Mon Sep 17 00:00:00 2001 From: stiffly Date: Fri, 5 Feb 2016 10:07:56 +0100 Subject: [PATCH 084/355] removed event that's not being used --- include/Engine/Sound/SoundSystem.h | 5 ----- src/Engine/Sound/SoundSystem.cpp | 11 +---------- 2 files changed, 1 insertion(+), 15 deletions(-) diff --git a/include/Engine/Sound/SoundSystem.h b/include/Engine/Sound/SoundSystem.h index d0b1a3dd..51f80427 100644 --- a/include/Engine/Sound/SoundSystem.h +++ b/include/Engine/Sound/SoundSystem.h @@ -31,8 +31,6 @@ #include "Core/EPlayerDeath.h" #include "Core/EPlayerHealthPickup.h" #include "Core/EComponentAttached.h" -#include "Core/EComponentDeleted.h" -#include "Core/EEntityDeleted.h" #include "Collision/ETrigger.h" #include "Core/EPause.h" #include "Game/Events/EDoubleJump.h" @@ -107,7 +105,6 @@ private: bool m_EditorEnabled = false; const double m_PlayerFootstepInterval = 1.0; double m_TimeSinceLastFootstep = 0; - // TEMP EntityID m_LocalPlayer = EntityID_Invalid; bool m_LeftFoot = false; std::default_random_engine generator; @@ -145,8 +142,6 @@ private: bool OnPlayerHealthPickup(const Events::PlayerHealthPickup &e); EventRelay m_EComponentAttached; bool OnComponentAttached(const Events::ComponentAttached &e); - EventRelay m_EComponentDeleted; - bool OnComponentDeleted(const Events::ComponentDeleted &e); EventRelay m_ETriggerTouch; bool OnTriggerTouch(const Events::TriggerTouch &e); EventRelay m_EPause; diff --git a/src/Engine/Sound/SoundSystem.cpp b/src/Engine/Sound/SoundSystem.cpp index 847230d9..3045b1f4 100644 --- a/src/Engine/Sound/SoundSystem.cpp +++ b/src/Engine/Sound/SoundSystem.cpp @@ -177,7 +177,6 @@ void SoundSystem::playQueue(QueuedBuffers qb) alSourcePlay(qb.first); } - void SoundSystem::stopSound(Source* source) { alSourceStop(source->ALsource); @@ -402,7 +401,7 @@ bool SoundSystem::OnPlayerDamage(const Events::PlayerDamage & e) source->Type = SoundType::SFX; m_Sources[child] = source; - // breathe + // Breathe std::vector buffers; buffers.push_back(source->SoundResource->Buffer()); int ammountOfbreaths = (static_cast(e.Damage) / 10) + 2; // TEMP: Idk something stupid like this shit @@ -452,14 +451,6 @@ bool SoundSystem::OnComponentAttached(const Events::ComponentAttached & e) return false; } -bool SoundSystem::OnComponentDeleted(const Events::ComponentDeleted & e) -{ - if (e.ComponentType == "SoundEmitter") { - - } - return false; -} - bool SoundSystem::OnTriggerTouch(const Events::TriggerTouch & e) { if (m_World->HasComponent(e.Trigger.ID, "CapturePoint")) { From d61e6050938b751f82b7bfd1b58cd1f5628bf358 Mon Sep 17 00:00:00 2001 From: William Moberg Date: Fri, 5 Feb 2016 10:56:34 +0100 Subject: [PATCH 085/355] Can walk up "stair-steps". Cleanup WIP. Better performance in RectanglevsTriangle check. Added IsOnGround flag and VerticalStepHeight in Physics. Lotsa commented code saved for historical reasons, remove later. --- include/Engine/Collision/Collision.h | 2 + resources/Schema/Components/Physics.xml | 2 + resources/Schema/Components/Physics.xsd | 4 + src/Engine/Collision/Collision.cpp | 226 +++++++++++++++++----- src/Engine/Collision/CollisionSystem.cpp | 30 ++- src/Game/Systems/PlayerMovementSystem.cpp | 18 +- 6 files changed, 221 insertions(+), 61 deletions(-) diff --git a/include/Engine/Collision/Collision.h b/include/Engine/Collision/Collision.h index 183c800c..6e4858b2 100644 --- a/include/Engine/Collision/Collision.h +++ b/include/Engine/Collision/Collision.h @@ -68,6 +68,8 @@ bool AABBvsTriangles(const AABB& box, const std::vector& modelIndices, const glm::mat4& modelMatrix, glm::vec3& boxVelocity, + float verticalStepHeight, + bool& isOnGround, glm::vec3& outResolutionVector); //Return true if the boxes are intersecting. diff --git a/resources/Schema/Components/Physics.xml b/resources/Schema/Components/Physics.xml index 9d1638fb..6cb73c75 100644 --- a/resources/Schema/Components/Physics.xml +++ b/resources/Schema/Components/Physics.xml @@ -2,4 +2,6 @@ true + false + 0.33 diff --git a/resources/Schema/Components/Physics.xsd b/resources/Schema/Components/Physics.xsd index 72037f48..7fed1fb5 100644 --- a/resources/Schema/Components/Physics.xsd +++ b/resources/Schema/Components/Physics.xsd @@ -13,6 +13,10 @@ m/s^2 + + + The largest height of a "stair-step" that can be walked over + diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index 083af229..7bb0d3c4 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -238,7 +238,7 @@ inline glm::vec3 signNonZero(const glm::vec3& x) { glm::vec3 r; for (int i = 0; i < 3; ++i) { - r[i] = signNonZero(x[i]); + r[i] = (float)signNonZero(x[i]); } return r; } @@ -253,11 +253,11 @@ bool rectangleVsTriangle(const glm::vec2& boxMin, const glm::vec2& boxMax, const std::array& triPos, glm::vec2& resolutionDirection, - float& resolutionDistance, + float& resolutionDistanceSq, bool& pushedFromTriNormal) { pushedFromTriNormal = false; - resolutionDistance = INFINITY; + resolutionDistanceSq = INFINITY; //Project along box normals (coordinate axes, since it's axis-aligned). for (int ax = 0; ax < 2; ++ax) { float minTri = INFINITY; @@ -275,9 +275,11 @@ bool rectangleVsTriangle(const glm::vec2& boxMin, float leftRes = minTri - boxMax[ax]; float rightRes = maxTri - boxMin[ax]; float push = rightRes < -leftRes ? rightRes : leftRes; - float absPush = abs(push); - if (absPush < resolutionDistance) { - resolutionDistance = absPush; + float absPushSq = abs(push); + absPushSq *= absPushSq; + + if (absPushSq < resolutionDistanceSq) { + resolutionDistanceSq = absPushSq; resolutionDirection[1 - ax] = 0.f; resolutionDirection[ax] = push; } @@ -326,9 +328,11 @@ bool rectangleVsTriangle(const glm::vec2& boxMin, float leftRes = minTri - maxBox; float rightRes = maxTri - minBox; float push = rightRes < -leftRes ? rightRes : leftRes; - float absPush = abs(push); - if (absPush < resolutionDistance) { - resolutionDistance = absPush; + float absPushSq = abs(push); + absPushSq *= absPushSq; + + if (absPushSq < resolutionDistanceSq) { + resolutionDistanceSq = absPushSq; resolutionDirection = push * normal; pushedFromTriNormal = true; } @@ -338,26 +342,35 @@ bool rectangleVsTriangle(const glm::vec2& boxMin, constexpr float SlopeConstant(float degrees) { - return (1.0 - degrees / 90.f); + return (1.0f - degrees / 90.f); +} + +//Returns true if the angle between horizon and the collision surface is less than 45 degrees. +constexpr bool FaceIsGround(float faceNormalY) +{ + //TODO: Perhaps the 45 degrees could be saved in a component or in the config.. + return faceNormalY > SlopeConstant(45.0f); } //An array containing 3 int pairs { 0, 2 }, { 0, 1 }, { 1, 2 } constexpr std::array, 3> dimensionPairs({ std::pair(0, 2), std::pair(0, 1), std::pair(1, 2) }); -//TODO: Prefer to move in y - if the resolution is small enough, value in physics comp. -//TODO: Walking down slopes correctly. bool AABBvsTriangle(const AABB& box, const std::array& triPos, + const glm::vec3& originalBoxVelocity, + float verticalStepHeight, + bool& isOnGround, glm::vec3& boxVelocity, - glm::vec3& outVector) + glm::vec3& outResolution) { //Check so we don't have a zero area triangle when calculating the normal. //Also, don't check a triangle facing away from the player. //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, boxVelocity) > 0)) { + if (!vectorHasLength(triNormal) || (glm::dot(triNormal, originalBoxVelocity) > 0)) { return false; } + triNormal = glm::normalize(triNormal); enum BoxTriResolveCase { @@ -366,13 +379,29 @@ bool AABBvsTriangle(const AABB& box, ResolveDimZ, Line, //Box edge colliding with triangle line. Corner //Box corner colliding with the triangle face. - } resolveCase; + }; + struct Resolution + { + Resolution() + : DistanceSq(INFINITY) + , Vector(0.f) + {} + BoxTriResolveCase Case; + float DistanceSq; + glm::vec3 Vector; + }; + //The smallest resolution that solves the collision. + Resolution resolveShortest; + //The smallest resolution that solves the collision, that resolves upwards. + Resolution resolveUpwards; + //If player stands on the ground and collides with a ground triangle, + //we might step up onto it if the step is small enough. + bool canStairStepUp = isOnGround && FaceIsGround(triNormal.y); const glm::vec3& origin = box.Origin(); const glm::vec3& half = box.HalfSize(); const glm::vec3& min = box.MinCorner(); const glm::vec3& max = box.MaxCorner(); - float minimumTranslation = INFINITY; //For each projection in xy-, xz-, and yx-planes. for (std::pair dim : dimensionPairs) { @@ -392,21 +421,35 @@ bool AABBvsTriangle(const AABB& box, //if projections don't overlap, return false. if (!rectangleVsTriangle(boxMin, boxMax, t2D, resolutionVector, resolutionDist, pushedFromTriangleLine)) { return false; - } else if (resolutionDist < minimumTranslation) { - outVector = glm::vec3(0.f); - outVector[dim.first] = resolutionVector.x; - outVector[dim.second] = resolutionVector.y; - minimumTranslation = resolutionDist; - //If we pushed away from triangle line (edge), or if we - //move the player along one coordinate axis (pick the dimension that isn't zero). - resolveCase = pushedFromTriangleLine ? Line : static_cast((abs(outVector[dim.first]) < 0.0001f) ? dim.second : dim.first); + } else { + //Overwrite the smallest resolution if this is smaller. + if (resolutionDist < resolveShortest.DistanceSq) { + resolveShortest.Vector = glm::vec3(0.f); + resolveShortest.Vector[dim.first] = resolutionVector.x; + resolveShortest.Vector[dim.second] = resolutionVector.y; + resolveShortest.DistanceSq = resolutionDist; + //If we pushed away from triangle line (edge), or if we + //move the player along one coordinate axis (pick the dimension that isn't zero). + resolveShortest.Case = pushedFromTriangleLine ? Line : static_cast((abs(resolveShortest.Vector[dim.first]) < 0.0001f) ? dim.second : dim.first); + } + //Overwrite the smallest upward resolution if this is smaller, and resolves upwards. + constexpr int yAxis = 1; + bool resIsUpwardsIn3D = dim.first == yAxis && resolutionVector.x > 0 || dim.second == yAxis && resolutionVector.y > 0; + if (canStairStepUp && resIsUpwardsIn3D && resolutionDist < resolveUpwards.DistanceSq) { + resolveUpwards.Vector = glm::vec3(0.f); + resolveUpwards.Vector[dim.first] = resolutionVector.x; + resolveUpwards.Vector[dim.second] = resolutionVector.y; + resolveUpwards.DistanceSq = resolutionDist; + //If we pushed away from triangle line (edge), or if we + //move the player along one coordinate axis (pick the dimension that isn't zero). + resolveUpwards.Case = pushedFromTriangleLine ? Line : static_cast((abs(resolveUpwards.Vector[dim.first]) < 0.0001f) ? dim.second : dim.first); + } } } //If the triangle does intersect any of the cube diagonals, it will //intersect the cube diagonal that comes //closest to being perpendicular to the plane of the triangle. - triNormal = glm::normalize(triNormal); glm::vec3 diagonal = signNonZero(triNormal) * half; //The triangle plane contains all points P in dot(triNormal, P) == dot(triNormal, v0) //The diagonal line contains all points P in P = origin + diagonal * t. @@ -416,24 +459,62 @@ bool AABBvsTriangle(const AABB& box, return false; } glm::vec3 cornerResolution = (1+t) * diagonal; - if (glm::length(cornerResolution) < minimumTranslation) { - outVector = cornerResolution; - resolveCase = Corner; + //Overwrite the smallest resolution if this is smaller. + float lenSq = glm::length2(cornerResolution); + if (lenSq < resolveShortest.DistanceSq) { + resolveShortest.Vector = cornerResolution; + resolveShortest.Case = Corner; + } + if (canStairStepUp && cornerResolution.y > 0 && lenSq < resolveUpwards.DistanceSq) { + resolveUpwards.Vector = cornerResolution; + resolveUpwards.Case = Corner; + resolveUpwards.DistanceSq = lenSq; } - glm::vec3 projNorm; - switch (resolveCase) { - case ResolveDimX: + //Force the resolution upwards if it is smaller than the threshold verticalStepHeight. + //Else take the shortest resolution. + bool takeUp = resolveUpwards.Vector.y > 0 && resolveUpwards.Vector.y < verticalStepHeight; + Resolution& bestResolve = takeUp ? resolveUpwards : resolveShortest; + outResolution = bestResolve.Vector; + + //TODO: Debug stuff. + std::string dbg; + switch (bestResolve.Case) { case ResolveDimY: + case ResolveDimX: + case ResolveDimZ: + dbg = "Axis"; + break; + case Line: + dbg = "Line"; + break; + case Corner: + dbg = "Corner"; + break; + default: + break; + } + std::string outs = (takeUp ? "Resolve upwards " : "Resolve normal ") + dbg; + //TODO: End debug stuff. + + glm::vec3 projNorm; + switch (bestResolve.Case) { + case ResolveDimY: + boxVelocity.y = 0.f; + if (outResolution.y > 0) + isOnGround = true; + case ResolveDimX: case ResolveDimZ: { //If we get here, the resolution is along one coordinate axis. - //set velocity to 0 in that dimension. - boxVelocity[resolveCase] = 0.f; + //set velocity to 0 in y if it is along y-axis. + outs += isOnGround ? " ground" : " air"; + ImGui::Text(outs.c_str()); + LOG_INFO(outs.c_str()); return true; } case Line: - projNorm = glm::normalize(outVector); + projNorm = glm::normalize(outResolution); break; case Corner: projNorm = triNormal; @@ -442,26 +523,64 @@ bool AABBvsTriangle(const AABB& box, break; } - //If the collision was not on steep wall or similarly (e.g. walking on the ground), do special treatment. - //Magic value that makes condition correspond to: - //if the angle between horizon and the collision surface is less than 45 degrees. - if (projNorm.y > SlopeConstant(45.0f)) { + isOnGround = false; + //If the collision was not on steep wall or similarly (e.g. walking on the ground), force resolution in y only. + if (FaceIsGround(projNorm.y)) { //Ensure that the player always is moved upwards, instead of sliding down. //Also zero the vertical velocity. - float len = glm::length(outVector); - float ang = glm::half_pi() - glm::acos(outVector.y / len); + float len = glm::length(outResolution); + float ang = glm::half_pi() - glm::acos(outResolution.y / len); if (len > 0.0000001f && ang > 0.0000001f) { - outVector.x = 0; - outVector.y = len / glm::sin(ang); - outVector.z = 0; - boxVelocity.y = 0.f; + outResolution.x = 0; + outResolution.y = len / glm::sin(ang); + outResolution.z = 0; } - } else if (projNorm.y > 0) { - //Enter here if the triangle is a steep slope, and it is not facing downwards. //Project the velocity onto the normal of the hit line/face. //w = v - *n, |n|==1. - boxVelocity = boxVelocity - glm::dot(boxVelocity, projNorm) * projNorm; + glm::vec3 projVel = boxVelocity - glm::dot(boxVelocity, projNorm) * projNorm; + if (abs(originalBoxVelocity.x) < 0.001f && abs(originalBoxVelocity.z) < 0.001f) { + boxVelocity.y = 0.f; + } else { + boxVelocity.y = std::min(projVel.y, 0.f); + } + + isOnGround = true; + } else if (projNorm.y > 0) { + //Enter here if the triangle is a steep slope, and it is not facing downwards. + //Ensure that the player will be pushed in the xz-plane. + //glm::vec3 moveDir(outResolution); + //moveDir.y = 0; + //if (vectorHasLength(moveDir)) { + // moveDir = glm::normalize(moveDir); + // float len = glm::length(outResolution); + // float dotMoveOut = moveDir.x * outResolution.x + moveDir.z * outResolution.z; + // float ang = glm::half_pi() - glm::acos(dotMoveOut / len); + // if (len > 0.0000001f && ang > 0.0000001f) { + // outResolution = (len / glm::sin(ang)) * moveDir; + // } + //} + //Project the velocity onto the normal of the hit line/face. + //w = v - *n, |n|==1. + //TODO: What do we want.. +#if 0 //Walk up steep walls. + glm::vec3 projVel = boxVelocity - glm::dot(boxVelocity, projNorm) * projNorm; + boxVelocity.y = std::min(projVel.y, 0.f); + isOnGround = true; +#elif 1 //"ice cream"-effect, air resistance + projected velocity. + if (!isOnGround) { + boxVelocity = boxVelocity - glm::dot(boxVelocity, projNorm) * projNorm; + } + isOnGround = false; +#elif 0 //"ice cream"-effect, ground friction (full control) + projected velocity. + if (!isOnGround) { + boxVelocity = boxVelocity - glm::dot(boxVelocity, projNorm) * projNorm; + } + isOnGround = true; +#endif } + outs += isOnGround ? " ground" : " air"; + ImGui::Text(outs.c_str()); + LOG_INFO(outs.c_str()); return true; } @@ -470,12 +589,16 @@ bool AABBvsTriangles(const AABB& box, const std::vector& modelIndices, const glm::mat4& modelMatrix, glm::vec3& boxVelocity, + float verticalStepHeight, + bool& isOnGround, glm::vec3& outResolutionVector) { bool hit = false; + bool everHitTheGround = false; AABB newBox = box; outResolutionVector = glm::vec3(0.f); + glm::vec3 originalBoxVelocity(boxVelocity); for (int i = 0; i < modelIndices.size(); ) { std::array triVertices = { Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix), @@ -483,13 +606,20 @@ bool AABBvsTriangles(const AABB& box, Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix) }; glm::vec3 outVec; - if (AABBvsTriangle(newBox, triVertices, boxVelocity, outVec)) { + bool collideWithGround = isOnGround; + if (AABBvsTriangle(newBox, triVertices, originalBoxVelocity, verticalStepHeight, collideWithGround, boxVelocity, outVec)) { hit = true; outResolutionVector += outVec; newBox = AABB::FromOriginSize(newBox.Origin() + outVec, newBox.Size()); + if (collideWithGround) { + everHitTheGround = isOnGround = true; + } } } + if (!everHitTheGround) { + isOnGround = false; + } return hit; } diff --git a/src/Engine/Collision/CollisionSystem.cpp b/src/Engine/Collision/CollisionSystem.cpp index 846d38a7..e5c194d6 100644 --- a/src/Engine/Collision/CollisionSystem.cpp +++ b/src/Engine/Collision/CollisionSystem.cpp @@ -37,15 +37,33 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c glm::mat4 modelMatrix = Transform::ModelMatrix(boxB.Entity); - glm::vec3 newVelocity = (glm::vec3)cPhysics["Velocity"]; - if (Collision::AABBvsTriangles(boxA, model->m_Vertices, model->m_Indices, modelMatrix, newVelocity, resolutionVector)) { - (glm::vec3&)cTransform["Position"] += resolutionVector; - cPhysics["Velocity"] = newVelocity; - } + glm::vec3 inOutVelocity = (glm::vec3)cPhysics["Velocity"]; + bool isOnGround = (bool)cPhysics["IsOnGround"]; + //glm::vec3 gravity = glm::vec3(0, 9.82f * dt, 0); + //TODO: glm::abs(inOutVelocity - gravity) doesn't work, because of velocity projection on ground normal. + //if (!isOnGround || glm::any(glm::greaterThan(glm::abs(inOutVelocity - gravity), glm::vec3(0.0001f)))) { + float verticalStepHeight = (float)(double)cPhysics["VerticalStepHeight"]; + if (Collision::AABBvsTriangles(boxA, model->m_Vertices, model->m_Indices, modelMatrix, inOutVelocity, verticalStepHeight, isOnGround, resolutionVector)) { + glm::vec3 pos = (glm::vec3)cTransform["Position"] + resolutionVector; + //Hack: Force the position to be at discrete values after collision, removes jittering. + //constexpr float discreteValue = 1.0e2f; + //pos = glm::vec3(glm::ivec3(discreteValue * pos)) / discreteValue; + //pos = glm::round(discreteValue * pos) / discreteValue; + (glm::vec3&)cTransform["Position"] = pos; + cPhysics["Velocity"] = inOutVelocity; + (bool)cPhysics["IsOnGround"] = isOnGround; + } else { + (bool)cPhysics["IsOnGround"] = false; + } + //} else { + // (glm::vec3&)cTransform["Position"] -= gravity; + // cPhysics["Velocity"] = glm::vec3(0.f); + //} } else if (Collision::AABBVsAABB(boxA, boxB, resolutionVector)) { //Enter here if boxB has no Model. (glm::vec3&)cTransform["Position"] += resolutionVector; - if (resolutionVector.y > 0) { + (bool)cPhysics["IsOnGround"] = resolutionVector.y > 0; + if ((bool)cPhysics["IsOnGround"]){ ((glm::vec3&)cPhysics["Velocity"]).y = 0.f; } } diff --git a/src/Game/Systems/PlayerMovementSystem.cpp b/src/Game/Systems/PlayerMovementSystem.cpp index 6eab02c5..92ddf549 100644 --- a/src/Game/Systems/PlayerMovementSystem.cpp +++ b/src/Game/Systems/PlayerMovementSystem.cpp @@ -50,11 +50,13 @@ void PlayerMovementSystem::Update(double dt) wishSpeed = playerMovementSpeed; } glm::vec3& velocity = cPhysics["Velocity"]; - ImGui::Text("velocity: (%f, %f, %f)", velocity.x, velocity.y, velocity.z); + bool isOnGround = (bool)cPhysics["IsOnGround"]; + ImGui::Text(isOnGround ? "On ground" : "In air"); + ImGui::Text("velocity: (%f, %f, %f) |%f|", velocity.x, velocity.y, velocity.z, glm::length(velocity)); glm::vec3 groundVelocity(0.f, 0.f, 0.f); - groundVelocity.x = glm::dot(velocity, glm::vec3(1.f, 0.f, 0.f)); - groundVelocity.z = glm::dot(velocity, glm::vec3(0.f, 0.f, 1.f)); - ImGui::Text("groundVelocity: (%f, %f, %f) |%f|", groundVelocity.x, groundVelocity.y, groundVelocity.z, glm::length(wishDirection)); + groundVelocity.x = velocity.x; + groundVelocity.z = velocity.z; + ImGui::Text("groundVelocity: (%f, %f, %f) |%f|", groundVelocity.x, groundVelocity.y, groundVelocity.z, glm::length(groundVelocity)); ImGui::Text("wishDirection: (%f, %f, %f) |%f|", wishDirection.x, wishDirection.y, wishDirection.z, glm::length(wishDirection)); float currentSpeedProj = glm::dot(groundVelocity, wishDirection); float addSpeed = wishSpeed - currentSpeedProj; @@ -67,7 +69,7 @@ void PlayerMovementSystem::Update(double dt) ImGui::InputFloat("accel", &accel); static float airAccel = 0.5f; ImGui::InputFloat("airAccel", &airAccel); - float actualAccel = (velocity.y != 0) ? airAccel : accel; + float actualAccel = isOnGround ? accel : airAccel; static float surfaceFriction = 5.f; ImGui::InputFloat("surfaceFriction", &surfaceFriction); float accelerationSpeed = actualAccel * (float)dt * wishSpeed * surfaceFriction; @@ -76,7 +78,8 @@ void PlayerMovementSystem::Update(double dt) ImGui::Text("velocity: (%f, %f, %f) |%f|", velocity.x, velocity.y, velocity.z, glm::length(velocity)); } - if (controller->Jumping() && !controller->Crouching() && velocity.y == 0.f) { + if (controller->Jumping() && !controller->Crouching() && isOnGround) { + (bool)cPhysics["IsOnGround"] = false; velocity.y += 4.f; } @@ -128,6 +131,7 @@ void PlayerMovementSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapp ComponentWrapper& cPhysics = entity["Physics"]; glm::vec3& velocity = cPhysics["Velocity"]; + bool isOnGround = (bool)cPhysics["IsOnGround"]; // Ground friction float speed = glm::length(velocity); @@ -135,7 +139,7 @@ void PlayerMovementSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapp ImGui::InputFloat("groundFriction", &groundFriction); static float airFriction = 0.f; ImGui::InputFloat("airFriction", &airFriction); - float friction = (velocity.y != 0) ? airFriction : groundFriction; + float friction = isOnGround ? groundFriction : airFriction; if (speed > 0) { float drop = speed * friction * (float)dt; float multiplier = glm::max(speed - drop, 0.f) / speed; From d1a309be10532ce58823f77578dd02d589263cbe Mon Sep 17 00:00:00 2001 From: Teejoon Date: Fri, 5 Feb 2016 13:51:47 +0100 Subject: [PATCH 086/355] Now supports reading of 3 different types of materials --- include/Engine/Rendering/RawModelCustom.h | 47 +++-- src/Engine/Rendering/RawModelCustom.cpp | 205 ++++++++++++++-------- 2 files changed, 171 insertions(+), 81 deletions(-) diff --git a/include/Engine/Rendering/RawModelCustom.h b/include/Engine/Rendering/RawModelCustom.h index 66477322..10bfd276 100644 --- a/include/Engine/Rendering/RawModelCustom.h +++ b/include/Engine/Rendering/RawModelCustom.h @@ -46,8 +46,14 @@ public: glm::vec4 BoneIndices; glm::vec4 BoneWeights; }; + + struct TextureProperties { + std::string TexturePath; + glm::vec2 UVRepeat; + std::shared_ptr<::Texture> Texture; + }; - struct MaterialGroup + struct MaterialBasic { float SpecularExponent; float ReflectionFactor; @@ -57,16 +63,32 @@ public: unsigned int StartIndex; unsigned int EndIndex; //float Transparency; - std::string TexturePath; - std::shared_ptr<::Texture> Texture; - std::string NormalMapPath; - std::shared_ptr<::Texture> NormalMap; - std::string SpecularMapPath; - std::shared_ptr<::Texture> SpecularMap; - std::string IncandescenceMapPath; - std::shared_ptr<::Texture> IncandescenceMap; }; + struct MaterialSplatMapping : public MaterialBasic + { + TextureProperties SplatMap; + std::vector ColorMaps; + std::vector NormalMaps; + std::vector SpecularMaps; + std::vector IncandescenceMaps; + }; + + struct MaterialSingleTextures : public MaterialBasic + { + TextureProperties ColorMaps; + TextureProperties NormalMaps; + TextureProperties SpecularMaps; + TextureProperties IncandescenceMaps; + }; + + enum class MaterialType { Basic = 1, SplatMapping, SingleTextures }; + + struct MaterialProperties { + MaterialType type; + MaterialBasic* material; + }; + const Vertex* Vertices() const { if (hasSkin) { return m_SkinedVertices.data(); @@ -94,8 +116,7 @@ public: bool isSkined() const { return hasSkin; }; - std::vector MaterialGroups; - + std::vector m_Materials; std::vector m_Indices; Skeleton* m_Skeleton = nullptr; @@ -115,6 +136,10 @@ private: void ReadMaterialFile(std::string filePath); void ReadMaterials(unsigned int &offset, char* fileData, unsigned int& fileByteSize); void ReadMaterialSingle(unsigned int &offset, char* fileData, unsigned int& fileByteSize); + void ReadMaterialBasic(MaterialBasic* Material, unsigned int &offset, char* fileData, unsigned int& fileByteSize); + void ReadMaterialSingleTexture(MaterialSingleTextures* Material, unsigned int &offset, char* fileData, unsigned int& fileByteSize); + void ReadMaterialSplatMapping(MaterialSplatMapping* Material, unsigned int &offset, char* fileData, unsigned int& fileByteSize); + void ReadMaterialTextureProperties(TextureProperties& texture, unsigned int &offset, char* fileData, unsigned int& fileByteSize); void ReadAnimationFile(std::string filePath); void ReadAnimationBindPoses(unsigned int &offset, char* fileData, unsigned int& fileByteSize); diff --git a/src/Engine/Rendering/RawModelCustom.cpp b/src/Engine/Rendering/RawModelCustom.cpp index f3291394..8bdfbbfc 100644 --- a/src/Engine/Rendering/RawModelCustom.cpp +++ b/src/Engine/Rendering/RawModelCustom.cpp @@ -122,7 +122,7 @@ void RawModelCustom::ReadMaterials(unsigned int& offset, char* fileData, unsigne { #ifdef BOOST_LITTLE_ENDIAN unsigned int* numMaterials = (unsigned int*)(fileData); - MaterialGroups.reserve(*numMaterials); + m_Materials.reserve(*numMaterials); offset += sizeof(unsigned int); for (int i = 0; i < *numMaterials; i++) { @@ -134,83 +134,148 @@ void RawModelCustom::ReadMaterials(unsigned int& offset, char* fileData, unsigne void RawModelCustom::ReadMaterialSingle(unsigned int &offset, char* fileData, unsigned int& fileByteSize) { - MaterialGroup newMaterial; - + MaterialProperties newMaterialProperty; #ifdef BOOST_LITTLE_ENDIAN - if (offset + sizeof(unsigned int) * 4 > fileByteSize) { - throw Resource::FailedLoadingException("Reading Material texture names length failed"); - } + if (offset + sizeof(MaterialType) > fileByteSize) { + throw Resource::FailedLoadingException("Reading Material Type failed"); + } + MaterialType type = *(MaterialType*)(fileData + offset); + offset += sizeof(MaterialType); - unsigned int* nameLengths = (unsigned int*)(fileData + offset); - offset += sizeof(unsigned int) * 4; + switch (type) { + case MaterialType::Basic: + newMaterialProperty.material = new MaterialBasic(); + ReadMaterialBasic(newMaterialProperty.material, offset, fileData, fileByteSize); + break; + case MaterialType::SplatMapping: + newMaterialProperty.material = new MaterialSplatMapping(); + ReadMaterialSplatMapping(static_cast(newMaterialProperty.material), offset, fileData, fileByteSize); + break; + case MaterialType::SingleTextures: + newMaterialProperty.material = new MaterialSingleTextures(); + ReadMaterialSingleTexture(static_cast(newMaterialProperty.material), offset, fileData, fileByteSize); + break; + default: + throw Resource::FailedLoadingException("Material contains an unknown MaterialType"); + }; - if (offset + sizeof(float) * 11 + sizeof(unsigned int) * 2 > fileByteSize) { - throw Resource::FailedLoadingException("Reading Material specular, reflection, color and start and end index values failed"); - } - - newMaterial.SpecularExponent = *(float*)(fileData + offset); - offset += sizeof(float); - newMaterial.ReflectionFactor = *(float*)(fileData + offset); - offset += sizeof(float); - - memcpy(&newMaterial.DiffuseColor[0], fileData + offset, sizeof(float) * 3); - offset += sizeof(float) * 3; - memcpy(&newMaterial.SpecularColor[0], fileData + offset, sizeof(float) * 3); - offset += sizeof(float) * 3; - memcpy(&newMaterial.IncandescenceColor[0], fileData + offset, sizeof(float) * 3); - offset += sizeof(float) * 3; - - newMaterial.StartIndex = *(unsigned int*)(fileData + offset); - offset += sizeof(unsigned int); - newMaterial.EndIndex = *(unsigned int*)(fileData + offset); - offset += sizeof(unsigned int); - - if (nameLengths[0] > 0) { - if (offset + nameLengths[0] > fileByteSize) { - throw Resource::FailedLoadingException("Reading Material texture path failed"); - } - - newMaterial.TexturePath = "Textures/"; - newMaterial.TexturePath += (fileData + offset); - newMaterial.TexturePath += ".png"; - offset += nameLengths[0]; - } - - if (nameLengths[1] > 0) { - if (offset + nameLengths[1] > fileByteSize) { - throw Resource::FailedLoadingException("Reading Material NormalMap path failed"); - } - newMaterial.NormalMapPath = "Textures/"; - newMaterial.NormalMapPath += (fileData + offset); - newMaterial.NormalMapPath += ".png"; - offset += nameLengths[1]; - } - - if (nameLengths[2] > 0) { - if (offset + nameLengths[2] > fileByteSize) { - throw Resource::FailedLoadingException("Reading Material SpecularMap path failed"); - } - newMaterial.SpecularMapPath = "Textures/"; - newMaterial.SpecularMapPath += (fileData + offset); - newMaterial.SpecularMapPath += ".png"; - offset += nameLengths[2]; - } - - if (nameLengths[3] > 0) { - if (offset + nameLengths[3] > fileByteSize) { - throw Resource::FailedLoadingException("Reading Material IncandescenceMap path failed"); - } - newMaterial.IncandescenceMapPath = "Textures/"; - newMaterial.IncandescenceMapPath += (fileData + offset); - newMaterial.IncandescenceMapPath += ".png"; - offset += nameLengths[3]; - } + newMaterialProperty.type = type; #else #endif - MaterialGroups.push_back(newMaterial); + m_Materials.push_back(newMaterialProperty); +} + +void RawModelCustom::ReadMaterialBasic(RawModelCustom::MaterialBasic* newMaterial, unsigned int &offset, char* fileData, unsigned int& fileByteSize) +{ + if (offset + sizeof(unsigned int) * 4 > fileByteSize) { + throw Resource::FailedLoadingException("Reading Material texture names length failed"); + } + + unsigned int* nameLengths = (unsigned int*)(fileData + offset); + offset += sizeof(unsigned int) * 4; + + if (offset + sizeof(float) * 11 + sizeof(unsigned int) * 2 > fileByteSize) { + throw Resource::FailedLoadingException("Reading Material specular, reflection, color and start and end index values failed"); + } + + newMaterial->SpecularExponent = *(float*)(fileData + offset); + offset += sizeof(float); + newMaterial->ReflectionFactor = *(float*)(fileData + offset); + offset += sizeof(float); + + memcpy(&newMaterial->DiffuseColor[0], fileData + offset, sizeof(float) * 3); + offset += sizeof(float) * 3; + memcpy(&newMaterial->SpecularColor[0], fileData + offset, sizeof(float) * 3); + offset += sizeof(float) * 3; + memcpy(&newMaterial->IncandescenceColor[0], fileData + offset, sizeof(float) * 3); + offset += sizeof(float) * 3; + + newMaterial->StartIndex = *(unsigned int*)(fileData + offset); + offset += sizeof(unsigned int); + newMaterial->EndIndex = *(unsigned int*)(fileData + offset); + offset += sizeof(unsigned int); +} + +void RawModelCustom::ReadMaterialSingleTexture(RawModelCustom::MaterialSingleTextures* newMaterial, unsigned int &offset, char* fileData, unsigned int& fileByteSize) +{ + unsigned char numberOfMaps[4]; + if (offset + sizeof(unsigned char) * 4 > fileByteSize) { + throw Resource::FailedLoadingException("Reading Material NumOfMaps failed"); + } + + if (numberOfMaps[0] > 0) + { + ReadMaterialTextureProperties(newMaterial->ColorMaps, offset, fileData, fileByteSize); + } + + if (numberOfMaps[1] > 0) + { + ReadMaterialTextureProperties(newMaterial->SpecularMaps, offset, fileData, fileByteSize); + } + + if (numberOfMaps[2] > 0) + { + ReadMaterialTextureProperties(newMaterial->NormalMaps, offset, fileData, fileByteSize); + } + + if (numberOfMaps[3] > 0) + { + ReadMaterialTextureProperties(newMaterial->IncandescenceMaps, offset, fileData, fileByteSize); + } +} + +void RawModelCustom::ReadMaterialSplatMapping(RawModelCustom::MaterialSplatMapping* newMaterial, unsigned int &offset, char* fileData, unsigned int& fileByteSize) +{ + ReadMaterialTextureProperties(newMaterial->SplatMap, offset, fileData, fileByteSize); + unsigned char numberOfMaps[4]; + if (offset + sizeof(unsigned char) * 4 > fileByteSize) { + throw Resource::FailedLoadingException("Reading Material NumOfMaps failed"); + } + + newMaterial->ColorMaps.resize(numberOfMaps[0]); + for (unsigned char i = 0; i < numberOfMaps[0]; i++) + { + ReadMaterialTextureProperties(newMaterial->ColorMaps[i], offset, fileData, fileByteSize); + } + + newMaterial->SpecularMaps.resize(numberOfMaps[1]); + for (unsigned char i = 0; i < numberOfMaps[1]; i++) + { + ReadMaterialTextureProperties(newMaterial->SpecularMaps[i], offset, fileData, fileByteSize); + } + + newMaterial->NormalMaps.resize(numberOfMaps[2]); + for (unsigned char i = 0; i < numberOfMaps[2]; i++) + { + ReadMaterialTextureProperties(newMaterial->NormalMaps[i], offset, fileData, fileByteSize); + } + + newMaterial->IncandescenceMaps.resize(numberOfMaps[3]); + for (unsigned char i = 0; i < numberOfMaps[3]; i++) + { + ReadMaterialTextureProperties(newMaterial->IncandescenceMaps[i], offset, fileData, fileByteSize); + } +} + +void RawModelCustom::ReadMaterialTextureProperties(RawModelCustom::TextureProperties& texture, unsigned int &offset, char* fileData, unsigned int& fileByteSize) { + unsigned int nameLength = *(unsigned int*)(fileData + offset); + if (nameLength > 0) { + if (offset + nameLength > fileByteSize) { + throw Resource::FailedLoadingException("Reading Material texture path failed"); + } + texture.TexturePath = "Textures/"; + texture.TexturePath += (fileData + offset); + texture.TexturePath += ".png"; + offset += nameLength; + if (offset + sizeof(glm::vec2) > fileByteSize) { + throw Resource::FailedLoadingException("Reading Material texture UVTiling failed"); + } + memcpy(&texture.UVRepeat[0], fileData + offset, sizeof(glm::vec2)); + offset += sizeof(glm::vec2); + } } void RawModelCustom::ReadAnimationFile(std::string filePath) From 4fe9e4f1c3586bb346684fe245a92a05adcae68a Mon Sep 17 00:00:00 2001 From: William Moberg Date: Fri, 5 Feb 2016 14:38:08 +0100 Subject: [PATCH 087/355] Debug cleanup and some bug fixes. --- src/Engine/Collision/Collision.cpp | 68 ++---------------------- src/Engine/Collision/CollisionSystem.cpp | 28 +++------- 2 files changed, 13 insertions(+), 83 deletions(-) diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index 7bb0d3c4..533fdc9b 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -459,7 +459,7 @@ bool AABBvsTriangle(const AABB& box, return false; } glm::vec3 cornerResolution = (1+t) * diagonal; - //Overwrite the smallest resolution if this is smaller. + //Overwrite the smallest resolution if cornerResolution is smaller. float lenSq = glm::length2(cornerResolution); if (lenSq < resolveShortest.DistanceSq) { resolveShortest.Vector = cornerResolution; @@ -477,26 +477,6 @@ bool AABBvsTriangle(const AABB& box, Resolution& bestResolve = takeUp ? resolveUpwards : resolveShortest; outResolution = bestResolve.Vector; - //TODO: Debug stuff. - std::string dbg; - switch (bestResolve.Case) { - case ResolveDimY: - case ResolveDimX: - case ResolveDimZ: - dbg = "Axis"; - break; - case Line: - dbg = "Line"; - break; - case Corner: - dbg = "Corner"; - break; - default: - break; - } - std::string outs = (takeUp ? "Resolve upwards " : "Resolve normal ") + dbg; - //TODO: End debug stuff. - glm::vec3 projNorm; switch (bestResolve.Case) { case ResolveDimY: @@ -505,14 +485,9 @@ bool AABBvsTriangle(const AABB& box, isOnGround = true; case ResolveDimX: 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. - outs += isOnGround ? " ground" : " air"; - ImGui::Text(outs.c_str()); - LOG_INFO(outs.c_str()); return true; - } case Line: projNorm = glm::normalize(outResolution); break; @@ -523,11 +498,9 @@ bool AABBvsTriangle(const AABB& box, break; } - isOnGround = false; //If the collision was not on steep wall or similarly (e.g. walking on the ground), force resolution in y only. if (FaceIsGround(projNorm.y)) { //Ensure that the player always is moved upwards, instead of sliding down. - //Also zero the vertical velocity. float len = glm::length(outResolution); float ang = glm::half_pi() - glm::acos(outResolution.y / len); if (len > 0.0000001f && ang > 0.0000001f) { @@ -535,52 +508,21 @@ bool AABBvsTriangle(const AABB& box, outResolution.y = len / glm::sin(ang); outResolution.z = 0; } + //Also zero the vertical velocity, if it is positive, else project it onto the normal. //Project the velocity onto the normal of the hit line/face. //w = v - *n, |n|==1. - glm::vec3 projVel = boxVelocity - glm::dot(boxVelocity, projNorm) * projNorm; - if (abs(originalBoxVelocity.x) < 0.001f && abs(originalBoxVelocity.z) < 0.001f) { - boxVelocity.y = 0.f; - } else { - boxVelocity.y = std::min(projVel.y, 0.f); - } - + boxVelocity.y = std::min(boxVelocity.y - glm::dot(boxVelocity, projNorm) * projNorm.y, 0.f); isOnGround = true; - } else if (projNorm.y > 0) { + } else { //Enter here if the triangle is a steep slope, and it is not facing downwards. - //Ensure that the player will be pushed in the xz-plane. - //glm::vec3 moveDir(outResolution); - //moveDir.y = 0; - //if (vectorHasLength(moveDir)) { - // moveDir = glm::normalize(moveDir); - // float len = glm::length(outResolution); - // float dotMoveOut = moveDir.x * outResolution.x + moveDir.z * outResolution.z; - // float ang = glm::half_pi() - glm::acos(dotMoveOut / len); - // if (len > 0.0000001f && ang > 0.0000001f) { - // outResolution = (len / glm::sin(ang)) * moveDir; - // } - //} //Project the velocity onto the normal of the hit line/face. //w = v - *n, |n|==1. - //TODO: What do we want.. -#if 0 //Walk up steep walls. - glm::vec3 projVel = boxVelocity - glm::dot(boxVelocity, projNorm) * projNorm; - boxVelocity.y = std::min(projVel.y, 0.f); - isOnGround = true; -#elif 1 //"ice cream"-effect, air resistance + projected velocity. + //"ice cream"-effect, air resistance + projected velocity. if (!isOnGround) { boxVelocity = boxVelocity - glm::dot(boxVelocity, projNorm) * projNorm; } isOnGround = false; -#elif 0 //"ice cream"-effect, ground friction (full control) + projected velocity. - if (!isOnGround) { - boxVelocity = boxVelocity - glm::dot(boxVelocity, projNorm) * projNorm; - } - isOnGround = true; -#endif } - outs += isOnGround ? " ground" : " air"; - ImGui::Text(outs.c_str()); - LOG_INFO(outs.c_str()); return true; } diff --git a/src/Engine/Collision/CollisionSystem.cpp b/src/Engine/Collision/CollisionSystem.cpp index e5c194d6..b5d7a1f0 100644 --- a/src/Engine/Collision/CollisionSystem.cpp +++ b/src/Engine/Collision/CollisionSystem.cpp @@ -39,26 +39,14 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c glm::vec3 inOutVelocity = (glm::vec3)cPhysics["Velocity"]; bool isOnGround = (bool)cPhysics["IsOnGround"]; - //glm::vec3 gravity = glm::vec3(0, 9.82f * dt, 0); - //TODO: glm::abs(inOutVelocity - gravity) doesn't work, because of velocity projection on ground normal. - //if (!isOnGround || glm::any(glm::greaterThan(glm::abs(inOutVelocity - gravity), glm::vec3(0.0001f)))) { - float verticalStepHeight = (float)(double)cPhysics["VerticalStepHeight"]; - if (Collision::AABBvsTriangles(boxA, model->m_Vertices, model->m_Indices, modelMatrix, inOutVelocity, verticalStepHeight, isOnGround, resolutionVector)) { - glm::vec3 pos = (glm::vec3)cTransform["Position"] + resolutionVector; - //Hack: Force the position to be at discrete values after collision, removes jittering. - //constexpr float discreteValue = 1.0e2f; - //pos = glm::vec3(glm::ivec3(discreteValue * pos)) / discreteValue; - //pos = glm::round(discreteValue * pos) / discreteValue; - (glm::vec3&)cTransform["Position"] = pos; - cPhysics["Velocity"] = inOutVelocity; - (bool)cPhysics["IsOnGround"] = isOnGround; - } else { - (bool)cPhysics["IsOnGround"] = false; - } - //} else { - // (glm::vec3&)cTransform["Position"] -= gravity; - // cPhysics["Velocity"] = glm::vec3(0.f); - //} + float verticalStepHeight = (float)(double)cPhysics["VerticalStepHeight"]; + if (Collision::AABBvsTriangles(boxA, model->m_Vertices, model->m_Indices, modelMatrix, inOutVelocity, verticalStepHeight, isOnGround, resolutionVector)) { + (glm::vec3&)cTransform["Position"] += resolutionVector; + cPhysics["Velocity"] = inOutVelocity; + (bool)cPhysics["IsOnGround"] = isOnGround; + } else { + (bool)cPhysics["IsOnGround"] = false; + } } else if (Collision::AABBVsAABB(boxA, boxB, resolutionVector)) { //Enter here if boxB has no Model. (glm::vec3&)cTransform["Position"] += resolutionVector; From 428dca003daf6daa38d81e67a3a1c29727f42094 Mon Sep 17 00:00:00 2001 From: William Moberg Date: Fri, 5 Feb 2016 14:40:50 +0100 Subject: [PATCH 088/355] Tiny bug fix. --- src/Engine/Collision/Collision.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index 533fdc9b..fe4eb5e0 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -521,7 +521,6 @@ bool AABBvsTriangle(const AABB& box, if (!isOnGround) { boxVelocity = boxVelocity - glm::dot(boxVelocity, projNorm) * projNorm; } - isOnGround = false; } return true; } From fe6fd0bbe35005f87f32dbd3853193423229c748 Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Fri, 5 Feb 2016 15:15:04 +0100 Subject: [PATCH 089/355] PickupSpawnSystem now spawns a new HealthPickup after the respawnTimer is up. Added HealthPickup.xml entity. Event PickupSpawned now gets published when a new HealthPickup spawns. Player now gains health as he picks up the HealthPickup. --- include/Engine/Core/EPickupSpawned.h | 2 +- include/Engine/Core/EPickupTaken.h | 19 -- include/Game/Systems/PickupSpawnSystem.h | 16 ++ resources/Schema/Components.xsd | 2 +- resources/Schema/Components/HealthPickup.xml | 4 + resources/Schema/Components/HealthPickup.xsd | 18 ++ resources/Schema/Components/PickupSpawn.xml | 2 - resources/Schema/Components/PickupSpawn.xsd | 11 - resources/Schema/Entities/CapturePoint.xml | 2 +- resources/Schema/Entities/HealthPickup.xml | 18 ++ .../Schema/Entities/HealthPickupTest.xml | 257 ++++++++++++++++++ src/Game/Game.cpp | 2 + src/Game/Systems/PickupSpawnSystem.cpp | 50 ++++ 13 files changed, 368 insertions(+), 35 deletions(-) delete mode 100644 include/Engine/Core/EPickupTaken.h create mode 100644 resources/Schema/Components/HealthPickup.xml create mode 100644 resources/Schema/Components/HealthPickup.xsd delete mode 100644 resources/Schema/Components/PickupSpawn.xml delete mode 100644 resources/Schema/Components/PickupSpawn.xsd create mode 100644 resources/Schema/Entities/HealthPickup.xml create mode 100644 resources/Schema/Entities/HealthPickupTest.xml diff --git a/include/Engine/Core/EPickupSpawned.h b/include/Engine/Core/EPickupSpawned.h index acb6776e..dc3bc632 100644 --- a/include/Engine/Core/EPickupSpawned.h +++ b/include/Engine/Core/EPickupSpawned.h @@ -10,7 +10,7 @@ namespace Events struct PickupSpawned : Event { EntityID PickupID; - EntityWrapper Spawner; + EntityWrapper Pickup; }; } diff --git a/include/Engine/Core/EPickupTaken.h b/include/Engine/Core/EPickupTaken.h deleted file mode 100644 index e06fd974..00000000 --- a/include/Engine/Core/EPickupTaken.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef EPickupTaken_h__ -#define EPickupTaken_h__ - -#include "Core/Event.h" -#include "Core/EntityWrapper.h" - -namespace Events -{ - -struct PickupTaken : Event -{ - EntityID PickupID; - EntityWrapper Spawner; - EntityWrapper Player; -}; - -} - -#endif \ No newline at end of file diff --git a/include/Game/Systems/PickupSpawnSystem.h b/include/Game/Systems/PickupSpawnSystem.h index 99dad0aa..8ae07265 100644 --- a/include/Game/Systems/PickupSpawnSystem.h +++ b/include/Game/Systems/PickupSpawnSystem.h @@ -9,9 +9,25 @@ #include "Rendering/ESetCamera.h" #include "Core/ConfigFile.h" #include "Core/EPickupSpawned.h" +#include "Core/EPlayerHealthPickup.h"; +#include "Engine/Collision/ETrigger.h" + +#include "Common.h" +#include class PickupSpawnSystem : public ImpureSystem { +public: + PickupSpawnSystem(World* world, EventBroker* eventBroker); + + virtual void Update(double dt) override; + +private: + EventRelay m_ETriggerTouch; + bool OnTriggerTouch(Events::TriggerTouch& e); + + std::vector> m_ETriggerTouchVector; + }; #endif diff --git a/resources/Schema/Components.xsd b/resources/Schema/Components.xsd index 445d96e7..996475cf 100644 --- a/resources/Schema/Components.xsd +++ b/resources/Schema/Components.xsd @@ -29,5 +29,5 @@ - + \ No newline at end of file diff --git a/resources/Schema/Components/HealthPickup.xml b/resources/Schema/Components/HealthPickup.xml new file mode 100644 index 00000000..e9d0a23d --- /dev/null +++ b/resources/Schema/Components/HealthPickup.xml @@ -0,0 +1,4 @@ + + + 3 + \ No newline at end of file diff --git a/resources/Schema/Components/HealthPickup.xsd b/resources/Schema/Components/HealthPickup.xsd new file mode 100644 index 00000000..db9661a7 --- /dev/null +++ b/resources/Schema/Components/HealthPickup.xsd @@ -0,0 +1,18 @@ + + + + + + + + A Health Pickup + + + + + The respawn timer for a health pickup + + + + + diff --git a/resources/Schema/Components/PickupSpawn.xml b/resources/Schema/Components/PickupSpawn.xml deleted file mode 100644 index f8ce1225..00000000 --- a/resources/Schema/Components/PickupSpawn.xml +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/resources/Schema/Components/PickupSpawn.xsd b/resources/Schema/Components/PickupSpawn.xsd deleted file mode 100644 index 7ab90407..00000000 --- a/resources/Schema/Components/PickupSpawn.xsd +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - Combined with a Spawner, defines a spawn point for a pickup - - - diff --git a/resources/Schema/Entities/CapturePoint.xml b/resources/Schema/Entities/CapturePoint.xml index 9b3c5036..9f33c4de 100644 --- a/resources/Schema/Entities/CapturePoint.xml +++ b/resources/Schema/Entities/CapturePoint.xml @@ -5,7 +5,7 @@ - C:\Users\123456\Workspace\TacticalZ\assets\Models\Core\UnitSphere.mesh + Models/Core/UnitSphere.mesh diff --git a/resources/Schema/Entities/HealthPickup.xml b/resources/Schema/Entities/HealthPickup.xml new file mode 100644 index 00000000..f1b787f6 --- /dev/null +++ b/resources/Schema/Entities/HealthPickup.xml @@ -0,0 +1,18 @@ + + + + + + + + Models/Core/UnitSphere.mesh + + + + + + + + + + diff --git a/resources/Schema/Entities/HealthPickupTest.xml b/resources/Schema/Entities/HealthPickupTest.xml new file mode 100644 index 00000000..6a368006 --- /dev/null +++ b/resources/Schema/Entities/HealthPickupTest.xml @@ -0,0 +1,257 @@ + + + + + + + + + + + + Models\MapVersion1.mesh + + + + + + + + + 2 + + + Models/DirectionalLightWidget.mesh + false + + + + + + + + + + + + + 8 + 2.7999999523162842 + + + + + + + + + + + 8 + 2.7999999523162842 + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + false + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + false + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Models/Core/UnitSphere.mesh + + + + + + + + + + + diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index f5afcaeb..9e803e9e 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -10,6 +10,7 @@ #include "Systems/PlayerSpawnSystem.h" #include "Core/EntityFileWriter.h" #include "Game/Systems/CapturePointSystem.h" +#include "Game/Systems/PickupSpawnSystem.h" #include "Game/Systems/WeaponSystem.h" #include "Game/Systems/PlayerHUD.h" #include "Game/Systems/LifetimeSystem.h" @@ -91,6 +92,7 @@ Game::Game(int argc, char* argv[]) m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); + m_SystemPipeline->AddSystem(updateOrderLevel); // Populate Octree with collidables ++updateOrderLevel; m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeCollision, "Collidable"); diff --git a/src/Game/Systems/PickupSpawnSystem.cpp b/src/Game/Systems/PickupSpawnSystem.cpp index 3b758764..28f0ca86 100644 --- a/src/Game/Systems/PickupSpawnSystem.cpp +++ b/src/Game/Systems/PickupSpawnSystem.cpp @@ -1 +1,51 @@ #include "Systems/PickupSpawnSystem.h" + +PickupSpawnSystem::PickupSpawnSystem(World* m_World, EventBroker* eventBroker) + : System(m_World, eventBroker) +{ + EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &PickupSpawnSystem::OnTriggerTouch); +} + +void PickupSpawnSystem::Update(double dt) +{ + for (auto &healthPickupPosition : m_ETriggerTouchVector) { + //set the double timer value (1) + std::get<1>(healthPickupPosition) -= dt; + if (std::get<1>(healthPickupPosition) < 0) { + //spawn and delete the vector item + auto entityFile = ResourceManager::Load("Schema/Entities/HealthPickup.xml"); + EntityFileParser parser(entityFile); + EntityID healthPickupID = parser.MergeEntities(m_World); + + //let the world know a pickup has spawned (graphics effects, etc) + Events::PickupSpawned ePickupSpawned; + ePickupSpawned.PickupID = healthPickupID; + ePickupSpawned.Pickup = EntityWrapper(m_World, healthPickupID); + m_EventBroker->Publish(ePickupSpawned); + + //erase the current element (healthPickupPosition) + m_ETriggerTouchVector.erase(std::remove(m_ETriggerTouchVector.begin(), m_ETriggerTouchVector.end(),healthPickupPosition), m_ETriggerTouchVector.end()); + break; + } + } +} + + +bool PickupSpawnSystem::OnTriggerTouch(Events::TriggerTouch& e) +{ + if (!e.Trigger.HasComponent("HealthPickup")) { + return false; + } + //personEntered = e.Entity, thingEntered = e.Trigger + Events::PlayerHealthPickup ePlayerHealthPickup; + ePlayerHealthPickup.HealthAmount = 30.0f; + ePlayerHealthPickup.PlayerHealedID = e.Entity.ID; + m_EventBroker->Publish(ePlayerHealthPickup); + + //copy the position to a vector -> respawntimer in ["HealthPickup"]["RespawnTimer"] + m_ETriggerTouchVector.push_back(std::make_tuple((glm::vec3)e.Trigger["Transform"]["Position"], e.Trigger["HealthPickup"]["RespawnTimer"])); + + //delete the healthpickup + m_World->DeleteEntity(e.Trigger.ID); + return true; +} From 7641ba49c751427fd419cafc59f86ab7a4b62052 Mon Sep 17 00:00:00 2001 From: William Moberg Date: Fri, 5 Feb 2016 15:16:24 +0100 Subject: [PATCH 090/355] Weapon doesn't explode in first person. --- resources/Schema/Entities/Player.xml | 7 ------- 1 file changed, 7 deletions(-) diff --git a/resources/Schema/Entities/Player.xml b/resources/Schema/Entities/Player.xml index fe24adcc..384ffb80 100644 --- a/resources/Schema/Entities/Player.xml +++ b/resources/Schema/Entities/Player.xml @@ -104,13 +104,6 @@ - - true - - 3.7999999523162842 - - true - Models/AssaultWeaponRed.mesh From 254239751188f582215b47cc287508723ca0998e Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Fri, 5 Feb 2016 15:35:51 +0100 Subject: [PATCH 091/355] Miscellaneous small fixes: For Tests, CapturePoint xml file, HealthSystem, DashAbility xml file. --- include/Engine/Core/EPlayerHealthPickup.h | 12 +++--- include/Game/Systems/HealthSystem.h | 2 +- resources/Schema/Components/DashAbility.xml | 4 +- resources/Schema/Entities/CapturePoint.xml | 2 +- resources/Schema/Entities/Player.xml | 7 ---- src/Game/Systems/HealthSystem.cpp | 41 +++------------------ src/Tests/CapturePointTest.cpp | 8 ++-- src/Tests/CollisionTest.cpp | 2 +- src/Tests/HealthSystemTest.cpp | 26 ++++++------- 9 files changed, 32 insertions(+), 72 deletions(-) diff --git a/include/Engine/Core/EPlayerHealthPickup.h b/include/Engine/Core/EPlayerHealthPickup.h index f3158f92..7d44e544 100644 --- a/include/Engine/Core/EPlayerHealthPickup.h +++ b/include/Engine/Core/EPlayerHealthPickup.h @@ -2,16 +2,16 @@ #define EPlayerHealthPickup_h__ #include "EventBroker.h" -#include "../Core/Entity.h" +#include "../Core/EntityWrapper.h" namespace Events { -struct PlayerHealthPickup : Event -{ - double HealthAmount; - EntityID PlayerHealedID; -}; + struct PlayerHealthPickup : Event + { + EntityWrapper Player; + double HealthAmount; + }; } diff --git a/include/Game/Systems/HealthSystem.h b/include/Game/Systems/HealthSystem.h index 3b069349..46f24630 100644 --- a/include/Game/Systems/HealthSystem.h +++ b/include/Game/Systems/HealthSystem.h @@ -26,7 +26,7 @@ private: EventRelay m_EPlayerDamage; bool HealthSystem::OnPlayerDamaged(Events::PlayerDamage& e); EventRelay m_EPlayerHealthPickup; - bool HealthSystem::OnPlayerHealthPickup(const Events::PlayerHealthPickup& e); + bool HealthSystem::OnPlayerHealthPickup(Events::PlayerHealthPickup& e); //vector which will keep track of health changes std::vector> m_DeltaHealthVector; diff --git a/resources/Schema/Components/DashAbility.xml b/resources/Schema/Components/DashAbility.xml index 25b9e19a..a313c447 100644 --- a/resources/Schema/Components/DashAbility.xml +++ b/resources/Schema/Components/DashAbility.xml @@ -1,4 +1,4 @@ - + 2.0 - \ No newline at end of file + \ No newline at end of file diff --git a/resources/Schema/Entities/CapturePoint.xml b/resources/Schema/Entities/CapturePoint.xml index 9b3c5036..9f33c4de 100644 --- a/resources/Schema/Entities/CapturePoint.xml +++ b/resources/Schema/Entities/CapturePoint.xml @@ -5,7 +5,7 @@ - C:\Users\123456\Workspace\TacticalZ\assets\Models\Core\UnitSphere.mesh + Models/Core/UnitSphere.mesh diff --git a/resources/Schema/Entities/Player.xml b/resources/Schema/Entities/Player.xml index fe24adcc..384ffb80 100644 --- a/resources/Schema/Entities/Player.xml +++ b/resources/Schema/Entities/Player.xml @@ -104,13 +104,6 @@ - - true - - 3.7999999523162842 - - true - Models/AssaultWeaponRed.mesh diff --git a/src/Game/Systems/HealthSystem.cpp b/src/Game/Systems/HealthSystem.cpp index 9e118070..91cae148 100644 --- a/src/Game/Systems/HealthSystem.cpp +++ b/src/Game/Systems/HealthSystem.cpp @@ -11,38 +11,6 @@ HealthSystem::HealthSystem(World* m_World, EventBroker* eventBroker) void HealthSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) { - //if entityID of health is 9 then the players ID is also 9 (player,health are connected to the same entity) - double maxHealth = (double)component["MaxHealth"]; - - //process the DeltaHealthVector and change the entitys health accordingly - for (size_t i = m_DeltaHealthVector.size(); i > 0; i--) - { - auto deltaHP = m_DeltaHealthVector[i - 1]; - //if we have a healthchange for the current player and health is greater than 0, then apply it - if (std::get<0>(deltaHP) == component.EntityID && (double)component["Health"] > 0.0f) { - //get the deltaHP value from the tuple and make sure you dont get more than maxHealth - double newHealth = std::min((double)component["Health"] + (double)std::get<1>(deltaHP), maxHealth); - component["Health"] = newHealth; - m_DeltaHealthVector.erase(m_DeltaHealthVector.begin() + i - 1); - //check if health is <= 0 - if ((double)component["Health"] <= 0.0f) { - component["Health"] = 0.0; - //publish death event - Events::PlayerDeath e; - e.PlayerID = component.EntityID; - m_EventBroker->Publish(e); - //clear the remaining hpDeltas for the dead player - for (size_t j = m_DeltaHealthVector.size(); j > 0; j--) - { - if (std::get<0>(m_DeltaHealthVector[j - 1]) == component.EntityID) - m_DeltaHealthVector.erase(m_DeltaHealthVector.begin() + j - 1); - } - //delete the player and break the loop - m_World->DeleteEntity(entity.ID); - break; - } - } - } } bool HealthSystem::OnPlayerDamaged(Events::PlayerDamage& e) @@ -58,10 +26,13 @@ bool HealthSystem::OnPlayerDamaged(Events::PlayerDamage& e) return true; } -bool HealthSystem::OnPlayerHealthPickup(const Events::PlayerHealthPickup& e) +bool HealthSystem::OnPlayerHealthPickup(Events::PlayerHealthPickup& e) { - //save the changed HP to a vector. it will be taken care of in UpdateComponent - m_DeltaHealthVector.push_back(std::make_tuple(e.PlayerHealedID, e.HealthAmount)); + ComponentWrapper cHealth = e.Player["Health"]; + double& health = cHealth["Health"]; + //NOTE: its possible to get more than MaxHealth health + health += e.HealthAmount; + return true; } diff --git a/src/Tests/CapturePointTest.cpp b/src/Tests/CapturePointTest.cpp index ffb01030..2c7bf430 100644 --- a/src/Tests/CapturePointTest.cpp +++ b/src/Tests/CapturePointTest.cpp @@ -255,14 +255,14 @@ void CapturePointTest::TestSetup8() } void CapturePointTest::DoTouchEvent(EntityID whoDidSomething, EntityID onWhatObject) { Events::TriggerTouch touchEvent; - touchEvent.Entity = whoDidSomething; - touchEvent.Trigger = onWhatObject; + touchEvent.Entity = EntityWrapper(m_World, whoDidSomething); + touchEvent.Trigger = EntityWrapper(m_World, onWhatObject); m_EventBroker->Publish(touchEvent); } void CapturePointTest::DoLeaveEvent(EntityID whoDidSomething, EntityID onWhatObject) { Events::TriggerLeave leaveEvent; - leaveEvent.Entity = whoDidSomething; - leaveEvent.Trigger = onWhatObject; + leaveEvent.Entity = EntityWrapper(m_World, whoDidSomething); + leaveEvent.Trigger = EntityWrapper(m_World, onWhatObject); m_EventBroker->Publish(leaveEvent); } void CapturePointTest::TestSuccess1() { diff --git a/src/Tests/CollisionTest.cpp b/src/Tests/CollisionTest.cpp index 67b6ce19..6cb6c88b 100644 --- a/src/Tests/CollisionTest.cpp +++ b/src/Tests/CollisionTest.cpp @@ -29,7 +29,7 @@ void RayTest(std::string fileName) { Ray ray(glm::vec3(-50, 0, 0), glm::vec3(1, 0, 0)); //using a - here, else we have to init the renderingsystem + //here, else we have to init the renderingsystem ResourceManager::RegisterType("RawModel"); auto unitBox = ResourceManager::Load(fileName); BOOST_REQUIRE(unitBox != nullptr); diff --git a/src/Tests/HealthSystemTest.cpp b/src/Tests/HealthSystemTest.cpp index bdd9ba4b..36608f8f 100644 --- a/src/Tests/HealthSystemTest.cpp +++ b/src/Tests/HealthSystemTest.cpp @@ -48,42 +48,38 @@ GameHealthSystemTest::GameHealthSystemTest() fp.MergeEntities(m_World); // Create system pipeline - m_SystemPipeline = new SystemPipeline(m_World,m_EventBroker); + m_SystemPipeline = new SystemPipeline(m_World, m_EventBroker); m_SystemPipeline->AddSystem(0); //The Test //create entity which has transform,player,model,health in it. i.e. is a player EntityID playerID = m_World->CreateEntity(); - ComponentWrapper transform = m_World->AttachComponent(playerID, "Transform"); - ComponentWrapper model = m_World->AttachComponent(playerID, "Model"); - model["Resource"] = "Models/Core/UnitSphere.mesh"; // 360NoScope UnitSphere ComponentWrapper player = m_World->AttachComponent(playerID, "Player"); ComponentWrapper health = m_World->AttachComponent(playerID, "Health"); healthsID = playerID; - double currentHealth = (double)m_World->GetComponent(healthsID, "Health")["Health"]; + + EntityID playerID2 = m_World->CreateEntity(); + ComponentWrapper player2 = m_World->AttachComponent(playerID2, "Player"); + ComponentWrapper health2 = m_World->AttachComponent(playerID2, "Health"); //heal player with 40 Events::PlayerHealthPickup e3; e3.HealthAmount = 40.0f; - e3.PlayerHealedID = healthsID; + e3.Player = EntityWrapper(m_World, player.EntityID); m_EventBroker->Publish(e3); + //damage player with 50 Events::PlayerDamage e; - e.DamageAmount = 50.0f; - e.PlayerDamagedID = healthsID; + e.Damage = 50.0f; + e.Player = EntityWrapper(m_World, player.EntityID); m_EventBroker->Publish(e); + //heal some other player with 40 Events::PlayerHealthPickup e2; e2.HealthAmount = 40.0f; - e2.PlayerHealedID = healthsID + 1; + e2.Player = EntityWrapper(m_World, player2.EntityID); m_EventBroker->Publish(e2); - EntityID playerID2 = m_World->CreateEntity(); - ComponentWrapper transform2 = m_World->AttachComponent(playerID2, "Transform"); - ComponentWrapper model2 = m_World->AttachComponent(playerID2, "Model"); - model2["Resource"] = "Models/Core/UnitSphere.mesh"; // 360NoScope UnitSphere - ComponentWrapper player2 = m_World->AttachComponent(playerID2, "Player"); - ComponentWrapper health2 = m_World->AttachComponent(playerID2, "Health"); //END TEST } From 66f442f1afbe6e6a0ce76bb461d1d20fdd19368a Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Fri, 5 Feb 2016 16:13:59 +0100 Subject: [PATCH 092/355] Added HealthGain to HealthPickup component. Changed PickupSpawnSystem so it copies the values from the old to the new entity. --- include/Game/Systems/PickupSpawnSystem.h | 14 +++-------- resources/Schema/Components/HealthPickup.xml | 1 + resources/Schema/Components/HealthPickup.xsd | 3 +++ .../Schema/Entities/HealthPickupTest.xml | 14 ----------- src/Game/Systems/PickupSpawnSystem.cpp | 25 +++++++++++++------ 5 files changed, 26 insertions(+), 31 deletions(-) diff --git a/include/Game/Systems/PickupSpawnSystem.h b/include/Game/Systems/PickupSpawnSystem.h index 8ae07265..fbb2f082 100644 --- a/include/Game/Systems/PickupSpawnSystem.h +++ b/include/Game/Systems/PickupSpawnSystem.h @@ -2,16 +2,12 @@ #define PickupSpawnSystem_h__ #include "Core/System.h" -#include "Input/EInputCommand.h" -#include "Systems/SpawnerSystem.h" -#include "Events/ESpawnerSpawn.h" -#include "Core/EPlayerSpawned.h" -#include "Rendering/ESetCamera.h" -#include "Core/ConfigFile.h" +#include "Core/Transform.h" +#include "Core/ResourceManager.h" +#include "Core/EntityFileParser.h" #include "Core/EPickupSpawned.h" #include "Core/EPlayerHealthPickup.h"; #include "Engine/Collision/ETrigger.h" - #include "Common.h" #include @@ -26,8 +22,6 @@ private: EventRelay m_ETriggerTouch; bool OnTriggerTouch(Events::TriggerTouch& e); - std::vector> m_ETriggerTouchVector; - - + std::vector> m_ETriggerTouchVector; }; #endif diff --git a/resources/Schema/Components/HealthPickup.xml b/resources/Schema/Components/HealthPickup.xml index e9d0a23d..1c9ee0f4 100644 --- a/resources/Schema/Components/HealthPickup.xml +++ b/resources/Schema/Components/HealthPickup.xml @@ -1,4 +1,5 @@ 3 + 30 \ No newline at end of file diff --git a/resources/Schema/Components/HealthPickup.xsd b/resources/Schema/Components/HealthPickup.xsd index db9661a7..c5fae00f 100644 --- a/resources/Schema/Components/HealthPickup.xsd +++ b/resources/Schema/Components/HealthPickup.xsd @@ -12,6 +12,9 @@ The respawn timer for a health pickup + + How much health the player will get when he picks the healthPickup up + diff --git a/resources/Schema/Entities/HealthPickupTest.xml b/resources/Schema/Entities/HealthPickupTest.xml index 6a368006..97fd3f4d 100644 --- a/resources/Schema/Entities/HealthPickupTest.xml +++ b/resources/Schema/Entities/HealthPickupTest.xml @@ -238,20 +238,6 @@ - - - - - - Models/Core/UnitSphere.mesh - - - - - - - - diff --git a/src/Game/Systems/PickupSpawnSystem.cpp b/src/Game/Systems/PickupSpawnSystem.cpp index 28f0ca86..558aef14 100644 --- a/src/Game/Systems/PickupSpawnSystem.cpp +++ b/src/Game/Systems/PickupSpawnSystem.cpp @@ -9,9 +9,9 @@ PickupSpawnSystem::PickupSpawnSystem(World* m_World, EventBroker* eventBroker) void PickupSpawnSystem::Update(double dt) { for (auto &healthPickupPosition : m_ETriggerTouchVector) { - //set the double timer value (1) - std::get<1>(healthPickupPosition) -= dt; - if (std::get<1>(healthPickupPosition) < 0) { + //set the double timer value (value 3) + std::get<3>(healthPickupPosition) -= dt; + if (std::get<3>(healthPickupPosition) < 0) { //spawn and delete the vector item auto entityFile = ResourceManager::Load("Schema/Entities/HealthPickup.xml"); EntityFileParser parser(entityFile); @@ -23,8 +23,14 @@ void PickupSpawnSystem::Update(double dt) ePickupSpawned.Pickup = EntityWrapper(m_World, healthPickupID); m_EventBroker->Publish(ePickupSpawned); + //set values from the old entity to the new entity + auto& newHealthPickupEntity = EntityWrapper(m_World, healthPickupID); + newHealthPickupEntity["Transform"]["Position"] = std::get<0>(healthPickupPosition); + newHealthPickupEntity["HealthPickup"]["HealthGain"] = std::get<1>(healthPickupPosition); + newHealthPickupEntity["HealthPickup"]["RespawnTimer"] = std::get<2>(healthPickupPosition); + //erase the current element (healthPickupPosition) - m_ETriggerTouchVector.erase(std::remove(m_ETriggerTouchVector.begin(), m_ETriggerTouchVector.end(),healthPickupPosition), m_ETriggerTouchVector.end()); + m_ETriggerTouchVector.erase(std::remove(m_ETriggerTouchVector.begin(), m_ETriggerTouchVector.end(), healthPickupPosition), m_ETriggerTouchVector.end()); break; } } @@ -38,12 +44,17 @@ bool PickupSpawnSystem::OnTriggerTouch(Events::TriggerTouch& e) } //personEntered = e.Entity, thingEntered = e.Trigger Events::PlayerHealthPickup ePlayerHealthPickup; - ePlayerHealthPickup.HealthAmount = 30.0f; + ePlayerHealthPickup.HealthAmount = e.Trigger["HealthPickup"]["HealthGain"]; ePlayerHealthPickup.PlayerHealedID = e.Entity.ID; m_EventBroker->Publish(ePlayerHealthPickup); - //copy the position to a vector -> respawntimer in ["HealthPickup"]["RespawnTimer"] - m_ETriggerTouchVector.push_back(std::make_tuple((glm::vec3)e.Trigger["Transform"]["Position"], e.Trigger["HealthPickup"]["RespawnTimer"])); + //copy position, healthgain, respawntimer (twice since one of the values will be counted down to 0, the other will be set in the new object) + //we need to copy all values since each value can be different for each healthPickup + m_ETriggerTouchVector.push_back(std::make_tuple( + (glm::vec3)e.Trigger["Transform"]["Position"], + e.Trigger["HealthPickup"]["HealthGain"], + e.Trigger["HealthPickup"]["RespawnTimer"], + e.Trigger["HealthPickup"]["RespawnTimer"])); //delete the healthpickup m_World->DeleteEntity(e.Trigger.ID); From 3e2afd7bf29773d6a8d3ff503321a1ad25d7d5d7 Mon Sep 17 00:00:00 2001 From: stiffly Date: Fri, 5 Feb 2016 16:37:56 +0100 Subject: [PATCH 093/355] Added dash sound --- assets | 2 +- include/Game/Events/EDashAbility.h | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) create mode 100644 include/Game/Events/EDashAbility.h diff --git a/assets b/assets index a7387630..cfeeb1f8 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit a73876309264a0751e3a46f15020dd46d5a67f98 +Subproject commit cfeeb1f880e19356477a703da92204eede09db5d diff --git a/include/Game/Events/EDashAbility.h b/include/Game/Events/EDashAbility.h new file mode 100644 index 00000000..62a2b935 --- /dev/null +++ b/include/Game/Events/EDashAbility.h @@ -0,0 +1,13 @@ +#ifndef Events_DashAbility_h__ +#define Events_DashAbility_h__ + +#include "Core/Event.h" + +namespace Events +{ + +struct DashAbility : public Event { }; + +} + +#endif \ No newline at end of file From fbdaf92953569db374bbd96dccafaa1e036b5869 Mon Sep 17 00:00:00 2001 From: stiffly Date: Fri, 5 Feb 2016 16:39:23 +0100 Subject: [PATCH 094/355] Started refactoring. Put player walk logic in a designated sound system. --- .../Engine/Input/FirstPersonInputController.h | 4 + .../Sound/{SoundSystem.h => SoundManager.h} | 89 +++--- include/Game/Game.h | 5 +- include/Game/Systems/SoundSystem.h | 31 ++ .../{SoundSystem.cpp => SoundManager.cpp} | 287 +++++++----------- src/Game/Game.cpp | 8 +- src/Game/Systems/SoundSystem.cpp | 73 +++++ 7 files changed, 281 insertions(+), 216 deletions(-) rename include/Engine/Sound/{SoundSystem.h => SoundManager.h} (71%) create mode 100644 include/Game/Systems/SoundSystem.h rename src/Engine/Sound/{SoundSystem.cpp => SoundManager.cpp} (65%) create mode 100644 src/Game/Systems/SoundSystem.cpp diff --git a/include/Engine/Input/FirstPersonInputController.h b/include/Engine/Input/FirstPersonInputController.h index 2bbd768d..f3b0a17a 100644 --- a/include/Engine/Input/FirstPersonInputController.h +++ b/include/Engine/Input/FirstPersonInputController.h @@ -4,6 +4,7 @@ #include "../GLM.h" #include "../Core/InputController.h" #include "../Core/ELockMouse.h" +#include "../Game/Events/EDashAbility.h" #include "InputHandler.h" template @@ -230,6 +231,9 @@ void FirstPersonInputController::AssaultDashCheck(double dt, bool m_AssaultDashDoubleTapped = true; m_AssaultDashDoubleTapDeltaTime = 0.f; m_AssaultDashCoolDownTimer = assaultDashCoolDownMaxTimer; + + Events::DashAbility e; + m_EventBroker->Publish(e); } #endif \ No newline at end of file diff --git a/include/Engine/Sound/SoundSystem.h b/include/Engine/Sound/SoundManager.h similarity index 71% rename from include/Engine/Sound/SoundSystem.h rename to include/Engine/Sound/SoundManager.h index 51f80427..a9fb23a9 100644 --- a/include/Engine/Sound/SoundSystem.h +++ b/include/Engine/Sound/SoundManager.h @@ -1,5 +1,5 @@ -#ifndef SoundSystem_h__ -#define SoundSystem_h__ +#ifndef SoundManager_h__ +#define SoundManager_h__ #include #include @@ -34,6 +34,7 @@ #include "Collision/ETrigger.h" #include "Core/EPause.h" #include "Game/Events/EDoubleJump.h" +#include "Game/Events/EDashAbility.h" typedef std::pair> QueuedBuffers; @@ -51,14 +52,30 @@ struct Source SoundType Type; }; -class SoundSystem +class SoundManager { public: - SoundSystem() { } - SoundSystem(World* world, EventBroker* eventBroker, bool editorMode); - ~SoundSystem(); + SoundManager() { } + SoundManager(World* world, EventBroker* eventBroker, bool editorMode); + ~SoundManager(); // Update emitters / listener void Update(double dt); + +protected: + // Specific logic + void playSound(Source* source); + // Need to be the same format (sample rate etc) + void playQueue(QueuedBuffers qb); + void stopSound(Source* source); + void playerJumps(); + void playerStep(double dt); + EntityID createChildEmitter(); + + // Logic + World* m_World = nullptr; + EventBroker* m_EventBroker = nullptr; + std::unordered_map m_Sources; + private: // Help functions for working with OpenaAL void setListenerPos(glm::vec3 pos) { alListener3f(AL_POSITION, pos.x, pos.y, pos.z); }; @@ -81,75 +98,63 @@ private: void setGain(Source* source, float gain); void setSoundProperties(Source* source, ComponentWrapper* soundComponent); - // Specific logic - void playSound(Source* source); - // Need to be the same format (sample rate etc) - void playQueue(QueuedBuffers qb); - void stopSound(Source* source); - void playerDamaged(); - void playerShot(); - void playerJumps(); - void playerStep(double dt); + // OpenAL system variables ALCdevice* m_ALCdevice = nullptr; ALCcontext* m_ALCcontext = nullptr; - // Logic - World* m_World = nullptr; - EventBroker* m_EventBroker = nullptr; - std::unordered_map m_Sources; + float m_BGMVolumeChannel = 1.0f; float m_SFXVolumeChannel = 1.0f; bool m_EditorEnabled = false; - const double m_PlayerFootstepInterval = 1.0; - double m_TimeSinceLastFootstep = 0; EntityID m_LocalPlayer = EntityID_Invalid; - bool m_LeftFoot = false; std::default_random_engine generator; // Events - EventRelay m_EPlaySoundOnEntity; + EventRelay m_EPlaySoundOnEntity; bool OnPlaySoundOnEntity(const Events::PlaySoundOnEntity &e); - EventRelay m_EPlaySoundOnPosition; + EventRelay m_EPlaySoundOnPosition; bool OnPlaySoundOnPosition(const Events::PlaySoundOnPosition &e); - EventRelay m_EPlayBackgroundMusic; + EventRelay m_EPlayBackgroundMusic; bool OnPlayBackgroundMusic(const Events::PlayBackgroundMusic &e); - EventRelay m_EPauseSound; + EventRelay m_EPauseSound; bool OnPauseSound(const Events::PauseSound &e); - EventRelay m_EStopSound; + EventRelay m_EStopSound; bool OnStopSound(const Events::StopSound &e); - EventRelay m_EContinueSound; + EventRelay m_EContinueSound; bool OnContinueSound(const Events::ContinueSound &e); - EventRelay m_ESetBGMGain; + EventRelay m_ESetBGMGain; bool OnSetBGMGain(const Events::SetBGMGain &e); - EventRelay m_ESetSFXGain; + EventRelay m_ESetSFXGain; bool OnSetSFXGain(const Events::SetSFXGain &e); - EventRelay m_EShoot; + EventRelay m_EShoot; bool OnShoot(const Events::Shoot &e); - EventRelay m_EPlayerSpawned; + EventRelay m_EPlayerSpawned; bool OnPlayerSpawned(const Events::PlayerSpawned &e); - EventRelay m_EInputCommand; + EventRelay m_EInputCommand; bool OnInputCommand(const Events::InputCommand &e); - EventRelay m_ECaptured; + EventRelay m_ECaptured; bool OnCaptured(const Events::Captured &e); - EventRelay m_EPlayerDamage; + EventRelay m_EPlayerDamage; bool OnPlayerDamage(const Events::PlayerDamage &e); - EventRelay m_EPlayerDeath; + EventRelay m_EPlayerDeath; bool OnPlayerDeath(const Events::PlayerDeath &e); - EventRelay m_EPlayerHealthPickup; + EventRelay m_EPlayerHealthPickup; bool OnPlayerHealthPickup(const Events::PlayerHealthPickup &e); - EventRelay m_EComponentAttached; + EventRelay m_EComponentAttached; bool OnComponentAttached(const Events::ComponentAttached &e); - EventRelay m_ETriggerTouch; + EventRelay m_ETriggerTouch; bool OnTriggerTouch(const Events::TriggerTouch &e); - EventRelay m_EPause; + EventRelay m_EPause; bool OnPause(const Events::Pause &e); - EventRelay m_EResume; + EventRelay m_EResume; bool OnResume(const Events::Resume &e); - EventRelay m_EDoubleJump; + EventRelay m_EDoubleJump; bool OnDoubleJump(const Events::DoubleJump &e); + EventRelay m_EDashAbility; + bool OnDashAbility(const Events::DashAbility &e); diff --git a/include/Game/Game.h b/include/Game/Game.h index 37267a68..b6a2c0d3 100644 --- a/include/Game/Game.h +++ b/include/Game/Game.h @@ -30,7 +30,8 @@ #include "Network/Client.h" // Sound -#include "Sound/SoundSystem.h" +//#include "Sound/SoundManager.h" +#include "Systems/SoundSystem.h" class Game { @@ -64,7 +65,7 @@ private: bool m_IsClientOrServer = false; // Sound - SoundSystem* m_SoundSystem; + SoundManager* m_SoundManager; //EventRelay m_EInputCommand; //bool debugOnInputCommand(const Events::InputCommand& e); diff --git a/include/Game/Systems/SoundSystem.h b/include/Game/Systems/SoundSystem.h new file mode 100644 index 00000000..33dbf1fc --- /dev/null +++ b/include/Game/Systems/SoundSystem.h @@ -0,0 +1,31 @@ +#ifndef Systems_SoundSystem_h__ +#define Systems_SoundSystem_h__ + +#include "../Engine/Core/System.h" +#include "../Engine/Sound/SoundManager.h" +#include "../Engine/Core/EPlayerSpawned.h" + + +class SoundSystem : public PureSystem, ImpureSystem, SoundManager +{ +public: + SoundSystem(World* world, EventBroker* eventbroker); + virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& cComponent, double dt) override; + virtual void Update(double dt) override; +private: + void playerStep(double dt); + EntityWrapper m_LocalPlayer = EntityWrapper(); + + World* m_World = nullptr; + EventBroker* m_EventBroker = nullptr; + + // TODO: WIP Update this + double m_TimeSinceLastFootstep = 0.0; + const double m_PlayerFootstepInterval = 1.0; + bool m_LeftFoot = false; + + EventRelay m_EPlayerSpawned; + bool OnPlayerSpawned(const Events::PlayerSpawned &e); +}; + +#endif diff --git a/src/Engine/Sound/SoundSystem.cpp b/src/Engine/Sound/SoundManager.cpp similarity index 65% rename from src/Engine/Sound/SoundSystem.cpp rename to src/Engine/Sound/SoundManager.cpp index 3045b1f4..3cec4deb 100644 --- a/src/Engine/Sound/SoundSystem.cpp +++ b/src/Engine/Sound/SoundManager.cpp @@ -1,6 +1,6 @@ -#include "Sound/SoundSystem.h" +#include "Sound/SoundManager.h" -SoundSystem::SoundSystem(World* world, EventBroker* eventBroker, bool editorMode) +SoundManager::SoundManager(World* world, EventBroker* eventBroker, bool editorMode) { m_EventBroker = eventBroker; m_World = world; @@ -12,27 +12,28 @@ SoundSystem::SoundSystem(World* world, EventBroker* eventBroker, bool editorMode alDistanceModel(AL_LINEAR_DISTANCE); alDopplerFactor(1); - EVENT_SUBSCRIBE_MEMBER(m_EPlaySoundOnEntity, &SoundSystem::OnPlaySoundOnEntity); - EVENT_SUBSCRIBE_MEMBER(m_EPlaySoundOnPosition, &SoundSystem::OnPlaySoundOnPosition); - EVENT_SUBSCRIBE_MEMBER(m_EPlayBackgroundMusic, &SoundSystem::OnPlayBackgroundMusic); - EVENT_SUBSCRIBE_MEMBER(m_EStopSound, &SoundSystem::OnStopSound); - EVENT_SUBSCRIBE_MEMBER(m_EPauseSound, &SoundSystem::OnPauseSound); - EVENT_SUBSCRIBE_MEMBER(m_EContinueSound, &SoundSystem::OnContinueSound); - EVENT_SUBSCRIBE_MEMBER(m_ESetBGMGain, &SoundSystem::OnSetBGMGain); - EVENT_SUBSCRIBE_MEMBER(m_ESetSFXGain, &SoundSystem::OnSetSFXGain); - EVENT_SUBSCRIBE_MEMBER(m_EShoot, &SoundSystem::OnShoot); - EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &SoundSystem::OnPlayerSpawned); - EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &SoundSystem::OnPlayerDamage); - EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &SoundSystem::OnInputCommand); - EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &SoundSystem::OnCaptured); - EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &SoundSystem::OnTriggerTouch); - EVENT_SUBSCRIBE_MEMBER(m_EPause, &SoundSystem::OnPause); - EVENT_SUBSCRIBE_MEMBER(m_EResume, &SoundSystem::OnResume); - EVENT_SUBSCRIBE_MEMBER(m_EComponentAttached, &SoundSystem::OnComponentAttached); - EVENT_SUBSCRIBE_MEMBER(m_EDoubleJump, &SoundSystem::OnDoubleJump); + EVENT_SUBSCRIBE_MEMBER(m_EPlaySoundOnEntity, &SoundManager::OnPlaySoundOnEntity); + EVENT_SUBSCRIBE_MEMBER(m_EPlaySoundOnPosition, &SoundManager::OnPlaySoundOnPosition); + EVENT_SUBSCRIBE_MEMBER(m_EPlayBackgroundMusic, &SoundManager::OnPlayBackgroundMusic); + EVENT_SUBSCRIBE_MEMBER(m_EStopSound, &SoundManager::OnStopSound); + EVENT_SUBSCRIBE_MEMBER(m_EPauseSound, &SoundManager::OnPauseSound); + EVENT_SUBSCRIBE_MEMBER(m_EContinueSound, &SoundManager::OnContinueSound); + EVENT_SUBSCRIBE_MEMBER(m_ESetBGMGain, &SoundManager::OnSetBGMGain); + EVENT_SUBSCRIBE_MEMBER(m_ESetSFXGain, &SoundManager::OnSetSFXGain); + EVENT_SUBSCRIBE_MEMBER(m_EShoot, &SoundManager::OnShoot); + EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &SoundManager::OnPlayerSpawned); + EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &SoundManager::OnPlayerDamage); + EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &SoundManager::OnInputCommand); + EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &SoundManager::OnCaptured); + EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &SoundManager::OnTriggerTouch); + EVENT_SUBSCRIBE_MEMBER(m_EPause, &SoundManager::OnPause); + EVENT_SUBSCRIBE_MEMBER(m_EResume, &SoundManager::OnResume); + EVENT_SUBSCRIBE_MEMBER(m_EComponentAttached, &SoundManager::OnComponentAttached); + EVENT_SUBSCRIBE_MEMBER(m_EDoubleJump, &SoundManager::OnDoubleJump); + EVENT_SUBSCRIBE_MEMBER(m_EDashAbility, &SoundManager::OnDashAbility); } -SoundSystem::~SoundSystem() +SoundManager::~SoundManager() { stopEmitters(); // Stopps emitters deleteInactiveEmitters(); // Deletes stopped emitters @@ -47,7 +48,7 @@ SoundSystem::~SoundSystem() alcCloseDevice(m_ALCdevice); } -void SoundSystem::stopEmitters() +void SoundManager::stopEmitters() { std::unordered_map::iterator it; for (it = m_Sources.begin(); it != m_Sources.end(); it++) { @@ -57,10 +58,9 @@ void SoundSystem::stopEmitters() } } -void SoundSystem::Update(double dt) +void SoundManager::Update(double dt) { - m_EventBroker->Process(); - playerStep(dt); + m_EventBroker->Process(); deleteInactiveEmitters(); // can be optimized with "EEntityDeleted" updateEmitters(dt); updateListener(dt); @@ -70,7 +70,7 @@ void SoundSystem::Update(double dt) ImGui::SliderFloat("SFX", &m_SFXVolumeChannel, 0.0f, 1.0f, "%.3f", 1.0f); } -void SoundSystem::deleteInactiveEmitters() +void SoundManager::deleteInactiveEmitters() { std::unordered_map::iterator it; for (it = m_Sources.begin(); it != m_Sources.end();) { @@ -99,7 +99,7 @@ void SoundSystem::deleteInactiveEmitters() } } -void SoundSystem::updateEmitters(double dt) +void SoundManager::updateEmitters(double dt) { std::unordered_map::iterator it; for (it = m_Sources.begin(); it != m_Sources.end(); it++) { @@ -132,7 +132,7 @@ void SoundSystem::updateEmitters(double dt) } } -void SoundSystem::updateListener(double dt) +void SoundManager::updateListener(double dt) { // Should only be one listener. auto listenerComponents = m_World->GetComponents("Listener"); @@ -151,7 +151,7 @@ void SoundSystem::updateListener(double dt) } } -Source* SoundSystem::createSource(std::string filePath) +Source* SoundManager::createSource(std::string filePath) { ALuint alSource; alGenSources((ALuint)1, &alSource); @@ -163,13 +163,13 @@ Source* SoundSystem::createSource(std::string filePath) return source; } -void SoundSystem::playSound(Source* source) +void SoundManager::playSound(Source* source) { alSourcei(source->ALsource, AL_BUFFER, source->SoundResource->Buffer()); alSourcePlay(source->ALsource); } -void SoundSystem::playQueue(QueuedBuffers qb) +void SoundManager::playQueue(QueuedBuffers qb) { for (int i = 0; i < qb.second.size(); i++) { alSourceQueueBuffers(qb.first, 1, &qb.second[i]); @@ -177,69 +177,37 @@ void SoundSystem::playQueue(QueuedBuffers qb) alSourcePlay(qb.first); } -void SoundSystem::stopSound(Source* source) +void SoundManager::stopSound(Source* source) { alSourceStop(source->ALsource); } -void SoundSystem::playerDamaged() -{ - -} - -void SoundSystem::playerShot() -{ } - -void SoundSystem::playerJumps() +void SoundManager::playerJumps() { glm::vec3 vel = (glm::vec3)m_World->GetComponent(m_LocalPlayer, "Physics")["Velocity"]; if (vel.y == 0) { Source* source = createSource("Audio/jump/jump1.wav"); - auto emitterID = m_World->CreateEntity(m_LocalPlayer); - m_World->AttachComponent(emitterID, "Transform"); - m_World->AttachComponent(emitterID, "SoundEmitter"); source->Type = SoundType::SFX; - m_Sources[emitterID] = source; + m_Sources[createChildEmitter()] = source; playSound(source); } } -void SoundSystem::playerStep(double dt) +void SoundManager::playerStep(double dt) { - if (!m_World->ValidEntity(m_LocalPlayer)) { - return; - } - if (m_LocalPlayer == EntityID_Invalid) { - return; - } - - m_TimeSinceLastFootstep += dt; - glm::vec3 vel = (glm::vec3)m_World->GetComponent(m_LocalPlayer, "Physics")["Velocity"]; - float playerSpeed = glm::length(vel); - bool isAirborne = vel.y != 0; - if (playerSpeed > 1 && !isAirborne) { - // Player is walking - if (m_TimeSinceLastFootstep * std::min(playerSpeed, 2) > m_PlayerFootstepInterval) { - // Create footstep sound - EntityID child = m_World->CreateEntity(m_LocalPlayer); - m_World->AttachComponent(child, "Transform"); - m_World->AttachComponent(child, "SoundEmitter"); - Events::PlaySoundOnEntity e; - e.EmitterID = child; - if (m_LeftFoot) { - e.FilePath = "Audio/footstep/footstep2.wav"; - } else { - e.FilePath = "Audio/footstep/footstep3.wav"; - } - m_LeftFoot = !m_LeftFoot; - m_EventBroker->Publish(e); - m_TimeSinceLastFootstep = 0; - } - } + } -bool SoundSystem::OnPlaySoundOnEntity(const Events::PlaySoundOnEntity & e) +EntityID SoundManager::createChildEmitter() +{ + EntityID child = m_World->CreateEntity(m_LocalPlayer); + m_World->AttachComponent(child, "Transform"); + m_World->AttachComponent(child, "SoundEmitter"); + return child; +} + +bool SoundManager::OnPlaySoundOnEntity(const Events::PlaySoundOnEntity & e) { Source* source = createSource(e.FilePath); source->Type = SoundType::SFX; @@ -248,7 +216,7 @@ bool SoundSystem::OnPlaySoundOnEntity(const Events::PlaySoundOnEntity & e) return false; } -bool SoundSystem::OnPlaySoundOnPosition(const Events::PlaySoundOnPosition & e) +bool SoundManager::OnPlaySoundOnPosition(const Events::PlaySoundOnPosition & e) { Source* source = createSource(e.FilePath); auto emitterID = m_World->CreateEntity(); @@ -267,25 +235,25 @@ bool SoundSystem::OnPlaySoundOnPosition(const Events::PlaySoundOnPosition & e) return true; } -bool SoundSystem::OnPauseSound(const Events::PauseSound & e) +bool SoundManager::OnPauseSound(const Events::PauseSound & e) { alSourcePause(m_Sources[e.EmitterID]->ALsource); return true; } -bool SoundSystem::OnStopSound(const Events::StopSound & e) +bool SoundManager::OnStopSound(const Events::StopSound & e) { alSourceStop(m_Sources[e.EmitterID]->ALsource); return true; } -bool SoundSystem::OnContinueSound(const Events::ContinueSound & e) +bool SoundManager::OnContinueSound(const Events::ContinueSound & e) { alSourcePlay(m_Sources[e.EmitterID]->ALsource); return true; } -bool SoundSystem::OnPlayBackgroundMusic(const Events::PlayBackgroundMusic & e) +bool SoundManager::OnPlayBackgroundMusic(const Events::PlayBackgroundMusic & e) { auto listenerComponents = m_World->GetComponents("Listener"); for (auto it = listenerComponents->begin(); it != listenerComponents->end(); it++) { @@ -303,53 +271,40 @@ bool SoundSystem::OnPlayBackgroundMusic(const Events::PlayBackgroundMusic & e) return true; } -bool SoundSystem::OnSetBGMGain(const Events::SetBGMGain & e) +bool SoundManager::OnSetBGMGain(const Events::SetBGMGain & e) { m_BGMVolumeChannel = e.Gain; return true; } -bool SoundSystem::OnSetSFXGain(const Events::SetSFXGain & e) +bool SoundManager::OnSetSFXGain(const Events::SetSFXGain & e) { m_SFXVolumeChannel = e.Gain; return true; } -bool SoundSystem::OnShoot(const Events::Shoot & e) +bool SoundManager::OnShoot(const Events::Shoot & e) { Source* source = createSource("Audio/laser/laser1.wav"); - auto emitterID = m_World->CreateEntity(e.Player.ID); - m_World->AttachComponent(emitterID, "Transform"); - auto emitter = m_World->AttachComponent(emitterID, "SoundEmitter"); + //auto emitterID = m_World->CreateEntity(e.Player.ID); + //m_World->AttachComponent(emitterID, "Transform"); + //auto emitter = m_World->AttachComponent(emitterID, "SoundEmitter"); source->Type = SoundType::SFX; - m_Sources[emitterID] = source; + m_Sources[createChildEmitter()] = source; playSound(source); return true; } -bool SoundSystem::OnPlayerSpawned(const Events::PlayerSpawned & e) +bool SoundManager::OnPlayerSpawned(const Events::PlayerSpawned & e) { if (e.PlayerID == -1) { // Local player m_World->AttachComponent(e.Player.ID, "Listener"); m_LocalPlayer = e.Player.ID; - EntityID child = m_World->CreateEntity(e.Player.ID); - m_World->AttachComponent(child, "SoundEmitter"); // Temp - m_World->AttachComponent(child, "Transform"); // Temp - Events::PlaySoundOnEntity event; - event.EmitterID = child; - event.FilePath = "Audio/announcer/go.wav"; - m_EventBroker->Publish(event); - // TEMP: starts bgm - { - Events::PlayBackgroundMusic ev; - ev.FilePath = "Audio/bgm/ambient.wav"; - m_EventBroker->Publish(ev); - } } return true; } -bool SoundSystem::OnInputCommand(const Events::InputCommand & e) +bool SoundManager::OnInputCommand(const Events::InputCommand & e) { if (e.Command == "Jump" && e.Value > 0) { if (e.PlayerID == -1) { // local player @@ -370,7 +325,7 @@ bool SoundSystem::OnInputCommand(const Events::InputCommand & e) return false; } -bool SoundSystem::OnCaptured(const Events::Captured & e) +bool SoundManager::OnCaptured(const Events::Captured & e) { int homeTeam = (int)m_World->GetComponent(e.CapturePointID, "Team")["Team"]; int team = (int)m_World->GetComponent(m_LocalPlayer, "Team")["Team"]; @@ -380,26 +335,20 @@ bool SoundSystem::OnCaptured(const Events::Captured & e) } else { ev.FilePath = "Audio/announcer/objective_failed.wav"; // have not been tested } - EntityID child = m_World->CreateEntity(m_LocalPlayer); - m_World->AttachComponent(child, "Transform"); - m_World->AttachComponent(child, "SoundEmitter"); - ev.EmitterID = child; + ev.EmitterID = createChildEmitter(); m_EventBroker->Publish(ev); return false; } -bool SoundSystem::OnPlayerDamage(const Events::PlayerDamage & e) +bool SoundManager::OnPlayerDamage(const Events::PlayerDamage & e) { // Should check for only local players here... - EntityID child = m_World->CreateEntity(m_LocalPlayer); - m_World->AttachComponent(child, "Transform"); - m_World->AttachComponent(child, "SoundEmitter"); std::uniform_int_distribution dist(1, 12); int rand = dist(generator); Source* source = createSource("Audio/hurt/hurt" + std::to_string(rand) + ".wav"); source->Type = SoundType::SFX; - m_Sources[child] = source; + m_Sources[createChildEmitter()] = source; // Breathe std::vector buffers; @@ -413,35 +362,29 @@ bool SoundSystem::OnPlayerDamage(const Events::PlayerDamage & e) return false; } -bool SoundSystem::OnPlayerDeath(const Events::PlayerDeath & e) +bool SoundManager::OnPlayerDeath(const Events::PlayerDeath & e) { if (e.PlayerID == m_LocalPlayer) { Events::PlaySoundOnEntity ev; - EntityID child = m_World->CreateEntity(m_LocalPlayer); - m_World->AttachComponent(child, "Transform"); - m_World->AttachComponent(child, "SoundEmitter"); - ev.EmitterID = child; + ev.EmitterID = createChildEmitter(); ev.FilePath = "Audio/die/die2.wav"; // should random between a bunch m_EventBroker->Publish(ev); } return false; } -bool SoundSystem::OnPlayerHealthPickup(const Events::PlayerHealthPickup & e) +bool SoundManager::OnPlayerHealthPickup(const Events::PlayerHealthPickup & e) { if (e.PlayerHealedID == m_LocalPlayer) { Events::PlaySoundOnEntity ev; - EntityID child = m_World->CreateEntity(m_LocalPlayer); - m_World->AttachComponent(child, "Transform"); - m_World->AttachComponent(child, "SoundEmitter"); - ev.EmitterID = child; + ev.EmitterID = createChildEmitter(); ev.FilePath = "Audio/pickup/pickup2.wav"; m_EventBroker->Publish(ev); } return false; } -bool SoundSystem::OnComponentAttached(const Events::ComponentAttached & e) +bool SoundManager::OnComponentAttached(const Events::ComponentAttached & e) { if (e.Component.Info.Name == "SoundEmitter") { auto component = m_World->GetComponent(e.Entity.ID, "SoundEmitter"); @@ -451,7 +394,7 @@ bool SoundSystem::OnComponentAttached(const Events::ComponentAttached & e) return false; } -bool SoundSystem::OnTriggerTouch(const Events::TriggerTouch & e) +bool SoundManager::OnTriggerTouch(const Events::TriggerTouch & e) { if (m_World->HasComponent(e.Trigger.ID, "CapturePoint")) { Events::PlayBackgroundMusic ev; @@ -461,7 +404,7 @@ bool SoundSystem::OnTriggerTouch(const Events::TriggerTouch & e) return false; } -bool SoundSystem::OnPause(const Events::Pause & e) +bool SoundManager::OnPause(const Events::Pause & e) { for (auto it = m_Sources.begin(); it != m_Sources.end(); it++) { alSourcePause(it->second->ALsource); @@ -469,7 +412,7 @@ bool SoundSystem::OnPause(const Events::Pause & e) return false; } -bool SoundSystem::OnResume(const Events::Resume &e) +bool SoundManager::OnResume(const Events::Resume &e) { for (auto it = m_Sources.begin(); it != m_Sources.end(); it++) { alSourcePlay(it->second->ALsource); @@ -477,19 +420,60 @@ bool SoundSystem::OnResume(const Events::Resume &e) return false; } -bool SoundSystem::OnDoubleJump(const Events::DoubleJump & e) +bool SoundManager::OnDoubleJump(const Events::DoubleJump & e) { Events::PlaySoundOnEntity ev; - EntityID child = m_World->CreateEntity(m_LocalPlayer); - m_World->AttachComponent(child, "Transform"); - m_World->AttachComponent(child, "SoundEmitter"); - ev.EmitterID = child; + ev.EmitterID = createChildEmitter(); ev.FilePath = "Audio/jump/jump2.wav"; m_EventBroker->Publish(ev); return false; } -void SoundSystem::setListenerOri(glm::vec3 ori) +bool SoundManager::OnDashAbility(const Events::DashAbility &e) +{ + Events::PlaySoundOnEntity ev; + ev.EmitterID = createChildEmitter(); + ev.FilePath = "Audio/jump/dash1.wav"; + m_EventBroker->Publish(ev); + return false; +} + +ALenum SoundManager::getSourceState(ALuint source) +{ + ALenum state; + alGetSourcei(source, AL_SOURCE_STATE, &state); + return state; +} + +void SoundManager::setGain(Source * source, float gain) +{ + alSourcef(source->ALsource, AL_GAIN, gain); +} + +void SoundManager::setSoundProperties(Source* source, ComponentWrapper* soundComponent) +{ + float gain = (source->Type == SoundType::SFX) ? m_SFXVolumeChannel : m_BGMVolumeChannel; + alSourcef(source->ALsource, AL_GAIN, (float)(double)(*soundComponent)["Gain"] * gain); + alSourcef(source->ALsource, AL_PITCH, (float)(double)(*soundComponent)["Pitch"]); + alSourcei(source->ALsource, AL_LOOPING, (int)(bool)(*soundComponent)["Loop"]); // YOLO + alSourcef(source->ALsource, AL_MAX_DISTANCE, (float)(double)(*soundComponent)["MaxDistance"]); + alSourcef(source->ALsource, AL_ROLLOFF_FACTOR, (float)(double)(*soundComponent)["RollOffFactor"]); + alSourcef(source->ALsource, AL_REFERENCE_DISTANCE, (float)(double)(*soundComponent)["ReferenceDistance"]); +} + +void SoundManager::initOpenAL() +{ + // Initialize OpenAL + m_ALCdevice = alcOpenDevice(nullptr); + if (m_ALCdevice != nullptr) { + m_ALCcontext = alcCreateContext(m_ALCdevice, nullptr); + alcMakeContextCurrent(m_ALCcontext); + } else { + LOG_ERROR("OpenAL failed to initialize."); + } +} + +void SoundManager::setListenerOri(glm::vec3 ori) { // Calculate forward and up vector. glm::vec3 forward = glm::vec3(0.0, 0.0, -1.0); @@ -504,39 +488,4 @@ void SoundSystem::setListenerOri(glm::vec3 ori) glm::normalize(up); ALfloat lOri[6] = { forward.x, forward.y, forward.z, up.x, up.y, up.z }; alListenerfv(AL_ORIENTATION, lOri); -} - -ALenum SoundSystem::getSourceState(ALuint source) -{ - ALenum state; - alGetSourcei(source, AL_SOURCE_STATE, &state); - return state; -} - -void SoundSystem::setGain(Source * source, float gain) -{ - alSourcef(source->ALsource, AL_GAIN, gain); -} - -void SoundSystem::setSoundProperties(Source* source, ComponentWrapper* soundComponent) -{ - float gain = (source->Type == SoundType::SFX) ? m_SFXVolumeChannel : m_BGMVolumeChannel; - alSourcef(source->ALsource, AL_GAIN, (float)(double)(*soundComponent)["Gain"] * gain); - alSourcef(source->ALsource, AL_PITCH, (float)(double)(*soundComponent)["Pitch"]); - alSourcei(source->ALsource, AL_LOOPING, (int)(bool)(*soundComponent)["Loop"]); // YOLO - alSourcef(source->ALsource, AL_MAX_DISTANCE, (float)(double)(*soundComponent)["MaxDistance"]); - alSourcef(source->ALsource, AL_ROLLOFF_FACTOR, (float)(double)(*soundComponent)["RollOffFactor"]); - alSourcef(source->ALsource, AL_REFERENCE_DISTANCE, (float)(double)(*soundComponent)["ReferenceDistance"]); -} - -void SoundSystem::initOpenAL() -{ - // Initialize OpenAL - m_ALCdevice = alcOpenDevice(nullptr); - if (m_ALCdevice != nullptr) { - m_ALCcontext = alcCreateContext(m_ALCdevice, nullptr); - alcMakeContextCurrent(m_ALCcontext); - } else { - LOG_ERROR("OpenAL failed to initialize."); - } } \ No newline at end of file diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index 04542f11..204f425e 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -81,6 +81,7 @@ Game::Game(int argc, char* argv[]) // All systems with orderlevel 0 will be updated first. unsigned int updateOrderLevel = 0; + m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); @@ -91,6 +92,7 @@ Game::Game(int argc, char* argv[]) m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); + m_SystemPipeline->AddSystem(updateOrderLevel); // Populate Octree with collidables ++updateOrderLevel; m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeCollision, "Collidable"); @@ -114,7 +116,7 @@ Game::Game(int argc, char* argv[]) } // Invoke sound system - m_SoundSystem = new SoundSystem(m_World, m_EventBroker, m_Config->Get("Debug.EditorEnabled", false)); + //m_SoundManager = new SoundManager(m_World, m_EventBroker, m_Config->Get("Debug.EditorEnabled", false)); m_LastTime = glfwGetTime(); } @@ -122,7 +124,7 @@ Game::Game(int argc, char* argv[]) Game::~Game() { delete m_SystemPipeline; - delete m_SoundSystem; + //delete m_SoundManager; delete m_OctreeFrustrumCulling; delete m_OctreeCollision; delete m_OctreeTrigger; @@ -157,7 +159,7 @@ void Game::Tick() if (m_IsClientOrServer) { m_ClientOrServer->Update(); } - m_SoundSystem->Update(dt); + //m_SoundManager->Update(dt); // Iterate through systems and update world! m_EventBroker->Process(); diff --git a/src/Game/Systems/SoundSystem.cpp b/src/Game/Systems/SoundSystem.cpp new file mode 100644 index 00000000..d51996ac --- /dev/null +++ b/src/Game/Systems/SoundSystem.cpp @@ -0,0 +1,73 @@ +#include "Game/Systems/SoundSystem.h" + +SoundSystem::SoundSystem(World* world, EventBroker* eventbroker) + : System(world, eventbroker) + , PureSystem("SoundEmitter") + , ImpureSystem() + , SoundManager(world, eventbroker, true) +{ + m_World = world; + m_EventBroker = eventbroker; + EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &SoundSystem::OnPlayerSpawned); +} + +void SoundSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& cComponent, double dt) +{ + +} + +void SoundSystem::Update(double dt) +{ + SoundManager::Update(dt); + playerStep(dt); +} + +void SoundSystem::playerStep(double dt) +{ + if (!m_LocalPlayer.Valid()) { + return; + } + if (m_LocalPlayer.ID == EntityID_Invalid) { + return; + } + + m_TimeSinceLastFootstep += dt; + glm::vec3 vel = (glm::vec3)m_World->GetComponent(m_LocalPlayer.ID, "Physics")["Velocity"]; + float playerSpeed = glm::length(vel); + bool isAirborne = vel.y != 0; + if (playerSpeed > 1 && !isAirborne) { + // Player is walking + if (m_TimeSinceLastFootstep * std::min(playerSpeed, 2) > m_PlayerFootstepInterval) { + // Create footstep sound + Events::PlaySoundOnEntity e; + e.EmitterID = createChildEmitter(); + if (m_LeftFoot) { + e.FilePath = "Audio/footstep/footstep2.wav"; + } else { + e.FilePath = "Audio/footstep/footstep3.wav"; + } + m_LeftFoot = !m_LeftFoot; + m_EventBroker->Publish(e); + m_TimeSinceLastFootstep = 0; + } + } +} + +bool SoundSystem::OnPlayerSpawned(const Events::PlayerSpawned &e) +{ + if (e.PlayerID == -1) { // Local player + m_World->AttachComponent(e.Player.ID, "Listener"); + m_LocalPlayer = e.Player; + Events::PlaySoundOnEntity event; + event.EmitterID = createChildEmitter(); + event.FilePath = "Audio/announcer/go.wav"; + m_EventBroker->Publish(event); + // TEMP: starts bgm +// { +// Events::PlayBackgroundMusic ev; +// ev.FilePath = "Audio/bgm/ambient.wav"; +// m_EventBroker->Publish(ev); +// } + } + return true; +} From 8034b42c870aa109efaa3362f2c67565b4e260fe Mon Sep 17 00:00:00 2001 From: viktorljung Date: Fri, 5 Feb 2016 16:43:57 +0100 Subject: [PATCH 095/355] spriteComponent WIP --- include/Engine/Rendering/Camera.h | 2 + include/Engine/Rendering/DrawFinalPass.h | 2 + include/Engine/Rendering/RenderQueue.h | 4 ++ include/Engine/Rendering/RenderSystem.h | 1 + include/Engine/Rendering/SpriteJob.h | 75 ++++++++++++++++++++ resources/Schema/Components.xsd | 1 + resources/Schema/Components/Sprite.xml | 7 ++ resources/Schema/Components/Sprite.xsd | 27 +++++++ resources/Schema/Entities/RenderingWorld.xml | 16 ++++- resources/Shaders/Sprite.frag.glsl | 41 +++++++++++ resources/Shaders/Sprite.vert.glsl | 24 +++++++ src/Engine/Rendering/Camera.cpp | 7 ++ src/Engine/Rendering/DrawFinalPass.cpp | 56 ++++++++++++++- src/Engine/Rendering/RenderSystem.cpp | 53 +++++++++++++- src/Engine/Rendering/Texture.cpp | 7 +- src/Game/Game.cpp | 3 +- 16 files changed, 318 insertions(+), 8 deletions(-) create mode 100644 include/Engine/Rendering/SpriteJob.h create mode 100644 resources/Schema/Components/Sprite.xml create mode 100644 resources/Schema/Components/Sprite.xsd create mode 100644 resources/Shaders/Sprite.frag.glsl create mode 100644 resources/Shaders/Sprite.vert.glsl diff --git a/include/Engine/Rendering/Camera.h b/include/Engine/Rendering/Camera.h index 29dd4626..6130fd01 100644 --- a/include/Engine/Rendering/Camera.h +++ b/include/Engine/Rendering/Camera.h @@ -33,6 +33,8 @@ public: glm::mat4 ViewMatrix() const { return m_ViewMatrix; } void SetViewMatrix(glm::mat4 val); + glm::mat4 BillboardMatrix(); + float AspectRatio() const { return m_AspectRatio; } void SetAspectRatio(float val); diff --git a/include/Engine/Rendering/DrawFinalPass.h b/include/Engine/Rendering/DrawFinalPass.h index 74f505fe..867ec844 100644 --- a/include/Engine/Rendering/DrawFinalPass.h +++ b/include/Engine/Rendering/DrawFinalPass.h @@ -31,6 +31,7 @@ private: void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const; void GenerateMipMapTexture(GLuint* texture, GLenum wrapping, glm::vec2 dimensions, GLint format, GLenum type, GLint numMipMaps) const; void DrawModelRenderQueues(std::list>& job, RenderScene& scene); + void DrawSprites(std::list>&jobs, RenderScene& scene); void BindExplosionUniforms(GLuint shaderHandle, std::shared_ptr& job, RenderScene& scene); void BindModelUniforms(GLuint shaderHandle, std::shared_ptr& job, RenderScene& scene); @@ -53,6 +54,7 @@ private: ShaderProgram* m_ForwardPlusProgram; ShaderProgram* m_ExplosionEffectProgram; + ShaderProgram* m_SpriteProgram; }; #endif \ No newline at end of file diff --git a/include/Engine/Rendering/RenderQueue.h b/include/Engine/Rendering/RenderQueue.h index af9d928e..47b15b63 100644 --- a/include/Engine/Rendering/RenderQueue.h +++ b/include/Engine/Rendering/RenderQueue.h @@ -15,6 +15,7 @@ #include "PointLightJob.h" #include "DirectionalLightJob.h" #include "ExplosionEffectJob.h" +#include "SpriteJob.h" struct RenderScene { @@ -24,6 +25,8 @@ struct RenderScene std::list> PointLightJobs; std::list> TextJobs; std::list> DirectionalLightJobs; + std::list> SpriteJobs; + Rectangle Viewport; bool ClearDepth = false; glm::vec4 AmbientColor; @@ -35,6 +38,7 @@ struct RenderScene PointLightJobs.clear(); TextJobs.clear(); DirectionalLightJobs.clear(); + SpriteJobs.clear(); } }; diff --git a/include/Engine/Rendering/RenderSystem.h b/include/Engine/Rendering/RenderSystem.h index d64147b9..6ab4b98b 100644 --- a/include/Engine/Rendering/RenderSystem.h +++ b/include/Engine/Rendering/RenderSystem.h @@ -45,6 +45,7 @@ private: void fillPointLights(std::list>& jobs, World* world); void fillDirectionalLights(std::list>& jobs, World* world); void fillLight(std::list>& jobs); + void fillSprites(std::list>& jobs, World* world); bool isChildOfACamera(EntityWrapper entity); bool isChildOfCurrentCamera(EntityWrapper entity); diff --git a/include/Engine/Rendering/SpriteJob.h b/include/Engine/Rendering/SpriteJob.h new file mode 100644 index 00000000..a20d0395 --- /dev/null +++ b/include/Engine/Rendering/SpriteJob.h @@ -0,0 +1,75 @@ +#ifndef SpriteJob_h__ +#define SpriteJob_h__ + +#include + +#include "../Common.h" +#include "../GLM.h" +#include "../Core/ComponentWrapper.h" +#include "Texture.h" +#include "Model.h" +#include "RenderJob.h" +#include "../Core/ResourceManager.h" +#include "Camera.h" +#include "../Core/World.h" +#include "../Core/Transform.h" +#include "Skeleton.h" + +struct SpriteJob : RenderJob +{ + SpriteJob(ComponentWrapper cSprite, Camera* camera, glm::mat4 matrix, World* world, glm::vec4 fillColor, float fillPercentage) + : RenderJob() + { + Model = ResourceManager::Load<::Model>("Models/Core/UnitQuad.mesh"); + ::RawModel::MaterialGroup matGroup = Model->MaterialGroups().front(); + TextureID = (matGroup.Texture) ? matGroup.Texture->ResourceID : 0; + + if (cSprite["DiffuseTexture"]) { + DiffuseTexture = ResourceManager::Load(cSprite["DiffuseTexture"]); + } else { + DiffuseTexture = nullptr; + } + if (cSprite["GlowMap"]) { + IncandescenceTexture = ResourceManager::Load(cSprite["GlowMap"]); + } else { + IncandescenceTexture = nullptr; + } + StartIndex = matGroup.StartIndex; + EndIndex = matGroup.EndIndex; + Matrix = matrix; + Color = cSprite["Color"]; + Entity = cSprite.EntityID; + glm::vec3 abspos = Transform::AbsolutePosition(world, cSprite.EntityID); + glm::vec3 viewpos = glm::vec3(camera->ViewMatrix() * glm::vec4(abspos, 1)); + Depth = viewpos.z; + World = world; + + FillColor = fillColor; + FillPercentage = fillPercentage; + }; + + unsigned int TextureID; + + EntityID Entity; + glm::mat4 Matrix; + const Texture* DiffuseTexture; + const Texture* NormalTexture; + const Texture* SpecularTexture; + const Texture* IncandescenceTexture; + float Shininess = 0.f; + glm::vec4 Color; + const ::Model* Model = nullptr; + unsigned int StartIndex = 0; + unsigned int EndIndex = 0; + World* World; + + glm::vec4 FillColor = glm::vec4(0); + float FillPercentage = 0.0; + + void CalculateHash() override + { + Hash = TextureID; + } +}; + +#endif \ No newline at end of file diff --git a/resources/Schema/Components.xsd b/resources/Schema/Components.xsd index 265a3cc5..3163c787 100644 --- a/resources/Schema/Components.xsd +++ b/resources/Schema/Components.xsd @@ -31,4 +31,5 @@ + \ No newline at end of file diff --git a/resources/Schema/Components/Sprite.xml b/resources/Schema/Components/Sprite.xml new file mode 100644 index 00000000..c2a2057f --- /dev/null +++ b/resources/Schema/Components/Sprite.xml @@ -0,0 +1,7 @@ + + + + + + true + diff --git a/resources/Schema/Components/Sprite.xsd b/resources/Schema/Components/Sprite.xsd new file mode 100644 index 00000000..c8f0c187 --- /dev/null +++ b/resources/Schema/Components/Sprite.xsd @@ -0,0 +1,27 @@ + + + + + + + + A sprite that will be facing the camera + + + + + Diffuse Texture file + + + GlowMap file + + + Color tint + + + Whether the model is visible or not + + + + + \ No newline at end of file diff --git a/resources/Schema/Entities/RenderingWorld.xml b/resources/Schema/Entities/RenderingWorld.xml index 20301d5f..d9f7c62d 100644 --- a/resources/Schema/Entities/RenderingWorld.xml +++ b/resources/Schema/Entities/RenderingWorld.xml @@ -52,11 +52,11 @@ - 0.65990006923675537 + Models/Core/UnitHexagon.mesh @@ -161,7 +161,7 @@ - + @@ -346,6 +346,18 @@ + + + + Textures/HexmapDiff.png + Textures/GlowFrame.png + + + + + + + diff --git a/resources/Shaders/Sprite.frag.glsl b/resources/Shaders/Sprite.frag.glsl new file mode 100644 index 00000000..c391322d --- /dev/null +++ b/resources/Shaders/Sprite.frag.glsl @@ -0,0 +1,41 @@ +#version 430 + +uniform vec4 Color; +uniform vec4 FillColor; +uniform float FillPercentage; +uniform mat4 M; +uniform mat4 V; +uniform mat4 P; + +layout (binding = 0) uniform sampler2D DiffuseTexture; +layout (binding = 1) uniform sampler2D GlowMapTexture; + + +in VertexData{ + vec3 Position; + vec3 Normal; + vec2 TextureCoordinate; +}Input; + + +out vec4 sceneColor; +out vec4 bloomColor; + +void main() +{ + vec4 diffuseTexel = texture2D(DiffuseTexture, Input.TextureCoordinate); + vec4 glowTexel = texture2D(GlowMapTexture, Input.TextureCoordinate); + + vec4 color_result = Color * diffuseTexel; + + float pos = ((P * vec4(Input.Position, 1)).y + 1.0)/2.0; + if(pos <= FillPercentage) { + color_result += FillColor; + } + sceneColor = vec4(color_result.xyz, clamp(color_result.a, 0, 1)); + color_result += glowTexel*3; + + bloomColor = vec4(clamp(color_result.xyz - 1.0, 0, 100), 1.0); +} + + diff --git a/resources/Shaders/Sprite.vert.glsl b/resources/Shaders/Sprite.vert.glsl new file mode 100644 index 00000000..e910a26a --- /dev/null +++ b/resources/Shaders/Sprite.vert.glsl @@ -0,0 +1,24 @@ +#version 430 + +uniform mat4 M; +uniform mat4 V; +uniform mat4 P; + +layout(location = 0) in vec3 Position; +layout(location = 1) in vec3 Normal; +layout(location = 4) in vec2 TextureCoords; + +out VertexData{ + vec3 Position; + vec3 Normal; + vec2 TextureCoordinate; +}Output; + +void main() +{ + gl_Position = P * M * vec4(Position, 1.0); + + Output.Position = Position; + Output.TextureCoordinate = TextureCoords; + Output.Normal = Normal; +} \ No newline at end of file diff --git a/src/Engine/Rendering/Camera.cpp b/src/Engine/Rendering/Camera.cpp index f6b2e5ef..c1246c6a 100644 --- a/src/Engine/Rendering/Camera.cpp +++ b/src/Engine/Rendering/Camera.cpp @@ -62,6 +62,13 @@ void Camera::SetViewMatrix(glm::mat4 val) m_ViewMatrix = val; } + +glm::mat4 Camera::BillboardMatrix() +{ + glm::mat4 matrix = glm::toMat4(m_Orientation); + return matrix; +} + //void Camera::Pitch(float val) //{ // m_Pitch = val; diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index 8247797e..e5919fbe 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -55,6 +55,15 @@ void DrawFinalPass::InitializeShaderPrograms() m_ExplosionEffectProgram->BindFragDataLocation(1, "bloomColor"); m_ExplosionEffectProgram->Link(); GLERROR("Creating explosion program"); + + m_SpriteProgram = ResourceManager::Load("#m_SpriteProgram"); + m_SpriteProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/Sprite.vert.glsl"))); + m_SpriteProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/Sprite.frag.glsl"))); + m_SpriteProgram->Compile(); + m_SpriteProgram->BindFragDataLocation(0, "sceneColor"); + m_SpriteProgram->BindFragDataLocation(1, "bloomColor"); + m_SpriteProgram->Link(); + GLERROR("Creating sprite program"); } void DrawFinalPass::Draw(RenderScene& scene) @@ -70,6 +79,8 @@ void DrawFinalPass::Draw(RenderScene& scene) GLERROR("OpaqueObjects"); DrawModelRenderQueues(scene.TransparentObjects, scene); GLERROR("TransparentObjects"); + DrawSprites(scene.SpriteJobs, scene); + GLERROR("SpriteJobs"); delete state; GLERROR("END"); @@ -201,6 +212,50 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& } + +void DrawFinalPass::DrawSprites(std::list>&jobs, RenderScene& scene) +{ + m_SpriteProgram->Bind(); + + GLuint shaderHandle = m_SpriteProgram->GetHandle(); + + for(auto& job : jobs) { + auto spriteJob = std::dynamic_pointer_cast(job); + + if(spriteJob) { + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(spriteJob->Matrix)); + 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())); + 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); + + glActiveTexture(GL_TEXTURE0); + if (spriteJob->DiffuseTexture != nullptr) { + glBindTexture(GL_TEXTURE_2D, spriteJob->DiffuseTexture->m_Texture); + } else { + glBindTexture(GL_TEXTURE_2D, m_WhiteTexture->m_Texture); + } + + glActiveTexture(GL_TEXTURE1); + if (spriteJob->IncandescenceTexture != nullptr) { + glBindTexture(GL_TEXTURE_2D, spriteJob->IncandescenceTexture->m_Texture); + } else { + glBindTexture(GL_TEXTURE_2D, m_BlackTexture->m_Texture); + } + + + glBindVertexArray(spriteJob->Model->VAO); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, spriteJob->Model->ElementBuffer); + glDrawElements(GL_TRIANGLES, spriteJob->EndIndex - spriteJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(spriteJob->StartIndex*sizeof(unsigned int))); + } + } + + + + // m_SpriteProgram->Unbind(); +} + void DrawFinalPass::BindExplosionUniforms(GLuint shaderHandle, std::shared_ptr& job, RenderScene& scene) { glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(job->Matrix)); @@ -245,7 +300,6 @@ void DrawFinalPass::BindModelUniforms(GLuint shaderHandle, std::shared_ptr& job) { glActiveTexture(GL_TEXTURE0); diff --git a/src/Engine/Rendering/RenderSystem.cpp b/src/Engine/Rendering/RenderSystem.cpp index eaecf99e..3a1729fc 100644 --- a/src/Engine/Rendering/RenderSystem.cpp +++ b/src/Engine/Rendering/RenderSystem.cpp @@ -31,6 +31,56 @@ bool RenderSystem::OnSetCamera(Events::SetCamera& e) return true; } + +void RenderSystem::fillSprites(std::list>& jobs, World* world) +{ + auto sprites = world->GetComponents("Sprite"); + if (sprites == nullptr) { + return; + } + + for (auto& cSprite : *sprites) { + bool visible = cSprite["Visible"]; + if (!visible) { + continue; + } + + + EntityWrapper entity(world, cSprite.EntityID); + + // Only render children of a camera if that camera is currently active + if (isChildOfACamera(entity) && !isChildOfCurrentCamera(entity)) { + continue; + } + + // Hide things parented to local player if they have the HiddenFromLocalPlayer component + if (entity.HasComponent("HiddenForLocalPlayer") && (entity == m_LocalPlayer || entity.IsChildOf(m_LocalPlayer))) { + continue; + } + + std::string diffuseResource = cSprite["DiffuseTexture"]; + std::string glowResource = cSprite["GlowMap"]; + if (diffuseResource.empty() && glowResource.empty()) { + continue; + } + + float fillPercentage = 0.f; + glm::vec4 fillColor = glm::vec4(0); + if (world->HasComponent(entity.ID, "Fill")) { + auto fillComponent = world->GetComponent(entity.ID, "Fill"); + fillPercentage = (float)(double)fillComponent["Percentage"]; + fillColor = (glm::vec4)fillComponent["Color"]; + } + + glm::mat4 modelMatrix = Transform::ModelMatrix(entity.ID, world); + //modelMatrix *= m_Camera->BillboardMatrix(); + + std::shared_ptr spriteJob = std::shared_ptr(new SpriteJob(cSprite, m_Camera, modelMatrix, world, fillColor, fillPercentage)); + + jobs.push_back(spriteJob); + } +} + bool RenderSystem::isChildOfACamera(EntityWrapper entity) { return entity.FirstParentWithComponent("Camera").Valid(); @@ -167,7 +217,6 @@ void RenderSystem::fillPointLights(std::list>& jobs, } } - void RenderSystem::fillDirectionalLights(std::list>& jobs, World* world) { auto directionalLights = world->GetComponents("DirectionalLight"); @@ -189,7 +238,6 @@ void RenderSystem::fillDirectionalLights(std::list>& } } - void RenderSystem::fillText(std::list>& jobs, World* world) { auto texts = world->GetComponents("Text"); @@ -255,6 +303,7 @@ void RenderSystem::Update(double dt) fillPointLights(scene.PointLightJobs, m_World); fillDirectionalLights(scene.DirectionalLightJobs, m_World); fillText(scene.TextJobs, m_World); + fillSprites(scene.SpriteJobs, m_World); m_RenderFrame->Add(scene); } \ No newline at end of file diff --git a/src/Engine/Rendering/Texture.cpp b/src/Engine/Rendering/Texture.cpp index 57f3ca36..492b35be 100644 --- a/src/Engine/Rendering/Texture.cpp +++ b/src/Engine/Rendering/Texture.cpp @@ -2,14 +2,17 @@ Texture::Texture(std::string path) { + PNG image(path); if (image.Width == 0 && image.Height == 0 || image.Format == Image::ImageFormat::Unknown) { - image = PNG("Textures/Core/ErrorTexture.png"); + //image = PNG("Textures/Core/ErrorTexture.png"); + return; // Temporary fix to remove crash + /* if (image.Width == 0 && image.Height == 0 || image.Format == Image::ImageFormat::Unknown) { LOG_ERROR("Couldn't even load the error texture. This is a dark day indeed."); return; - } + }*/ } this->Width = image.Width; diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index f5afcaeb..d7806ba5 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -14,6 +14,7 @@ #include "Game/Systems/PlayerHUD.h" #include "Game/Systems/LifetimeSystem.h" #include "../Engine/Rendering/AnimationSystem.h" +#include "../Engine/Core/UniformScaleSystem.h" Game::Game(int argc, char* argv[]) { @@ -97,7 +98,7 @@ Game::Game(int argc, char* argv[]) m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeTrigger, "Player"); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); - + m_SystemPipeline->AddSystem(updateOrderLevel); // Collision and TriggerSystem should update after player. ++updateOrderLevel; m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeCollision); From febbadbd013415648464602c10d5925c3499f36c Mon Sep 17 00:00:00 2001 From: stiffly Date: Fri, 5 Feb 2016 17:21:31 +0100 Subject: [PATCH 096/355] Accidentally added the sound system twice. Lead to funny behavior. --- src/Game/Game.cpp | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index 204f425e..541aa001 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -92,7 +92,6 @@ Game::Game(int argc, char* argv[]) m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); - m_SystemPipeline->AddSystem(updateOrderLevel); // Populate Octree with collidables ++updateOrderLevel; m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeCollision, "Collidable"); @@ -115,16 +114,12 @@ Game::Game(int argc, char* argv[]) networkFunction(); } - // Invoke sound system - //m_SoundManager = new SoundManager(m_World, m_EventBroker, m_Config->Get("Debug.EditorEnabled", false)); - m_LastTime = glfwGetTime(); } Game::~Game() { delete m_SystemPipeline; - //delete m_SoundManager; delete m_OctreeFrustrumCulling; delete m_OctreeCollision; delete m_OctreeTrigger; From 454eef82257c28b1f657d6a9738df09323f8711e Mon Sep 17 00:00:00 2001 From: stiffly Date: Fri, 5 Feb 2016 17:21:48 +0100 Subject: [PATCH 097/355] WIP. Improving player walk logic. --- include/Engine/Sound/SoundManager.h | 8 ++--- include/Game/Systems/LifetimeSystem.h | 4 ++- include/Game/Systems/SoundSystem.h | 5 +-- src/Engine/Sound/SoundManager.cpp | 31 ++++++++-------- src/Game/Systems/SoundSystem.cpp | 51 ++++++++++++--------------- 5 files changed, 47 insertions(+), 52 deletions(-) diff --git a/include/Engine/Sound/SoundManager.h b/include/Engine/Sound/SoundManager.h index a9fb23a9..ef291380 100644 --- a/include/Engine/Sound/SoundManager.h +++ b/include/Engine/Sound/SoundManager.h @@ -69,12 +69,11 @@ protected: void stopSound(Source* source); void playerJumps(); void playerStep(double dt); - EntityID createChildEmitter(); + EntityID createChildEmitter(EntityWrapper localPlayer); // Logic World* m_World = nullptr; EventBroker* m_EventBroker = nullptr; - std::unordered_map m_Sources; private: // Help functions for working with OpenaAL @@ -98,7 +97,8 @@ private: void setGain(Source* source, float gain); void setSoundProperties(Source* source, ComponentWrapper* soundComponent); - + std::unordered_map m_Sources; + // OpenAL system variables ALCdevice* m_ALCdevice = nullptr; @@ -109,7 +109,7 @@ private: float m_BGMVolumeChannel = 1.0f; float m_SFXVolumeChannel = 1.0f; bool m_EditorEnabled = false; - EntityID m_LocalPlayer = EntityID_Invalid; + EntityWrapper m_LocalPlayer = EntityWrapper(); std::default_random_engine generator; // Events diff --git a/include/Game/Systems/LifetimeSystem.h b/include/Game/Systems/LifetimeSystem.h index da88cfa2..99cafd89 100644 --- a/include/Game/Systems/LifetimeSystem.h +++ b/include/Game/Systems/LifetimeSystem.h @@ -9,7 +9,9 @@ public: LifetimeSystem(World* world, EventBroker* eventBroker) : System(world, eventBroker) , PureSystem("Lifetime") - { } + { + LOG_INFO("ASDASDASSA"); + } virtual void Update(double dt) override; virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& cLifetime, double dt) override; diff --git a/include/Game/Systems/SoundSystem.h b/include/Game/Systems/SoundSystem.h index 33dbf1fc..ec87e98a 100644 --- a/include/Game/Systems/SoundSystem.h +++ b/include/Game/Systems/SoundSystem.h @@ -20,8 +20,9 @@ private: EventBroker* m_EventBroker = nullptr; // TODO: WIP Update this - double m_TimeSinceLastFootstep = 0.0; - const double m_PlayerFootstepInterval = 1.0; + double m_DistanceMoved = 0.0; + const float m_PlayerStepLength = 1.0; + glm::vec3 m_LastPosition = glm::vec3(); bool m_LeftFoot = false; EventRelay m_EPlayerSpawned; diff --git a/src/Engine/Sound/SoundManager.cpp b/src/Engine/Sound/SoundManager.cpp index 3cec4deb..b7aaaff6 100644 --- a/src/Engine/Sound/SoundManager.cpp +++ b/src/Engine/Sound/SoundManager.cpp @@ -184,14 +184,13 @@ void SoundManager::stopSound(Source* source) void SoundManager::playerJumps() { - glm::vec3 vel = (glm::vec3)m_World->GetComponent(m_LocalPlayer, "Physics")["Velocity"]; + glm::vec3 vel = (glm::vec3)m_World->GetComponent(m_LocalPlayer.ID, "Physics")["Velocity"]; if (vel.y == 0) { Source* source = createSource("Audio/jump/jump1.wav"); source->Type = SoundType::SFX; - m_Sources[createChildEmitter()] = source; + m_Sources[createChildEmitter(m_LocalPlayer)] = source; playSound(source); } - } void SoundManager::playerStep(double dt) @@ -199,9 +198,9 @@ void SoundManager::playerStep(double dt) } -EntityID SoundManager::createChildEmitter() +EntityID SoundManager::createChildEmitter(EntityWrapper localPlayer) { - EntityID child = m_World->CreateEntity(m_LocalPlayer); + EntityID child = m_World->CreateEntity(localPlayer.ID); m_World->AttachComponent(child, "Transform"); m_World->AttachComponent(child, "SoundEmitter"); return child; @@ -290,7 +289,7 @@ bool SoundManager::OnShoot(const Events::Shoot & e) //m_World->AttachComponent(emitterID, "Transform"); //auto emitter = m_World->AttachComponent(emitterID, "SoundEmitter"); source->Type = SoundType::SFX; - m_Sources[createChildEmitter()] = source; + m_Sources[createChildEmitter(m_LocalPlayer)] = source; playSound(source); return true; } @@ -299,7 +298,7 @@ bool SoundManager::OnPlayerSpawned(const Events::PlayerSpawned & e) { if (e.PlayerID == -1) { // Local player m_World->AttachComponent(e.Player.ID, "Listener"); - m_LocalPlayer = e.Player.ID; + m_LocalPlayer.ID = e.Player.ID; } return true; } @@ -328,14 +327,14 @@ bool SoundManager::OnInputCommand(const Events::InputCommand & e) bool SoundManager::OnCaptured(const Events::Captured & e) { int homeTeam = (int)m_World->GetComponent(e.CapturePointID, "Team")["Team"]; - int team = (int)m_World->GetComponent(m_LocalPlayer, "Team")["Team"]; + int team = (int)m_World->GetComponent(m_LocalPlayer.ID, "Team")["Team"]; Events::PlaySoundOnEntity ev; if (team == homeTeam) { ev.FilePath = "Audio/announcer/objective_achieved.wav"; } else { ev.FilePath = "Audio/announcer/objective_failed.wav"; // have not been tested } - ev.EmitterID = createChildEmitter(); + ev.EmitterID = createChildEmitter(m_LocalPlayer); m_EventBroker->Publish(ev); return false; } @@ -348,7 +347,7 @@ bool SoundManager::OnPlayerDamage(const Events::PlayerDamage & e) int rand = dist(generator); Source* source = createSource("Audio/hurt/hurt" + std::to_string(rand) + ".wav"); source->Type = SoundType::SFX; - m_Sources[createChildEmitter()] = source; + m_Sources[createChildEmitter(m_LocalPlayer)] = source; // Breathe std::vector buffers; @@ -364,9 +363,9 @@ bool SoundManager::OnPlayerDamage(const Events::PlayerDamage & e) bool SoundManager::OnPlayerDeath(const Events::PlayerDeath & e) { - if (e.PlayerID == m_LocalPlayer) { + if (e.PlayerID == m_LocalPlayer.ID) { Events::PlaySoundOnEntity ev; - ev.EmitterID = createChildEmitter(); + ev.EmitterID = createChildEmitter(m_LocalPlayer); ev.FilePath = "Audio/die/die2.wav"; // should random between a bunch m_EventBroker->Publish(ev); } @@ -375,9 +374,9 @@ bool SoundManager::OnPlayerDeath(const Events::PlayerDeath & e) bool SoundManager::OnPlayerHealthPickup(const Events::PlayerHealthPickup & e) { - if (e.PlayerHealedID == m_LocalPlayer) { + if (e.PlayerHealedID == m_LocalPlayer.ID) { Events::PlaySoundOnEntity ev; - ev.EmitterID = createChildEmitter(); + ev.EmitterID = createChildEmitter(m_LocalPlayer); ev.FilePath = "Audio/pickup/pickup2.wav"; m_EventBroker->Publish(ev); } @@ -423,7 +422,7 @@ bool SoundManager::OnResume(const Events::Resume &e) bool SoundManager::OnDoubleJump(const Events::DoubleJump & e) { Events::PlaySoundOnEntity ev; - ev.EmitterID = createChildEmitter(); + ev.EmitterID = createChildEmitter(m_LocalPlayer); ev.FilePath = "Audio/jump/jump2.wav"; m_EventBroker->Publish(ev); return false; @@ -432,7 +431,7 @@ bool SoundManager::OnDoubleJump(const Events::DoubleJump & e) bool SoundManager::OnDashAbility(const Events::DashAbility &e) { Events::PlaySoundOnEntity ev; - ev.EmitterID = createChildEmitter(); + ev.EmitterID = createChildEmitter(m_LocalPlayer); ev.FilePath = "Audio/jump/dash1.wav"; m_EventBroker->Publish(ev); return false; diff --git a/src/Game/Systems/SoundSystem.cpp b/src/Game/Systems/SoundSystem.cpp index d51996ac..99f3242d 100644 --- a/src/Game/Systems/SoundSystem.cpp +++ b/src/Game/Systems/SoundSystem.cpp @@ -18,39 +18,32 @@ void SoundSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& cComp void SoundSystem::Update(double dt) { - SoundManager::Update(dt); playerStep(dt); + SoundManager::Update(dt); } void SoundSystem::playerStep(double dt) { - if (!m_LocalPlayer.Valid()) { - return; - } - if (m_LocalPlayer.ID == EntityID_Invalid) { - return; - } - - m_TimeSinceLastFootstep += dt; - glm::vec3 vel = (glm::vec3)m_World->GetComponent(m_LocalPlayer.ID, "Physics")["Velocity"]; - float playerSpeed = glm::length(vel); - bool isAirborne = vel.y != 0; - if (playerSpeed > 1 && !isAirborne) { - // Player is walking - if (m_TimeSinceLastFootstep * std::min(playerSpeed, 2) > m_PlayerFootstepInterval) { - // Create footstep sound - Events::PlaySoundOnEntity e; - e.EmitterID = createChildEmitter(); - if (m_LeftFoot) { - e.FilePath = "Audio/footstep/footstep2.wav"; - } else { - e.FilePath = "Audio/footstep/footstep3.wav"; - } - m_LeftFoot = !m_LeftFoot; - m_EventBroker->Publish(e); - m_TimeSinceLastFootstep = 0; - } - } + //if (!m_LocalPlayer.Valid()) { + // return; + //} + //glm::vec3 pos = (glm::vec3)m_World->GetComponent(m_LocalPlayer.ID, "Transform")["Position"]; + //glm::vec3 vel = (glm::vec3)m_World->GetComponent(m_LocalPlayer.ID, "Physics")["Velocity"]; + //glm::vec3 difference = pos - m_LastPosition; + //m_DistanceMoved += glm::length(difference); + //bool isAirborne = vel.y != 0; + //if (m_DistanceMoved > m_PlayerStepLength && !isAirborne) { + // // Player is walking + // if (m_TimeSinceLastFootstep * std::min(playerSpeed, 2) > m_PlayerFootstepInterval) { + // // Create footstep sound + // Events::PlaySoundOnEntity e; + // e.EmitterID = createChildEmitter(m_LocalPlayer); + // e.FilePath = m_LeftFoot ? "Audio/footstep/footstep2.wav" : "Audio/footstep/footstep3.wav"; + // m_LeftFoot = !m_LeftFoot; + // m_EventBroker->Publish(e); + // m_TimeSinceLastFootstep = 0; + // } + //} } bool SoundSystem::OnPlayerSpawned(const Events::PlayerSpawned &e) @@ -59,7 +52,7 @@ bool SoundSystem::OnPlayerSpawned(const Events::PlayerSpawned &e) m_World->AttachComponent(e.Player.ID, "Listener"); m_LocalPlayer = e.Player; Events::PlaySoundOnEntity event; - event.EmitterID = createChildEmitter(); + event.EmitterID = createChildEmitter(m_LocalPlayer); event.FilePath = "Audio/announcer/go.wav"; m_EventBroker->Publish(event); // TEMP: starts bgm From 59bdc614f2b28991b91cc1f2b0f871cefb28a1f4 Mon Sep 17 00:00:00 2001 From: William Moberg Date: Fri, 5 Feb 2016 17:34:19 +0100 Subject: [PATCH 098/355] Put SpecialAbility on left shift, and Sprint on left shift in DefaultInput. --- resources/DefaultInput.ini | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/resources/DefaultInput.ini b/resources/DefaultInput.ini index a3f7d166..589dfb3f 100644 --- a/resources/DefaultInput.ini +++ b/resources/DefaultInput.ini @@ -13,7 +13,8 @@ A=Right,-1 R=Reload Space=Jump LeftControl=Crouch -LeftShift=Sprint +RightShift=Sprint +LeftShift=SpecialAbility F1=ToggleEditor C=ConnectToServer N=SwitchToServer From becb197feb237fb034f3a4a8d1c670b176f09e49 Mon Sep 17 00:00:00 2001 From: stiffly Date: Fri, 5 Feb 2016 17:46:27 +0100 Subject: [PATCH 099/355] Player walk is now based on distance traveled, and it is also reset when key is released. However when dashing the player step sound is still played. The distance of a step is also hard coded in the header file. Will config it up some day. --- include/Engine/Sound/SoundManager.h | 2 - include/Game/Systems/SoundSystem.h | 10 +++- src/Engine/Sound/SoundManager.cpp | 32 +------------ src/Game/Systems/SoundSystem.cpp | 72 ++++++++++++++++++++--------- 4 files changed, 60 insertions(+), 56 deletions(-) diff --git a/include/Engine/Sound/SoundManager.h b/include/Engine/Sound/SoundManager.h index ef291380..9ba4d2ad 100644 --- a/include/Engine/Sound/SoundManager.h +++ b/include/Engine/Sound/SoundManager.h @@ -133,8 +133,6 @@ private: bool OnShoot(const Events::Shoot &e); EventRelay m_EPlayerSpawned; bool OnPlayerSpawned(const Events::PlayerSpawned &e); - EventRelay m_EInputCommand; - bool OnInputCommand(const Events::InputCommand &e); EventRelay m_ECaptured; bool OnCaptured(const Events::Captured &e); EventRelay m_EPlayerDamage; diff --git a/include/Game/Systems/SoundSystem.h b/include/Game/Systems/SoundSystem.h index ec87e98a..aaadc3fd 100644 --- a/include/Game/Systems/SoundSystem.h +++ b/include/Game/Systems/SoundSystem.h @@ -4,6 +4,7 @@ #include "../Engine/Core/System.h" #include "../Engine/Sound/SoundManager.h" #include "../Engine/Core/EPlayerSpawned.h" +#include "../Engine/Input/EInputCommand.h" class SoundSystem : public PureSystem, ImpureSystem, SoundManager @@ -19,14 +20,19 @@ private: World* m_World = nullptr; EventBroker* m_EventBroker = nullptr; + void playerJumps(); + + // TODO: WIP Update this - double m_DistanceMoved = 0.0; - const float m_PlayerStepLength = 1.0; + float m_DistanceMoved = 0.0f; + const float m_PlayerStepLength = 2.0f; glm::vec3 m_LastPosition = glm::vec3(); bool m_LeftFoot = false; EventRelay m_EPlayerSpawned; bool OnPlayerSpawned(const Events::PlayerSpawned &e); + EventRelay m_InputCommand; + bool OnInputCommand(const Events::InputCommand &e); }; #endif diff --git a/src/Engine/Sound/SoundManager.cpp b/src/Engine/Sound/SoundManager.cpp index b7aaaff6..7046ecc1 100644 --- a/src/Engine/Sound/SoundManager.cpp +++ b/src/Engine/Sound/SoundManager.cpp @@ -23,7 +23,6 @@ SoundManager::SoundManager(World* world, EventBroker* eventBroker, bool editorMo EVENT_SUBSCRIBE_MEMBER(m_EShoot, &SoundManager::OnShoot); EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &SoundManager::OnPlayerSpawned); EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &SoundManager::OnPlayerDamage); - EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &SoundManager::OnInputCommand); EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &SoundManager::OnCaptured); EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &SoundManager::OnTriggerTouch); EVENT_SUBSCRIBE_MEMBER(m_EPause, &SoundManager::OnPause); @@ -182,16 +181,7 @@ void SoundManager::stopSound(Source* source) alSourceStop(source->ALsource); } -void SoundManager::playerJumps() -{ - glm::vec3 vel = (glm::vec3)m_World->GetComponent(m_LocalPlayer.ID, "Physics")["Velocity"]; - if (vel.y == 0) { - Source* source = createSource("Audio/jump/jump1.wav"); - source->Type = SoundType::SFX; - m_Sources[createChildEmitter(m_LocalPlayer)] = source; - playSound(source); - } -} + void SoundManager::playerStep(double dt) { @@ -303,26 +293,6 @@ bool SoundManager::OnPlayerSpawned(const Events::PlayerSpawned & e) return true; } -bool SoundManager::OnInputCommand(const Events::InputCommand & e) -{ - if (e.Command == "Jump" && e.Value > 0) { - if (e.PlayerID == -1) { // local player - playerJumps(); - return true; - } - } - // TEMP: testing purpose (obviously) - if (e.Command == "TakeDamage" && e.Value > 0) { - if (e.PlayerID == -1) { //Local Player - Events::PlayerDamage ePlayerDamage; - ePlayerDamage.Damage = 1; - ePlayerDamage.Player = EntityWrapper(m_World, e.Player.ID); - m_EventBroker->Publish(ePlayerDamage); - return true; - } - } - return false; -} bool SoundManager::OnCaptured(const Events::Captured & e) { diff --git a/src/Game/Systems/SoundSystem.cpp b/src/Game/Systems/SoundSystem.cpp index 99f3242d..e8ae324f 100644 --- a/src/Game/Systems/SoundSystem.cpp +++ b/src/Game/Systems/SoundSystem.cpp @@ -9,11 +9,12 @@ SoundSystem::SoundSystem(World* world, EventBroker* eventbroker) m_World = world; m_EventBroker = eventbroker; EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &SoundSystem::OnPlayerSpawned); + EVENT_SUBSCRIBE_MEMBER(m_InputCommand, &SoundSystem::OnInputCommand); } void SoundSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& cComponent, double dt) { - + } void SoundSystem::Update(double dt) @@ -24,26 +25,25 @@ void SoundSystem::Update(double dt) void SoundSystem::playerStep(double dt) { - //if (!m_LocalPlayer.Valid()) { - // return; - //} - //glm::vec3 pos = (glm::vec3)m_World->GetComponent(m_LocalPlayer.ID, "Transform")["Position"]; - //glm::vec3 vel = (glm::vec3)m_World->GetComponent(m_LocalPlayer.ID, "Physics")["Velocity"]; - //glm::vec3 difference = pos - m_LastPosition; - //m_DistanceMoved += glm::length(difference); - //bool isAirborne = vel.y != 0; - //if (m_DistanceMoved > m_PlayerStepLength && !isAirborne) { - // // Player is walking - // if (m_TimeSinceLastFootstep * std::min(playerSpeed, 2) > m_PlayerFootstepInterval) { - // // Create footstep sound - // Events::PlaySoundOnEntity e; - // e.EmitterID = createChildEmitter(m_LocalPlayer); - // e.FilePath = m_LeftFoot ? "Audio/footstep/footstep2.wav" : "Audio/footstep/footstep3.wav"; - // m_LeftFoot = !m_LeftFoot; - // m_EventBroker->Publish(e); - // m_TimeSinceLastFootstep = 0; - // } - //} + if (!m_LocalPlayer.Valid()) { + return; + } + glm::vec3 pos = (glm::vec3)m_World->GetComponent(m_LocalPlayer.ID, "Transform")["Position"]; + glm::vec3 vel = (glm::vec3)m_World->GetComponent(m_LocalPlayer.ID, "Physics")["Velocity"]; + glm::vec3 difference = pos - m_LastPosition; + m_LastPosition = pos; + m_DistanceMoved += glm::length(difference); + bool isAirborne = vel.y != 0; + if (m_DistanceMoved > m_PlayerStepLength && !isAirborne) { + // Player moved a step's distance + // Create footstep sound + Events::PlaySoundOnEntity e; + e.EmitterID = createChildEmitter(m_LocalPlayer); + e.FilePath = m_LeftFoot ? "Audio/footstep/footstep2.wav" : "Audio/footstep/footstep3.wav"; + m_LeftFoot = !m_LeftFoot; + m_EventBroker->Publish(e); + m_DistanceMoved = 0.f; + } } bool SoundSystem::OnPlayerSpawned(const Events::PlayerSpawned &e) @@ -64,3 +64,33 @@ bool SoundSystem::OnPlayerSpawned(const Events::PlayerSpawned &e) } return true; } + +bool SoundSystem::OnInputCommand(const Events::InputCommand & e) +{ + if (e.Command == "Jump" && e.Value > 0) { + if (e.PlayerID == -1) { // local player + playerJumps(); + return true; + } + } + if (e.Command == "Forward" || e.Command == "Right") { + if (e.Value == 0) { + // Key released + // Reset the distance moved + m_DistanceMoved = 0.f; + } + } + + return false; +} + +void SoundSystem::playerJumps() +{ + glm::vec3 vel = (glm::vec3)m_World->GetComponent(m_LocalPlayer.ID, "Physics")["Velocity"]; + if (vel.y == 0) { + Events::PlaySoundOnEntity e; + e.EmitterID = createChildEmitter(m_LocalPlayer); + e.FilePath = "Audio/jump/jump1.wav"; + m_EventBroker->Publish(e); + } +} From 09fb3a6571c99193ecc932ab727256c89af7b49c Mon Sep 17 00:00:00 2001 From: stiffly Date: Fri, 5 Feb 2016 18:04:36 +0100 Subject: [PATCH 100/355] Added some comments. --- include/Game/Systems/SoundSystem.h | 11 ++++++++--- src/Game/Systems/SoundSystem.cpp | 19 +++++++++++-------- 2 files changed, 19 insertions(+), 11 deletions(-) diff --git a/include/Game/Systems/SoundSystem.h b/include/Game/Systems/SoundSystem.h index aaadc3fd..77ebcfa1 100644 --- a/include/Game/Systems/SoundSystem.h +++ b/include/Game/Systems/SoundSystem.h @@ -14,19 +14,24 @@ public: virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& cComponent, double dt) override; virtual void Update(double dt) override; private: + // The logic for making the sound play when player is moving void playerStep(double dt); EntityWrapper m_LocalPlayer = EntityWrapper(); World* m_World = nullptr; EventBroker* m_EventBroker = nullptr; + // Logic for playing a sound when a player jumps void playerJumps(); - - // TODO: WIP Update this + // Walking logic + // Keeps track of how far the player has walked within this "key press session". float m_DistanceMoved = 0.0f; - const float m_PlayerStepLength = 2.0f; + // How far a step is (How often the step sound will be played). + const float m_PlayerStepLength = 1.75f; + // To get a difference when calculating the walking state. glm::vec3 m_LastPosition = glm::vec3(); + // Determine what sound file to play. bool m_LeftFoot = false; EventRelay m_EPlayerSpawned; diff --git a/src/Game/Systems/SoundSystem.cpp b/src/Game/Systems/SoundSystem.cpp index e8ae324f..06e028f2 100644 --- a/src/Game/Systems/SoundSystem.cpp +++ b/src/Game/Systems/SoundSystem.cpp @@ -20,6 +20,7 @@ void SoundSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& cComp void SoundSystem::Update(double dt) { playerStep(dt); + // Update listener and emitters. SoundManager::Update(dt); } @@ -28,11 +29,13 @@ void SoundSystem::playerStep(double dt) if (!m_LocalPlayer.Valid()) { return; } + // Position of the local player, used see how far a player has moved. glm::vec3 pos = (glm::vec3)m_World->GetComponent(m_LocalPlayer.ID, "Transform")["Position"]; + // Velocity of the local player, used to see if a player is airborne. glm::vec3 vel = (glm::vec3)m_World->GetComponent(m_LocalPlayer.ID, "Physics")["Velocity"]; - glm::vec3 difference = pos - m_LastPosition; + m_DistanceMoved += glm::length(pos - m_LastPosition); + // Set the last position for next iteration m_LastPosition = pos; - m_DistanceMoved += glm::length(difference); bool isAirborne = vel.y != 0; if (m_DistanceMoved > m_PlayerStepLength && !isAirborne) { // Player moved a step's distance @@ -56,11 +59,11 @@ bool SoundSystem::OnPlayerSpawned(const Events::PlayerSpawned &e) event.FilePath = "Audio/announcer/go.wav"; m_EventBroker->Publish(event); // TEMP: starts bgm -// { -// Events::PlayBackgroundMusic ev; -// ev.FilePath = "Audio/bgm/ambient.wav"; -// m_EventBroker->Publish(ev); -// } + { + Events::PlayBackgroundMusic ev; + ev.FilePath = "Audio/bgm/ambient.wav"; + m_EventBroker->Publish(ev); + } } return true; } @@ -76,7 +79,7 @@ bool SoundSystem::OnInputCommand(const Events::InputCommand & e) if (e.Command == "Forward" || e.Command == "Right") { if (e.Value == 0) { // Key released - // Reset the distance moved + // Reset the distance moved (player walk logic) m_DistanceMoved = 0.f; } } From 4103c878ec69399e256ab13c302ef5bb3390dabf Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Fri, 5 Feb 2016 18:05:46 +0100 Subject: [PATCH 101/355] Refactoring: Changed HealthPickupSystem to use a struct instead. Removed the Id in EPickupSpawned --- include/Engine/Core/EPickupSpawned.h | 1 - include/Game/Systems/PickupSpawnSystem.h | 10 +++- resources/Schema/Entities/HealthPickup.xml | 2 +- .../Schema/Entities/HealthPickupTest.xml | 51 +++++++++++++++++++ src/Game/Systems/PickupSpawnSystem.cpp | 24 ++++----- 5 files changed, 71 insertions(+), 17 deletions(-) diff --git a/include/Engine/Core/EPickupSpawned.h b/include/Engine/Core/EPickupSpawned.h index dc3bc632..9f85913a 100644 --- a/include/Engine/Core/EPickupSpawned.h +++ b/include/Engine/Core/EPickupSpawned.h @@ -9,7 +9,6 @@ namespace Events struct PickupSpawned : Event { - EntityID PickupID; EntityWrapper Pickup; }; diff --git a/include/Game/Systems/PickupSpawnSystem.h b/include/Game/Systems/PickupSpawnSystem.h index fbb2f082..24cee2b9 100644 --- a/include/Game/Systems/PickupSpawnSystem.h +++ b/include/Game/Systems/PickupSpawnSystem.h @@ -6,7 +6,7 @@ #include "Core/ResourceManager.h" #include "Core/EntityFileParser.h" #include "Core/EPickupSpawned.h" -#include "Core/EPlayerHealthPickup.h"; +#include "Core/EPlayerHealthPickup.h" #include "Engine/Collision/ETrigger.h" #include "Common.h" #include @@ -22,6 +22,12 @@ private: EventRelay m_ETriggerTouch; bool OnTriggerTouch(Events::TriggerTouch& e); - std::vector> m_ETriggerTouchVector; + struct NewHealthPickup { + glm::vec3 Pos; + double HealthGain; + double RespawnTimer; + double DecreaseThisRespawnTimer; + }; + std::vector m_ETriggerTouchVector; }; #endif diff --git a/resources/Schema/Entities/HealthPickup.xml b/resources/Schema/Entities/HealthPickup.xml index f1b787f6..dfc6f938 100644 --- a/resources/Schema/Entities/HealthPickup.xml +++ b/resources/Schema/Entities/HealthPickup.xml @@ -8,7 +8,7 @@ Models/Core/UnitSphere.mesh - + diff --git a/resources/Schema/Entities/HealthPickupTest.xml b/resources/Schema/Entities/HealthPickupTest.xml index 97fd3f4d..2980fb51 100644 --- a/resources/Schema/Entities/HealthPickupTest.xml +++ b/resources/Schema/Entities/HealthPickupTest.xml @@ -238,6 +238,57 @@ + + + + + 1 + 22 + + + Models/Core/UnitSphere.mesh + + + + + + + + + + + + + 1 + 22 + + + Models/Core/UnitSphere.mesh + + + + + + + + + + + + + 4 + 44 + + + Models/Core/UnitSphere.mesh + + + + + + + + diff --git a/src/Game/Systems/PickupSpawnSystem.cpp b/src/Game/Systems/PickupSpawnSystem.cpp index 558aef14..783f7a62 100644 --- a/src/Game/Systems/PickupSpawnSystem.cpp +++ b/src/Game/Systems/PickupSpawnSystem.cpp @@ -8,10 +8,12 @@ PickupSpawnSystem::PickupSpawnSystem(World* m_World, EventBroker* eventBroker) void PickupSpawnSystem::Update(double dt) { - for (auto &healthPickupPosition : m_ETriggerTouchVector) { + for (auto it = m_ETriggerTouchVector.begin(); it != m_ETriggerTouchVector.end(); ++it) + { + auto& healthPickupPosition = *it; //set the double timer value (value 3) - std::get<3>(healthPickupPosition) -= dt; - if (std::get<3>(healthPickupPosition) < 0) { + healthPickupPosition.DecreaseThisRespawnTimer -= dt; + if (healthPickupPosition.DecreaseThisRespawnTimer < 0) { //spawn and delete the vector item auto entityFile = ResourceManager::Load("Schema/Entities/HealthPickup.xml"); EntityFileParser parser(entityFile); @@ -19,18 +21,17 @@ void PickupSpawnSystem::Update(double dt) //let the world know a pickup has spawned (graphics effects, etc) Events::PickupSpawned ePickupSpawned; - ePickupSpawned.PickupID = healthPickupID; ePickupSpawned.Pickup = EntityWrapper(m_World, healthPickupID); m_EventBroker->Publish(ePickupSpawned); //set values from the old entity to the new entity auto& newHealthPickupEntity = EntityWrapper(m_World, healthPickupID); - newHealthPickupEntity["Transform"]["Position"] = std::get<0>(healthPickupPosition); - newHealthPickupEntity["HealthPickup"]["HealthGain"] = std::get<1>(healthPickupPosition); - newHealthPickupEntity["HealthPickup"]["RespawnTimer"] = std::get<2>(healthPickupPosition); + newHealthPickupEntity["Transform"]["Position"] = healthPickupPosition.Pos; + newHealthPickupEntity["HealthPickup"]["HealthGain"] = healthPickupPosition.HealthGain; + newHealthPickupEntity["HealthPickup"]["RespawnTimer"] = healthPickupPosition.RespawnTimer; //erase the current element (healthPickupPosition) - m_ETriggerTouchVector.erase(std::remove(m_ETriggerTouchVector.begin(), m_ETriggerTouchVector.end(), healthPickupPosition), m_ETriggerTouchVector.end()); + m_ETriggerTouchVector.erase(it); break; } } @@ -50,11 +51,8 @@ bool PickupSpawnSystem::OnTriggerTouch(Events::TriggerTouch& e) //copy position, healthgain, respawntimer (twice since one of the values will be counted down to 0, the other will be set in the new object) //we need to copy all values since each value can be different for each healthPickup - m_ETriggerTouchVector.push_back(std::make_tuple( - (glm::vec3)e.Trigger["Transform"]["Position"], - e.Trigger["HealthPickup"]["HealthGain"], - e.Trigger["HealthPickup"]["RespawnTimer"], - e.Trigger["HealthPickup"]["RespawnTimer"])); + m_ETriggerTouchVector.push_back({ (glm::vec3)e.Trigger["Transform"]["Position"] ,e.Trigger["HealthPickup"]["HealthGain"], + e.Trigger["HealthPickup"]["RespawnTimer"],e.Trigger["HealthPickup"]["RespawnTimer"] }); //delete the healthpickup m_World->DeleteEntity(e.Trigger.ID); From 88d7b79cd32f60a91c12ec413cf99b31da453700 Mon Sep 17 00:00:00 2001 From: Jocke Date: Fri, 5 Feb 2016 18:30:31 +0100 Subject: [PATCH 102/355] TCP and UDP Client are working for 1 connected player, more players are not tested yet --- include/Engine/Network/Client.h | 4 +- include/Engine/Network/HybridClient.h | 1 + include/Engine/Network/HybridServer.h | 7 +- include/Engine/Network/Network.h | 2 +- include/Engine/Network/Packet.h | 2 + include/Engine/Network/PlayerDefinition.h | 2 + include/Engine/Network/Server.h | 18 ++-- include/Engine/Network/TCPClient.h | 1 + include/Engine/Network/TCPServer.h | 11 --- src/Engine/Network/Client.cpp | 16 ++-- src/Engine/Network/HybridClient.cpp | 14 ++- src/Engine/Network/HybridServer.cpp | 93 ++----------------- src/Engine/Network/Packet.cpp | 9 +- src/Engine/Network/Server.cpp | 103 ++++++++++++++++++++-- src/Engine/Network/TCPClient.cpp | 61 ++++++++++--- src/Engine/Network/TCPServer.cpp | 85 ++++++++++-------- src/Game/Game.cpp | 6 +- 17 files changed, 253 insertions(+), 182 deletions(-) diff --git a/include/Engine/Network/Client.h b/include/Engine/Network/Client.h index 1c445cac..5259504b 100644 --- a/include/Engine/Network/Client.h +++ b/include/Engine/Network/Client.h @@ -35,7 +35,7 @@ protected: int port = 0; // Sending message to server logic int bytesRead = -1; - char readBuf[INPUTSIZE] = { 0 }; + char readBuffer[BUFFERSIZE] = { 0 }; // Packet loss logic PacketID m_PacketID = 0; @@ -68,7 +68,7 @@ protected: // Private member functions virtual void send(Packet& packet) = 0; virtual void readFromServer() = 0; - void connect(); + virtual void connect() = 0; void disconnect(); void parseMessageType(Packet& packet); void updateFields(Packet& packet, const ComponentInfo& componentInfo, const EntityID& entityID, const std::string& componentType); diff --git a/include/Engine/Network/HybridClient.h b/include/Engine/Network/HybridClient.h index 8c9d1a68..fb2777d4 100644 --- a/include/Engine/Network/HybridClient.h +++ b/include/Engine/Network/HybridClient.h @@ -16,6 +16,7 @@ private: boost::asio::io_service m_IOService; boost::asio::ip::udp::socket m_Socket; + void connect(); void readFromServer(); int receive(char * data); void send(Packet & packet); diff --git a/include/Engine/Network/HybridServer.h b/include/Engine/Network/HybridServer.h index 95a9ffde..f12dc660 100644 --- a/include/Engine/Network/HybridServer.h +++ b/include/Engine/Network/HybridServer.h @@ -13,18 +13,13 @@ private: // UDP logic boost::asio::io_service m_IOService; std::unique_ptr m_Socket; + boost::asio::ip::udp::endpoint m_ReceiverEndpoint; void readFromClients(); - void parseClientPing(); - void parsePing(); - void parseDisconnect(); void parseConnect(Packet & packet); - void parseOnInputCommand(Packet & packet); - void parsePlayerTransform(Packet & packet); void send(Packet & packet, PlayerDefinition & playerDefinition); void send(Packet & packet); int receive(char * data); - PlayerID GetPlayerIDFromEndpoint(boost::asio::ip::udp::endpoint endpoint); }; #endif \ No newline at end of file diff --git a/include/Engine/Network/Network.h b/include/Engine/Network/Network.h index e1e64fc1..caf55f13 100644 --- a/include/Engine/Network/Network.h +++ b/include/Engine/Network/Network.h @@ -12,7 +12,7 @@ #include #include -#define INPUTSIZE 32000 +#define BUFFERSIZE 32000 typedef unsigned int PlayerID; typedef unsigned int PacketID; diff --git a/include/Engine/Network/Packet.h b/include/Engine/Network/Packet.h index d38ddf58..b7e774c2 100644 --- a/include/Engine/Network/Packet.h +++ b/include/Engine/Network/Packet.h @@ -49,6 +49,8 @@ public: void WriteData(char* data, int sizeOfData); // Pops the first element as if it was a string. std::string ReadString(); + // Update size of packet variable in header + void UpdateSize(); char* ReadData(int SizeOfData); void ChangePacketID(unsigned int& packetID); int Size() { return m_Offset; }; diff --git a/include/Engine/Network/PlayerDefinition.h b/include/Engine/Network/PlayerDefinition.h index 3a3dd122..e4c3e5c5 100644 --- a/include/Engine/Network/PlayerDefinition.h +++ b/include/Engine/Network/PlayerDefinition.h @@ -10,6 +10,8 @@ struct PlayerDefinition { boost::asio::ip::udp::endpoint Endpoint; unsigned int PacketID; std::clock_t StopTime; + boost::asio::ip::address Address; + unsigned short Port; // use for tcp connections boost::shared_ptr TCPSocket; }; diff --git a/include/Engine/Network/Server.h b/include/Engine/Network/Server.h index 2926558f..4ff169d2 100644 --- a/include/Engine/Network/Server.h +++ b/include/Engine/Network/Server.h @@ -25,12 +25,13 @@ public: void Start(World* m_world, EventBroker *eventBroker) override; void Update() override; protected: - template - T m_ReceiverEndpoint; + // dont forget to set these in the childrens receive logic + boost::asio::ip::address m_Address; + unsigned short m_Port; // Sending messages to client logic std::map m_ConnectedPlayers; // HACK: Fix INPUTSIZE - char readBuffer[INPUTSIZE] = { 0 }; + char readBuffer[BUFFERSIZE] = { 0 }; int bytesRead = 0; // time for previouse message std::clock_t previousePingMessage = std::clock(); @@ -65,15 +66,17 @@ protected: void parseOnPlayerDamage(Packet& packet); void identifyPacketLoss(); void kick(PlayerID player); + PlayerID GetPlayerIDFromEndpoint(); + void parsePlayerTransform(Packet& packet); + void parseOnInputCommand(Packet& packet); + void parseClientPing(); + void parsePing(); + void parseDisconnect(); // Pure virtual functions - virtual void parseOnInputCommand(Packet& packet) = 0; virtual void readFromClients() = 0; virtual void send(Packet& packet, PlayerDefinition & playerDefinition) = 0; virtual void send(Packet& packet) = 0; virtual void parseConnect(Packet& packet) = 0; - virtual void parseDisconnect() = 0; - virtual void parseClientPing() = 0; - virtual void parsePing() = 0; // Debug event EventRelay m_EInputCommand; bool OnInputCommand(const Events::InputCommand& e); @@ -83,7 +86,6 @@ protected: bool OnEntityDeleted(const Events::EntityDeleted& e); EventRelay m_EComponentDeleted; bool OnComponentDeleted(const Events::ComponentDeleted& e); - virtual void parsePlayerTransform(Packet& packet) = 0; }; #endif diff --git a/include/Engine/Network/TCPClient.h b/include/Engine/Network/TCPClient.h index 14415eef..e90e049c 100644 --- a/include/Engine/Network/TCPClient.h +++ b/include/Engine/Network/TCPClient.h @@ -15,6 +15,7 @@ private: boost::asio::io_service m_IOService; boost::shared_ptr m_Socket; + void connect(); void readFromServer(); int receive(char * data); void send(Packet & packet); diff --git a/include/Engine/Network/TCPServer.h b/include/Engine/Network/TCPServer.h index 23f6d666..61e40639 100644 --- a/include/Engine/Network/TCPServer.h +++ b/include/Engine/Network/TCPServer.h @@ -8,30 +8,19 @@ class TCPServer : public Server public: TCPServer(); ~TCPServer(); - private: // TCP logic - boost::asio::ip::udp::endpoint m_ReceiverEndpoint; boost::asio::io_service m_IOService; std::unique_ptr acceptor; boost::shared_ptr lastReceivedSocket; - void Start(World* world, EventBroker* eventBroker); void readFromClients(); void acceptNewConnections(); void handle_accept(boost::shared_ptr socket, const boost::system::error_code & error); - void parseDisconnect(); void parseConnect(Packet & packet); - ///// Implement method to get which player it was - void parseClientPing(); - void parsePing(); - void parseOnInputCommand(Packet & packet); - void parsePlayerTransform(Packet & packet); - ///////////////////////// void send(Packet & packet, PlayerDefinition & playerDefinition); void send(Packet & packet); int receive(char * data, boost::asio::ip::tcp::socket& socket); - PlayerID GetPlayerIDFromEndpoint(boost::asio::ip::udp::endpoint endpoint); }; #endif \ No newline at end of file diff --git a/src/Engine/Network/Client.cpp b/src/Engine/Network/Client.cpp index 6f9519d5..13efad40 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -49,6 +49,9 @@ void Client::Update() void Client::parseMessageType(Packet& packet) { + // Pop packetSize which is used by TCP Client to + // create a packet of the correct size + packet.ReadPrimitive(); int messageType = packet.ReadPrimitive(); if (messageType == -1) return; @@ -240,16 +243,9 @@ void Client::parseSnapshot(Packet& packet) } } -void Client::connect() -{ - Packet packet(MessageType::Connect, m_SendPacketID); - packet.WriteString(m_PlayerName); - m_StartPingTime = std::clock(); - send(packet); -} - void Client::disconnect() { + m_IsConnected = false; m_PreviousPacketID = 0; m_PacketID = 0; Packet packet(MessageType::Disconnect, m_SendPacketID); @@ -283,7 +279,9 @@ bool Client::OnInputCommand(const Events::InputCommand & e) m_SaveDataTimer = std::clock(); } } else { - m_InputCommandBuffer.push_back(e); + if (m_IsConnected) { + m_InputCommandBuffer.push_back(e); + } //LOG_DEBUG("Client::OnInputCommand: Command is %s. Value is %f. PlayerID is %i.", e.Command.c_str(), e.Value, e.PlayerID); return true; } diff --git a/src/Engine/Network/HybridClient.cpp b/src/Engine/Network/HybridClient.cpp index fd0b6649..eabe109b 100644 --- a/src/Engine/Network/HybridClient.cpp +++ b/src/Engine/Network/HybridClient.cpp @@ -21,9 +21,9 @@ void HybridClient::Start(World* world, EventBroker* eventBroker) void HybridClient::readFromServer() { while (m_Socket.available()) { - bytesRead = receive(readBuf); + bytesRead = receive(readBuffer); if (bytesRead > 0) { - Packet packet(readBuf, bytesRead); + Packet packet(readBuffer, bytesRead); parseMessageType(packet); } } @@ -34,7 +34,7 @@ int HybridClient::receive(char* data) boost::system::error_code error; int bytesReceived = m_Socket.receive_from(boost - ::asio::buffer((void*)data, INPUTSIZE), + ::asio::buffer((void*)data, BUFFERSIZE), m_ReceiverEndpoint, 0, error); // Network Debug data @@ -61,4 +61,12 @@ void HybridClient::send(Packet& packet) m_NetworkData.DataSentThisInterval += packet.Size(); m_NetworkData.AmountOfMessagesSent++; } +} + +void HybridClient::connect() +{ + Packet packet(MessageType::Connect, m_SendPacketID); + packet.WriteString(m_PlayerName); + m_StartPingTime = std::clock(); + send(packet); } \ No newline at end of file diff --git a/src/Engine/Network/HybridServer.cpp b/src/Engine/Network/HybridServer.cpp index e4142725..6c22bab7 100644 --- a/src/Engine/Network/HybridServer.cpp +++ b/src/Engine/Network/HybridServer.cpp @@ -15,6 +15,8 @@ void HybridServer::readFromClients() while (m_Socket->available()) { try { bytesRead = receive(readBuffer); + m_Address = m_ReceiverEndpoint.address(); + m_Port = m_ReceiverEndpoint.port(); Packet packet(readBuffer, bytesRead); parseMessageType(packet); } catch (const std::exception& err) { @@ -41,53 +43,19 @@ void HybridServer::readFromClients() } } -void HybridServer::parseClientPing() -{ - LOG_INFO("%i: Parsing ping", m_PacketID); - PlayerID player = GetPlayerIDFromEndpoint(m_ReceiverEndpoint); - if (player == -1) { - return; - } - // Return ping - Packet packet(MessageType::Ping, m_ConnectedPlayers[player].PacketID); - packet.WriteString("Ping received"); - send(packet); -} - -void HybridServer::parsePing() -{ - for (int i = 0; i < m_ConnectedPlayers.size(); i++) { - if (m_ConnectedPlayers[i].Endpoint.address() == m_ReceiverEndpoint.address()) { - m_ConnectedPlayers[i].StopTime = std::clock(); - break; - } - } -} - -void HybridServer::parseDisconnect() -{ - LOG_INFO("%i: Parsing disconnect", m_PacketID); - - for (auto& kv : m_ConnectedPlayers) { - if (kv.second.Endpoint.address() == m_ReceiverEndpoint.address() && - kv.second.Endpoint.port() == m_ReceiverEndpoint.port()) { - disconnect(kv.first); - break; - } - } -} - void HybridServer::parseConnect(Packet& packet) { LOG_INFO("Parsing connections"); // Check if player is already connected - if (GetPlayerIDFromEndpoint(m_ReceiverEndpoint) != -1) { + if (GetPlayerIDFromEndpoint() != -1) { return; } // Create a new player PlayerDefinition pd; pd.EntityID = 0; // Overlook this pd.Endpoint = m_ReceiverEndpoint; + pd.Address = m_ReceiverEndpoint.address(); + pd.Port = m_ReceiverEndpoint.port(); pd.Name = packet.ReadString(); pd.PacketID = 0; pd.StopTime = std::clock(); @@ -103,44 +71,6 @@ void HybridServer::parseConnect(Packet& packet) broadcast(notificationPacket); } -void HybridServer::parseOnInputCommand(Packet& packet) -{ - PlayerID player = -1; - // Check which player it was who sent the message - player = GetPlayerIDFromEndpoint(m_ReceiverEndpoint); - if (player != -1) { - while (packet.DataReadSize() < packet.Size()) { - Events::InputCommand e; - e.Command = packet.ReadString(); - e.PlayerID = player; // Set correct player id - e.Player = EntityWrapper(m_World, m_ConnectedPlayers.at(player).EntityID); - e.Value = packet.ReadPrimitive(); - m_EventBroker->Publish(e); - LOG_INFO("Server::parseOnInputCommand: Command is %s. Value is %f. PlayerID is %i.", e.Command.c_str(), e.Value, e.PlayerID); - } - } -} - -void HybridServer::parsePlayerTransform(Packet& packet) -{ - glm::vec3 position; - glm::vec3 orientation; - position.x = packet.ReadPrimitive(); - position.y = packet.ReadPrimitive(); - position.z = packet.ReadPrimitive(); - orientation.x = packet.ReadPrimitive(); - orientation.y = packet.ReadPrimitive(); - orientation.z = packet.ReadPrimitive(); - - PlayerID playerID = GetPlayerIDFromEndpoint(m_ReceiverEndpoint); - EntityWrapper player(m_World, m_ConnectedPlayers.at(playerID).EntityID); - - if (player.Valid()) { - player["Transform"]["Position"] = position; - player["Transform"]["Orientation"] = orientation; - } -} - void HybridServer::send(Packet& packet, PlayerDefinition & playerDefinition) { try { @@ -180,7 +110,7 @@ int HybridServer::receive(char * data) { unsigned int length = m_Socket->receive_from( boost::asio::buffer((void*)data - , INPUTSIZE) + , BUFFERSIZE) , m_ReceiverEndpoint, 0); // Network Debug data if (isReadingData) { @@ -191,13 +121,4 @@ int HybridServer::receive(char * data) return length; } -PlayerID HybridServer::GetPlayerIDFromEndpoint(boost::asio::ip::udp::endpoint endpoint) -{ - for (auto& kv : m_ConnectedPlayers) { - if (kv.second.Endpoint.address() == endpoint.address() && - kv.second.Endpoint.port() == endpoint.port()) { - return kv.first; - } - } - return -1; -} + diff --git a/src/Engine/Network/Packet.cpp b/src/Engine/Network/Packet.cpp index d40a1b32..28622611 100644 --- a/src/Engine/Network/Packet.cpp +++ b/src/Engine/Network/Packet.cpp @@ -34,6 +34,8 @@ void Packet::Init(MessageType type, unsigned int & packetID) m_ReturnDataOffset = 0; m_Offset = 0; // Create message header + // allocate memory for size of packet(only used in tcp) + Packet::WritePrimitive(0); // Add message type int messageType = static_cast(type); Packet::WritePrimitive(messageType); @@ -76,6 +78,11 @@ std::string Packet::ReadString() return returnValue; } +void Packet::UpdateSize() +{ + memcpy(m_Data, &m_Offset, sizeof(int)); +} + char * Packet::ReadData(int SizeOfData) { if (m_Offset < m_ReturnDataOffset + SizeOfData) { @@ -91,7 +98,7 @@ void Packet::ChangePacketID(unsigned int & packetID) { packetID = packetID + 1; // Overwrite old PacketID - memcpy(m_Data + sizeof(int), &packetID, sizeof(int)); + memcpy(m_Data + 2*sizeof(int), &packetID, sizeof(int)); } void Packet::resizeData() diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index 37b2e752..55f59a03 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -35,6 +35,10 @@ void Server::Update() void Server::parseMessageType(Packet& packet) { + // Pop packetSize which is used by TCP Client to + // create a packet of the correct size + packet.ReadPrimitive(); + int messageType = packet.ReadPrimitive(); // Read what type off message was sent from server // Read packet ID m_PreviousPacketID = m_PacketID; // Set previous packet id @@ -150,25 +154,38 @@ void Server::checkForTimeOuts() int startPing = 1000 * m_StartPingTime / static_cast(CLOCKS_PER_SEC); - for (int i = 0; i < m_ConnectedPlayers.size(); i++) { - if (m_ConnectedPlayers[i].Endpoint.address() != boost::asio::ip::address()) { - int stopPing = 1000 * m_ConnectedPlayers[i].StopTime / + for (auto& kv : m_ConnectedPlayers) { + if (kv.second.Address != boost::asio::ip::address()) { + int stopPing = 1000 * kv.second.StopTime / static_cast(CLOCKS_PER_SEC); if (startPing > stopPing + m_TimeoutMs) { - LOG_INFO("User %i timed out!", i); - disconnect(i); + LOG_INFO("User %i timed out!", kv.second.Name); + disconnect(kv.first); } } } } +void Server::parseDisconnect() +{ + LOG_INFO("%i: Parsing disconnect", m_PacketID); + + for (auto& kv : m_ConnectedPlayers) { + if (kv.second.Address == m_Address && + kv.second.Port == m_Port) { + disconnect(kv.first); + break; + } + } +} + void Server::disconnect(PlayerID playerID) { //broadcast("A player disconnected"); LOG_INFO("User %s disconnected/timed out", m_ConnectedPlayers[playerID].Name.c_str()); // Remove enteties and stuff (When we can remove entity, remove it and tell clients to remove the copy they have) Events::PlayerDisconnected e; - e.Entity = m_ConnectedPlayers[playerID].EntityID; + e.Entity = m_ConnectedPlayers.at(playerID).EntityID; e.PlayerID = playerID; m_EventBroker->Publish(e); @@ -250,3 +267,77 @@ bool Server::OnComponentDeleted(const Events::ComponentDeleted & e) } return false; } + + +void Server::parseClientPing() +{ + LOG_INFO("%i: Parsing ping", m_PacketID); + PlayerID player = GetPlayerIDFromEndpoint(); + if (player == -1) { + return; + } + // Return ping + Packet packet(MessageType::Ping, m_ConnectedPlayers[player].PacketID); + packet.WriteString("Ping received"); + send(packet); +} + +void Server::parsePing() +{ + for (auto& kv : m_ConnectedPlayers) { + if (kv.second.Address == m_Address && + kv.second.Port == m_Port) { + kv.second.StopTime = std::clock(); + break; + } + } +} + +void Server::parseOnInputCommand(Packet& packet) +{ + PlayerID player = -1; + // Check which player it was who sent the message + player = GetPlayerIDFromEndpoint(); + if (player != -1) { + while (packet.DataReadSize() < packet.Size()) { + Events::InputCommand e; + e.Command = packet.ReadString(); + e.PlayerID = player; // Set correct player id + e.Player = EntityWrapper(m_World, m_ConnectedPlayers.at(player).EntityID); + e.Value = packet.ReadPrimitive(); + m_EventBroker->Publish(e); + LOG_INFO("Server::parseOnInputCommand: Command is %s. Value is %f. PlayerID is %i.", e.Command.c_str(), e.Value, e.PlayerID); + } + } +} + +void Server::parsePlayerTransform(Packet& packet) +{ + glm::vec3 position; + glm::vec3 orientation; + position.x = packet.ReadPrimitive(); + position.y = packet.ReadPrimitive(); + position.z = packet.ReadPrimitive(); + orientation.x = packet.ReadPrimitive(); + orientation.y = packet.ReadPrimitive(); + orientation.z = packet.ReadPrimitive(); + + PlayerID playerID = GetPlayerIDFromEndpoint(); + EntityWrapper player(m_World, m_ConnectedPlayers.at(playerID).EntityID); + + if (player.Valid()) { + player["Transform"]["Position"] = position; + player["Transform"]["Orientation"] = orientation; + } +} + +PlayerID Server::GetPlayerIDFromEndpoint() +{ + for (auto& kv : m_ConnectedPlayers) { + if (kv.second.Address == m_Address && + kv.second.Port == m_Port) { + return kv.first; + } + } + return -1; +} \ No newline at end of file diff --git a/src/Engine/Network/TCPClient.cpp b/src/Engine/Network/TCPClient.cpp index d4909f56..3d7261b7 100644 --- a/src/Engine/Network/TCPClient.cpp +++ b/src/Engine/Network/TCPClient.cpp @@ -3,39 +3,76 @@ using namespace boost::asio::ip; TCPClient::TCPClient(ConfigFile * config) : Client(config) -{ +{ m_Endpoint = tcp::endpoint(boost::asio::ip::address::from_string(address), port); - m_Socket = boost::shared_ptr(new tcp::socket(m_IOService)); + m_Socket = boost::shared_ptr(new tcp::socket(m_IOService, m_Endpoint)); + tcp::no_delay option(true); + m_Socket->set_option(option); } TCPClient::~TCPClient() -{ +{ } void TCPClient::Start(World * world, EventBroker * eventBroker) -{ +{ Client::Start(world, eventBroker); - boost::system::error_code error = boost::asio::error::host_not_found; - while (error) { +} +void TCPClient::connect() +{ + if (!m_IsConnected) { + boost::system::error_code error = boost::asio::error::host_not_found; m_Socket->close(); - m_Socket->connect(m_Endpoint,error); + m_Socket->connect(m_Endpoint, error); LOG_INFO(error.message().c_str()); + if (!error) { + Packet packet(MessageType::Connect, m_SendPacketID); + packet.WriteString(m_PlayerName); + m_StartPingTime = std::clock(); + send(packet); + } } } - +// TODO FIX CRASH TCP CLIENT SEVER DISCONNECTS FIRST void TCPClient::readFromServer() -{ - +{ + while (m_Socket->available()) { + bytesRead = receive(readBuffer); + Packet packet(readBuffer, bytesRead); + parseMessageType(packet); + } } int TCPClient::receive(char * data) { - return 0; + boost::system::error_code error; + // Read size of packet + int bytesReceived = m_Socket->read_some(boost + ::asio::buffer((void*)data, sizeof(int)), + error); + int sizeOfPacket = 0; + memcpy(&sizeOfPacket, data, sizeof(int)); + + // Read the rest of the message + bytesReceived += m_Socket->read_some(boost + ::asio::buffer((void*)(data + bytesReceived), sizeOfPacket - bytesReceived), + error); + // Network Debug data + if (isReadingData) { + m_NetworkData.TotalDataReceived += bytesReceived; + m_NetworkData.DataReceivedThisInterval += bytesReceived; + m_NetworkData.AmountOfMessagesReceived++; + } + if (error) { + //LOG_ERROR("receive: %s", error.message().c_str()); + } + return bytesReceived; } void TCPClient::send(Packet & packet) -{ +{ + packet.UpdateSize(); m_Socket->send(boost::asio::buffer( packet.Data(), packet.Size())); diff --git a/src/Engine/Network/TCPServer.cpp b/src/Engine/Network/TCPServer.cpp index 930e7913..caf37ee8 100644 --- a/src/Engine/Network/TCPServer.cpp +++ b/src/Engine/Network/TCPServer.cpp @@ -11,11 +11,6 @@ TCPServer::~TCPServer() } -void TCPServer::Start(World* world, EventBroker* eventBroker) -{ - Server::Start(world, eventBroker); -} - void TCPServer::readFromClients() { acceptNewConnections(); @@ -24,6 +19,11 @@ void TCPServer::readFromClients() try { bytesRead = receive(readBuffer, *kv.second.TCPSocket); lastReceivedSocket = kv.second.TCPSocket; + // Get logic for mother class + boost::asio::ip::tcp::endpoint remoteEndpoint = kv.second.TCPSocket->remote_endpoint(); + m_Address = remoteEndpoint.address(); + m_Port = remoteEndpoint.port(); + // Recreate packets Packet packet(readBuffer, bytesRead); parseMessageType(packet); } catch (const std::exception& err) { @@ -63,41 +63,48 @@ void TCPServer::acceptNewConnections() void TCPServer::handle_accept(boost::shared_ptr socket, const boost::system::error_code& error) { - if (!error) { + if (!error && GetPlayerIDFromEndpoint() == -1) { // Add tcp socket to connections + boost::asio::ip::tcp::no_delay option(true); + socket->set_option(option); PlayerDefinition pd; pd.StopTime = std::clock(); pd.TCPSocket = socket; + pd.Address = socket.get()->remote_endpoint().address(); + pd.Port = socket.get()->remote_endpoint().port(); m_ConnectedPlayers[m_NextPlayerID++] = pd; } } -void TCPServer::parseClientPing() -{ -} -void TCPServer::parsePing() -{ - -} -void TCPServer::parseDisconnect() -{ - -} void TCPServer::parseConnect(Packet & packet) { + LOG_INFO("Parsing connections"); + // Check if player is already connected + PlayerID playerID = GetPlayerIDFromEndpoint(); + if(playerID = -1){ + return; + } -} -void TCPServer::parseOnInputCommand(Packet & packet) -{ + // Create a new player + m_ConnectedPlayers.at(playerID).EntityID = 0; // Overlook this + m_ConnectedPlayers.at(playerID).Name = packet.ReadString(); + m_ConnectedPlayers.at(playerID).PacketID = 0; + m_ConnectedPlayers.at(playerID).StopTime = std::clock(); + LOG_INFO("Spectator \"%s\" connected on IP: %s", m_ConnectedPlayers.at(playerID).Name.c_str(), m_ConnectedPlayers.at(playerID).Endpoint.address().to_string().c_str()); -} -void TCPServer::parsePlayerTransform(Packet & packet) -{ + // Send a message to the player that connected + Packet connnectPacket(MessageType::Connect, m_ConnectedPlayers.at(playerID).PacketID); + send(connnectPacket); + // Send notification that a player has connected + Packet notificationPacket(MessageType::PlayerConnected); + broadcast(notificationPacket); } + void TCPServer::send(Packet & packet, PlayerDefinition & playerDefinition) { try { + packet.UpdateSize(); int bytesSent = playerDefinition.TCPSocket->send( boost::asio::buffer(packet.Data(), packet.Size()), 0); @@ -115,6 +122,7 @@ void TCPServer::send(Packet & packet, PlayerDefinition & playerDefinition) void TCPServer::send(Packet & packet) { + packet.UpdateSize(); lastReceivedSocket->send( boost::asio::buffer( packet.Data(), @@ -128,21 +136,28 @@ void TCPServer::send(Packet & packet) } //boost::shared_ptr socket -int TCPServer::receive(char * data,boost::asio::ip::tcp::socket& socket) +int TCPServer::receive(char * data, boost::asio::ip::tcp::socket& socket) { - unsigned int length = socket.read_some( - boost::asio::buffer((void*)data, INPUTSIZE)); + boost::system::error_code error; + // Read size of packet + int bytesReceived = socket.read_some(boost + ::asio::buffer((void*)data, sizeof(int)), + error); + int sizeOfPacket = 0; + memcpy(&sizeOfPacket, data, sizeof(int)); + + // Read the rest of the message + bytesReceived += socket.read_some(boost + ::asio::buffer((void*)(data + bytesReceived), sizeOfPacket - bytesReceived), + error); // Network Debug data if (isReadingData) { - m_NetworkData.TotalDataReceived += length; - m_NetworkData.DataReceivedThisInterval += length; + m_NetworkData.TotalDataReceived += bytesReceived; + m_NetworkData.DataReceivedThisInterval += bytesReceived; m_NetworkData.AmountOfMessagesReceived++; } - return length; - -} - -PlayerID TCPServer::GetPlayerIDFromEndpoint(boost::asio::ip::udp::endpoint endpoint) -{ - return PlayerID(); + if (error) { + //LOG_ERROR("receive: %s", error.message().c_str()); + } + return bytesReceived; } \ No newline at end of file diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index 969fa46c..a2bde7cb 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -181,11 +181,13 @@ void Game::networkFunction() bool isServer = m_Config->Get("Networking.IsServer", false); if (!isServer) { m_IsClientOrServer = true; - m_ClientOrServer = new TCPClient(m_Config); + //m_ClientOrServer = new TCPClient(m_Config); + m_ClientOrServer = new HybridClient(m_Config); } if (isServer) { m_IsClientOrServer = true; - m_ClientOrServer = new TCPServer(); + //m_ClientOrServer = new TCPServer(); + m_ClientOrServer = new HybridServer(); } m_ClientOrServer->Start(m_World, m_EventBroker); From 933a32aa8db98ff5391637447f7b59835579ceef Mon Sep 17 00:00:00 2001 From: viktorljung Date: Sat, 6 Feb 2016 18:09:51 +0100 Subject: [PATCH 103/355] Animations kind of working --- include/Engine/Rendering/Skeleton.h | 2 +- resources/Schema/Entities/AnimationTests2.xml | 112 ++++++++--------- resources/Schema/Entities/RenderingWorld.xml | 17 ++- resources/Shaders/Sprite.frag.glsl | 41 +++++++ resources/Shaders/Sprite.vert.glsl | 24 ++++ src/Engine/Rendering/AnimationSystem.cpp | 2 + src/Engine/Rendering/BoneAttachmentSystem.cpp | 11 +- src/Engine/Rendering/Skeleton.cpp | 115 ++++++++++++------ 8 files changed, 224 insertions(+), 100 deletions(-) create mode 100644 resources/Shaders/Sprite.frag.glsl create mode 100644 resources/Shaders/Sprite.vert.glsl diff --git a/include/Engine/Rendering/Skeleton.h b/include/Engine/Rendering/Skeleton.h index f1ef22c7..90e24578 100644 --- a/include/Engine/Rendering/Skeleton.h +++ b/include/Engine/Rendering/Skeleton.h @@ -92,7 +92,7 @@ public: void PrintSkeleton(const Bone* parent, int depthCount); std::map Animations; - glm::mat4 GetBoneTransform(const Bone* bone, const Animation::Keyframe& currentFrame, const Animation::Keyframe& nextFrame, float progress, glm::mat4 parentMatrix); + glm::mat4 GetBoneTransform(const Bone* bone, const Animation* animation, float time, glm::mat4 parentMatrix); int GetKeyframe(const Animation& animation, double time); private: diff --git a/resources/Schema/Entities/AnimationTests2.xml b/resources/Schema/Entities/AnimationTests2.xml index a116803f..21a899f5 100644 --- a/resources/Schema/Entities/AnimationTests2.xml +++ b/resources/Schema/Entities/AnimationTests2.xml @@ -13,7 +13,6 @@ - @@ -32,39 +31,21 @@ - + - Run - - 1 + Wave + + 0.099999986588954926 - Models/Asstest.mesh + Models/finaltest.mesh - + - - - - R_Leg_Top - - - - Models/Core/UnitCube.mesh - - - - - - - - - - @@ -76,9 +57,8 @@ - + - @@ -94,9 +74,8 @@ - + - @@ -112,9 +91,8 @@ - + - @@ -130,9 +108,8 @@ - + - @@ -148,9 +125,8 @@ - + - @@ -166,9 +142,8 @@ - + - @@ -184,9 +159,8 @@ - + - @@ -202,9 +176,8 @@ - + - @@ -220,9 +193,8 @@ - + - @@ -238,9 +210,8 @@ - + - @@ -256,9 +227,8 @@ - + - @@ -274,9 +244,8 @@ - + - @@ -292,9 +261,8 @@ - + - @@ -310,9 +278,8 @@ - + - @@ -328,9 +295,44 @@ - + - + + + + + + + + + + Run + + 0.099999986588954926 + + + Models/Supertest2.mesh + + + + + + + + + + R_Leg_Top + + + + + Models/Core/UnitCube.mesh + + + + + + diff --git a/resources/Schema/Entities/RenderingWorld.xml b/resources/Schema/Entities/RenderingWorld.xml index 1ac95a3b..4564b3f5 100644 --- a/resources/Schema/Entities/RenderingWorld.xml +++ b/resources/Schema/Entities/RenderingWorld.xml @@ -60,6 +60,7 @@ Models/Core/UnitHexagon.mesh + true @@ -161,7 +162,7 @@ - + @@ -346,6 +347,20 @@ + + + + Run + + 0.004999999888241291 + + + Models/SuperTest.mesh + + + + + diff --git a/resources/Shaders/Sprite.frag.glsl b/resources/Shaders/Sprite.frag.glsl new file mode 100644 index 00000000..c391322d --- /dev/null +++ b/resources/Shaders/Sprite.frag.glsl @@ -0,0 +1,41 @@ +#version 430 + +uniform vec4 Color; +uniform vec4 FillColor; +uniform float FillPercentage; +uniform mat4 M; +uniform mat4 V; +uniform mat4 P; + +layout (binding = 0) uniform sampler2D DiffuseTexture; +layout (binding = 1) uniform sampler2D GlowMapTexture; + + +in VertexData{ + vec3 Position; + vec3 Normal; + vec2 TextureCoordinate; +}Input; + + +out vec4 sceneColor; +out vec4 bloomColor; + +void main() +{ + vec4 diffuseTexel = texture2D(DiffuseTexture, Input.TextureCoordinate); + vec4 glowTexel = texture2D(GlowMapTexture, Input.TextureCoordinate); + + vec4 color_result = Color * diffuseTexel; + + float pos = ((P * vec4(Input.Position, 1)).y + 1.0)/2.0; + if(pos <= FillPercentage) { + color_result += FillColor; + } + sceneColor = vec4(color_result.xyz, clamp(color_result.a, 0, 1)); + color_result += glowTexel*3; + + bloomColor = vec4(clamp(color_result.xyz - 1.0, 0, 100), 1.0); +} + + diff --git a/resources/Shaders/Sprite.vert.glsl b/resources/Shaders/Sprite.vert.glsl new file mode 100644 index 00000000..e910a26a --- /dev/null +++ b/resources/Shaders/Sprite.vert.glsl @@ -0,0 +1,24 @@ +#version 430 + +uniform mat4 M; +uniform mat4 V; +uniform mat4 P; + +layout(location = 0) in vec3 Position; +layout(location = 1) in vec3 Normal; +layout(location = 4) in vec2 TextureCoords; + +out VertexData{ + vec3 Position; + vec3 Normal; + vec2 TextureCoordinate; +}Output; + +void main() +{ + gl_Position = P * M * vec4(Position, 1.0); + + Output.Position = Position; + Output.TextureCoordinate = TextureCoords; + Output.Normal = Normal; +} \ No newline at end of file diff --git a/src/Engine/Rendering/AnimationSystem.cpp b/src/Engine/Rendering/AnimationSystem.cpp index c78aafd9..ef035dca 100644 --- a/src/Engine/Rendering/AnimationSystem.cpp +++ b/src/Engine/Rendering/AnimationSystem.cpp @@ -19,6 +19,7 @@ void AnimationSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& a if(skeleton == nullptr) { return; } +/* ImGui::SliderFloat("Angle", &angle, -100.f, 100.f); { @@ -28,6 +29,7 @@ void AnimationSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& a it->second->ModificationMatrix = glm::mat4(glm::quat(glm::vec3(glm::radians(angle), 0.f, 0.f))); } } +*/ const Skeleton::Animation* animation = skeleton->GetAnimation(animationComponent["AnimationName"]); diff --git a/src/Engine/Rendering/BoneAttachmentSystem.cpp b/src/Engine/Rendering/BoneAttachmentSystem.cpp index 1f98c28e..f172d0ab 100644 --- a/src/Engine/Rendering/BoneAttachmentSystem.cpp +++ b/src/Engine/Rendering/BoneAttachmentSystem.cpp @@ -2,7 +2,7 @@ void BoneAttachmentSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& BoneAttachmentComponent, double dt) { -/* + if(!entity.HasComponent("Transform")) { return; @@ -33,13 +33,8 @@ void BoneAttachmentSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapp return; } - int currentKeyframeIndex = skeleton->GetKeyframe(*animation, parent["Animation"]["Time"]); - const Skeleton::Animation::Keyframe& currentFrame = animation->Keyframes[currentKeyframeIndex]; - const Skeleton::Animation::Keyframe& nextFrame = animation->Keyframes[(currentKeyframeIndex + 1) % animation->Keyframes.size()]; - float alpha = ((double)parent["Animation"]["Time"] - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); - - glm::mat4 boneTransform = skeleton->GetBoneTransform(skeleton->Bones[id], currentFrame, nextFrame, alpha, glm::mat4(1)); + glm::mat4 boneTransform = skeleton->GetBoneTransform(skeleton->Bones[id], animation, (double)parent["Animation"]["Time"], glm::mat4(1)); @@ -68,5 +63,5 @@ void BoneAttachmentSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapp } if ((bool)entity["BoneAttachment"]["InheritScale"]) { (glm::vec3&)entity["Transform"]["Scale"] = scale * (glm::vec3)entity["BoneAttachment"]["ScaleOffset"]; - }*/ + } } diff --git a/src/Engine/Rendering/Skeleton.cpp b/src/Engine/Rendering/Skeleton.cpp index 5ae6a264..d857fa5d 100644 --- a/src/Engine/Rendering/Skeleton.cpp +++ b/src/Engine/Rendering/Skeleton.cpp @@ -61,7 +61,7 @@ std::vector Skeleton::GetFrameBones(const Animation* animation, doubl //auto animationFrame = Animations[""].Keyframes[frame]; std::map frameBones; - AccumulateBoneTransforms(noRootMotion, animation, time, frameBones, RootBone, glm::mat4(1)); + AccumulateBoneTransforms(true, animation, time, frameBones, RootBone, glm::mat4(1)); //AccumulateBoneTransforms(noRootMotion, currentFrame, nextFrame, alpha, frameBones, RootBone, glm::mat4(1)); std::vector finalMatrices; @@ -71,21 +71,18 @@ std::vector Skeleton::GetFrameBones(const Animation* animation, doubl return finalMatrices; } - - - void Skeleton::AccumulateBoneTransforms(bool noRootMotion, const Animation* animation, float time, std::map& boneMatrices, const Bone* bone, glm::mat4 parentMatrix) { - glm::mat4 boneMatrix;// = glm::mat4(1); + glm::mat4 boneMatrix; Animation::Keyframe currentFrame; Animation::Keyframe nextFrame; - if(animation->JointAnimations.find(bone->ID) != animation->JointAnimations.end()) { // find the bone keyframes that surrounds the current frame + if(animation->JointAnimations.find(bone->ID) != animation->JointAnimations.end()) { std::vector boneKeyFrames = animation->JointAnimations.at(bone->ID); - + if(boneKeyFrames.size() > 1) { // 2+ keyframes for the current bone - for (int index = boneKeyFrames.size()-1; index >= 0; index--) { + for (int index = boneKeyFrames.size()-1; index >= 0; index--) { // find the bone keyframes that surrounds the current frame if (time >= boneKeyFrames.at(index).Time) { currentFrame = boneKeyFrames.at(index); nextFrame = boneKeyFrames.at((index + 1) % boneKeyFrames.size()); @@ -93,10 +90,18 @@ void Skeleton::AccumulateBoneTransforms(bool noRootMotion, const Animation* anim } } - float progress = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); // fix loopinguuuu + float progress; + + if(nextFrame.Index == 0) { + progress = (time - currentFrame.Time) / (animation->Duration - currentFrame.Time); + } else { + progress = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); // fix loopinguuuu + + } + + if(progress > 1.0f || progress < 0.0f) { - LOG_INFO("Progress %f", progress); - progress = 0.f; + progress = glm::clamp(progress, 0.0f, 1.0f); } Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties; Animation::Keyframe::BoneProperty nextBoneProperty = nextFrame.BoneProperties; @@ -111,53 +116,93 @@ void Skeleton::AccumulateBoneTransforms(bool noRootMotion, const Animation* anim positionInterp.z = 0; } - boneMatrix = parentMatrix * bone->ModificationMatrix * (glm::translate(positionInterp) * glm::toMat4(rotationInterp) * glm::scale(scaleInterp)); - boneMatrices[bone->ID] = boneMatrix *bone->OffsetMatrix; + boneMatrix = parentMatrix * (glm::translate(positionInterp) * glm::toMat4(rotationInterp) * glm::scale(scaleInterp)); + boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix; } else { // 1 keyframes for the current bone currentFrame = boneKeyFrames.at(0); - boneMatrix = parentMatrix * bone->ModificationMatrix *(glm::translate(currentFrame.BoneProperties.Position) * glm::toMat4(currentFrame.BoneProperties.Rotation) * glm::scale(currentFrame.BoneProperties.Scale)); - boneMatrices[bone->ID] = boneMatrix *bone->OffsetMatrix; + boneMatrix = parentMatrix * (glm::translate(currentFrame.BoneProperties.Position) * glm::toMat4(currentFrame.BoneProperties.Rotation) * glm::scale(currentFrame.BoneProperties.Scale)); + + boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix; } } else { // 0 keyframes for the current bone - boneMatrix = parentMatrix * bone->ModificationMatrix; - boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix; - + // LOG_INFO("%s Has no keyframe", bone->Name.c_str()); + if (bone->Parent) { + boneMatrix = parentMatrix * glm::inverse(bone->OffsetMatrix) * bone->Parent->OffsetMatrix; + boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix; + } else { + boneMatrix = glm::inverse(bone->OffsetMatrix); + boneMatrices[bone->ID] = parentMatrix; + } + } for (auto &child : bone->Children) { - std::string name = child->Name; AccumulateBoneTransforms(noRootMotion, animation, time, boneMatrices, child, boneMatrix); } } -glm::mat4 Skeleton::GetBoneTransform(const Bone* bone, const Animation::Keyframe& currentFrame, const Animation::Keyframe& nextFrame, float progress, glm::mat4 parentMatrix) +glm::mat4 Skeleton::GetBoneTransform(const Bone* bone, const Animation* animation, float time, glm::mat4 parentMatrix) { - /* glm::mat4 boneMatrix; + glm::mat4 boneMatrix; - if (currentFrame.BoneProperties.find(bone->ID) != currentFrame.BoneProperties.end() || nextFrame.BoneProperties.find(bone->ID) != nextFrame.BoneProperties.end()) { - Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties.at(bone->ID); - Animation::Keyframe::BoneProperty nextBoneProperty = nextFrame.BoneProperties.at(bone->ID); + Animation::Keyframe currentFrame; + Animation::Keyframe nextFrame; - glm::vec3 positionInterp = currentBoneProperty.Position * (1.f - progress) + nextBoneProperty.Position * progress; - glm::quat rotationInterp = glm::slerp(currentBoneProperty.Rotation, nextBoneProperty.Rotation, progress); - glm::vec3 scaleInterp = currentBoneProperty.Scale * (1.f - progress) + nextBoneProperty.Scale * progress; + if (animation->JointAnimations.find(bone->ID) != animation->JointAnimations.end()) { + std::vector boneKeyFrames = animation->JointAnimations.at(bone->ID); + if (boneKeyFrames.size() > 1) { // 2+ keyframes for the current bone + for (int index = boneKeyFrames.size()-1; index >= 0; index--) { // find the bone keyframes that surrounds the current frame + if (time >= boneKeyFrames.at(index).Time) { + currentFrame = boneKeyFrames.at(index); + nextFrame = boneKeyFrames.at((index + 1) % boneKeyFrames.size()); + break; + } + } + + float progress; + + if (nextFrame.Index == 0) { + progress = (time - currentFrame.Time) / (animation->Duration - currentFrame.Time); + } else { + progress = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); // fix loopinguuuu + + } + + if (progress > 1.0f || progress < 0.0f) { + LOG_INFO("Progress %f", progress); + progress = glm::clamp(progress, 0.0f, 1.0f); + } + Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties; + Animation::Keyframe::BoneProperty nextBoneProperty = nextFrame.BoneProperties; + + glm::vec3 positionInterp = currentBoneProperty.Position * (1.f - progress) + nextBoneProperty.Position * progress; + glm::quat rotationInterp = glm::slerp(currentBoneProperty.Rotation, nextBoneProperty.Rotation, progress); + glm::vec3 scaleInterp = currentBoneProperty.Scale * (1.f - progress) + nextBoneProperty.Scale * progress; + + boneMatrix = parentMatrix * (glm::translate(positionInterp) * glm::toMat4(rotationInterp) * glm::scale(scaleInterp)); + + } else { // 1 keyframes for the current bone + currentFrame = boneKeyFrames.at(0); + boneMatrix = parentMatrix * (glm::translate(currentFrame.BoneProperties.Position) * glm::toMat4(currentFrame.BoneProperties.Rotation) * glm::scale(currentFrame.BoneProperties.Scale)); - boneMatrix = (glm::translate(positionInterp) * glm::toMat4(rotationInterp) * glm::scale(scaleInterp)) * bone->ModificationMatrix * parentMatrix; - } else { - if (bone->Parent) { - boneMatrix = parentMatrix; } + } else { // 0 keyframes for the current bone + if (bone->Parent) { + boneMatrix = glm::inverse(bone->OffsetMatrix) * bone->Parent->OffsetMatrix * parentMatrix; + } else { + boneMatrix = parentMatrix * glm::inverse(bone->OffsetMatrix); + } + } - if(bone->Parent) { - return GetBoneTransform(bone->Parent, currentFrame, nextFrame, progress, boneMatrix); + if (bone->Parent) { + return GetBoneTransform(bone->Parent, animation, time, boneMatrix); } else { return boneMatrix; - }*/ - return parentMatrix; + } } int Skeleton::GetBoneID(std::string name) From 92ab22e77947f36ebf6a7e8f5c8bb088cd6b5e62 Mon Sep 17 00:00:00 2001 From: Teejoon Date: Sun, 7 Feb 2016 13:39:13 +0100 Subject: [PATCH 104/355] Splatmapping now working. Rendering pipleline now support 3 different types of Material: Basic: a material with a single color on every property (diffuse, specular, ect). SingleTextures: a material with a single texture in all or any property. Have a single color on the rest. SplatMapping: has a SplatMap and 0 to 5 different textures to every property. Properties with o texture uses a single color insted. All materials with a texture has a UVRepeat, telling how many time to till in U and in V. modelJobs now uses ShadeID, ModelID and TextureID for the Hash insted of only Texture MayaExported exports 3 differnt types of material, the same as the piplen now supports. --- include/Engine/Rendering/DrawFinalPass.h | 1 + include/Engine/Rendering/ExplosionEffectJob.h | 2 +- include/Engine/Rendering/Model.h | 2 +- include/Engine/Rendering/ModelJob.h | 126 ++++++--- include/Engine/Rendering/RawModelCustom.h | 16 +- include/Engine/Rendering/RenderSystem.h | 1 - .../Shaders/ForwardPlusSplatMap.frag.glsl | 245 ++++++++++++++++++ src/Engine/Rendering/DrawBloomPass.cpp | 16 +- .../Rendering/DrawColorCorrectionPass.cpp | 4 +- src/Engine/Rendering/DrawFinalPass.cpp | 208 +++++++++++---- src/Engine/Rendering/DrawScreenQuadPass.cpp | 4 +- src/Engine/Rendering/Model.cpp | 76 +++++- src/Engine/Rendering/RawModelCustom.cpp | 49 ++-- src/Engine/Rendering/RenderSystem.cpp | 5 +- src/Engine/Rendering/Skeleton.cpp | 6 +- tools/MayaExporter/MayaExporter/Material.cpp | 190 ++++++++++++-- tools/MayaExporter/MayaExporter/Material.h | 131 ++++++---- tools/MayaExporter/MayaExporter/Mesh.cpp | 172 ++++++------ tools/MayaExporter/MayaExporter/Mesh.h | 2 +- tools/MayaExporter/MayaExporter/Skeleton.cpp | 24 +- 20 files changed, 971 insertions(+), 309 deletions(-) create mode 100644 resources/Shaders/ForwardPlusSplatMap.frag.glsl diff --git a/include/Engine/Rendering/DrawFinalPass.h b/include/Engine/Rendering/DrawFinalPass.h index 74f505fe..a32c562b 100644 --- a/include/Engine/Rendering/DrawFinalPass.h +++ b/include/Engine/Rendering/DrawFinalPass.h @@ -53,6 +53,7 @@ private: ShaderProgram* m_ForwardPlusProgram; ShaderProgram* m_ExplosionEffectProgram; + ShaderProgram* m_ForwardPlusSplatMapProgram; }; #endif \ No newline at end of file diff --git a/include/Engine/Rendering/ExplosionEffectJob.h b/include/Engine/Rendering/ExplosionEffectJob.h index 89b1342b..8f339526 100644 --- a/include/Engine/Rendering/ExplosionEffectJob.h +++ b/include/Engine/Rendering/ExplosionEffectJob.h @@ -15,7 +15,7 @@ struct ExplosionEffectJob : ModelJob { - ExplosionEffectJob(ComponentWrapper explosionEffectComponent, ::Model* model, Camera* camera, glm::mat4 matrix, ::RawModel::MaterialGroup matGroup, ComponentWrapper modelComponent, ::World* world, glm::vec4 fillColor, float fillPercentage) + ExplosionEffectJob(ComponentWrapper explosionEffectComponent, ::Model* model, Camera* camera, glm::mat4 matrix, ::RawModel::MaterialProperties matGroup, ComponentWrapper modelComponent, ::World* world, glm::vec4 fillColor, float fillPercentage) : ModelJob(model, camera, matrix, matGroup, modelComponent, world, fillColor, fillPercentage) { ExplosionOrigin = (glm::vec3)explosionEffectComponent["ExplosionOrigin"]; diff --git a/include/Engine/Rendering/Model.h b/include/Engine/Rendering/Model.h index 34d8462f..024c97c8 100644 --- a/include/Engine/Rendering/Model.h +++ b/include/Engine/Rendering/Model.h @@ -14,7 +14,7 @@ private: public: ~Model(); - const std::vector& MaterialGroups() const { return m_RawModel->MaterialGroups; } + const std::vector& MaterialGroups() const { return m_RawModel->m_Materials; } const glm::mat4& Matrix() const { return m_RawModel->m_Matrix; } const RawModel::Vertex* Vertices() const { return m_RawModel->Vertices(); } unsigned int NumberOfVertices() const { return m_RawModel->NumVertices(); } diff --git a/include/Engine/Rendering/ModelJob.h b/include/Engine/Rendering/ModelJob.h index 2cb2169c..2c662f09 100644 --- a/include/Engine/Rendering/ModelJob.h +++ b/include/Engine/Rendering/ModelJob.h @@ -14,39 +14,98 @@ #include "../Core/World.h" #include "../Core/Transform.h" #include "Skeleton.h" +#include "ShaderProgram.h" struct ModelJob : RenderJob { - ModelJob(Model* model, Camera* camera, glm::mat4 matrix, ::RawModel::MaterialGroup matGroup, ComponentWrapper modelComponent, World* world, glm::vec4 fillColor, float fillPercentage) + ModelJob(Model* model, Camera* camera, glm::mat4 matrix, ::RawModel::MaterialProperties matProp, ComponentWrapper modelComponent, World* world, glm::vec4 fillColor, float fillPercentage) : RenderJob() { Model = model; - TextureID = (matGroup.Texture) ? matGroup.Texture->ResourceID : 0; - if (modelComponent["DiffuseTexture"]) { - DiffuseTexture = matGroup.Texture.get(); - } else { - DiffuseTexture = nullptr; - } - if (modelComponent["NormalMap"]) { - NormalTexture = matGroup.NormalMap.get(); - } else { - NormalTexture = nullptr; - } - if (modelComponent["SpecularMap"]) { - SpecularTexture = matGroup.SpecularMap.get(); - } else { - SpecularTexture = nullptr; - } - if (modelComponent["GlowMap"]) { - IncandescenceTexture = matGroup.IncandescenceMap.get(); - } else { - IncandescenceTexture = nullptr; - } - DiffuseColor = matGroup.DiffuseColor; - SpecularColor = matGroup.SpecularColor; - IncandescenceColor = matGroup.IncandescenceColor; - StartIndex = matGroup.StartIndex; - EndIndex = matGroup.EndIndex; + ModelID = model->ResourceID; + Type = matProp.type; + ::RawModel::MaterialBasic* matGroup = matProp.material; + switch(matProp.type){ + case ::RawModel::MaterialType::Basic: + if (Model->isSkined()) { + ShaderID = ResourceManager::Load("#ForwardPlusProgram")->ResourceID; + } + else { + //JOHAN TODO: Add Non-skined shader + } + TextureID = 0; + break; + case ::RawModel::MaterialType::SingleTextures: + { + if (Model->isSkined()) { + ShaderID = ResourceManager::Load("#ForwardPlusProgram")->ResourceID; + } + else { + //JOHAN TODO: Add Non-skined shader + } + ::RawModel::MaterialSingleTextures* singleTextures = static_cast<::RawModel::MaterialSingleTextures*>(matProp.material); + TextureID = (singleTextures->ColorMap.Texture) ? singleTextures->ColorMap.Texture->ResourceID : 0; + if (modelComponent["DiffuseTexture"]) { + DiffuseTexture.push_back(singleTextures->ColorMap.Texture.get()); + } + + if (modelComponent["NormalMap"]) { + NormalTexture.push_back(singleTextures->NormalMap.Texture.get()); + } + + if (modelComponent["SpecularMap"]) { + SpecularTexture.push_back(singleTextures->SpecularMap.Texture.get()); + } + + if (modelComponent["GlowMap"]) { + IncandescenceTexture.push_back(singleTextures->IncandescenceMap.Texture.get()); + } + } + break; + case ::RawModel::MaterialType::SplatMapping: + { + if (Model->isSkined()) { + ShaderID = ResourceManager::Load("#ForwardPlusSplatMapProgram")->ResourceID; + } + else { + //JOHAN TODO: Add Non-skinned shader + } + ::RawModel::MaterialSplatMapping* SplatTextures = static_cast<::RawModel::MaterialSplatMapping*>(matProp.material); + + SplatMap = SplatTextures->SplatMap.Texture.get(); + + TextureID = (SplatTextures->ColorMaps[0].Texture) ? SplatTextures->ColorMaps[0].Texture->ResourceID : 0; + if (modelComponent["DiffuseTexture"]) { + for (auto texture : SplatTextures->ColorMaps) { + DiffuseTexture.push_back(texture.Texture.get()); + } + } + + if (modelComponent["NormalMap"]) { + for (auto texture : SplatTextures->NormalMaps) { + NormalTexture.push_back(texture.Texture.get()); + } + } + + if (modelComponent["SpecularMap"]) { + for (auto texture : SplatTextures->SpecularMaps) { + SpecularTexture.push_back(texture.Texture.get()); + } + } + + if (modelComponent["GlowMap"]) { + for (auto texture : SplatTextures->IncandescenceMaps) { + IncandescenceTexture.push_back(texture.Texture.get()); + } + } + } + break; + } + DiffuseColor = matGroup->DiffuseColor; + SpecularColor = matGroup->SpecularColor; + IncandescenceColor = matGroup->IncandescenceColor; + StartIndex = matGroup->StartIndex; + EndIndex = matGroup->EndIndex; Matrix = matrix; Color = modelComponent["Color"]; Entity = modelComponent.EntityID; @@ -68,13 +127,16 @@ struct ModelJob : RenderJob unsigned int TextureID; unsigned int ShaderID; + unsigned int ModelID; + ::RawModel::MaterialType Type; EntityID Entity; glm::mat4 Matrix; - const Texture* DiffuseTexture; - const Texture* NormalTexture; - const Texture* SpecularTexture; - const Texture* IncandescenceTexture; + const Texture* SplatMap; + std::vector DiffuseTexture; + std::vector NormalTexture; + std::vector SpecularTexture; + std::vector IncandescenceTexture; float Shininess = 0.f; glm::vec4 Color; const ::Model* Model = nullptr; @@ -95,7 +157,7 @@ struct ModelJob : RenderJob void CalculateHash() override { - Hash = TextureID; + Hash = TextureID + ModelID << 10 + ShaderID << 20; } }; diff --git a/include/Engine/Rendering/RawModelCustom.h b/include/Engine/Rendering/RawModelCustom.h index d0e35646..476bf52e 100644 --- a/include/Engine/Rendering/RawModelCustom.h +++ b/include/Engine/Rendering/RawModelCustom.h @@ -76,10 +76,10 @@ public: struct MaterialSingleTextures : public MaterialBasic { - TextureProperties ColorMaps; - TextureProperties NormalMaps; - TextureProperties SpecularMaps; - TextureProperties IncandescenceMaps; + TextureProperties ColorMap; + TextureProperties NormalMap; + TextureProperties SpecularMap; + TextureProperties IncandescenceMap; }; enum class MaterialType { Basic = 1, SplatMapping, SingleTextures }; @@ -136,10 +136,10 @@ private: void ReadMaterialFile(std::string filePath); void ReadMaterials(std::size_t& offset, char* fileData, const unsigned int& fileByteSize); void ReadMaterialSingle(std::size_t& offset, char* fileData, const unsigned int& fileByteSize); - void ReadMaterialBasic(MaterialBasic* Material, unsigned int &offset, char* fileData, unsigned int& fileByteSize); - void ReadMaterialSingleTexture(MaterialSingleTextures* Material, unsigned int &offset, char* fileData, unsigned int& fileByteSize); - void ReadMaterialSplatMapping(MaterialSplatMapping* Material, unsigned int &offset, char* fileData, unsigned int& fileByteSize); - void ReadMaterialTextureProperties(TextureProperties& texture, unsigned int &offset, char* fileData, unsigned int& fileByteSize); + void ReadMaterialBasic(MaterialBasic* Material, std::size_t& offset, char* fileData, const unsigned int& fileByteSize); + void ReadMaterialSingleTexture(MaterialSingleTextures* Material, std::size_t& offset, char* fileData, const unsigned int& fileByteSize); + void ReadMaterialSplatMapping(MaterialSplatMapping* Material, std::size_t& offset, char* fileData, const unsigned int& fileByteSize); + void ReadMaterialTextureProperties(TextureProperties& texture, std::size_t& offset, char* fileData, const unsigned int& fileByteSize); void ReadAnimationFile(std::string filePath); void ReadAnimationBindPoses(std::size_t& offset, char* fileData, const unsigned int& fileByteSize); diff --git a/include/Engine/Rendering/RenderSystem.h b/include/Engine/Rendering/RenderSystem.h index d64147b9..50ccdb0c 100644 --- a/include/Engine/Rendering/RenderSystem.h +++ b/include/Engine/Rendering/RenderSystem.h @@ -47,7 +47,6 @@ private: void fillLight(std::list>& jobs); bool isChildOfACamera(EntityWrapper entity); bool isChildOfCurrentCamera(EntityWrapper entity); - }; #endif \ No newline at end of file diff --git a/resources/Shaders/ForwardPlusSplatMap.frag.glsl b/resources/Shaders/ForwardPlusSplatMap.frag.glsl new file mode 100644 index 00000000..fe26469e --- /dev/null +++ b/resources/Shaders/ForwardPlusSplatMap.frag.glsl @@ -0,0 +1,245 @@ +#version 430 + +uniform mat4 M; +uniform mat4 V; +uniform mat4 P; +uniform vec2 ScreenDimensions; +uniform float FillPercentage; +uniform vec4 DiffuseColor; +uniform vec4 FillColor; +uniform vec4 Color; +uniform vec4 AmbientColor; +layout (binding = 0) uniform sampler2D SplatMapTexture; +layout (binding = 1) uniform sampler2D DiffuseTexture1; +layout (binding = 2) uniform sampler2D DiffuseTexture2; +layout (binding = 3) uniform sampler2D DiffuseTexture3; +layout (binding = 4) uniform sampler2D DiffuseTexture4; +layout (binding = 5) uniform sampler2D DiffuseTexture5; +layout (binding = 6) uniform sampler2D NormalMapTexture1; +layout (binding = 7) uniform sampler2D NormalMapTexture2; +layout (binding = 8) uniform sampler2D NormalMapTexture3; +layout (binding = 9) uniform sampler2D NormalMapTexture4; +layout (binding = 10) uniform sampler2D NormalMapTexture5; +layout (binding = 11) uniform sampler2D SpecularMapTexture1; +layout (binding = 12) uniform sampler2D SpecularMapTexture2; +layout (binding = 13) uniform sampler2D SpecularMapTexture3; +layout (binding = 14) uniform sampler2D SpecularMapTexture4; +layout (binding = 15) uniform sampler2D SpecularMapTexture5; +layout (binding = 16) uniform sampler2D GlowMapTexture1; +layout (binding = 17) uniform sampler2D GlowMapTexture2; +layout (binding = 18) uniform sampler2D GlowMapTexture3; +layout (binding = 19) uniform sampler2D GlowMapTexture4; +layout (binding = 20) uniform sampler2D GlowMapTexture5; + +#define TILE_SIZE 16 + +struct LightSource { + vec4 Position; + vec4 Direction; + vec4 Color; + float Radius; + float Intensity; + float Falloff; + int Type; +}; + +layout (std430, binding = 1) buffer LightBuffer +{ + LightSource List[]; +} LightSources; + +struct LightGrid { + float Start; + float Amount; + vec2 Padding; +}; + +layout (std430, binding = 2) buffer LightGridBuffer +{ + LightGrid Data[]; +} LightGrids; + +layout (std430, binding = 4) buffer LightIndexBuffer +{ + float LightIndex[]; +}; + + +in VertexData{ + vec3 Position; + vec3 Normal; + vec3 Tangent; + vec3 BiTangent; + vec2 TextureCoordinate; + vec4 ExplosionColor; + float ExplosionPercentageElapsed; +}Input; + +out vec4 sceneColor; +out vec4 bloomColor; + +struct LightResult { + vec4 Diffuse; + vec4 Specular; +}; + +float CalcAttenuation(float radius, float dist, float falloff) { + return 1.0 - smoothstep(radius * 0.3, radius, dist); +} + +vec4 CalcSpecular(vec4 lightColor, vec4 viewVec, vec4 lightVec, vec4 normal) { + vec4 R = normalize( reflect(-lightVec, normal)); + float RdotV = max( dot(R, viewVec), 0.0); + return lightColor * pow(RdotV, 90.0); +} + +vec4 CalcDiffuse(vec4 lightColor, vec4 lightVec, vec4 normal) { + float power = max( dot(normal, lightVec), 0.0); + return lightColor * power; +} + +LightResult CalcPointLightSource(vec4 lightPos, float lightRadius, vec4 lightColor, float intensity, vec4 viewVec, vec4 position, vec4 normal, float falloff) +{ + vec4 L = lightPos - position; + float dist = length(L); + L = normalize(L); + + float attenuation = CalcAttenuation(lightRadius, dist, falloff); + + LightResult result; + result.Diffuse = CalcDiffuse(lightColor, L, normal) * attenuation * intensity; + result.Specular = CalcSpecular(lightColor, viewVec, L, normal) * attenuation * intensity; + return result; +} + +LightResult CalcDirectionalLightSource(vec4 direction, vec4 color, float intensity, vec4 viewVec, vec4 vertNormal) +{ + vec4 L = normalize( -vec4(direction.xyz, 0) ); + + LightResult result; + result.Diffuse = CalcDiffuse(color, L, vertNormal) * intensity; + result.Specular = CalcSpecular(color, viewVec, L, vertNormal) * intensity; + return result; +} + +vec4 CalcNormalMappedValue(vec3 normal, vec3 tangent, vec3 bitangent, vec2 textureCoordinate, sampler2D normalMap) +{ + mat3 TBN = mat3(tangent, bitangent, normal); + vec3 NormalMap = texture(normalMap, textureCoordinate).xyz * 2.0 - vec3(1.0); + return vec4(TBN * normalize(NormalMap), 0.0); +} + +#define TEXTURE_TILE 5.0 + +vec4 CalcBlendedTexel(vec4 blendValue, sampler2D R, sampler2D G, sampler2D B, sampler2D A, sampler2D D, vec2 tileValues){ + vec4 R_Channel = texture2D(R, Input.TextureCoordinate * tileValues); + vec4 G_Channel = texture2D(G, Input.TextureCoordinate * tileValues); + vec4 B_Channel = texture2D(B, Input.TextureCoordinate * tileValues); + vec4 A_Channel = texture2D(A, Input.TextureCoordinate * tileValues); + vec4 D_Channel = texture2D(D, Input.TextureCoordinate * tileValues); + + float total = blendValue.r + blendValue.g + blendValue.b + blendValue.a; + if(total > 1.0f){ + blendValue.r / total; + blendValue.g / total; + blendValue.b / total; + blendValue.a / total; + } + float D_percent = clamp( 1.0f - total, 0.0f, 1.0f); + + return blendValue.r * R_Channel + + blendValue.g * G_Channel + + blendValue.b * B_Channel + + blendValue.a * A_Channel + + D_percent * D_Channel; +} + +vec4 CalcBlendedNormal(vec4 blendValue, sampler2D R, sampler2D G, sampler2D B, sampler2D A, sampler2D D, vec2 tileValues){ + mat3 TBN = mat3(Input.Tangent, Input.BiTangent, Input.Normal); + vec3 R_Channel = texture(R, Input.TextureCoordinate * tileValues).xyz * 2.0 - vec3(1.0); + vec3 G_Channel = texture(G, Input.TextureCoordinate * tileValues).xyz * 2.0 - vec3(1.0); + vec3 B_Channel = texture(B, Input.TextureCoordinate * tileValues).xyz * 2.0 - vec3(1.0); + vec3 A_Channel = texture(A, Input.TextureCoordinate * tileValues).xyz * 2.0 - vec3(1.0); + vec3 D_Channel = texture(D, Input.TextureCoordinate * tileValues).xyz * 2.0 - vec3(1.0); + + if(blendValue.length() > 1.0f){ + blendValue = normalize(blendValue); + } + float D_percent = 1.0f - blendValue.r - blendValue.g - blendValue.b - blendValue.a; + + vec3 Normal_result = blendValue.r * R_Channel + + blendValue.g * G_Channel + + blendValue.b * B_Channel + + blendValue.a * A_Channel + + D_percent * D_Channel; + + return vec4(TBN * normalize(Normal_result), 0.0); +} + +void main() +{ + vec4 splatTexel = texture2D(SplatMapTexture, Input.TextureCoordinate); + + vec4 diffuseTexel = CalcBlendedTexel(splatTexel, DiffuseTexture1, DiffuseTexture2, DiffuseTexture3, DiffuseTexture4, DiffuseTexture5, vec2(TEXTURE_TILE, TEXTURE_TILE)); + vec4 glowTexel = CalcBlendedTexel(splatTexel, GlowMapTexture1, GlowMapTexture2, GlowMapTexture3, GlowMapTexture4, GlowMapTexture5, vec2(TEXTURE_TILE, TEXTURE_TILE)); + vec4 specularTexel = CalcBlendedTexel(splatTexel, SpecularMapTexture1, SpecularMapTexture2, SpecularMapTexture3, SpecularMapTexture4, SpecularMapTexture5, vec2(TEXTURE_TILE, TEXTURE_TILE)); + vec4 position = V * M * vec4(Input.Position, 1.0); + //vec4 normal = V * CalcNormalMappedValue(Input.Normal, Input.Tangent, Input.BiTangent, Input.TextureCoordinate, SplatMapTexture); + vec4 normal = V * CalcBlendedNormal(splatTexel, NormalMapTexture1, NormalMapTexture2, NormalMapTexture3, NormalMapTexture4, NormalMapTexture5, vec2(TEXTURE_TILE, TEXTURE_TILE)); + normal = normalize(normal); + //vec4 normal = normalize(V * vec4(Input.Normal, 0.0)); + vec4 viewVec = normalize(-position); + + vec2 tilePos; + tilePos.x = int(gl_FragCoord.x/TILE_SIZE); + tilePos.y = int(gl_FragCoord.y/TILE_SIZE); + + LightResult totalLighting; + totalLighting.Diffuse = vec4(AmbientColor.rgb, 1.0); + int currentTile = int(floor(gl_FragCoord.x/TILE_SIZE) + (floor(gl_FragCoord.y/TILE_SIZE) * int(ScreenDimensions.x/TILE_SIZE))); + + int start = int(LightGrids.Data[currentTile].Start); + int amount = int(LightGrids.Data[currentTile].Amount); + + for(int i = start; i < start + amount; i++) { + + int l = int(LightIndex[i]); + LightSource light = LightSources.List[l]; + + LightResult light_result; + //These if statements should be removed. + if(light.Type == 1) { // point + light_result = CalcPointLightSource(V * light.Position, light.Radius, light.Color, light.Intensity, viewVec, position, normal, light.Falloff); + } else if (light.Type == 2) { //Directional + light_result = CalcDirectionalLightSource(V * light.Direction, light.Color, light.Intensity, viewVec, normal); + } + totalLighting.Diffuse += light_result.Diffuse; + totalLighting.Specular += light_result.Specular; + } + + vec4 color_result = mix((Color * diffuseTexel * DiffuseColor), Input.ExplosionColor, Input.ExplosionPercentageElapsed); + color_result = color_result * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)); + //vec4 color_result = (DiffuseColor + Input.ExplosionColor) * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)) * diffuseTexel * Color; + + + float pos = ((P * vec4(Input.Position, 1)).y + 1.0)/2.0; + + if(pos <= FillPercentage) { + color_result += FillColor; + } + sceneColor = vec4(color_result.xyz, clamp(color_result.a, 0, 1)); + color_result += glowTexel*3; + + bloomColor = vec4(clamp(color_result.xyz - 1.0, 0, 100), 1.0); + + //Tiled Debug Code + /* + if(int(gl_FragCoord.x)%16 == 0 || int(gl_FragCoord.y)%16 == 0 ) { + sceneColor += vec4(0.5, 0, 0, 0); + } else { + sceneColor += vec4(LightGrids.Data[int(tilePos.x + tilePos.y*80)].Amount/LightSources.List.length(), 0, 0, 1); + } + */ +} + + diff --git a/src/Engine/Rendering/DrawBloomPass.cpp b/src/Engine/Rendering/DrawBloomPass.cpp index 5d8b2359..6cf3a2cc 100644 --- a/src/Engine/Rendering/DrawBloomPass.cpp +++ b/src/Engine/Rendering/DrawBloomPass.cpp @@ -77,8 +77,8 @@ void DrawBloomPass::Draw(GLuint texture) glBindVertexArray(m_ScreenQuad->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); - glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].EndIndex - m_ScreenQuad->MaterialGroups()[0].StartIndex +1 - , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].StartIndex); + 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); //Iterate some times to make it more gaussian. for (int i = 1; i < m_iterations; i++) { @@ -90,8 +90,8 @@ void DrawBloomPass::Draw(GLuint texture) glBindVertexArray(m_ScreenQuad->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); - glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].EndIndex - m_ScreenQuad->MaterialGroups()[0].StartIndex +1 - , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].StartIndex); + 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 @@ -102,8 +102,8 @@ void DrawBloomPass::Draw(GLuint texture) glBindVertexArray(m_ScreenQuad->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); - glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].EndIndex - m_ScreenQuad->MaterialGroups()[0].StartIndex +1 - , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].StartIndex); + 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); } //final vertical gaussian after the iterations are done @@ -115,8 +115,8 @@ void DrawBloomPass::Draw(GLuint texture) glBindVertexArray(m_ScreenQuad->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); - glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].EndIndex - m_ScreenQuad->MaterialGroups()[0].StartIndex +1 - , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].StartIndex); + 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"); } diff --git a/src/Engine/Rendering/DrawColorCorrectionPass.cpp b/src/Engine/Rendering/DrawColorCorrectionPass.cpp index 95de26e2..d74a0d13 100644 --- a/src/Engine/Rendering/DrawColorCorrectionPass.cpp +++ b/src/Engine/Rendering/DrawColorCorrectionPass.cpp @@ -38,6 +38,6 @@ void DrawColorCorrectionPass::Draw(GLuint sceneTexture, GLuint bloomTexture, GLf glBindVertexArray(m_ScreenQuad->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); - glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].EndIndex - m_ScreenQuad->MaterialGroups()[0].StartIndex +1 - , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].StartIndex); + 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); } diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index 8247797e..1ceddb4e 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -55,6 +55,15 @@ void DrawFinalPass::InitializeShaderPrograms() m_ExplosionEffectProgram->BindFragDataLocation(1, "bloomColor"); m_ExplosionEffectProgram->Link(); GLERROR("Creating explosion program"); + + m_ForwardPlusSplatMapProgram = ResourceManager::Load("#ForwardPlusSplatMapProgram"); + m_ForwardPlusSplatMapProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ForwardPlus.vert.glsl"))); + m_ForwardPlusSplatMapProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ForwardPlusSplatMap.frag.glsl"))); + m_ForwardPlusSplatMapProgram->Compile(); + m_ForwardPlusSplatMapProgram->BindFragDataLocation(0, "sceneColor"); + m_ForwardPlusSplatMapProgram->BindFragDataLocation(1, "bloomColor"); + m_ForwardPlusSplatMapProgram->Link(); + GLERROR("Creating SplatMap program"); } void DrawFinalPass::Draw(RenderScene& scene) @@ -114,8 +123,9 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& { GLuint forwardHandle = m_ForwardPlusProgram->GetHandle(); GLERROR("forwardHandle"); - GLuint explosionHandle = m_ExplosionEffectProgram->GetHandle(); + GLuint explosionHandle = m_ExplosionEffectProgram->GetHandle(); GLERROR("explosionHandle"); + GLuint forwardSplatHandle = m_ForwardPlusSplatMapProgram->GetHandle(); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, m_LightCullingPass->LightSSBO()); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, m_LightCullingPass->LightGridSSBO()); @@ -171,14 +181,32 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& auto modelJob = std::dynamic_pointer_cast(job); if (modelJob) { //bind forward program - m_ForwardPlusProgram->Bind(); - glUniform2f(glGetUniformLocation(forwardHandle, "ScreenDimensions"), m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); + //TODO: JOHAN/TOBIAS: Bind shader based on ModelJob->ShaderID; + switch (modelJob->Type) { + case RawModel::MaterialType::Basic: + case RawModel::MaterialType::SingleTextures: + { + m_ForwardPlusProgram->Bind(); + GLERROR("Bind Forward program"); + //bind uniforms + BindModelUniforms(forwardHandle, modelJob, scene); + break; + } + case RawModel::MaterialType::SplatMapping: + { + m_ForwardPlusSplatMapProgram->Bind(); + GLERROR("Bind SplatMap program"); + //bind uniforms + BindModelUniforms(forwardSplatHandle, modelJob, scene); + break; + } + } + + //bind textures + BindModelTextures(modelJob); + GLERROR("asdasd"); - //bind uniforms - BindModelUniforms(forwardHandle, modelJob, scene); - //bind textures - BindModelTextures(modelJob); if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { @@ -230,48 +258,65 @@ void DrawFinalPass::BindExplosionUniforms(GLuint shaderHandle, std::shared_ptr& job, RenderScene& scene) { - glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(job->Matrix)); - 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())); + GLERROR("Bind 1 uniform"); + GLint Location_M = glGetUniformLocation(shaderHandle, "M"); + glUniformMatrix4fv(Location_M, 1, GL_FALSE, glm::value_ptr(job->Matrix)); + GLERROR("Bind 2 uniform"); + GLint Location_V = glGetUniformLocation(shaderHandle, "V"); + glUniformMatrix4fv(Location_V, 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix())); + GLERROR("Bind 3 uniform"); + GLint Location_P = glGetUniformLocation(shaderHandle, "P"); + glUniformMatrix4fv(Location_P, 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix())); + GLERROR("Bind 4 uniform"); - glUniform2f(glGetUniformLocation(shaderHandle, "ScreenDimensions"), m_Renderer->Resolution().Width, m_Renderer->Resolution().Height); + GLint Location_ScreenDimensions = glGetUniformLocation(shaderHandle, "ScreenDimensions"); + glUniform2f(Location_ScreenDimensions, m_Renderer->Resolution().Width, m_Renderer->Resolution().Height); + GLERROR("Bind 5 uniform"); - glUniform4fv(glGetUniformLocation(shaderHandle, "Color"), 1, glm::value_ptr(job->Color)); - glUniform4fv(glGetUniformLocation(shaderHandle, "DiffuseColor"), 1, glm::value_ptr(job->DiffuseColor)); - glUniform4fv(glGetUniformLocation(shaderHandle, "FillColor"), 1, glm::value_ptr(job->FillColor)); - glUniform1f(glGetUniformLocation(shaderHandle, "FillPercentage"), job->FillPercentage); - glUniform4fv(glGetUniformLocation(shaderHandle, "AmbientColor"), 1, glm::value_ptr(scene.AmbientColor)); + GLint Location_FillPercentage = glGetUniformLocation(shaderHandle, "FillPercentage"); + glUniform1f(Location_FillPercentage, job->FillPercentage); + GLERROR("Bind 6 uniform"); + GLint Location_DiffuseColor = glGetUniformLocation(shaderHandle, "DiffuseColor"); + glUniform4fv(Location_DiffuseColor, 1, glm::value_ptr(job->DiffuseColor)); + GLERROR("Bind 7 uniform"); + GLint Location_FillColor = glGetUniformLocation(shaderHandle, "FillColor"); + glUniform4fv(Location_FillColor, 1, glm::value_ptr(job->FillColor)); + GLERROR("Bind 8 uniform"); + GLint Location_Color = glGetUniformLocation(shaderHandle, "Color"); + glUniform4fv(Location_Color, 1, glm::value_ptr(job->Color)); + GLERROR("Bind 9 uniform"); + GLint Location_AmbientColor = glGetUniformLocation(shaderHandle, "AmbientColor"); + glUniform4fv(Location_AmbientColor, 1, glm::value_ptr(scene.AmbientColor)); - GLERROR("END"); + GLERROR("END"); } - void DrawFinalPass::BindExplosionTextures(std::shared_ptr& job) { glActiveTexture(GL_TEXTURE0); - if (job->DiffuseTexture != nullptr) { - glBindTexture(GL_TEXTURE_2D, job->DiffuseTexture->m_Texture); + if (job->DiffuseTexture.size() > 0 && job->DiffuseTexture[0] != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->DiffuseTexture[0]->m_Texture); //JOHAN TODO: support multiple diffuse Textures } else { glBindTexture(GL_TEXTURE_2D, m_WhiteTexture->m_Texture); } glActiveTexture(GL_TEXTURE1); - if (job->NormalTexture != nullptr) { - glBindTexture(GL_TEXTURE_2D, job->NormalTexture->m_Texture); + if (job->NormalTexture.size() > 0 && job->NormalTexture[0] != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->NormalTexture[0]->m_Texture); //JOHAN TODO: support multiple diffuse Textures } else { glBindTexture(GL_TEXTURE_2D, m_NeutralNormalTexture->m_Texture); } glActiveTexture(GL_TEXTURE2); - if (job->SpecularTexture != nullptr) { - glBindTexture(GL_TEXTURE_2D, job->SpecularTexture->m_Texture); + if (job->SpecularTexture.size() > 0 && job->SpecularTexture[0] != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->SpecularTexture[0]->m_Texture); //JOHAN TODO: support multiple diffuse Textures } else { glBindTexture(GL_TEXTURE_2D, m_GreyTexture->m_Texture); } glActiveTexture(GL_TEXTURE3); - if (job->IncandescenceTexture != nullptr) { - glBindTexture(GL_TEXTURE_2D, job->IncandescenceTexture->m_Texture); + if (job->IncandescenceTexture.size() > 0 && job->IncandescenceTexture[0] != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->IncandescenceTexture[0]->m_Texture); //JOHAN TODO: support multiple diffuse Textures } else { glBindTexture(GL_TEXTURE_2D, m_BlackTexture->m_Texture); } @@ -279,32 +324,95 @@ void DrawFinalPass::BindExplosionTextures(std::shared_ptr& j void DrawFinalPass::BindModelTextures(std::shared_ptr& job) { - glActiveTexture(GL_TEXTURE0); - if (job->DiffuseTexture != nullptr) { - glBindTexture(GL_TEXTURE_2D, job->DiffuseTexture->m_Texture); - } else { - glBindTexture(GL_TEXTURE_2D, m_WhiteTexture->m_Texture); - } + switch (job->Type) { + case RawModel::MaterialType::SingleTextures: + case RawModel::MaterialType::Basic: + { + glActiveTexture(GL_TEXTURE0); + if (job->DiffuseTexture.size() > 0 && job->DiffuseTexture[0] != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->DiffuseTexture[0]->m_Texture); + } + else { + glBindTexture(GL_TEXTURE_2D, m_WhiteTexture->m_Texture); + } - glActiveTexture(GL_TEXTURE1); - if (job->NormalTexture != nullptr) { - glBindTexture(GL_TEXTURE_2D, job->NormalTexture->m_Texture); - } else { - glBindTexture(GL_TEXTURE_2D, m_NeutralNormalTexture->m_Texture); - } + glActiveTexture(GL_TEXTURE1); + if (job->NormalTexture.size() > 0 && job->NormalTexture[0] != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->NormalTexture[0]->m_Texture); + } + else { + glBindTexture(GL_TEXTURE_2D, m_NeutralNormalTexture->m_Texture); + } - glActiveTexture(GL_TEXTURE2); - if (job->SpecularTexture != nullptr) { - glBindTexture(GL_TEXTURE_2D, job->SpecularTexture->m_Texture); - } else { - glBindTexture(GL_TEXTURE_2D, m_GreyTexture->m_Texture); - } + glActiveTexture(GL_TEXTURE2); + if (job->SpecularTexture.size() > 0 && job->SpecularTexture[0] != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->SpecularTexture[0]->m_Texture); + } + else { + glBindTexture(GL_TEXTURE_2D, m_GreyTexture->m_Texture); + } - glActiveTexture(GL_TEXTURE3); - if (job->IncandescenceTexture != nullptr) { - glBindTexture(GL_TEXTURE_2D, job->IncandescenceTexture->m_Texture); - } else { - glBindTexture(GL_TEXTURE_2D, m_BlackTexture->m_Texture); - } + glActiveTexture(GL_TEXTURE3); + if (job->IncandescenceTexture.size() > 0 && job->IncandescenceTexture[0] != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->IncandescenceTexture[0]->m_Texture); + } + else { + glBindTexture(GL_TEXTURE_2D, m_BlackTexture->m_Texture); + } + break; + } + case RawModel::MaterialType::SplatMapping: + { + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, job->SplatMap->m_Texture); + + int texturePosition = GL_TEXTURE1; + //Bind 5 diffuse textures + for (unsigned int i = 0; i < 5; i++) { + glActiveTexture(texturePosition); + if (job->DiffuseTexture.size() > i && job->DiffuseTexture[i] != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->DiffuseTexture[i]->m_Texture); + } + else { + glBindTexture(GL_TEXTURE_2D, m_WhiteTexture->m_Texture); + } + texturePosition++; + } + //Bind 5 Normal textures + for (unsigned int i = 0; i < 5; i++) { + glActiveTexture(texturePosition); + if (job->NormalTexture.size() > i && job->NormalTexture[i] != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->NormalTexture[i]->m_Texture); + } + else { + glBindTexture(GL_TEXTURE_2D, m_NeutralNormalTexture->m_Texture); + } + texturePosition++; + } + //Bind 5 Specular textures + for (unsigned int i = 0; i < 5; i++) { + glActiveTexture(texturePosition); + if (job->SpecularTexture.size() > i && job->SpecularTexture[i] != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->SpecularTexture[i]->m_Texture); + } + else { + glBindTexture(GL_TEXTURE_2D, m_GreyTexture->m_Texture); + } + texturePosition++; + } + //Bind 5 Incandescence textures + for (unsigned int i = 0; i < 5; i++) { + glActiveTexture(texturePosition); + if (job->IncandescenceTexture.size() > i && job->IncandescenceTexture[i] != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->IncandescenceTexture[i]->m_Texture); + } + else { + glBindTexture(GL_TEXTURE_2D, m_BlackTexture->m_Texture); + } + texturePosition++; + } + break; + } + } } diff --git a/src/Engine/Rendering/DrawScreenQuadPass.cpp b/src/Engine/Rendering/DrawScreenQuadPass.cpp index b17f5e29..7a522b72 100644 --- a/src/Engine/Rendering/DrawScreenQuadPass.cpp +++ b/src/Engine/Rendering/DrawScreenQuadPass.cpp @@ -32,6 +32,6 @@ void DrawScreenQuadPass::Draw(GLuint texture) glBindVertexArray(m_ScreenQuad->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); - glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->MaterialGroups()[0].EndIndex - m_ScreenQuad->MaterialGroups()[0].StartIndex +1 - , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].StartIndex); + 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); } diff --git a/src/Engine/Rendering/Model.cpp b/src/Engine/Rendering/Model.cpp index bf264b5a..7b880208 100644 --- a/src/Engine/Rendering/Model.cpp +++ b/src/Engine/Rendering/Model.cpp @@ -5,19 +5,69 @@ Model::Model(std::string fileName) //Try loading the model asyncronously, if it throws any exceptions then let it propagate back to caller. m_RawModel = ResourceManager::Load(fileName); - for (auto& group : m_RawModel->MaterialGroups) { - if (!group.TexturePath.empty()) { - group.Texture = std::shared_ptr(ResourceManager::Load(group.TexturePath)); - } - if (!group.NormalMapPath.empty()) { - group.NormalMap = std::shared_ptr(ResourceManager::Load(group.NormalMapPath)); - } - if (!group.SpecularMapPath.empty()) { - group.SpecularMap = std::shared_ptr(ResourceManager::Load(group.SpecularMapPath)); - } - if (!group.IncandescenceMapPath.empty()) { - group.IncandescenceMap = std::shared_ptr(ResourceManager::Load(group.IncandescenceMapPath)); - } + for (auto& materialProperty : m_RawModel->m_Materials) { + switch (materialProperty.type) { + case RawModel::MaterialType::SingleTextures: + { + RawModel::MaterialSingleTextures* materialSingleTexture = static_cast(materialProperty.material); + if (!materialSingleTexture->ColorMap.TexturePath.empty()) { + materialSingleTexture->ColorMap.Texture = std::shared_ptr(ResourceManager::Load(materialSingleTexture->ColorMap.TexturePath)); + } + if (!materialSingleTexture->NormalMap.TexturePath.empty()) { + materialSingleTexture->NormalMap.Texture = std::shared_ptr(ResourceManager::Load(materialSingleTexture->NormalMap.TexturePath)); + } + if (!materialSingleTexture->SpecularMap.TexturePath.empty()) { + materialSingleTexture->SpecularMap.Texture = std::shared_ptr(ResourceManager::Load(materialSingleTexture->SpecularMap.TexturePath)); + } + if (!materialSingleTexture->IncandescenceMap.TexturePath.empty()) { + materialSingleTexture->IncandescenceMap.Texture = std::shared_ptr(ResourceManager::Load(materialSingleTexture->IncandescenceMap.TexturePath)); + } + } + break; + case RawModel::MaterialType::SplatMapping: + { + RawModel::MaterialSplatMapping* materialSplatMapping = static_cast(materialProperty.material); + if (!materialSplatMapping->SplatMap.TexturePath.empty()) { + materialSplatMapping->SplatMap.Texture = std::shared_ptr(ResourceManager::Load(materialSplatMapping->SplatMap.TexturePath)); + } + for (auto& texture : materialSplatMapping->ColorMaps) + { + if (!texture.TexturePath.empty()) { + texture.Texture = std::shared_ptr(ResourceManager::Load(texture.TexturePath)); + } + else { + texture.Texture = nullptr; + } + } + for (auto& texture : materialSplatMapping->NormalMaps) + { + if (!texture.TexturePath.empty()) { + texture.Texture = std::shared_ptr(ResourceManager::Load(texture.TexturePath)); + } else { + texture.Texture = nullptr; + } + } + for (auto& texture : materialSplatMapping->SpecularMaps) + { + if (!texture.TexturePath.empty()) { + texture.Texture = std::shared_ptr(ResourceManager::Load(texture.TexturePath)); + } + else { + texture.Texture = nullptr; + } + } + for (auto& texture : materialSplatMapping->IncandescenceMaps) + { + if (!texture.TexturePath.empty()) { + texture.Texture = std::shared_ptr(ResourceManager::Load(texture.TexturePath)); + } + else { + texture.Texture = nullptr; + } + } + } + break; + } } // Generate GL buffers diff --git a/src/Engine/Rendering/RawModelCustom.cpp b/src/Engine/Rendering/RawModelCustom.cpp index e6d25dfd..00ae0e33 100644 --- a/src/Engine/Rendering/RawModelCustom.cpp +++ b/src/Engine/Rendering/RawModelCustom.cpp @@ -34,7 +34,7 @@ void RawModelCustom::ReadMeshFile(std::string filePath) ReadMeshFileHeader(offset, fileData); ReadMesh(offset, fileData, fileByteSize); } - delete fileData; + delete[] fileData; } void RawModelCustom::ReadMeshFileHeader(std::size_t& offset, char* fileData) @@ -116,7 +116,7 @@ void RawModelCustom::ReadMaterialFile(std::string filePath) if (fileByteSize > 0) { ReadMaterials(offset, fileData, fileByteSize); } - delete fileData; + delete[] fileData; } void RawModelCustom::ReadMaterials(std::size_t& offset, char* fileData, const unsigned int& fileByteSize) @@ -169,15 +169,8 @@ void RawModelCustom::ReadMaterialSingle(std::size_t& offset, char* fileData, con m_Materials.push_back(newMaterialProperty); } -void RawModelCustom::ReadMaterialBasic(RawModelCustom::MaterialBasic* newMaterial, unsigned int &offset, char* fileData, unsigned int& fileByteSize) +void RawModelCustom::ReadMaterialBasic(RawModelCustom::MaterialBasic* newMaterial, std::size_t& offset, char* fileData, const unsigned int& fileByteSize) { - if (offset + sizeof(unsigned int) * 4 > fileByteSize) { - throw Resource::FailedLoadingException("Reading Material texture names length failed"); - } - - unsigned int* nameLengths = (unsigned int*)(fileData + offset); - offset += sizeof(unsigned int) * 4; - if (offset + sizeof(float) * 11 + sizeof(unsigned int) * 2 > fileByteSize) { throw Resource::FailedLoadingException("Reading Material specular, reflection, color and start and end index values failed"); } @@ -200,42 +193,49 @@ void RawModelCustom::ReadMaterialBasic(RawModelCustom::MaterialBasic* newMateria offset += sizeof(unsigned int); } -void RawModelCustom::ReadMaterialSingleTexture(RawModelCustom::MaterialSingleTextures* newMaterial, unsigned int &offset, char* fileData, unsigned int& fileByteSize) -{ - unsigned char numberOfMaps[4]; +void RawModelCustom::ReadMaterialSingleTexture(RawModelCustom::MaterialSingleTextures* newMaterial, std::size_t& offset, char* fileData, const unsigned int& fileByteSize) +{ + ReadMaterialBasic(newMaterial, offset, fileData, fileByteSize); if (offset + sizeof(unsigned char) * 4 > fileByteSize) { throw Resource::FailedLoadingException("Reading Material NumOfMaps failed"); } + unsigned char numberOfMaps[4]; + memcpy(numberOfMaps, fileData + offset, sizeof(unsigned char) * 4); + offset += sizeof(unsigned char) * 4; if (numberOfMaps[0] > 0) { - ReadMaterialTextureProperties(newMaterial->ColorMaps, offset, fileData, fileByteSize); + ReadMaterialTextureProperties(newMaterial->ColorMap, offset, fileData, fileByteSize); } if (numberOfMaps[1] > 0) { - ReadMaterialTextureProperties(newMaterial->SpecularMaps, offset, fileData, fileByteSize); + ReadMaterialTextureProperties(newMaterial->SpecularMap, offset, fileData, fileByteSize); } if (numberOfMaps[2] > 0) { - ReadMaterialTextureProperties(newMaterial->NormalMaps, offset, fileData, fileByteSize); + ReadMaterialTextureProperties(newMaterial->NormalMap, offset, fileData, fileByteSize); } if (numberOfMaps[3] > 0) { - ReadMaterialTextureProperties(newMaterial->IncandescenceMaps, offset, fileData, fileByteSize); + ReadMaterialTextureProperties(newMaterial->IncandescenceMap, offset, fileData, fileByteSize); } } -void RawModelCustom::ReadMaterialSplatMapping(RawModelCustom::MaterialSplatMapping* newMaterial, unsigned int &offset, char* fileData, unsigned int& fileByteSize) +void RawModelCustom::ReadMaterialSplatMapping(RawModelCustom::MaterialSplatMapping* newMaterial, std::size_t& offset, char* fileData, const unsigned int& fileByteSize) { + ReadMaterialBasic(newMaterial, offset, fileData, fileByteSize); ReadMaterialTextureProperties(newMaterial->SplatMap, offset, fileData, fileByteSize); - unsigned char numberOfMaps[4]; if (offset + sizeof(unsigned char) * 4 > fileByteSize) { throw Resource::FailedLoadingException("Reading Material NumOfMaps failed"); } + unsigned char numberOfMaps[4]; + memcpy(numberOfMaps, fileData + offset, sizeof(unsigned char) * 4); + offset += sizeof(unsigned char) * 4; + newMaterial->ColorMaps.resize(numberOfMaps[0]); for (unsigned char i = 0; i < numberOfMaps[0]; i++) { @@ -261,8 +261,10 @@ void RawModelCustom::ReadMaterialSplatMapping(RawModelCustom::MaterialSplatMappi } } -void RawModelCustom::ReadMaterialTextureProperties(RawModelCustom::TextureProperties& texture, unsigned int &offset, char* fileData, unsigned int& fileByteSize) { +void RawModelCustom::ReadMaterialTextureProperties(RawModelCustom::TextureProperties& texture, std::size_t& offset, char* fileData, const unsigned int& fileByteSize) { unsigned int nameLength = *(unsigned int*)(fileData + offset); + offset += sizeof(unsigned int); + if (nameLength > 0) { if (offset + nameLength > fileByteSize) { throw Resource::FailedLoadingException("Reading Material texture path failed"); @@ -312,7 +314,7 @@ void RawModelCustom::ReadAnimationFile(std::string filePath) ReadAnimationBindPoses(offset, fileData, fileByteSize); ReadAnimationClips(offset, fileData, fileByteSize, numAnimations); } - delete fileData; + delete[] fileData; } void RawModelCustom::ReadAnimationBindPoses(std::size_t& offset, char* fileData, const unsigned int& fileByteSize) @@ -432,7 +434,7 @@ void RawModelCustom::ReadAnimationClipSingle(std::size_t& offset, char* fileData #endif } -void RawModelCustom::ReadAnimationKeyFrame(std::size_t& &offset, char* fileData, const unsigned int& fileByteSize, std::vector& animation) +void RawModelCustom::ReadAnimationKeyFrame(std::size_t& offset, char* fileData, const unsigned int& fileByteSize, std::vector& animation) { Skeleton::Animation::Keyframe newKeyFrame; @@ -475,6 +477,9 @@ RawModelCustom::~RawModelCustom() if (m_Skeleton != nullptr) { delete m_Skeleton; } + for (auto material : m_Materials) { + delete material.material; + } } #endif \ No newline at end of file diff --git a/src/Engine/Rendering/RenderSystem.cpp b/src/Engine/Rendering/RenderSystem.cpp index eaecf99e..d058a443 100644 --- a/src/Engine/Rendering/RenderSystem.cpp +++ b/src/Engine/Rendering/RenderSystem.cpp @@ -113,6 +113,7 @@ void RenderSystem::fillModels(std::list>& opaqueJobs, if (cModel["Transparent"]) { transparentJobs.push_back(explosionEffectJob); } else { + explosionEffectJob->CalculateHash(); opaqueJobs.push_back(explosionEffectJob); } } else { @@ -132,6 +133,7 @@ void RenderSystem::fillModels(std::list>& opaqueJobs, if (cModel["Transparent"]) { transparentJobs.push_back(modelJob); } else { + modelJob->CalculateHash(); opaqueJobs.push_back(modelJob); } } @@ -196,7 +198,7 @@ void RenderSystem::fillText(std::list>& jobs, World* if (texts == nullptr) { return; } - + for (auto& textComponent : *texts) { bool visible = textComponent["Visible"]; if (!visible) { @@ -252,6 +254,7 @@ void RenderSystem::Update(double dt) } fillModels(scene.OpaqueObjects, scene.TransparentObjects); + scene.OpaqueObjects.sort(); fillPointLights(scene.PointLightJobs, m_World); fillDirectionalLights(scene.DirectionalLightJobs, m_World); fillText(scene.TextJobs, m_World); diff --git a/src/Engine/Rendering/Skeleton.cpp b/src/Engine/Rendering/Skeleton.cpp index c00094cd..e9c4d381 100644 --- a/src/Engine/Rendering/Skeleton.cpp +++ b/src/Engine/Rendering/Skeleton.cpp @@ -48,16 +48,16 @@ std::vector Skeleton::GetFrameBones(const Animation& animation, doubl while (time > animation.Duration) { time -= animation.Duration; } - + //JOHAN TODO: Ask Viktor about stuff //int currentKeyframeIndex = GetKeyframe(animation, time); //const Animation::Keyframe& currentFrame = animation.Keyframes[currentKeyframeIndex]; //const Animation::Keyframe& nextFrame = animation.Keyframes[(currentKeyframeIndex + 1) % animation.Keyframes.size()]; - double alpha = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); + //double alpha = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); ////auto animationFrame = Animations[""].Keyframes[frame]; std::map frameBones; - AccumulateBoneTransforms(noRootMotion, currentFrame, nextFrame, static_cast(alpha), frameBones, RootBone, glm::mat4(1)); + //AccumulateBoneTransforms(noRootMotion, currentFrame, nextFrame, static_cast(alpha), frameBones, RootBone, glm::mat4(1)); std::vector finalMatrices; for (auto &kv : frameBones) { diff --git a/tools/MayaExporter/MayaExporter/Material.cpp b/tools/MayaExporter/MayaExporter/Material.cpp index e487d87f..a5717aa6 100644 --- a/tools/MayaExporter/MayaExporter/Material.cpp +++ b/tools/MayaExporter/MayaExporter/Material.cpp @@ -88,14 +88,30 @@ bool Material::findColorTexture(MaterialNode& material_node, MFnDependencyNode& newTexture.FileName = FullPath.erase(FullPath.find_last_of("."), FullPath.find_last_of(".") - FullPath.size()); newTexture.FileNameLength = newTexture.FileName.length() + 1; - newTexture.UVTiling[0] = TextureNode.findPlug("RepeatU").asFloat(); - newTexture.UVTiling[1] = TextureNode.findPlug("RepeatV").asFloat(); + MPlug uvRepeatFile = TextureNode.findPlug("repeatUV"); + + uvRepeatFile.connectedTo(AllConnections, true, false); + + for (int i = 0; i < AllConnections.length(); i++) { + if (AllConnections[i].node().hasFn(MFn::kPlace2dTexture)) { + MFnDependencyNode place2DTexture(AllConnections[i].node()); + MPlug uvRepeat = place2DTexture.findPlug("repeatUV"); + + newTexture.UVTiling[0] = uvRepeat.child(0).asFloat(); + newTexture.UVTiling[1] = uvRepeat.child(1).asFloat(); + } + } material_node.ColorMaps.push_back(newTexture); + if(material_node.type == MaterialNode::MaterialType::Basic) + material_node.type = MaterialNode::MaterialType::SingleTextures; return true; + + } else if (AllConnections[i].node().hasFn(MFn::kLayeredTexture)) { + MGlobal::displayInfo(MString() + "find splat map"); + return findSplatTextures(material_node, material_node.ColorMaps, MFnDependencyNode(AllConnections[i].node())); } } - return false; } @@ -130,11 +146,25 @@ bool Material::findNormalTexture(MaterialNode& material_node, MFnDependencyNode& newTexture.FileName = FullPath.erase(FullPath.find_last_of("."), FullPath.find_last_of(".") - FullPath.size()); newTexture.FileNameLength = newTexture.FileName.length() + 1; - newTexture.UVTiling[0] = TextureNode.findPlug("RepeatU").asFloat(); - newTexture.UVTiling[1] = TextureNode.findPlug("RepeatV").asFloat(); + MPlug uvRepeatFile = TextureNode.findPlug("repeatUV"); + + uvRepeatFile.connectedTo(AllConnections, true, false); + + for (int i = 0; i < AllConnections.length(); i++) { + if (AllConnections[i].node().hasFn(MFn::kPlace2dTexture)) { + MFnDependencyNode place2DTexture(AllConnections[i].node()); + MPlug uvRepeat = place2DTexture.findPlug("repeatUV"); + + newTexture.UVTiling[0] = uvRepeat.child(0).asFloat(); + newTexture.UVTiling[1] = uvRepeat.child(1).asFloat(); + } + } material_node.NormalMaps.push_back(newTexture); return true; + } else if (AllConnections[i].node().hasFn(MFn::kLayeredTexture)) { + MGlobal::displayInfo(MString() + "find splat map"); + return findSplatTextures(material_node, material_node.NormalMaps, MFnDependencyNode(AllConnections[i].node())); } } } @@ -168,11 +198,28 @@ bool Material::findSpecularTexture(MaterialNode& material_node, MFnDependencyNod newTexture.FileName = FullPath.erase(FullPath.find_last_of("."), FullPath.find_last_of(".") - FullPath.size()); newTexture.FileNameLength = newTexture.FileName.length() + 1; - newTexture.UVTiling[0] = TextureNode.findPlug("RepeatU").asFloat(); - newTexture.UVTiling[1] = TextureNode.findPlug("RepeatV").asFloat(); + MPlug uvRepeatFile = TextureNode.findPlug("repeatUV"); + + uvRepeatFile.connectedTo(AllConnections, true, false); + + for (int i = 0; i < AllConnections.length(); i++) { + if (AllConnections[i].node().hasFn(MFn::kPlace2dTexture)) { + //C:\Users\kamisama\Desktop\TacticalZ\assets\test + MFnDependencyNode place2DTexture(AllConnections[i].node()); + MPlug uvRepeat = place2DTexture.findPlug("repeatUV"); + + newTexture.UVTiling[0] = uvRepeat.child(0).asFloat(); + newTexture.UVTiling[1] = uvRepeat.child(1).asFloat(); + } + } material_node.SpecularMaps.push_back(newTexture); + if (material_node.type == MaterialNode::MaterialType::Basic) + material_node.type = MaterialNode::MaterialType::SingleTextures; return true; + } else if (AllConnections[i].node().hasFn(MFn::kLayeredTexture)) { + MGlobal::displayInfo(MString() + "find splat map"); + return findSplatTextures(material_node, material_node.SpecularMaps, MFnDependencyNode(AllConnections[i].node())); } } return false; @@ -203,21 +250,133 @@ bool Material::findIncandescenceTexture(MaterialNode& material_node, MFnDependen newTexture.FileName = FullPath.erase(FullPath.find_last_of("."), FullPath.find_last_of(".") - FullPath.size()); newTexture.FileNameLength = newTexture.FileName.length() + 1; - newTexture.UVTiling[0] = TextureNode.findPlug("RepeatU").asFloat(); - newTexture.UVTiling[1] = TextureNode.findPlug("RepeatV").asFloat(); + MPlug uvRepeatFile = TextureNode.findPlug("repeatUV"); + + uvRepeatFile.connectedTo(AllConnections, true, false); + + for (int i = 0; i < AllConnections.length(); i++) { + if (AllConnections[i].node().hasFn(MFn::kPlace2dTexture)) { + MFnDependencyNode place2DTexture(AllConnections[i].node()); + MPlug uvRepeat = place2DTexture.findPlug("repeatUV"); + + newTexture.UVTiling[0] = uvRepeat.child(0).asFloat(); + newTexture.UVTiling[1] = uvRepeat.child(1).asFloat(); + } + } material_node.IncandescenceMaps.push_back(newTexture); + if (material_node.type == MaterialNode::MaterialType::Basic) + material_node.type = MaterialNode::MaterialType::SingleTextures; return true; } else if (AllConnections[i].node().hasFn(MFn::kLayeredTexture)) { - return findSplatTextures(material_node.IncandescenceMaps, MFnDependencyNode(AllConnections[i].node())); + MGlobal::displayInfo(MString() + "find splat map"); + return findSplatTextures(material_node, material_node.IncandescenceMaps, MFnDependencyNode(AllConnections[i].node())); } } return false; } -bool Material::findSplatTextures(std::vector& textureVector, MFnDependencyNode& node) { - return false; +//C:\Users\kamisama\Desktop\TacticalZ\assets\test + +bool Material::findSplatTextures(MaterialNode& material_node, std::vector& textureVector, MFnDependencyNode& node) { + //Get all Inputs in LayeredTexture + MPlug inputs = node.findPlug("inputs"); + MGlobal::displayInfo(MString() + "inputs.numElements(): " + inputs.numElements()); + + MPlugArray AllConnections; + MStatus test; + //Try to find splat texture if using custom splatmap build up. + inputs[0].child(1).connectedTo(AllConnections, true, false); + for (int i = 0; i < AllConnections.length(); i++) { + if (AllConnections[i].node().hasFn(MFn::kMultiplyDivide)) { + MGlobal::displayInfo(MString() + "found kMultiplyDivide"); + MFnDependencyNode multiplyDivide(AllConnections[i].node()); + multiplyDivide.findPlug("input1", &test).child(0).connectedTo(AllConnections, true, false);; + for (int i = 0; i < AllConnections.length(); i++) { + if (AllConnections[i].node().hasFn(MFn::kFileTexture)) { + MFnDependencyNode TextureNode(AllConnections[i].node()); + + std::string FullPath = TextureNode.findPlug("ftn").asString().asChar(); + m_TexturePaths.push_back(FullPath); + + MString workspace; + MStatus status = MGlobal::executeCommand(MString("workspace -q -rd;"), + workspace); + FullPath = FullPath.substr(workspace.length()); + FullPath = FullPath.substr(FullPath.find_first_of("/") + 1); + + MaterialNode::Texture newTexture; + + newTexture.FileName = FullPath.erase(FullPath.find_last_of("."), FullPath.find_last_of(".") - FullPath.size()); + newTexture.FileNameLength = newTexture.FileName.length() + 1; + + MPlug uvRepeatFile = TextureNode.findPlug("repeatUV"); + + uvRepeatFile.connectedTo(AllConnections, true, false); + + for (int i = 0; i < AllConnections.length(); i++) { + if (AllConnections[i].node().hasFn(MFn::kPlace2dTexture)) { + MFnDependencyNode place2DTexture(AllConnections[i].node()); + MPlug uvRepeat = place2DTexture.findPlug("repeatUV"); + + newTexture.UVTiling[0] = uvRepeat.child(0).asFloat(); + newTexture.UVTiling[1] = uvRepeat.child(1).asFloat(); + } + } + material_node.SplatMap = newTexture; + material_node.type = MaterialNode::MaterialType::SplatMapping; + } + } + } + } + + for (unsigned int i = 0; i < inputs.numElements(); i++) { + //Get connections to color in input[i] + inputs[i].child(0).connectedTo(AllConnections, true, false); + + for (int i = 0; i < AllConnections.length(); i++) { + if (AllConnections[i].node().hasFn(MFn::kFileTexture)) { + MFnDependencyNode TextureNode(AllConnections[i].node()); + + std::string FullPath = TextureNode.findPlug("ftn").asString().asChar(); + m_TexturePaths.push_back(FullPath); + + MString workspace; + MStatus status = MGlobal::executeCommand(MString("workspace -q -rd;"), + workspace); + FullPath = FullPath.substr(workspace.length()); + FullPath = FullPath.substr(FullPath.find_first_of("/") + 1); + + MaterialNode::Texture newTexture; + + newTexture.FileName = FullPath.erase(FullPath.find_last_of("."), FullPath.find_last_of(".") - FullPath.size()); + newTexture.FileNameLength = newTexture.FileName.length() + 1; + + MPlug uvRepeatFile = TextureNode.findPlug("repeatUV"); + + uvRepeatFile.connectedTo(AllConnections, true, false); + + for (int i = 0; i < AllConnections.length(); i++) { + if (AllConnections[i].node().hasFn(MFn::kPlace2dTexture)) { + MFnDependencyNode place2DTexture(AllConnections[i].node()); + MPlug uvRepeat = place2DTexture.findPlug("repeatUV"); + + newTexture.UVTiling[0] = uvRepeat.child(0).asFloat(); + newTexture.UVTiling[1] = uvRepeat.child(1).asFloat(); + } + } + textureVector.push_back(newTexture); + break; + } + } + if (AllConnections.length() == 0) { + MaterialNode::Texture newTexture; + newTexture.FileNameLength = 0; + textureVector.push_back(newTexture); + } + } + return true; } // Returns the absolute path for all textures. Use for copying texture files. @@ -244,8 +403,6 @@ std::vector* Material::DoIt(Mesh mesh) meshHasMaterial = true; MaterialStorage.IndexStart = totalIndices; MaterialStorage.IndexEnd = totalIndices + aMeshMaterial.second.size() - 1; - MGlobal::displayInfo("Oh noes, breaking in material"); - break; } totalIndices += aMeshMaterial.second.size(); } @@ -262,7 +419,10 @@ std::vector* Material::DoIt(Mesh mesh) MaterialStorage.ReflectionFactor = 0.0f; MaterialStorage.SpecularExponent = 0.0f; } - + MaterialStorage.NumColorMaps = MaterialStorage.ColorMaps.size(); + MaterialStorage.NumNormalMaps = MaterialStorage.NormalMaps.size(); + MaterialStorage.NumSpecularMaps = MaterialStorage.SpecularMaps.size(); + MaterialStorage.NumIncandescenceMaps = MaterialStorage.IncandescenceMaps.size(); m_AllMaterials.push_back(MaterialStorage); } matIt.next(); diff --git a/tools/MayaExporter/MayaExporter/Material.h b/tools/MayaExporter/MayaExporter/Material.h index 844b3876..d70a6399 100644 --- a/tools/MayaExporter/MayaExporter/Material.h +++ b/tools/MayaExporter/MayaExporter/Material.h @@ -17,6 +17,8 @@ //#define NormalMapSplat 1 << 2 //#define IncandescenceMapSplat 1 << 3 + + class MaterialNode : public OutputData { public: @@ -41,6 +43,10 @@ public: } }; + enum class MaterialType { Basic = 1, SplatMapping, SingleTextures }; + + MaterialType type = MaterialType::Basic; + std::string Name; float ReflectionFactor; @@ -53,11 +59,11 @@ public: unsigned int IndexStart; unsigned int IndexEnd; - char NumColormaps = 0; - char NumSpecularMap = 0; - char NumNormalMap = 0; - char NumIncandescenceMap = 0; - + unsigned char NumColorMaps = 0; + unsigned char NumSpecularMaps = 0; + unsigned char NumNormalMaps = 0; + unsigned char NumIncandescenceMaps = 0; + Texture SplatMap; std::vector ColorMaps; std::vector SpecularMaps; std::vector NormalMaps; @@ -65,6 +71,8 @@ public: virtual void WriteBinary(std::ostream& out) { + + out.write((char*)&type, sizeof(MaterialType)); out.write((char*)&SpecularExponent, sizeof(float)); out.write((char*)&ReflectionFactor, sizeof(float)); @@ -74,30 +82,52 @@ public: out.write((char*)&IndexStart, sizeof(unsigned int)); out.write((char*)&IndexEnd, sizeof(unsigned int)); + if (type != MaterialType::Basic) { + if (type == MaterialType::SplatMapping) { + SplatMap.WriteBinary(out); + } + out.write((char*)&NumColorMaps, sizeof(unsigned char)); + out.write((char*)&NumSpecularMaps, sizeof(unsigned char)); + out.write((char*)&NumNormalMaps, sizeof(unsigned char)); + out.write((char*)&NumIncandescenceMaps, sizeof(unsigned char)); + } - out.write((char*)&NumColormaps, sizeof(char)); - out.write((char*)&NumSpecularMap, sizeof(char)); - out.write((char*)&NumNormalMap, sizeof(char)); - out.write((char*)&NumIncandescenceMap, sizeof(char)); - - for(auto aTexture : ColorMaps) { - aTexture.WriteBinary(out); - } - for (auto aTexture : SpecularMaps) { - aTexture.WriteBinary(out); - } - for (auto aTexture : NormalMaps) { - aTexture.WriteBinary(out); - } - for (auto aTexture : IncandescenceMaps) { - aTexture.WriteBinary(out); + if (type != MaterialType::Basic) { + for (auto aTexture : ColorMaps) { + aTexture.WriteBinary(out); + } + for (auto aTexture : SpecularMaps) { + aTexture.WriteBinary(out); + } + for (auto aTexture : NormalMaps) { + aTexture.WriteBinary(out); + } + for (auto aTexture : IncandescenceMaps) { + aTexture.WriteBinary(out); + } } } virtual void WriteASCII(std::ostream& out) const { out << "New Material _ not in binary" << endl; - out << "number of indices: " << Name << " _ not in binary" << endl; + + out << "MaterialType(enum): "; + switch (type) { + case MaterialType::Basic: + out << "Basic"; + break; + case MaterialType::SplatMapping: + out << "SplatMapping"; + break; + case MaterialType::SingleTextures: + out << "SingleTextures"; + break; + }; + + out << endl; + + out << "Material Name: " << Name << " _ not in binary" << endl; out << "SpecularExponent: " << SpecularExponent << endl; out << "ReflectionFactor: " << ReflectionFactor << endl; @@ -107,37 +137,38 @@ public: out << "IndexStart: " << IndexStart << endl; out << "IndexEnd: " << IndexEnd << endl; - if (NumColormaps > 0) - out << "NumColormaps: " << NumColormaps << endl; + switch (type) { + case MaterialType::SplatMapping: + out << "SplatMap _ not in binary " << endl; + SplatMap.WriteASCII(out); + //Intended fall trought + case MaterialType::SingleTextures: + out << "NumColormaps (is unsigned char in Binary): " << ((unsigned int)NumColorMaps) << endl; + out << "NumSpecularMap (is unsigned char in Binary): " << ((unsigned int)NumSpecularMaps) << endl; + out << "NumNormalMap (is unsigned char in Binary): " << ((unsigned int)NumNormalMaps) << endl; + out << "NumIncandescenceMap (is unsigned char in Binary): " << ((unsigned int)NumIncandescenceMaps )<< endl; - if (NumSpecularMap > 0) - out << "NumSpecularMap: " << NumSpecularMap << endl; - - if (NumNormalMap > 0) - out << "NumNormalMap: " << NumNormalMap << endl; - - if (NumIncandescenceMap > 0) - out << "NumIncandescenceMap: " << NumIncandescenceMap << endl; + out << "ColorMaps _ not in binary " << endl; + for (auto aTexture : ColorMaps) { + aTexture.WriteASCII(out); + } - out << "ColorMaps _ not in binary " << endl; - for (auto aTexture : ColorMaps) { - aTexture.WriteASCII(out); - } + out << "SpecularMaps _ not in binary " << endl; + for (auto aTexture : SpecularMaps) { + aTexture.WriteASCII(out); + } - out << "SpecularMaps _ not in binary " << endl; - for (auto aTexture : SpecularMaps) { - aTexture.WriteASCII(out); - } + out << "NormalMaps _ not in binary " << endl; + for (auto aTexture : NormalMaps) { + aTexture.WriteASCII(out); + } - out << "NormalMaps _ not in binary " << endl; - for (auto aTexture : NormalMaps) { - aTexture.WriteASCII(out); - } - - out << "IncandescenceMaps _ not in binary " << endl; - for (auto aTexture : IncandescenceMaps) { - aTexture.WriteASCII(out); - } + out << "IncandescenceMaps _ not in binary " << endl; + for (auto aTexture : IncandescenceMaps) { + aTexture.WriteASCII(out); + } + break; + }; } }; @@ -158,7 +189,7 @@ private: bool findNormalTexture(MaterialNode& material_node, MFnDependencyNode& node); bool findSpecularTexture(MaterialNode& material_node, MFnDependencyNode& node); bool findIncandescenceTexture(MaterialNode& material_node, MFnDependencyNode& node); - bool findSplatTextures(std::vector& textureVector, MFnDependencyNode& node); + bool findSplatTextures(MaterialNode& material_node, std::vector& textureVector, MFnDependencyNode& node); void grabLambertProperties(MaterialNode& material_node, MFnDependencyNode& node); void grabBlinnProperties(MaterialNode& material_node, MFnDependencyNode& node); void grabPhongProperties(MaterialNode& material_node, MFnDependencyNode& node); diff --git a/tools/MayaExporter/MayaExporter/Mesh.cpp b/tools/MayaExporter/MayaExporter/Mesh.cpp index 01737683..52b1392e 100644 --- a/tools/MayaExporter/MayaExporter/Mesh.cpp +++ b/tools/MayaExporter/MayaExporter/Mesh.cpp @@ -8,91 +8,91 @@ MeshClass::MeshClass() } -std::map MeshClass::GetWeightData() -{ - MS status; - map weightMap; - - MItDependencyNodes it(MFn::kSkinClusterFilter); - - while (!it.isDone()) { - - MObject object = it.thisNode(&status); - if (status != MS::kSuccess) { - MGlobal::displayError(MString() + " it.thisNode() ERROR: " + status.errorString()); - break; - } - MFnSkinCluster skinCluster(object, &status); - if (status != MS::kSuccess) { - MGlobal::displayError(MString() + "skinCluster() ERROR: " + status.errorString()); - break; - } - MDagPathArray influences; - - unsigned int nrOfInfluences = skinCluster.influenceObjects(influences,&status); - if (status != MS::kSuccess) { - MGlobal::displayError(MString() + "skinCluster.influenceObjects() ERROR: " + status.errorString()); - break; - } - - unsigned int index; - index = skinCluster.indexForOutputConnection(0,&status); - if (status != MS::kSuccess) { - MGlobal::displayError(MString() + "skinCluster.indexForOutputConnection() ERROR: " + status.errorString()); - break; - } - MDagPath skinPath; - status = skinCluster.getPathAtIndex(index, skinPath); - if (status != MS::kSuccess) { - MGlobal::displayError(MString() + "skinCluster.getPathAtIndex() ERROR: " + status.errorString()); - break; - } - - MItGeometry geomIter(skinPath); - //for (unsigned int i = 0; i < nrOfInfluences; i++) { - // MGlobal::displayInfo(MString() + " Influence object name: " + influences[i].partialPathName().asChar()); - //} - WeightInfo weightInfo; - - while (!geomIter.isDone()) { - MObject comp = geomIter.component(&status); - if (status != MS::kSuccess) { - MGlobal::displayError(MString() + "geomIter.component() ERROR: " + status.errorString()); - break; - } - MFloatArray weights; - unsigned int influenceCount; - status = skinCluster.getWeights(skinPath, comp, weights, influenceCount); - if (status != MS::kSuccess) { - MGlobal::displayError(MString() + "skinCluster.getWeights() ERROR: " + status.errorString()); - break; - } - MFnDependencyNode test(comp); - unsigned int nrOfWeights = 0; - - for (unsigned int j = 0; j < weights.length() && nrOfWeights != 4; j++) { - if (weights[j] > 0.00001) { - weightInfo.BoneWeights[nrOfWeights] = weights[j]; - weightInfo.BoneIndices[nrOfWeights] = j; - nrOfWeights++; - } - } - - float totalWeight = 0.0f; - for (unsigned int i = 0; i < 4; i++) { - totalWeight += weightInfo.BoneWeights[i]; - } - for (unsigned int i = 0; i < 4; i++) { - weightInfo.BoneWeights[i] /= totalWeight; - } - weightMap[geomIter.index()] = weightInfo; - - geomIter.next(); - } - it.next(); - } - return weightMap; -} +//std::map MeshClass::GetWeightData() +//{ +// MS status; +// map weightMap; +// +// MItDependencyNodes it(MFn::kSkinClusterFilter); +// +// while (!it.isDone()) { +// +// MObject object = it.thisNode(&status); +// if (status != MS::kSuccess) { +// MGlobal::displayError(MString() + " it.thisNode() ERROR: " + status.errorString()); +// break; +// } +// MFnSkinCluster skinCluster(object, &status); +// if (status != MS::kSuccess) { +// MGlobal::displayError(MString() + "skinCluster() ERROR: " + status.errorString()); +// break; +// } +// MDagPathArray influences; +// +// unsigned int nrOfInfluences = skinCluster.influenceObjects(influences,&status); +// if (status != MS::kSuccess) { +// MGlobal::displayError(MString() + "skinCluster.influenceObjects() ERROR: " + status.errorString()); +// break; +// } +// +// unsigned int index; +// index = skinCluster.indexForOutputConnection(0,&status); +// if (status != MS::kSuccess) { +// MGlobal::displayError(MString() + "skinCluster.indexForOutputConnection() ERROR: " + status.errorString()); +// break; +// } +// MDagPath skinPath; +// status = skinCluster.getPathAtIndex(index, skinPath); +// if (status != MS::kSuccess) { +// MGlobal::displayError(MString() + "skinCluster.getPathAtIndex() ERROR: " + status.errorString()); +// break; +// } +// +// MItGeometry geomIter(skinPath); +// //for (unsigned int i = 0; i < nrOfInfluences; i++) { +// // MGlobal::displayInfo(MString() + " Influence object name: " + influences[i].partialPathName().asChar()); +// //} +// WeightInfo weightInfo; +// +// while (!geomIter.isDone()) { +// MObject comp = geomIter.component(&status); +// if (status != MS::kSuccess) { +// MGlobal::displayError(MString() + "geomIter.component() ERROR: " + status.errorString()); +// break; +// } +// MFloatArray weights; +// unsigned int influenceCount; +// status = skinCluster.getWeights(skinPath, comp, weights, influenceCount); +// if (status != MS::kSuccess) { +// MGlobal::displayError(MString() + "skinCluster.getWeights() ERROR: " + status.errorString()); +// break; +// } +// MFnDependencyNode test(comp); +// unsigned int nrOfWeights = 0; +// +// for (unsigned int j = 0; j < weights.length() && nrOfWeights != 4; j++) { +// if (weights[j] > 0.00001) { +// weightInfo.BoneWeights[nrOfWeights] = weights[j]; +// weightInfo.BoneIndices[nrOfWeights] = j; +// nrOfWeights++; +// } +// } +// +// float totalWeight = 0.0f; +// for (unsigned int i = 0; i < 4; i++) { +// totalWeight += weightInfo.BoneWeights[i]; +// } +// for (unsigned int i = 0; i < 4; i++) { +// weightInfo.BoneWeights[i] /= totalWeight; +// } +// weightMap[geomIter.index()] = weightInfo; +// +// geomIter.next(); +// } +// it.next(); +// } +// return weightMap; +//} Mesh MeshClass::GetMeshData(MObjectArray object) { @@ -317,7 +317,7 @@ Mesh MeshClass::GetMeshData(MObjectArray object) } for (unsigned int i = 0; i < 4; i++) { - thisVertex.BoneWeights[i] = thisVertex.BoneWeights[i] / totalWeight; + //thisVertex.BoneWeights[i] = thisVertex.BoneWeights[i] / totalWeight; } } else { thisVertex.useWeights = false; diff --git a/tools/MayaExporter/MayaExporter/Mesh.h b/tools/MayaExporter/MayaExporter/Mesh.h index 87e0ce19..eda79805 100644 --- a/tools/MayaExporter/MayaExporter/Mesh.h +++ b/tools/MayaExporter/MayaExporter/Mesh.h @@ -62,7 +62,7 @@ public: class Mesh : public OutputData { public: - bool hasSkin = false; + bool hasSkin = true; //Should be false by default... Have it true now since pipeline only support skinned vertecies unsigned int NumVertices; unsigned int NumIndices; std::vector Vertices; diff --git a/tools/MayaExporter/MayaExporter/Skeleton.cpp b/tools/MayaExporter/MayaExporter/Skeleton.cpp index 49a7309c..2e432476 100644 --- a/tools/MayaExporter/MayaExporter/Skeleton.cpp +++ b/tools/MayaExporter/MayaExporter/Skeleton.cpp @@ -230,7 +230,7 @@ Animation Skeleton::GetAnimData(std::string animationName, int startFrame, int e MTime time = MAnimControl::currentTime(); MFnTransform thisJoint(jointIt.currentItem()); - MTransformationMatrix TransformationMatrix = thisJoint.transformationMatrix(); + MTransformationMatrix transformationMatrix = thisJoint.transformationMatrix(); double doubleMat[4][4]; @@ -256,7 +256,7 @@ Animation Skeleton::GetAnimData(std::string animationName, int startFrame, int e MMatrix LastJointMatrix(doubleMat); //Is same as last KeyFrame - if (LastJointMatrix.isEquivalent(transformationMatrix)) { + if (LastJointMatrix.isEquivalent(transformationMatrix.asMatrix())) { //jointID++; //jointIt.next(); currentFrame++; @@ -264,7 +264,7 @@ Animation Skeleton::GetAnimData(std::string animationName, int startFrame, int e continue; } else if(!haxBool){ haxBool = true; - MTransformationMatrix TransformationMatrix = LastJointMatrix; + MTransformationMatrix LastJointTransformationMatrix = LastJointMatrix; MObject jointOrientObj = thisJoint.attribute("jointOrient"); MFnNumericAttribute jointOrient(jointOrientObj); double jointOrientDouble[3]; @@ -279,7 +279,7 @@ Animation Skeleton::GetAnimData(std::string animationName, int startFrame, int e MQuaternion jo = joEuler.asQuaternion(); double tmp[4]; - TransformationMatrix.getRotationQuaternion(tmp[0], tmp[1], tmp[2], tmp[3]); + LastJointTransformationMatrix.getRotationQuaternion(tmp[0], tmp[1], tmp[2], tmp[3]); MQuaternion rotation(tmp); rotation = rotation * jo; @@ -294,11 +294,11 @@ Animation Skeleton::GetAnimData(std::string animationName, int startFrame, int e previousKeyFrame.Rotation[1] = tmp[1]; previousKeyFrame.Rotation[2] = tmp[2]; previousKeyFrame.Rotation[3] = tmp[3]; - TransformationMatrix.getTranslation(MSpace::kTransform).get(tmp); + LastJointTransformationMatrix.getTranslation(MSpace::kTransform).get(tmp); previousKeyFrame.Position[0] = tmp[0]; previousKeyFrame.Position[1] = tmp[1]; previousKeyFrame.Position[2] = tmp[2]; - TransformationMatrix.getScale(tmp, MSpace::kTransform); + LastJointTransformationMatrix.getScale(tmp, MSpace::kTransform); previousKeyFrame.Scale[0] = tmp[0]; previousKeyFrame.Scale[1] = tmp[1]; previousKeyFrame.Scale[2] = tmp[2]; @@ -307,7 +307,7 @@ Animation Skeleton::GetAnimData(std::string animationName, int startFrame, int e } } - transformationMatrix.get(doubleMat); + transformationMatrix.asMatrix().get(doubleMat); //Save transformationMatrix to joinCheckMap joinCheckMap[thisJoint.name().asChar()][0][0] = doubleMat[0][0]; @@ -327,8 +327,6 @@ Animation Skeleton::GetAnimData(std::string animationName, int startFrame, int e joinCheckMap[thisJoint.name().asChar()][3][2] = doubleMat[3][2]; joinCheckMap[thisJoint.name().asChar()][3][3] = doubleMat[3][3]; - MTransformationMatrix TransformationMatrix = thisJoint.transformation(); - if (currentFrame == startFrame) { MPlug thisJointBindPose = thisJoint.findPlug("bindPose"); MDataHandle DataHandle; @@ -348,7 +346,7 @@ Animation Skeleton::GetAnimData(std::string animationName, int startFrame, int e thisJointBindPoseMatrix = thisJointBindPoseMatrix * parentBindPoseMatrix.inverse(); } - if (thisJointBindPoseMatrix.isEquivalent(TransformationMatrix.asMatrix())) { + if (thisJointBindPoseMatrix.isEquivalent(transformationMatrix.asMatrix())) { //jointID++; //jointIt.next(); currentFrame++; @@ -372,7 +370,7 @@ Animation Skeleton::GetAnimData(std::string animationName, int startFrame, int e MQuaternion jo = joEuler.asQuaternion(); double tmp[4]; - TransformationMatrix.getRotationQuaternion(tmp[0], tmp[1], tmp[2], tmp[3]); + transformationMatrix.getRotationQuaternion(tmp[0], tmp[1], tmp[2], tmp[3]); MQuaternion rotation(tmp); rotation = rotation * jo; @@ -386,11 +384,11 @@ Animation Skeleton::GetAnimData(std::string animationName, int startFrame, int e thisKeyFrame.Rotation[1] = tmp[1]; thisKeyFrame.Rotation[2] = tmp[2]; thisKeyFrame.Rotation[3] = tmp[3]; - TransformationMatrix.getTranslation(MSpace::kTransform).get(tmp); + transformationMatrix.getTranslation(MSpace::kTransform).get(tmp); thisKeyFrame.Position[0] = tmp[0]; thisKeyFrame.Position[1] = tmp[1]; thisKeyFrame.Position[2] = tmp[2]; - TransformationMatrix.getScale(tmp, MSpace::kTransform); + transformationMatrix.getScale(tmp, MSpace::kTransform); thisKeyFrame.Scale[0] = tmp[0]; thisKeyFrame.Scale[1] = tmp[1]; thisKeyFrame.Scale[2] = tmp[2]; From 43719f8304c924cc63e8cf8a6b6ef796fa5f819b Mon Sep 17 00:00:00 2001 From: Teejoon Date: Sun, 7 Feb 2016 15:27:26 +0100 Subject: [PATCH 105/355] Added texture tiling to shaders (exkluding ExplosinEffects) --- include/Engine/Rendering/DrawFinalPass.h | 2 +- include/Engine/Rendering/ModelJob.h | 36 +++---- .../Schema/Entities/SplatMapTesWorld.xml | 21 ++++ resources/Shaders/ForwardPlus.frag.glsl | 13 ++- .../Shaders/ForwardPlusSplatMap.frag.glsl | 70 ++++++++---- src/Engine/Rendering/DrawFinalPass.cpp | 102 +++++++++++------- 6 files changed, 162 insertions(+), 82 deletions(-) create mode 100644 resources/Schema/Entities/SplatMapTesWorld.xml diff --git a/include/Engine/Rendering/DrawFinalPass.h b/include/Engine/Rendering/DrawFinalPass.h index a32c562b..830ded3c 100644 --- a/include/Engine/Rendering/DrawFinalPass.h +++ b/include/Engine/Rendering/DrawFinalPass.h @@ -36,7 +36,7 @@ private: void BindModelUniforms(GLuint shaderHandle, std::shared_ptr& job, RenderScene& scene); void BindExplosionTextures(std::shared_ptr& job); - void BindModelTextures(std::shared_ptr& job); + void BindModelTextures(GLuint shaderHandle, std::shared_ptr& job); Texture* m_WhiteTexture; Texture* m_BlackTexture; diff --git a/include/Engine/Rendering/ModelJob.h b/include/Engine/Rendering/ModelJob.h index 2c662f09..fe8fe26f 100644 --- a/include/Engine/Rendering/ModelJob.h +++ b/include/Engine/Rendering/ModelJob.h @@ -46,19 +46,19 @@ struct ModelJob : RenderJob ::RawModel::MaterialSingleTextures* singleTextures = static_cast<::RawModel::MaterialSingleTextures*>(matProp.material); TextureID = (singleTextures->ColorMap.Texture) ? singleTextures->ColorMap.Texture->ResourceID : 0; if (modelComponent["DiffuseTexture"]) { - DiffuseTexture.push_back(singleTextures->ColorMap.Texture.get()); + DiffuseTexture.push_back(&singleTextures->ColorMap); } if (modelComponent["NormalMap"]) { - NormalTexture.push_back(singleTextures->NormalMap.Texture.get()); + NormalTexture.push_back(&singleTextures->NormalMap); } if (modelComponent["SpecularMap"]) { - SpecularTexture.push_back(singleTextures->SpecularMap.Texture.get()); + SpecularTexture.push_back(&singleTextures->SpecularMap); } if (modelComponent["GlowMap"]) { - IncandescenceTexture.push_back(singleTextures->IncandescenceMap.Texture.get()); + IncandescenceTexture.push_back(&singleTextures->IncandescenceMap); } } break; @@ -72,30 +72,30 @@ struct ModelJob : RenderJob } ::RawModel::MaterialSplatMapping* SplatTextures = static_cast<::RawModel::MaterialSplatMapping*>(matProp.material); - SplatMap = SplatTextures->SplatMap.Texture.get(); + SplatMap = &SplatTextures->SplatMap; TextureID = (SplatTextures->ColorMaps[0].Texture) ? SplatTextures->ColorMaps[0].Texture->ResourceID : 0; if (modelComponent["DiffuseTexture"]) { - for (auto texture : SplatTextures->ColorMaps) { - DiffuseTexture.push_back(texture.Texture.get()); + for (auto& texture : SplatTextures->ColorMaps) { + DiffuseTexture.push_back(&texture); } } if (modelComponent["NormalMap"]) { - for (auto texture : SplatTextures->NormalMaps) { - NormalTexture.push_back(texture.Texture.get()); + for (auto& texture : SplatTextures->NormalMaps) { + NormalTexture.push_back(&texture); } } if (modelComponent["SpecularMap"]) { - for (auto texture : SplatTextures->SpecularMaps) { - SpecularTexture.push_back(texture.Texture.get()); + for (auto& texture : SplatTextures->SpecularMaps) { + SpecularTexture.push_back(&texture); } } if (modelComponent["GlowMap"]) { - for (auto texture : SplatTextures->IncandescenceMaps) { - IncandescenceTexture.push_back(texture.Texture.get()); + for (auto& texture : SplatTextures->IncandescenceMaps) { + IncandescenceTexture.push_back(&texture); } } } @@ -132,11 +132,11 @@ struct ModelJob : RenderJob ::RawModel::MaterialType Type; EntityID Entity; glm::mat4 Matrix; - const Texture* SplatMap; - std::vector DiffuseTexture; - std::vector NormalTexture; - std::vector SpecularTexture; - std::vector IncandescenceTexture; + const ::RawModel::TextureProperties* SplatMap; + std::vector DiffuseTexture; + std::vector NormalTexture; + std::vector SpecularTexture; + std::vector IncandescenceTexture; float Shininess = 0.f; glm::vec4 Color; const ::Model* Model = nullptr; diff --git a/resources/Schema/Entities/SplatMapTesWorld.xml b/resources/Schema/Entities/SplatMapTesWorld.xml new file mode 100644 index 00000000..11660a63 --- /dev/null +++ b/resources/Schema/Entities/SplatMapTesWorld.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + Models/Test/SplatMapTest.mesh + + + + + + + + diff --git a/resources/Shaders/ForwardPlus.frag.glsl b/resources/Shaders/ForwardPlus.frag.glsl index c09e0438..471ee20b 100644 --- a/resources/Shaders/ForwardPlus.frag.glsl +++ b/resources/Shaders/ForwardPlus.frag.glsl @@ -9,6 +9,11 @@ uniform vec2 ScreenDimensions; uniform vec4 FillColor; uniform vec4 AmbientColor; uniform float FillPercentage; + +uniform vec2 DiffuseUVRepeat; +uniform vec2 NormalUVRepeat; +uniform vec2 SpecularUVRepeat; +uniform vec2 GlowUVRepeat; layout (binding = 0) uniform sampler2D DiffuseTexture; layout (binding = 1) uniform sampler2D NormalMapTexture; layout (binding = 2) uniform sampler2D SpecularMapTexture; @@ -114,11 +119,11 @@ vec4 CalcNormalMappedValue(vec3 normal, vec3 tangent, vec3 bitangent, vec2 textu void main() { - vec4 diffuseTexel = texture2D(DiffuseTexture, Input.TextureCoordinate); - vec4 glowTexel = texture2D(GlowMapTexture, Input.TextureCoordinate); - vec4 specularTexel = texture2D(SpecularMapTexture, Input.TextureCoordinate); + vec4 diffuseTexel = texture2D(DiffuseTexture, Input.TextureCoordinate * DiffuseUVRepeat); + vec4 glowTexel = texture2D(GlowMapTexture, Input.TextureCoordinate * GlowUVRepeat); + vec4 specularTexel = texture2D(SpecularMapTexture, Input.TextureCoordinate * SpecularUVRepeat); vec4 position = V * M * vec4(Input.Position, 1.0); - vec4 normal = V * CalcNormalMappedValue(Input.Normal, Input.Tangent, Input.BiTangent, Input.TextureCoordinate, NormalMapTexture); + vec4 normal = V * CalcNormalMappedValue(Input.Normal, Input.Tangent, Input.BiTangent, Input.TextureCoordinate * NormalUVRepeat, NormalMapTexture); normal = normalize(normal); //vec4 normal = normalize(V * vec4(Input.Normal, 0.0)); vec4 viewVec = normalize(-position); diff --git a/resources/Shaders/ForwardPlusSplatMap.frag.glsl b/resources/Shaders/ForwardPlusSplatMap.frag.glsl index fe26469e..c4908534 100644 --- a/resources/Shaders/ForwardPlusSplatMap.frag.glsl +++ b/resources/Shaders/ForwardPlusSplatMap.frag.glsl @@ -9,6 +9,28 @@ uniform vec4 DiffuseColor; uniform vec4 FillColor; uniform vec4 Color; uniform vec4 AmbientColor; + +//Get bineded at the same time as the textures +uniform vec2 DiffuseUVRepeat1; +uniform vec2 DiffuseUVRepeat2; +uniform vec2 DiffuseUVRepeat3; +uniform vec2 DiffuseUVRepeat4; +uniform vec2 DiffuseUVRepeat5; +uniform vec2 NormalUVRepeat1; +uniform vec2 NormalUVRepeat2; +uniform vec2 NormalUVRepeat3; +uniform vec2 NormalUVRepeat4; +uniform vec2 NormalUVRepeat5; +uniform vec2 SpecularUVRepeat1; +uniform vec2 SpecularUVRepeat2; +uniform vec2 SpecularUVRepeat3; +uniform vec2 SpecularUVRepeat4; +uniform vec2 SpecularUVRepeat5; +uniform vec2 GlowUVRepeat1; +uniform vec2 GlowUVRepeat2; +uniform vec2 GlowUVRepeat3; +uniform vec2 GlowUVRepeat4; +uniform vec2 GlowUVRepeat5; layout (binding = 0) uniform sampler2D SplatMapTexture; layout (binding = 1) uniform sampler2D DiffuseTexture1; layout (binding = 2) uniform sampler2D DiffuseTexture2; @@ -131,12 +153,13 @@ vec4 CalcNormalMappedValue(vec3 normal, vec3 tangent, vec3 bitangent, vec2 textu #define TEXTURE_TILE 5.0 -vec4 CalcBlendedTexel(vec4 blendValue, sampler2D R, sampler2D G, sampler2D B, sampler2D A, sampler2D D, vec2 tileValues){ - vec4 R_Channel = texture2D(R, Input.TextureCoordinate * tileValues); - vec4 G_Channel = texture2D(G, Input.TextureCoordinate * tileValues); - vec4 B_Channel = texture2D(B, Input.TextureCoordinate * tileValues); - vec4 A_Channel = texture2D(A, Input.TextureCoordinate * tileValues); - vec4 D_Channel = texture2D(D, Input.TextureCoordinate * tileValues); +vec4 CalcBlendedTexel(vec4 blendValue, sampler2D R, sampler2D G, sampler2D B, sampler2D A, sampler2D D, + vec2 R_TileValues, vec2 G_TileValues, vec2 B_TileValues, vec2 A_TileValues, vec2 D_TileValues){ + vec4 R_Channel = texture2D(R, Input.TextureCoordinate * R_TileValues); + vec4 G_Channel = texture2D(G, Input.TextureCoordinate * G_TileValues); + vec4 B_Channel = texture2D(B, Input.TextureCoordinate * B_TileValues); + vec4 A_Channel = texture2D(A, Input.TextureCoordinate * A_TileValues); + vec4 D_Channel = texture2D(D, Input.TextureCoordinate * D_TileValues); float total = blendValue.r + blendValue.g + blendValue.b + blendValue.a; if(total > 1.0f){ @@ -154,18 +177,23 @@ vec4 CalcBlendedTexel(vec4 blendValue, sampler2D R, sampler2D G, sampler2D B, sa + D_percent * D_Channel; } -vec4 CalcBlendedNormal(vec4 blendValue, sampler2D R, sampler2D G, sampler2D B, sampler2D A, sampler2D D, vec2 tileValues){ +vec4 CalcBlendedNormal(vec4 blendValue, sampler2D R, sampler2D G, sampler2D B, sampler2D A, sampler2D D, + vec2 R_TileValues, vec2 G_TileValues, vec2 B_TileValues, vec2 A_TileValues, vec2 D_TileValues){ mat3 TBN = mat3(Input.Tangent, Input.BiTangent, Input.Normal); - vec3 R_Channel = texture(R, Input.TextureCoordinate * tileValues).xyz * 2.0 - vec3(1.0); - vec3 G_Channel = texture(G, Input.TextureCoordinate * tileValues).xyz * 2.0 - vec3(1.0); - vec3 B_Channel = texture(B, Input.TextureCoordinate * tileValues).xyz * 2.0 - vec3(1.0); - vec3 A_Channel = texture(A, Input.TextureCoordinate * tileValues).xyz * 2.0 - vec3(1.0); - vec3 D_Channel = texture(D, Input.TextureCoordinate * tileValues).xyz * 2.0 - vec3(1.0); + vec3 R_Channel = texture(R, Input.TextureCoordinate * R_TileValues).xyz * 2.0 - vec3(1.0); + vec3 G_Channel = texture(G, Input.TextureCoordinate * G_TileValues).xyz * 2.0 - vec3(1.0); + vec3 B_Channel = texture(B, Input.TextureCoordinate * B_TileValues).xyz * 2.0 - vec3(1.0); + vec3 A_Channel = texture(A, Input.TextureCoordinate * A_TileValues).xyz * 2.0 - vec3(1.0); + vec3 D_Channel = texture(D, Input.TextureCoordinate * D_TileValues).xyz * 2.0 - vec3(1.0); - if(blendValue.length() > 1.0f){ - blendValue = normalize(blendValue); + float total = blendValue.r + blendValue.g + blendValue.b + blendValue.a; + if(total > 1.0f){ + blendValue.r / total; + blendValue.g / total; + blendValue.b / total; + blendValue.a / total; } - float D_percent = 1.0f - blendValue.r - blendValue.g - blendValue.b - blendValue.a; + float D_percent = clamp( 1.0f - total, 0.0f, 1.0f); vec3 Normal_result = blendValue.r * R_Channel + blendValue.g * G_Channel @@ -180,12 +208,16 @@ void main() { vec4 splatTexel = texture2D(SplatMapTexture, Input.TextureCoordinate); - vec4 diffuseTexel = CalcBlendedTexel(splatTexel, DiffuseTexture1, DiffuseTexture2, DiffuseTexture3, DiffuseTexture4, DiffuseTexture5, vec2(TEXTURE_TILE, TEXTURE_TILE)); - vec4 glowTexel = CalcBlendedTexel(splatTexel, GlowMapTexture1, GlowMapTexture2, GlowMapTexture3, GlowMapTexture4, GlowMapTexture5, vec2(TEXTURE_TILE, TEXTURE_TILE)); - vec4 specularTexel = CalcBlendedTexel(splatTexel, SpecularMapTexture1, SpecularMapTexture2, SpecularMapTexture3, SpecularMapTexture4, SpecularMapTexture5, vec2(TEXTURE_TILE, TEXTURE_TILE)); + vec4 diffuseTexel = CalcBlendedTexel(splatTexel, DiffuseTexture1, DiffuseTexture2, DiffuseTexture3, DiffuseTexture4, DiffuseTexture5, + DiffuseUVRepeat1, DiffuseUVRepeat2, DiffuseUVRepeat3, DiffuseUVRepeat4, DiffuseUVRepeat5); + vec4 glowTexel = CalcBlendedTexel(splatTexel, GlowMapTexture1, GlowMapTexture2, GlowMapTexture3, GlowMapTexture4, GlowMapTexture5, + GlowUVRepeat1, GlowUVRepeat2, GlowUVRepeat3, GlowUVRepeat4, GlowUVRepeat5); + vec4 specularTexel = CalcBlendedTexel(splatTexel, SpecularMapTexture1, SpecularMapTexture2, SpecularMapTexture3, SpecularMapTexture4, SpecularMapTexture5, + SpecularUVRepeat1, SpecularUVRepeat2, SpecularUVRepeat3, SpecularUVRepeat4, SpecularUVRepeat5); vec4 position = V * M * vec4(Input.Position, 1.0); //vec4 normal = V * CalcNormalMappedValue(Input.Normal, Input.Tangent, Input.BiTangent, Input.TextureCoordinate, SplatMapTexture); - vec4 normal = V * CalcBlendedNormal(splatTexel, NormalMapTexture1, NormalMapTexture2, NormalMapTexture3, NormalMapTexture4, NormalMapTexture5, vec2(TEXTURE_TILE, TEXTURE_TILE)); + vec4 normal = V * CalcBlendedNormal(splatTexel, NormalMapTexture1, NormalMapTexture2, NormalMapTexture3, NormalMapTexture4, NormalMapTexture5, + NormalUVRepeat1, NormalUVRepeat2, NormalUVRepeat3, NormalUVRepeat4, NormalUVRepeat5); normal = normalize(normal); //vec4 normal = normalize(V * vec4(Input.Normal, 0.0)); vec4 viewVec = normalize(-position); diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index 1ceddb4e..3c4406fe 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -190,6 +190,10 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& GLERROR("Bind Forward program"); //bind uniforms BindModelUniforms(forwardHandle, modelJob, scene); + //bind textures + BindModelTextures(forwardHandle, modelJob); + GLERROR("asdasd"); + break; } case RawModel::MaterialType::SplatMapping: @@ -198,16 +202,14 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& GLERROR("Bind SplatMap program"); //bind uniforms BindModelUniforms(forwardSplatHandle, modelJob, scene); + //bind textures + BindModelTextures(forwardSplatHandle, modelJob); + GLERROR("asdasd"); + break; } } - //bind textures - BindModelTextures(modelJob); - GLERROR("asdasd"); - - - if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { if (modelJob->Animation != nullptr) { @@ -294,120 +296,140 @@ void DrawFinalPass::BindModelUniforms(GLuint shaderHandle, std::shared_ptr& job) { glActiveTexture(GL_TEXTURE0); - if (job->DiffuseTexture.size() > 0 && job->DiffuseTexture[0] != nullptr) { - glBindTexture(GL_TEXTURE_2D, job->DiffuseTexture[0]->m_Texture); //JOHAN TODO: support multiple diffuse Textures + if (job->DiffuseTexture.size() > 0 && job->DiffuseTexture[0]->Texture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->DiffuseTexture[0]->Texture->m_Texture); //JOHAN TODO: support multiple diffuse Textures } else { glBindTexture(GL_TEXTURE_2D, m_WhiteTexture->m_Texture); } glActiveTexture(GL_TEXTURE1); - if (job->NormalTexture.size() > 0 && job->NormalTexture[0] != nullptr) { - glBindTexture(GL_TEXTURE_2D, job->NormalTexture[0]->m_Texture); //JOHAN TODO: support multiple diffuse Textures + if (job->NormalTexture.size() > 0 && job->NormalTexture[0]->Texture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->NormalTexture[0]->Texture->m_Texture); //JOHAN TODO: support multiple diffuse Textures } else { glBindTexture(GL_TEXTURE_2D, m_NeutralNormalTexture->m_Texture); } glActiveTexture(GL_TEXTURE2); - if (job->SpecularTexture.size() > 0 && job->SpecularTexture[0] != nullptr) { - glBindTexture(GL_TEXTURE_2D, job->SpecularTexture[0]->m_Texture); //JOHAN TODO: support multiple diffuse Textures + if (job->SpecularTexture.size() > 0 && job->SpecularTexture[0]->Texture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->SpecularTexture[0]->Texture->m_Texture); //JOHAN TODO: support multiple diffuse Textures } else { glBindTexture(GL_TEXTURE_2D, m_GreyTexture->m_Texture); } glActiveTexture(GL_TEXTURE3); - if (job->IncandescenceTexture.size() > 0 && job->IncandescenceTexture[0] != nullptr) { - glBindTexture(GL_TEXTURE_2D, job->IncandescenceTexture[0]->m_Texture); //JOHAN TODO: support multiple diffuse Textures + if (job->IncandescenceTexture.size() > 0 && job->IncandescenceTexture[0]->Texture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->IncandescenceTexture[0]->Texture->m_Texture); //JOHAN TODO: support multiple diffuse Textures } else { glBindTexture(GL_TEXTURE_2D, m_BlackTexture->m_Texture); } } -void DrawFinalPass::BindModelTextures(std::shared_ptr& job) +void DrawFinalPass::BindModelTextures(GLuint shaderHandle, std::shared_ptr& job) { switch (job->Type) { case RawModel::MaterialType::SingleTextures: case RawModel::MaterialType::Basic: { glActiveTexture(GL_TEXTURE0); - if (job->DiffuseTexture.size() > 0 && job->DiffuseTexture[0] != nullptr) { - glBindTexture(GL_TEXTURE_2D, job->DiffuseTexture[0]->m_Texture); + if (job->DiffuseTexture.size() > 0 && job->DiffuseTexture[0]->Texture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->DiffuseTexture[0]->Texture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, "DiffuseUVRepeat"), 1, glm::value_ptr(job->DiffuseTexture[0]->UVRepeat)); } else { glBindTexture(GL_TEXTURE_2D, m_WhiteTexture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, "DiffuseUVRepeat"), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f))); } glActiveTexture(GL_TEXTURE1); - if (job->NormalTexture.size() > 0 && job->NormalTexture[0] != nullptr) { - glBindTexture(GL_TEXTURE_2D, job->NormalTexture[0]->m_Texture); + if (job->NormalTexture.size() > 0 && job->NormalTexture[0]->Texture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->NormalTexture[0]->Texture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, "NormalUVRepeat"), 1, glm::value_ptr(job->NormalTexture[0]->UVRepeat)); } else { glBindTexture(GL_TEXTURE_2D, m_NeutralNormalTexture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, "NormalUVRepeat"), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f))); } glActiveTexture(GL_TEXTURE2); - if (job->SpecularTexture.size() > 0 && job->SpecularTexture[0] != nullptr) { - glBindTexture(GL_TEXTURE_2D, job->SpecularTexture[0]->m_Texture); + if (job->SpecularTexture.size() > 0 && job->SpecularTexture[0]->Texture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->SpecularTexture[0]->Texture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, "SpecularUVRepeat"), 1, glm::value_ptr(job->SpecularTexture[0]->UVRepeat)); } else { glBindTexture(GL_TEXTURE_2D, m_GreyTexture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, "SpecularUVRepeat"), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f))); } glActiveTexture(GL_TEXTURE3); - if (job->IncandescenceTexture.size() > 0 && job->IncandescenceTexture[0] != nullptr) { - glBindTexture(GL_TEXTURE_2D, job->IncandescenceTexture[0]->m_Texture); + if (job->IncandescenceTexture.size() > 0 && job->IncandescenceTexture[0]->Texture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->IncandescenceTexture[0]->Texture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, "GlowUVRepeat"), 1, glm::value_ptr(job->IncandescenceTexture[0]->UVRepeat)); } else { glBindTexture(GL_TEXTURE_2D, m_BlackTexture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, "GlowUVRepeat"), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f))); } break; } case RawModel::MaterialType::SplatMapping: { glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_2D, job->SplatMap->m_Texture); + glBindTexture(GL_TEXTURE_2D, job->SplatMap->Texture->m_Texture); int texturePosition = GL_TEXTURE1; + //Bind 5 diffuse textures + std::string UniformName = "DiffuseUVRepeat"; for (unsigned int i = 0; i < 5; i++) { glActiveTexture(texturePosition); - if (job->DiffuseTexture.size() > i && job->DiffuseTexture[i] != nullptr) { - glBindTexture(GL_TEXTURE_2D, job->DiffuseTexture[i]->m_Texture); - } - else { + if (job->DiffuseTexture.size() > i && job->DiffuseTexture[i]->Texture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->DiffuseTexture[i]->Texture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(job->DiffuseTexture[i]->UVRepeat)); + } else { glBindTexture(GL_TEXTURE_2D, m_WhiteTexture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f))); } texturePosition++; } + //Bind 5 Normal textures + UniformName = "NormalUVRepeat"; for (unsigned int i = 0; i < 5; i++) { glActiveTexture(texturePosition); - if (job->NormalTexture.size() > i && job->NormalTexture[i] != nullptr) { - glBindTexture(GL_TEXTURE_2D, job->NormalTexture[i]->m_Texture); - } - else { + if (job->NormalTexture.size() > i && job->NormalTexture[i]->Texture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->NormalTexture[i]->Texture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(job->NormalTexture[i]->UVRepeat)); + } else { glBindTexture(GL_TEXTURE_2D, m_NeutralNormalTexture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f))); } texturePosition++; } + //Bind 5 Specular textures + UniformName = "SpecularUVRepeat"; for (unsigned int i = 0; i < 5; i++) { glActiveTexture(texturePosition); - if (job->SpecularTexture.size() > i && job->SpecularTexture[i] != nullptr) { - glBindTexture(GL_TEXTURE_2D, job->SpecularTexture[i]->m_Texture); - } - else { + if (job->SpecularTexture.size() > i && job->SpecularTexture[i]->Texture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->SpecularTexture[i]->Texture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(job->SpecularTexture[i]->UVRepeat)); + } else { glBindTexture(GL_TEXTURE_2D, m_GreyTexture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f))); } texturePosition++; } + //Bind 5 Incandescence textures + UniformName = "GlowUVRepeat"; for (unsigned int i = 0; i < 5; i++) { glActiveTexture(texturePosition); - if (job->IncandescenceTexture.size() > i && job->IncandescenceTexture[i] != nullptr) { - glBindTexture(GL_TEXTURE_2D, job->IncandescenceTexture[i]->m_Texture); - } - else { + if (job->IncandescenceTexture.size() > i && job->IncandescenceTexture[i]->Texture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->IncandescenceTexture[i]->Texture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(job->IncandescenceTexture[i]->UVRepeat)); + } else { glBindTexture(GL_TEXTURE_2D, m_BlackTexture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f))); } texturePosition++; } From ce228541689d695c7a09ef96527dc572a874193e Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Mon, 8 Feb 2016 11:22:28 +0100 Subject: [PATCH 106/355] HealthPickups are now based on a percentage of player maxhealth. You can no longer pickup healthpacks if you are at max health. You can no longer gain more than maxHealth. --- include/Game/Systems/HealthSystem.h | 1 + resources/Schema/Components/HealthPickup.xsd | 2 +- src/Game/Systems/HealthSystem.cpp | 4 ++-- src/Game/Systems/PickupSpawnSystem.cpp | 10 ++++++++-- 4 files changed, 12 insertions(+), 5 deletions(-) diff --git a/include/Game/Systems/HealthSystem.h b/include/Game/Systems/HealthSystem.h index 46f24630..61456d5d 100644 --- a/include/Game/Systems/HealthSystem.h +++ b/include/Game/Systems/HealthSystem.h @@ -12,6 +12,7 @@ #include #include +#include class HealthSystem : public PureSystem { diff --git a/resources/Schema/Components/HealthPickup.xsd b/resources/Schema/Components/HealthPickup.xsd index c5fae00f..bf3b327c 100644 --- a/resources/Schema/Components/HealthPickup.xsd +++ b/resources/Schema/Components/HealthPickup.xsd @@ -13,7 +13,7 @@ The respawn timer for a health pickup - How much health the player will get when he picks the healthPickup up + How much percent max-health the player will get when he picks the healthPickup up diff --git a/src/Game/Systems/HealthSystem.cpp b/src/Game/Systems/HealthSystem.cpp index 91cae148..94d98222 100644 --- a/src/Game/Systems/HealthSystem.cpp +++ b/src/Game/Systems/HealthSystem.cpp @@ -18,7 +18,7 @@ bool HealthSystem::OnPlayerDamaged(Events::PlayerDamage& e) ComponentWrapper cHealth = e.Player["Health"]; double& health = cHealth["Health"]; health -= e.Damage; - + if (health <= 0.0) { m_World->DeleteEntity(e.Player.ID); } @@ -30,8 +30,8 @@ bool HealthSystem::OnPlayerHealthPickup(Events::PlayerHealthPickup& e) { ComponentWrapper cHealth = e.Player["Health"]; double& health = cHealth["Health"]; - //NOTE: its possible to get more than MaxHealth health health += e.HealthAmount; + health = std::min(health, (double)cHealth["MaxHealth"]); return true; } diff --git a/src/Game/Systems/PickupSpawnSystem.cpp b/src/Game/Systems/PickupSpawnSystem.cpp index 783f7a62..e9f201c1 100644 --- a/src/Game/Systems/PickupSpawnSystem.cpp +++ b/src/Game/Systems/PickupSpawnSystem.cpp @@ -43,10 +43,16 @@ bool PickupSpawnSystem::OnTriggerTouch(Events::TriggerTouch& e) if (!e.Trigger.HasComponent("HealthPickup")) { return false; } + double healthGiven = 0.01*(double)e.Trigger["HealthPickup"]["HealthGain"] * (double)e.Entity["Health"]["MaxHealth"]; + //cant pick up healthpacks if you are already at MaxHealth + if ((double)e.Entity["Health"]["Health"] >= (double)e.Entity["Health"]["MaxHealth"]) { + return false; + } + //personEntered = e.Entity, thingEntered = e.Trigger Events::PlayerHealthPickup ePlayerHealthPickup; - ePlayerHealthPickup.HealthAmount = e.Trigger["HealthPickup"]["HealthGain"]; - ePlayerHealthPickup.PlayerHealedID = e.Entity.ID; + ePlayerHealthPickup.HealthAmount = healthGiven; + ePlayerHealthPickup.Player = e.Entity; m_EventBroker->Publish(ePlayerHealthPickup); //copy position, healthgain, respawntimer (twice since one of the values will be counted down to 0, the other will be set in the new object) From 99cbdd3c1e668b85603ed3fa07d5f9f84ff6f7fa Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Mon, 8 Feb 2016 11:39:29 +0100 Subject: [PATCH 107/355] Player death effect fixes --- include/Game/Systems/PlayerDeathSystem.h | 3 ++ include/Game/Systems/PlayerSpawnSystem.h | 1 + .../PlayerDeathExplosionWithCamera.xml | 30 +++++++---------- src/Game/Systems/PlayerDeathSystem.cpp | 33 +++++++++++-------- src/Game/Systems/PlayerSpawnSystem.cpp | 4 ++- 5 files changed, 39 insertions(+), 32 deletions(-) diff --git a/include/Game/Systems/PlayerDeathSystem.h b/include/Game/Systems/PlayerDeathSystem.h index 7d989dbf..988dad57 100644 --- a/include/Game/Systems/PlayerDeathSystem.h +++ b/include/Game/Systems/PlayerDeathSystem.h @@ -22,5 +22,8 @@ public: private: EventRelay m_OnPlayerDeath; bool OnPlayerDeath(Events::PlayerDeath& e); + + void createDeathEffect(EntityWrapper player); + }; #endif \ No newline at end of file diff --git a/include/Game/Systems/PlayerSpawnSystem.h b/include/Game/Systems/PlayerSpawnSystem.h index b0ff1d79..f5aa7b82 100644 --- a/include/Game/Systems/PlayerSpawnSystem.h +++ b/include/Game/Systems/PlayerSpawnSystem.h @@ -3,6 +3,7 @@ #include "Systems/SpawnerSystem.h" #include "Events/ESpawnerSpawn.h" #include "Core/EPlayerSpawned.h" +#include "Core/EPlayerDeath.h" #include "Rendering/ESetCamera.h" #include "Core/ConfigFile.h" diff --git a/resources/Schema/Entities/PlayerDeathExplosionWithCamera.xml b/resources/Schema/Entities/PlayerDeathExplosionWithCamera.xml index ff33476d..8a9f5e5b 100644 --- a/resources/Schema/Entities/PlayerDeathExplosionWithCamera.xml +++ b/resources/Schema/Entities/PlayerDeathExplosionWithCamera.xml @@ -4,17 +4,18 @@ Hold Pos - - 0 - 4 + 2.5 - 0 - 4 - - + true + + + true + 3 + + true Models/AssaultAnimated.mesh @@ -22,24 +23,17 @@ true - + - - 1 - - - 120 - 0.1 - 10000 - + - - + + diff --git a/src/Game/Systems/PlayerDeathSystem.cpp b/src/Game/Systems/PlayerDeathSystem.cpp index f7fe1ab5..60c31ce5 100644 --- a/src/Game/Systems/PlayerDeathSystem.cpp +++ b/src/Game/Systems/PlayerDeathSystem.cpp @@ -11,18 +11,31 @@ void PlayerDeathSystem::Update(double dt) } bool PlayerDeathSystem::OnPlayerDeath(Events::PlayerDeath& e) +{ + if (!e.Player.Valid()) { + return false; + } + + createDeathEffect(e.Player); + + // Delete player + m_World->DeleteEntity(e.Player.ID); + + return true; +} + +void PlayerDeathSystem::createDeathEffect(EntityWrapper player) { //load the explosioneffect XML auto deathEffect = ResourceManager::Load("Schema/Entities/PlayerDeathExplosionWithCamera.xml"); - EntityFileParser parser(deathEffect); EntityID deathEffectID = parser.MergeEntities(m_World); EntityWrapper deathEffectEW = EntityWrapper(m_World, deathEffectID); //components that we need from player - auto playerCamera = e.Player.FirstChildByName("Camera"); - auto playerEntityModel = e.Player.FirstChildByName("PlayerModel")["Model"]; - auto playerEntityAnimation = e.Player.FirstChildByName("PlayerModel")["Animation"]; + auto playerCamera = player.FirstChildByName("Camera"); + auto playerEntityModel = player.FirstChildByName("PlayerModel")["Model"]; + auto playerEntityAnimation = player.FirstChildByName("PlayerModel")["Animation"]; //copy the data from player to explisioneffectmodel playerEntityModel.Copy(deathEffectEW["Model"]); @@ -31,20 +44,14 @@ bool PlayerDeathSystem::OnPlayerDeath(Events::PlayerDeath& e) deathEffectEW["Animation"]["Speed"] = 0.0; //copy the models position,orientation - deathEffectEW["Transform"]["Position"] = (glm::vec3)e.Player["Transform"]["Position"]; - deathEffectEW["Transform"]["Orientation"] = (glm::vec3)e.Player["Transform"]["Orientation"]; + deathEffectEW["Transform"]["Position"] = (glm::vec3)player["Transform"]["Position"]; + deathEffectEW["Transform"]["Orientation"] = (glm::vec3)player["Transform"]["Orientation"]; //effect,camera is relative to playersPosition - deathEffectEW["ExplosionEffect"]["ExplosionOrigin"] = glm::vec3(0, 0, 0); + //deathEffectEW["ExplosionEffect"]["ExplosionOrigin"] = glm::vec3(0, 0, 0); //camera (with lifetime) behind the player auto cam = deathEffectEW.FirstChildByName("Camera"); - cam["Transform"]["Position"] = glm::vec3(0, 2.5f, 1.8f); - cam["Transform"]["Orientation"] = glm::vec3(5.655f, 0, 0); Events::SetCamera eSetCamera; eSetCamera.CameraEntity = cam; m_EventBroker->Publish(eSetCamera); - - //done -> del entity - m_World->DeleteEntity(e.Player.ID); - return true; } diff --git a/src/Game/Systems/PlayerSpawnSystem.cpp b/src/Game/Systems/PlayerSpawnSystem.cpp index 7db6e8ff..5f46cce3 100644 --- a/src/Game/Systems/PlayerSpawnSystem.cpp +++ b/src/Game/Systems/PlayerSpawnSystem.cpp @@ -75,7 +75,9 @@ bool PlayerSpawnSystem::OnPlayerSpawned(Events::PlayerSpawned& e) // Check if a player already exists if (m_PlayerEntities.count(e.PlayerID) != 0) { // TODO: Disallow infinite respawning here - m_World->DeleteEntity(m_PlayerEntities[e.PlayerID].ID); + if (m_PlayerEntities[e.PlayerID].Valid()) { + m_World->DeleteEntity(m_PlayerEntities[e.PlayerID].ID); + } } // Store the player for future reference From 94b59af973e0ad7551e8c5b092825d5b1c766724 Mon Sep 17 00:00:00 2001 From: Tleety Date: Mon, 8 Feb 2016 11:47:35 +0100 Subject: [PATCH 108/355] Defender shield should now be working --- .../Rendering/DrawColorCorrectionPass.h | 2 +- include/Engine/Rendering/DrawFinalPass.h | 6 + .../Shaders/DrawColorCorrection.frag.glsl | 13 ++- resources/Shaders/FillDepthBuffer.frag.glsl | 11 ++ resources/Shaders/FillDepthBuffer.vert.glsl | 21 ++++ resources/Shaders/ShieldStencil.frag.glsl | 2 +- .../Rendering/DrawColorCorrectionPass.cpp | 8 +- src/Engine/Rendering/DrawFinalPass.cpp | 105 +++++++++++++++--- src/Engine/Rendering/Renderer.cpp | 2 +- 9 files changed, 145 insertions(+), 25 deletions(-) create mode 100644 resources/Shaders/FillDepthBuffer.frag.glsl create mode 100644 resources/Shaders/FillDepthBuffer.vert.glsl diff --git a/include/Engine/Rendering/DrawColorCorrectionPass.h b/include/Engine/Rendering/DrawColorCorrectionPass.h index fcde73d7..231e2d33 100644 --- a/include/Engine/Rendering/DrawColorCorrectionPass.h +++ b/include/Engine/Rendering/DrawColorCorrectionPass.h @@ -17,7 +17,7 @@ public: void InitializeFrameBuffers(); void InitializeShaderPrograms(); - void Draw(GLuint sceneTexture, GLuint bloomTexture, GLfloat gamma, GLfloat exposure); + void Draw(GLuint sceneTexture, GLuint bloomTexture, GLuint sceneTextureLowRes, GLuint bloomTextureLowRes, GLfloat gamma, GLfloat exposure); private: const IRenderer* m_Renderer; diff --git a/include/Engine/Rendering/DrawFinalPass.h b/include/Engine/Rendering/DrawFinalPass.h index bacc7a8c..28ac958c 100644 --- a/include/Engine/Rendering/DrawFinalPass.h +++ b/include/Engine/Rendering/DrawFinalPass.h @@ -38,6 +38,7 @@ private: void DrawModelRenderQueues(std::list>& jobs, RenderScene& scene); void DrawShieldToStencilBuffer(std::list>& jobs, RenderScene& scene); void DrawShieldedModelRenderQueue(std::list>& jobs, RenderScene& scene); + void DrawToDepthBuffer(std::list>& jobs, RenderScene& scene); void BindExplosionUniforms(GLuint shaderHandle, std::shared_ptr& job, RenderScene& scene); void BindModelUniforms(GLuint shaderHandle, std::shared_ptr& job, RenderScene& scene); @@ -57,6 +58,10 @@ private: GLuint m_BloomTextureLowRes; GLuint m_SceneTextureLowRes; GLuint m_DepthBuffer; + GLuint m_DepthBufferLowRes; + + //maqke this component based i guess? + GLuint m_ShieldPixelRate = 16; const IRenderer* m_Renderer; const LightCullingPass* m_LightCullingPass; @@ -64,6 +69,7 @@ private: ShaderProgram* m_ForwardPlusProgram; ShaderProgram* m_ExplosionEffectProgram; ShaderProgram* m_ShieldToStencilProgram; + ShaderProgram* m_FillDepthBufferProgram; }; #endif \ No newline at end of file diff --git a/resources/Shaders/DrawColorCorrection.frag.glsl b/resources/Shaders/DrawColorCorrection.frag.glsl index 91ace0c7..76db3e82 100644 --- a/resources/Shaders/DrawColorCorrection.frag.glsl +++ b/resources/Shaders/DrawColorCorrection.frag.glsl @@ -2,6 +2,8 @@ layout (binding = 0) uniform sampler2D SceneTexture; layout (binding = 1) uniform sampler2D BloomTexture; +layout (binding = 2) uniform sampler2D SceneTextureLowRes; +layout (binding = 3) uniform sampler2D BloomTextureLowRes; uniform float Exposure; uniform float Gamma; @@ -15,10 +17,19 @@ void main() { vec4 hdrColor = texture(SceneTexture, Input.TextureCoordinate); vec4 bloomColor = texture(BloomTexture, Input.TextureCoordinate); + vec4 hdrColorLowRes = texture(SceneTextureLowRes, Input.TextureCoordinate); + vec4 bloomColorLowRes = texture(BloomTextureLowRes, Input.TextureCoordinate); hdrColor += bloomColor; + hdrColorLowRes; + float hdrColorsum = hdrColorLowRes.r + hdrColorLowRes.g + hdrColorLowRes.b; //Toon mapping thingy - vec3 result = vec3(1.0) - exp(-hdrColor.rgb * Exposure); + vec3 result; + if(hdrColorsum > 0.0) { + result = vec3(1.0) - exp(-hdrColorLowRes.rgb * Exposure); + } else { + result = vec3(1.0) - exp(-hdrColor.rgb * Exposure); + } //gamme correction result = pow(result, vec3(1.0 / Gamma)); diff --git a/resources/Shaders/FillDepthBuffer.frag.glsl b/resources/Shaders/FillDepthBuffer.frag.glsl new file mode 100644 index 00000000..a125fc25 --- /dev/null +++ b/resources/Shaders/FillDepthBuffer.frag.glsl @@ -0,0 +1,11 @@ +#version 430 + +in VertexData{ + vec3 Position; +}Input; + +void main() +{ +} + + diff --git a/resources/Shaders/FillDepthBuffer.vert.glsl b/resources/Shaders/FillDepthBuffer.vert.glsl new file mode 100644 index 00000000..ff849790 --- /dev/null +++ b/resources/Shaders/FillDepthBuffer.vert.glsl @@ -0,0 +1,21 @@ +#version 430 + +uniform mat4 M; +uniform mat4 V; +uniform mat4 P; + +layout(location = 0) in vec3 Position; +layout(location = 5) in vec4 BoneIndices; +layout(location = 6) in vec4 BoneWeights; + + +out VertexData{ + vec3 Position; +}Output; + +void main() +{ + gl_Position = P * V * M * vec4(Position, 1.0); + + Output.Position = Position; +} \ No newline at end of file diff --git a/resources/Shaders/ShieldStencil.frag.glsl b/resources/Shaders/ShieldStencil.frag.glsl index bc114fc9..db88ab24 100644 --- a/resources/Shaders/ShieldStencil.frag.glsl +++ b/resources/Shaders/ShieldStencil.frag.glsl @@ -9,7 +9,7 @@ out vec4 fragmentColor; void main() { - fragmentColor = vec4(0.5, 0.5, 0.5, 0.2); + fragmentColor = vec4(0.5, 0.0, 0.0, 0.0); } diff --git a/src/Engine/Rendering/DrawColorCorrectionPass.cpp b/src/Engine/Rendering/DrawColorCorrectionPass.cpp index 45401bce..bc2c9783 100644 --- a/src/Engine/Rendering/DrawColorCorrectionPass.cpp +++ b/src/Engine/Rendering/DrawColorCorrectionPass.cpp @@ -6,8 +6,6 @@ DrawColorCorrectionPass::DrawColorCorrectionPass(IRenderer* renderer) m_ScreenQuad = ResourceManager::Load("Models/Core/ScreenQuad.mesh"); - //m_Exposure = 0.4; //TODO: Renderer: Fixa så att denna går att ändra på genom komponent eller setting. - InitializeShaderPrograms(); } @@ -20,7 +18,7 @@ void DrawColorCorrectionPass::InitializeShaderPrograms() m_ColorCorrectionProgram->Link(); } -void DrawColorCorrectionPass::Draw(GLuint sceneTexture, GLuint bloomTexture, GLfloat gamma, GLfloat exposure) +void DrawColorCorrectionPass::Draw(GLuint sceneTexture, GLuint bloomTexture, GLuint sceneTextureLowRes, GLuint bloomTextureLowRes, GLfloat gamma, GLfloat exposure) { //glBindFramebuffer(GL_FRAMEBUFFER, 0); GLERROR("DrawScreenQuadPass::Draw: Pre"); @@ -35,6 +33,10 @@ void DrawColorCorrectionPass::Draw(GLuint sceneTexture, GLuint bloomTexture, GLf glBindTexture(GL_TEXTURE_2D, sceneTexture); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, bloomTexture); + glActiveTexture(GL_TEXTURE2); + glBindTexture(GL_TEXTURE_2D, sceneTextureLowRes); + glActiveTexture(GL_TEXTURE3); + glBindTexture(GL_TEXTURE_2D, bloomTextureLowRes); glBindVertexArray(m_ScreenQuad->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index 0a5c626b..57eecd1a 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -2,8 +2,10 @@ DrawFinalPass::DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCullingPass) { + //TODO: Make sure that uniforms are not sent into shader if not needed. m_Renderer = renderer; m_LightCullingPass = lightCullingPass; + m_ShieldPixelRate = 8; InitializeTextures(); InitializeShaderPrograms(); InitializeFrameBuffers(); @@ -37,13 +39,18 @@ void DrawFinalPass::InitializeFrameBuffers() m_FinalPassFrameBuffer.Generate(); GLERROR("FBO generation"); - GenerateTexture(&m_SceneTextureLowRes, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width/16, m_Renderer->GetViewportSize().Height/16), GL_RGB16F, GL_RGB, GL_FLOAT); + glGenRenderbuffers(1, &m_DepthBufferLowRes); + glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBufferLowRes); + glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, (int)(m_Renderer->GetViewportSize().Width/m_ShieldPixelRate), (int)(m_Renderer->GetViewportSize().Height/m_ShieldPixelRate)); + GLERROR("RenderBufferLowRes generation"); + + GenerateTexture(&m_SceneTextureLowRes, GL_CLAMP_TO_EDGE, GL_NEAREST, glm::vec2((int)(m_Renderer->GetViewportSize().Width/m_ShieldPixelRate), (int)(m_Renderer->GetViewportSize().Height/m_ShieldPixelRate)), 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); - GenerateTexture(&m_BloomTextureLowRes, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width/16, m_Renderer->GetViewportSize().Height/16), GL_RGB16F, GL_RGB, GL_FLOAT); + GenerateTexture(&m_BloomTextureLowRes, GL_CLAMP_TO_EDGE, GL_NEAREST, glm::vec2((int)(m_Renderer->GetViewportSize().Width/m_ShieldPixelRate), (int)(m_Renderer->GetViewportSize().Height/m_ShieldPixelRate)), 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); - m_FinalPassFrameBufferLowRes.AddResource(std::shared_ptr(new RenderBuffer(&m_DepthBuffer, GL_DEPTH_STENCIL_ATTACHMENT))); + m_FinalPassFrameBufferLowRes.AddResource(std::shared_ptr(new RenderBuffer(&m_DepthBufferLowRes, GL_DEPTH_STENCIL_ATTACHMENT))); //m_FinalPassFrameBufferLowRes.AddResource(std::shared_ptr(new Texture2D(&m_StencilTexture, GL_STENCIL_ATTACHMENT))); m_FinalPassFrameBufferLowRes.AddResource(std::shared_ptr(new Texture2D(&m_SceneTextureLowRes, GL_COLOR_ATTACHMENT0))); m_FinalPassFrameBufferLowRes.AddResource(std::shared_ptr(new Texture2D(&m_BloomTextureLowRes, GL_COLOR_ATTACHMENT1))); @@ -79,6 +86,12 @@ void DrawFinalPass::InitializeShaderPrograms() m_ShieldToStencilProgram->Link(); GLERROR("Creating Shield program"); + m_FillDepthBufferProgram = ResourceManager::Load("#FillDepthBufferProgram"); + m_FillDepthBufferProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/FillDepthBuffer.vert.glsl"))); + m_FillDepthBufferProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/FillDepthBuffer.frag.glsl"))); + m_FillDepthBufferProgram->Compile(); + m_FillDepthBufferProgram->Link(); + GLERROR("Creating DepthFill program"); } void DrawFinalPass::Draw(RenderScene& scene) @@ -122,36 +135,59 @@ void DrawFinalPass::Draw(RenderScene& scene) DrawFinalPassState* stateLowRes = new DrawFinalPassState(m_FinalPassFrameBufferLowRes.GetHandle()); //Draw the lowres texture that will be shown behind the shield. - if (scene.ClearDepth) { - glClear(GL_DEPTH_BUFFER_BIT); - } - //TODO: Do we need check for this or will it be per scene always? - //glClearStencil(0x00); - //glClear(GL_STENCIL_BUFFER_BIT); + state->Enable(GL_SCISSOR_TEST); + state->Enable(GL_DEPTH_TEST); + //TODO: Viewports and scissor should be in state + glViewport(0, 0, m_Renderer->GetViewportSize().Width/m_ShieldPixelRate, m_Renderer->GetViewportSize().Height/m_ShieldPixelRate); + glScissor(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); - //state->StencilMask(0x00); - //state->StencilFunc(GL_ALWAYS, 1, 0xFF); - state->Disable(GL_STENCIL_TEST); - state->Disable(GL_DEPTH_TEST); + glClearStencil(0x00); + glClear(GL_STENCIL_BUFFER_BIT); + + //TODO: This should not be here... + state->StencilFunc(GL_ALWAYS, 1, 0xFF); + state->StencilMask(0x00); + DrawToDepthBuffer(scene.Jobs.OpaqueObjects, scene); + DrawToDepthBuffer(scene.Jobs.TransparentObjects, scene); + + //Draw shields to stencil pass + state->StencilFunc(GL_ALWAYS, 1, 0xFF); + state->StencilMask(0xFF); + state->Enable(GL_DEPTH_TEST); + DrawShieldToStencilBuffer(scene.Jobs.ShieldObjects, scene); + GLERROR("StencilPass"); + + glClear(GL_DEPTH_BUFFER_BIT); + + state->Enable(GL_DEPTH_TEST); + state->StencilFunc(GL_LEQUAL, 1, 0xFF); + state->StencilMask(0x00); DrawModelRenderQueues(scene.Jobs.OpaqueObjects, scene); GLERROR("OpaqueObjects"); DrawModelRenderQueues(scene.Jobs.TransparentObjects, scene); GLERROR("TransparentObjects"); + glViewport(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); + glScissor(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); delete stateLowRes; } void DrawFinalPass::ClearBuffer() { + m_FinalPassFrameBufferLowRes.Bind(); + glViewport(0, 0, m_Renderer->GetViewportSize().Width/m_ShieldPixelRate, m_Renderer->GetViewportSize().Height/m_ShieldPixelRate); + glScissor(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); + glClearColor(0.f, 0.f, 0.f, 0.f); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + glDisable(GL_SCISSOR_TEST); + m_FinalPassFrameBufferLowRes.Unbind(); + m_FinalPassFrameBuffer.Bind(); + glViewport(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); + glScissor(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); glClearColor(0.f, 0.f, 0.f, 0.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_FinalPassFrameBuffer.Unbind(); - - m_FinalPassFrameBufferLowRes.Bind(); - glClearColor(0.f, 0.f, 0.f, 0.f); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - m_FinalPassFrameBufferLowRes.Unbind(); } void DrawFinalPass::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const @@ -385,6 +421,39 @@ void DrawFinalPass::DrawShieldedModelRenderQueue(std::list>& jobs, RenderScene& scene) +{ + m_FillDepthBufferProgram->Bind(); + GLuint shaderHandle = m_FillDepthBufferProgram->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())); + + for (auto &job : jobs) { + auto modelJob = std::dynamic_pointer_cast(job); + + //bind uniforms + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); + + if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { + + if (modelJob->Animation != nullptr) { + std::vector frameBones = modelJob->Skeleton->GetFrameBones(*modelJob->Animation, modelJob->AnimationTime); + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + } + } + + //draw + glBindVertexArray(modelJob->Model->VAO); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer); + glDrawElements(GL_TRIANGLES, modelJob->EndIndex - modelJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(modelJob->StartIndex*sizeof(unsigned int))); + if (GLERROR("models end")) { + continue; + } + } + +} + void DrawFinalPass::BindExplosionUniforms(GLuint shaderHandle, std::shared_ptr& job, RenderScene& scene) { glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(job->Matrix)); diff --git a/src/Engine/Rendering/Renderer.cpp b/src/Engine/Rendering/Renderer.cpp index 15554ab1..8530b291 100644 --- a/src/Engine/Rendering/Renderer.cpp +++ b/src/Engine/Rendering/Renderer.cpp @@ -120,7 +120,7 @@ void Renderer::Draw(RenderFrame& frame) } m_DrawBloomPass->Draw(m_DrawFinalPass->BloomTexture()); if (m_DebugTextureToDraw == 0) { - m_DrawColorCorrectionPass->Draw(m_DrawFinalPass->SceneTexture(), m_DrawBloomPass->GaussianTexture(), frame.Gamma, frame.Exposure); + m_DrawColorCorrectionPass->Draw(m_DrawFinalPass->SceneTexture(), m_DrawBloomPass->GaussianTexture(), m_DrawFinalPass->SceneTextureLowRes(), m_DrawFinalPass->BloomTextureLowRes(), frame.Gamma, frame.Exposure); } if (m_DebugTextureToDraw == 1) { m_DrawScreenQuadPass->Draw(m_DrawFinalPass->SceneTexture()); From 2ee21e05d48eba278eeb3e4c905044b4fa2668f7 Mon Sep 17 00:00:00 2001 From: Tleety Date: Mon, 8 Feb 2016 12:29:41 +0100 Subject: [PATCH 109/355] Fixed so that Shielded objects can be picked. Shield objects can not however, so they will not be able to be picked in editor either. --- src/Engine/Rendering/PickingPass.cpp | 92 ++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) diff --git a/src/Engine/Rendering/PickingPass.cpp b/src/Engine/Rendering/PickingPass.cpp index 3baf2b2a..b0733ae2 100644 --- a/src/Engine/Rendering/PickingPass.cpp +++ b/src/Engine/Rendering/PickingPass.cpp @@ -147,6 +147,98 @@ void PickingPass::Draw(RenderScene& scene) glDrawElements(GL_TRIANGLES, modelJob->EndIndex - modelJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(modelJob->StartIndex * sizeof(unsigned int))); } } + + for (auto &job : scene.Jobs.OpaqueShieldedObjects) { + auto modelJob = std::dynamic_pointer_cast(job); + + if (modelJob) { + int pickColor[2] = { m_ColorCounter[0], m_ColorCounter[1] }; + + PickingInfo pickInfo; + pickInfo.Entity = modelJob->Entity; + pickInfo.World = modelJob->World; + pickInfo.Camera = scene.Camera; + + auto color = m_EntityColors.find(std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)); + if (color != m_EntityColors.end()) { + pickColor[0] = color->second[0]; + pickColor[1] = color->second[1]; + } else { + m_EntityColors[std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)] = glm::ivec2(pickColor[0], pickColor[1]); + if (m_ColorCounter[0] > 255) { + m_ColorCounter[0] = 0; + m_ColorCounter[1] += 1; + } else { + m_ColorCounter[0] += 1; + } + } + + m_PickingColorsToEntity[glm::ivec2(pickColor[0], pickColor[1])] = pickInfo; + + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); + 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())); + glUniform2fv(glGetUniformLocation(shaderHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1]))); + + if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { + + if (modelJob->Animation != nullptr) { + std::vector frameBones = modelJob->Skeleton->GetFrameBones(*modelJob->Animation, modelJob->AnimationTime); + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + } + } + + glBindVertexArray(modelJob->Model->VAO); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer); + glDrawElements(GL_TRIANGLES, modelJob->EndIndex - modelJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(modelJob->StartIndex * sizeof(unsigned int))); + } + } + + for (auto &job : scene.Jobs.TransparentShieldedObjects) { + auto modelJob = std::dynamic_pointer_cast(job); + + if (modelJob) { + int pickColor[2] = { m_ColorCounter[0], m_ColorCounter[1] }; + + PickingInfo pickInfo; + pickInfo.Entity = modelJob->Entity; + pickInfo.World = modelJob->World; + pickInfo.Camera = scene.Camera; + + auto color = m_EntityColors.find(std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)); + if (color != m_EntityColors.end()) { + pickColor[0] = color->second[0]; + pickColor[1] = color->second[1]; + } else { + m_EntityColors[std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)] = glm::ivec2(pickColor[0], pickColor[1]); + if (m_ColorCounter[0] > 255) { + m_ColorCounter[0] = 0; + m_ColorCounter[1] += 1; + } else { + m_ColorCounter[0] += 1; + } + } + + m_PickingColorsToEntity[glm::ivec2(pickColor[0], pickColor[1])] = pickInfo; + + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); + 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())); + glUniform2fv(glGetUniformLocation(shaderHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1]))); + + if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { + + if (modelJob->Animation != nullptr) { + std::vector frameBones = modelJob->Skeleton->GetFrameBones(*modelJob->Animation, modelJob->AnimationTime); + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + } + } + + glBindVertexArray(modelJob->Model->VAO); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer); + glDrawElements(GL_TRIANGLES, modelJob->EndIndex - modelJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(modelJob->StartIndex * sizeof(unsigned int))); + } + } m_PickingBuffer.Unbind(); GLERROR("PickingPass Error"); From d2cfa592f0581c970b93ae2b15c3b8dcc060cf4c Mon Sep 17 00:00:00 2001 From: Teejoon Date: Mon, 8 Feb 2016 13:01:10 +0100 Subject: [PATCH 110/355] Supports skinnd and unskinned meshes ExplosionEffects now supports SplatMapping --- include/Engine/Rendering/DrawFinalPass.h | 9 +- include/Engine/Rendering/ModelJob.h | 12 +- resources/Shaders/ForwardPlus.vert.glsl | 17 +- .../Shaders/ForwardPlusSkinned.vert.glsl | 46 +++ src/Engine/Rendering/DrawFinalPass.cpp | 370 ++++++++++++++---- src/Engine/Rendering/RawModelCustom.cpp | 9 +- tools/MayaExporter/MayaExporter.opensdf | Bin 0 -> 38 bytes tools/MayaExporter/MayaExporter/Mesh.h | 4 +- 8 files changed, 355 insertions(+), 112 deletions(-) create mode 100644 resources/Shaders/ForwardPlusSkinned.vert.glsl create mode 100644 tools/MayaExporter/MayaExporter.opensdf diff --git a/include/Engine/Rendering/DrawFinalPass.h b/include/Engine/Rendering/DrawFinalPass.h index 830ded3c..dd0df84a 100644 --- a/include/Engine/Rendering/DrawFinalPass.h +++ b/include/Engine/Rendering/DrawFinalPass.h @@ -35,7 +35,7 @@ private: void BindExplosionUniforms(GLuint shaderHandle, std::shared_ptr& job, RenderScene& scene); void BindModelUniforms(GLuint shaderHandle, std::shared_ptr& job, RenderScene& scene); - void BindExplosionTextures(std::shared_ptr& job); + void BindExplosionTextures(GLuint shaderHandle, std::shared_ptr& job); void BindModelTextures(GLuint shaderHandle, std::shared_ptr& job); Texture* m_WhiteTexture; @@ -53,7 +53,14 @@ private: ShaderProgram* m_ForwardPlusProgram; ShaderProgram* m_ExplosionEffectProgram; + ShaderProgram* m_ExplosionEffectSplatMapProgram; ShaderProgram* m_ForwardPlusSplatMapProgram; + + + ShaderProgram* m_ForwardPlusSkinnedProgram; + ShaderProgram* m_ExplosionEffectSkinnedProgram; + ShaderProgram* m_ExplosionEffectSplatMapSkinnedProgram; + ShaderProgram* m_ForwardPlusSplatMapSkinnedProgram; }; #endif \ No newline at end of file diff --git a/include/Engine/Rendering/ModelJob.h b/include/Engine/Rendering/ModelJob.h index fe8fe26f..de7db78e 100644 --- a/include/Engine/Rendering/ModelJob.h +++ b/include/Engine/Rendering/ModelJob.h @@ -28,20 +28,20 @@ struct ModelJob : RenderJob switch(matProp.type){ case ::RawModel::MaterialType::Basic: if (Model->isSkined()) { - ShaderID = ResourceManager::Load("#ForwardPlusProgram")->ResourceID; + ShaderID = ResourceManager::Load("#ForwardPlusSkinnedProgram")->ResourceID; } else { - //JOHAN TODO: Add Non-skined shader + ShaderID = ResourceManager::Load("#ForwardPlusProgram")->ResourceID; } TextureID = 0; break; case ::RawModel::MaterialType::SingleTextures: { if (Model->isSkined()) { - ShaderID = ResourceManager::Load("#ForwardPlusProgram")->ResourceID; + ShaderID = ResourceManager::Load("#ForwardPlusSkinnedProgram")->ResourceID; } else { - //JOHAN TODO: Add Non-skined shader + ShaderID = ResourceManager::Load("#ForwardPlusProgram")->ResourceID; } ::RawModel::MaterialSingleTextures* singleTextures = static_cast<::RawModel::MaterialSingleTextures*>(matProp.material); TextureID = (singleTextures->ColorMap.Texture) ? singleTextures->ColorMap.Texture->ResourceID : 0; @@ -65,10 +65,10 @@ struct ModelJob : RenderJob case ::RawModel::MaterialType::SplatMapping: { if (Model->isSkined()) { - ShaderID = ResourceManager::Load("#ForwardPlusSplatMapProgram")->ResourceID; + ShaderID = ResourceManager::Load("#ForwardPlusSplatMapSkinnedProgram")->ResourceID; } else { - //JOHAN TODO: Add Non-skinned shader + ShaderID = ResourceManager::Load("#ForwardPlusSplatMapProgram")->ResourceID; } ::RawModel::MaterialSplatMapping* SplatTextures = static_cast<::RawModel::MaterialSplatMapping*>(matProp.material); diff --git a/resources/Shaders/ForwardPlus.vert.glsl b/resources/Shaders/ForwardPlus.vert.glsl index 3b3e931c..d475d825 100644 --- a/resources/Shaders/ForwardPlus.vert.glsl +++ b/resources/Shaders/ForwardPlus.vert.glsl @@ -3,15 +3,12 @@ uniform mat4 M; uniform mat4 V; uniform mat4 P; -uniform mat4 Bones[100]; layout(location = 0) in vec3 Position; layout(location = 1) in vec3 Normal; layout(location = 2) in vec3 Tangent; layout(location = 3) in vec3 BiTangent; layout(location = 4) in vec2 TextureCoords; -layout(location = 5) in vec4 BoneIndices; -layout(location = 6) in vec4 BoneWeights; out VertexData{ vec3 Position; @@ -25,19 +22,9 @@ out VertexData{ void main() { - - - mat4 boneTransform = mat4(1); - if(BoneWeights[0] > 0.0f){ - boneTransform = BoneWeights[0] * Bones[int(BoneIndices[0])] - + BoneWeights[1] * Bones[int(BoneIndices[1])] - + BoneWeights[2] * Bones[int(BoneIndices[2])] - + BoneWeights[3] * Bones[int(BoneIndices[3])]; - } - - gl_Position = P*V*M*boneTransform * vec4(Position, 1.0); + gl_Position = P*V*M * vec4(Position, 1.0); - Output.Position = (boneTransform * vec4(Position, 1.0)).xyz; + Output.Position = Position; Output.TextureCoordinate = TextureCoords; Output.Normal = vec3(M * vec4(Normal, 0.0)); Output.Tangent = vec3(M * vec4(Tangent, 0.0)); diff --git a/resources/Shaders/ForwardPlusSkinned.vert.glsl b/resources/Shaders/ForwardPlusSkinned.vert.glsl new file mode 100644 index 00000000..3d47b0c4 --- /dev/null +++ b/resources/Shaders/ForwardPlusSkinned.vert.glsl @@ -0,0 +1,46 @@ +#version 430 + +uniform mat4 M; +uniform mat4 V; +uniform mat4 P; +uniform mat4 Bones[100]; + +layout(location = 0) in vec3 Position; +layout(location = 1) in vec3 Normal; +layout(location = 2) in vec3 Tangent; +layout(location = 3) in vec3 BiTangent; +layout(location = 4) in vec2 TextureCoords; +layout(location = 5) in vec4 BoneIndices; +layout(location = 6) in vec4 BoneWeights; + +out VertexData{ + vec3 Position; + vec3 Normal; + vec3 Tangent; + vec3 BiTangent; + vec2 TextureCoordinate; + vec4 ExplosionColor; + float ExplosionPercentageElapsed; +}Output; + +void main() +{ + mat4 boneTransform = mat4(1); + //Remove if(). Shoudln't have to do this scine we know it's skinned and uses bones + if(BoneWeights[0] > 0.0f){ + boneTransform = BoneWeights[0] * Bones[int(BoneIndices[0])] + + BoneWeights[1] * Bones[int(BoneIndices[1])] + + BoneWeights[2] * Bones[int(BoneIndices[2])] + + BoneWeights[3] * Bones[int(BoneIndices[3])]; + } + + gl_Position = P*V*M*boneTransform * vec4(Position, 1.0); + + Output.Position = (boneTransform * vec4(Position, 1.0)).xyz; + Output.TextureCoordinate = TextureCoords; + Output.Normal = vec3(M * vec4(Normal, 0.0)); + Output.Tangent = vec3(M * vec4(Tangent, 0.0)); + Output.BiTangent = vec3(M * vec4(BiTangent, 0.0)); + Output.ExplosionColor = vec4(1.0); + Output.ExplosionPercentageElapsed = 0.0; +} \ No newline at end of file diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index 3c4406fe..c97ab6b5 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -63,7 +63,54 @@ void DrawFinalPass::InitializeShaderPrograms() m_ForwardPlusSplatMapProgram->BindFragDataLocation(0, "sceneColor"); m_ForwardPlusSplatMapProgram->BindFragDataLocation(1, "bloomColor"); m_ForwardPlusSplatMapProgram->Link(); - GLERROR("Creating SplatMap program"); + GLERROR("Creating Forward SplatMap program"); + + m_ExplosionEffectSplatMapProgram = ResourceManager::Load("#ExplosionEffectSplatMapProgram"); + m_ExplosionEffectSplatMapProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ForwardPlus.vert.glsl"))); + m_ExplosionEffectSplatMapProgram->AddShader(std::shared_ptr(new GeometryShader("Shaders/ExplosionEffect.geom.glsl"))); + m_ExplosionEffectSplatMapProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ForwardPlusSplatMap.frag.glsl"))); + m_ExplosionEffectSplatMapProgram->Compile(); + m_ExplosionEffectSplatMapProgram->BindFragDataLocation(0, "sceneColor"); + m_ExplosionEffectSplatMapProgram->BindFragDataLocation(1, "bloomColor"); + m_ExplosionEffectSplatMapProgram->Link(); + GLERROR("Creating explosion SplatMap program"); + + m_ForwardPlusSkinnedProgram = ResourceManager::Load("#ForwardPlusSkinnedProgram"); + m_ForwardPlusSkinnedProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ForwardPlusSkinned.vert.glsl"))); + m_ForwardPlusSkinnedProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ForwardPlus.frag.glsl"))); + m_ForwardPlusSkinnedProgram->Compile(); + m_ForwardPlusSkinnedProgram->BindFragDataLocation(0, "sceneColor"); + m_ForwardPlusSkinnedProgram->BindFragDataLocation(1, "bloomColor"); + m_ForwardPlusSkinnedProgram->Link(); + GLERROR("Creating forward+ Skinned program"); + + m_ExplosionEffectSkinnedProgram = ResourceManager::Load("#ExplosionEffectSkinnedProgram"); + m_ExplosionEffectSkinnedProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ForwardPlusSkinned.vert.glsl"))); + m_ExplosionEffectSkinnedProgram->AddShader(std::shared_ptr(new GeometryShader("Shaders/ExplosionEffect.geom.glsl"))); + m_ExplosionEffectSkinnedProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ForwardPlus.frag.glsl"))); + m_ExplosionEffectSkinnedProgram->Compile(); + m_ExplosionEffectSkinnedProgram->BindFragDataLocation(0, "sceneColor"); + m_ExplosionEffectSkinnedProgram->BindFragDataLocation(1, "bloomColor"); + m_ExplosionEffectSkinnedProgram->Link(); + GLERROR("Creating explosion Skinned program"); + + m_ExplosionEffectSplatMapSkinnedProgram = ResourceManager::Load("#ExplosionEffectSplatMapSkinnedProgram"); + m_ExplosionEffectSplatMapSkinnedProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ForwardPlusSkinned.vert.glsl"))); + m_ExplosionEffectSplatMapSkinnedProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ForwardPlusSplatMap.frag.glsl"))); + m_ExplosionEffectSplatMapSkinnedProgram->Compile(); + m_ExplosionEffectSplatMapSkinnedProgram->BindFragDataLocation(0, "sceneColor"); + m_ExplosionEffectSplatMapSkinnedProgram->BindFragDataLocation(1, "bloomColor"); + m_ExplosionEffectSplatMapSkinnedProgram->Link(); + GLERROR("Creating Forward SplatMap Skinned program"); + + m_ForwardPlusSplatMapSkinnedProgram = ResourceManager::Load("#ForwardPlusSplatMapSkinnedProgram"); + m_ForwardPlusSplatMapSkinnedProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ForwardPlusSkinned.vert.glsl"))); + m_ForwardPlusSplatMapSkinnedProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ForwardPlusSplatMap.frag.glsl"))); + m_ForwardPlusSplatMapSkinnedProgram->Compile(); + m_ForwardPlusSplatMapSkinnedProgram->BindFragDataLocation(0, "sceneColor"); + m_ForwardPlusSplatMapSkinnedProgram->BindFragDataLocation(1, "bloomColor"); + m_ForwardPlusSplatMapSkinnedProgram->Link(); + GLERROR("Creating Forward SplatMap Skinned program"); } void DrawFinalPass::Draw(RenderScene& scene) @@ -125,7 +172,18 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& GLERROR("forwardHandle"); GLuint explosionHandle = m_ExplosionEffectProgram->GetHandle(); GLERROR("explosionHandle"); + GLuint explosionSplatMapHandle = m_ExplosionEffectSplatMapProgram->GetHandle(); + GLERROR("explosionSplatMapHandle"); GLuint forwardSplatHandle = m_ForwardPlusSplatMapProgram->GetHandle(); + GLERROR("forwardSplatHandle"); + GLuint forwardSkinnedHandle = m_ForwardPlusSkinnedProgram->GetHandle(); + GLERROR("forwardSkinnedHandle"); + GLuint explosionSkinnedHandle = m_ExplosionEffectSkinnedProgram->GetHandle(); + GLERROR("explosionSkinnedHandle"); + GLuint explosionSplatMapSkinnedHandle = m_ExplosionEffectSplatMapSkinnedProgram->GetHandle(); + GLERROR("explosionSplatMapSkinnedHandle"); + GLuint forwardSplatMapSkinnedHandle = m_ForwardPlusSplatMapSkinnedProgram->GetHandle(); + GLERROR("forwardSplatSkinnedHandle"); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, m_LightCullingPass->LightSSBO()); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, m_LightCullingPass->LightGridSSBO()); @@ -135,48 +193,68 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& { auto explosionEffectJob = std::dynamic_pointer_cast(job); if(explosionEffectJob) { - //Bind program - if(GLERROR("Prebind")) { - continue; - } - m_ExplosionEffectProgram->Bind(); - if(GLERROR("BindProgram")) { - continue; - } - + switch (explosionEffectJob->Type) { + case RawModel::MaterialType::Basic: + case RawModel::MaterialType::SingleTextures: + { + if (explosionEffectJob->Model->isSkined()) { + m_ExplosionEffectSkinnedProgram->Bind(); + GLERROR("Bind ExplosionEffectSkinned program"); + //bind uniforms + BindExplosionUniforms(explosionSkinnedHandle, explosionEffectJob, scene); + //bind textures + BindExplosionTextures(explosionSkinnedHandle, explosionEffectJob); + if (explosionEffectJob->Animation != nullptr) { + std::vector frameBones = explosionEffectJob->Skeleton->GetFrameBones(*explosionEffectJob->Animation, explosionEffectJob->AnimationTime); + glUniformMatrix4fv(glGetUniformLocation(forwardSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + } + } + else { + m_ExplosionEffectProgram->Bind(); + GLERROR("Bind ExplosionEffect program"); + //bind uniforms + BindExplosionUniforms(explosionHandle, explosionEffectJob, scene); + //bind textures + BindExplosionTextures(explosionHandle, explosionEffectJob); + } + break; + } + case RawModel::MaterialType::SplatMapping: + { + if (explosionEffectJob->Model->isSkined()) { + m_ExplosionEffectSplatMapSkinnedProgram->Bind(); + GLERROR("Bind ExplosionEffectSplatMapSkinned program"); + //bind uniforms + BindExplosionUniforms(explosionSplatMapSkinnedHandle, explosionEffectJob, scene); + //bind textures + BindExplosionTextures(explosionSplatMapSkinnedHandle, explosionEffectJob); + GLERROR("asdasd"); + if (explosionEffectJob->Animation != nullptr) { + std::vector frameBones = explosionEffectJob->Skeleton->GetFrameBones(*explosionEffectJob->Animation, explosionEffectJob->AnimationTime); + glUniformMatrix4fv(glGetUniformLocation(explosionSplatMapSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + } + } + else { + m_ExplosionEffectSplatMapProgram->Bind(); + GLERROR("Bind ExplosionEffectSplatMap program"); + //bind uniforms + //bind uniforms + BindExplosionUniforms(explosionSplatMapHandle, explosionEffectJob, scene); + //bind textures + BindExplosionTextures(explosionSplatMapHandle, explosionEffectJob); + GLERROR("asdasd"); + } + break; + } + } glDisable(GL_CULL_FACE); - //Bind uniforms - BindExplosionUniforms(explosionHandle, explosionEffectJob, scene); - if(GLERROR("BindExplosionUniforms")) { - continue; - } - - if (explosionEffectJob->Model->m_RawModel->m_Skeleton != nullptr) { - - if (explosionEffectJob->Animation != nullptr) { - std::vector frameBones = explosionEffectJob->Skeleton->GetFrameBones(*explosionEffectJob->Animation, explosionEffectJob->AnimationTime); - glUniformMatrix4fv(glGetUniformLocation(explosionHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - } - } - if(GLERROR("Animation")) { - continue; - } - - //bind textures - BindExplosionTextures(explosionEffectJob); - if(GLERROR("BindExplosionTextures")) { - continue; - } //draw glBindVertexArray(explosionEffectJob->Model->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, explosionEffectJob->Model->ElementBuffer); glDrawElements(GL_TRIANGLES, explosionEffectJob->EndIndex - explosionEffectJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(explosionEffectJob->StartIndex*sizeof(unsigned int))); glEnable(GL_CULL_FACE); - if(GLERROR("explosion effect end")) { - continue; - } - + GLERROR("explosion effect end"); } else { auto modelJob = std::dynamic_pointer_cast(job); if (modelJob) { @@ -186,38 +264,54 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& case RawModel::MaterialType::Basic: case RawModel::MaterialType::SingleTextures: { - m_ForwardPlusProgram->Bind(); - GLERROR("Bind Forward program"); - //bind uniforms - BindModelUniforms(forwardHandle, modelJob, scene); - //bind textures - BindModelTextures(forwardHandle, modelJob); - GLERROR("asdasd"); - + if (modelJob->Model->isSkined()) { + m_ForwardPlusSkinnedProgram->Bind(); + GLERROR("Bind ForwardPlusSkinnedProgram"); + //bind uniforms + BindModelUniforms(forwardSkinnedHandle, modelJob, scene); + //bind textures + BindModelTextures(forwardSkinnedHandle, modelJob); + if (modelJob->Animation != nullptr) { + std::vector frameBones = modelJob->Skeleton->GetFrameBones(*modelJob->Animation, modelJob->AnimationTime); + glUniformMatrix4fv(glGetUniformLocation(forwardSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + } + } else { + m_ForwardPlusProgram->Bind(); + GLERROR("Bind ForwardPlusProgram"); + //bind uniforms + BindModelUniforms(forwardHandle, modelJob, scene); + //bind textures + BindModelTextures(forwardHandle, modelJob); + } break; } case RawModel::MaterialType::SplatMapping: { - m_ForwardPlusSplatMapProgram->Bind(); - GLERROR("Bind SplatMap program"); - //bind uniforms - BindModelUniforms(forwardSplatHandle, modelJob, scene); - //bind textures - BindModelTextures(forwardSplatHandle, modelJob); - GLERROR("asdasd"); - + if (modelJob->Model->isSkined()) { + m_ForwardPlusSplatMapSkinnedProgram->Bind(); + GLERROR("Bind SplatMap program"); + //bind uniforms + BindModelUniforms(forwardSplatMapSkinnedHandle, modelJob, scene); + //bind textures + BindModelTextures(forwardSplatMapSkinnedHandle, modelJob); + GLERROR("asdasd"); + if (modelJob->Animation != nullptr) { + std::vector frameBones = modelJob->Skeleton->GetFrameBones(*modelJob->Animation, modelJob->AnimationTime); + glUniformMatrix4fv(glGetUniformLocation(forwardSplatMapSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + } + } else { + m_ForwardPlusSplatMapProgram->Bind(); + GLERROR("Bind SplatMap program"); + //bind uniforms + BindModelUniforms(forwardSplatHandle, modelJob, scene); + //bind textures + BindModelTextures(forwardSplatHandle, modelJob); + GLERROR("asdasd"); + } break; } } - if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { - - if (modelJob->Animation != nullptr) { - std::vector frameBones = modelJob->Skeleton->GetFrameBones(*modelJob->Animation, modelJob->AnimationTime); - glUniformMatrix4fv(glGetUniformLocation(forwardHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - } - } - //draw glBindVertexArray(modelJob->Model->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer); @@ -233,27 +327,46 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& void DrawFinalPass::BindExplosionUniforms(GLuint shaderHandle, std::shared_ptr& job, RenderScene& scene) { + GLERROR("Bind 1 uniform"); glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(job->Matrix)); + GLERROR("Bind 2 uniform"); glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "V"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix())); + GLERROR("Bind 3 uniform"); glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix())); + GLERROR("Bind 4 uniform"); glUniform2f(glGetUniformLocation(shaderHandle, "ScreenDimensions"), m_Renderer->Resolution().Width, m_Renderer->Resolution().Height); + GLERROR("Bind 5 uniform"); glUniform3fv(glGetUniformLocation(shaderHandle, "ExplosionOrigin"), 1, glm::value_ptr(job->ExplosionOrigin)); + GLERROR("Bind 6 uniform"); glUniform1f(glGetUniformLocation(shaderHandle, "TimeSinceDeath"), job->TimeSinceDeath); + GLERROR("Bind 7 uniform"); glUniform1f(glGetUniformLocation(shaderHandle, "ExplosionDuration"), job->ExplosionDuration); + GLERROR("Bind 8 uniform"); glUniform4fv(glGetUniformLocation(shaderHandle, "EndColor"), 1, glm::value_ptr(job->EndColor)); + GLERROR("Bind 9 uniform"); glUniform1i(glGetUniformLocation(shaderHandle, "Randomness"), job->Randomness); + GLERROR("Bind 10 uniform"); glUniform1fv(glGetUniformLocation(shaderHandle, "RandomNumbers"), 50, job->RandomNumbers.data()); + GLERROR("Bind 11 uniform"); glUniform1f(glGetUniformLocation(shaderHandle, "RandomnessScalar"), job->RandomnessScalar); + GLERROR("Bind 12 uniform"); glUniform2fv(glGetUniformLocation(shaderHandle, "Velocity"), 1, glm::value_ptr(job->Velocity)); + GLERROR("Bind 13 uniform"); glUniform1i(glGetUniformLocation(shaderHandle, "ColorByDistance"), job->ColorByDistance); + GLERROR("Bind 14 uniform"); glUniform1i(glGetUniformLocation(shaderHandle, "ExponentialAccelaration"), job->ExponentialAccelaration); + GLERROR("Bind 15 uniform"); glUniform4fv(glGetUniformLocation(shaderHandle, "Color"), 1, glm::value_ptr(job->Color)); + GLERROR("Bind 16 uniform"); glUniform4fv(glGetUniformLocation(shaderHandle, "DiffuseColor"), 1, glm::value_ptr(job->DiffuseColor)); + GLERROR("Bind 17 uniform"); glUniform4fv(glGetUniformLocation(shaderHandle, "FillColor"), 1, glm::value_ptr(job->FillColor)); + GLERROR("Bind 18 uniform"); glUniform1f(glGetUniformLocation(shaderHandle, "FillPercentage"), job->FillPercentage); + GLERROR("Bind 19 uniform"); glUniform4fv(glGetUniformLocation(shaderHandle, "AmbientColor"), 1, glm::value_ptr(scene.AmbientColor)); GLERROR("END"); } @@ -293,35 +406,122 @@ void DrawFinalPass::BindModelUniforms(GLuint shaderHandle, std::shared_ptr& job) +void DrawFinalPass::BindExplosionTextures(GLuint shaderHandle, std::shared_ptr& job) { - glActiveTexture(GL_TEXTURE0); - if (job->DiffuseTexture.size() > 0 && job->DiffuseTexture[0]->Texture != nullptr) { - glBindTexture(GL_TEXTURE_2D, job->DiffuseTexture[0]->Texture->m_Texture); //JOHAN TODO: support multiple diffuse Textures - } else { - glBindTexture(GL_TEXTURE_2D, m_WhiteTexture->m_Texture); - } + switch (job->Type) { + case RawModel::MaterialType::SingleTextures: + case RawModel::MaterialType::Basic: + { + glActiveTexture(GL_TEXTURE0); + if (job->DiffuseTexture.size() > 0 && job->DiffuseTexture[0]->Texture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->DiffuseTexture[0]->Texture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, "DiffuseUVRepeat"), 1, glm::value_ptr(job->DiffuseTexture[0]->UVRepeat)); + } + else { + glBindTexture(GL_TEXTURE_2D, m_WhiteTexture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, "DiffuseUVRepeat"), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f))); + } - glActiveTexture(GL_TEXTURE1); - if (job->NormalTexture.size() > 0 && job->NormalTexture[0]->Texture != nullptr) { - glBindTexture(GL_TEXTURE_2D, job->NormalTexture[0]->Texture->m_Texture); //JOHAN TODO: support multiple diffuse Textures - } else { - glBindTexture(GL_TEXTURE_2D, m_NeutralNormalTexture->m_Texture); - } + glActiveTexture(GL_TEXTURE1); + if (job->NormalTexture.size() > 0 && job->NormalTexture[0]->Texture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->NormalTexture[0]->Texture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, "NormalUVRepeat"), 1, glm::value_ptr(job->NormalTexture[0]->UVRepeat)); + } + else { + glBindTexture(GL_TEXTURE_2D, m_NeutralNormalTexture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, "NormalUVRepeat"), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f))); + } - glActiveTexture(GL_TEXTURE2); - if (job->SpecularTexture.size() > 0 && job->SpecularTexture[0]->Texture != nullptr) { - glBindTexture(GL_TEXTURE_2D, job->SpecularTexture[0]->Texture->m_Texture); //JOHAN TODO: support multiple diffuse Textures - } else { - glBindTexture(GL_TEXTURE_2D, m_GreyTexture->m_Texture); - } + glActiveTexture(GL_TEXTURE2); + if (job->SpecularTexture.size() > 0 && job->SpecularTexture[0]->Texture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->SpecularTexture[0]->Texture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, "SpecularUVRepeat"), 1, glm::value_ptr(job->SpecularTexture[0]->UVRepeat)); + } + else { + glBindTexture(GL_TEXTURE_2D, m_GreyTexture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, "SpecularUVRepeat"), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f))); + } - glActiveTexture(GL_TEXTURE3); - if (job->IncandescenceTexture.size() > 0 && job->IncandescenceTexture[0]->Texture != nullptr) { - glBindTexture(GL_TEXTURE_2D, job->IncandescenceTexture[0]->Texture->m_Texture); //JOHAN TODO: support multiple diffuse Textures - } else { - glBindTexture(GL_TEXTURE_2D, m_BlackTexture->m_Texture); - } + glActiveTexture(GL_TEXTURE3); + if (job->IncandescenceTexture.size() > 0 && job->IncandescenceTexture[0]->Texture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->IncandescenceTexture[0]->Texture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, "GlowUVRepeat"), 1, glm::value_ptr(job->IncandescenceTexture[0]->UVRepeat)); + } + else { + glBindTexture(GL_TEXTURE_2D, m_BlackTexture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, "GlowUVRepeat"), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f))); + } + break; + } + case RawModel::MaterialType::SplatMapping: + { + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, job->SplatMap->Texture->m_Texture); + + int texturePosition = GL_TEXTURE1; + + //Bind 5 diffuse textures + std::string UniformName = "DiffuseUVRepeat"; + for (unsigned int i = 0; i < 5; i++) { + glActiveTexture(texturePosition); + if (job->DiffuseTexture.size() > i && job->DiffuseTexture[i]->Texture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->DiffuseTexture[i]->Texture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(job->DiffuseTexture[i]->UVRepeat)); + } + else { + glBindTexture(GL_TEXTURE_2D, m_WhiteTexture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f))); + } + texturePosition++; + } + + //Bind 5 Normal textures + UniformName = "NormalUVRepeat"; + for (unsigned int i = 0; i < 5; i++) { + glActiveTexture(texturePosition); + if (job->NormalTexture.size() > i && job->NormalTexture[i]->Texture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->NormalTexture[i]->Texture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(job->NormalTexture[i]->UVRepeat)); + } + else { + glBindTexture(GL_TEXTURE_2D, m_NeutralNormalTexture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f))); + } + texturePosition++; + } + + //Bind 5 Specular textures + UniformName = "SpecularUVRepeat"; + for (unsigned int i = 0; i < 5; i++) { + glActiveTexture(texturePosition); + if (job->SpecularTexture.size() > i && job->SpecularTexture[i]->Texture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->SpecularTexture[i]->Texture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(job->SpecularTexture[i]->UVRepeat)); + } + else { + glBindTexture(GL_TEXTURE_2D, m_GreyTexture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f))); + } + texturePosition++; + } + + //Bind 5 Incandescence textures + UniformName = "GlowUVRepeat"; + for (unsigned int i = 0; i < 5; i++) { + glActiveTexture(texturePosition); + if (job->IncandescenceTexture.size() > i && job->IncandescenceTexture[i]->Texture != nullptr) { + glBindTexture(GL_TEXTURE_2D, job->IncandescenceTexture[i]->Texture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(job->IncandescenceTexture[i]->UVRepeat)); + } + else { + glBindTexture(GL_TEXTURE_2D, m_BlackTexture->m_Texture); + glUniform2fv(glGetUniformLocation(shaderHandle, std::string(UniformName + ((char)(i + '1'))).c_str()), 1, glm::value_ptr(glm::vec2(1.0f, 1.0f))); + } + texturePosition++; + } + break; + } + } } void DrawFinalPass::BindModelTextures(GLuint shaderHandle, std::shared_ptr& job) diff --git a/src/Engine/Rendering/RawModelCustom.cpp b/src/Engine/Rendering/RawModelCustom.cpp index 00ae0e33..69175a45 100644 --- a/src/Engine/Rendering/RawModelCustom.cpp +++ b/src/Engine/Rendering/RawModelCustom.cpp @@ -40,8 +40,8 @@ void RawModelCustom::ReadMeshFile(std::string filePath) void RawModelCustom::ReadMeshFileHeader(std::size_t& offset, char* fileData) { #ifdef BOOST_LITTLE_ENDIAN - hasSkin = true;//*(bool*)(fileData + offset); - //offset += sizeof(bool); + hasSkin = *(bool*)(fileData + offset); + offset += sizeof(bool); if (hasSkin) { m_SkinedVertices.resize(static_cast(*(unsigned int*)(fileData + offset))); } @@ -290,7 +290,10 @@ void RawModelCustom::ReadAnimationFile(std::string filePath) if (!in.is_open()) { //throw Resource::FailedLoadingException("Open animation file failed"); return; - } + } else if (hasSkin) { + throw Resource::FailedLoadingException("Open animation file for a skinned mesh failed, unknown stuff will happen"); + return; + } unsigned int fileByteSize = static_cast(in.tellg()); in.seekg(0, std::ios_base::beg); diff --git a/tools/MayaExporter/MayaExporter.opensdf b/tools/MayaExporter/MayaExporter.opensdf new file mode 100644 index 0000000000000000000000000000000000000000..31dea47bab049adbbcfae9b67e37a5ada58ecdf3 GIT binary patch literal 38 ncmd01NMy)m$Ydx6(}@fW3?U4z3_%RO44w>r430paKad9ihMopW literal 0 HcmV?d00001 diff --git a/tools/MayaExporter/MayaExporter/Mesh.h b/tools/MayaExporter/MayaExporter/Mesh.h index eda79805..affc4320 100644 --- a/tools/MayaExporter/MayaExporter/Mesh.h +++ b/tools/MayaExporter/MayaExporter/Mesh.h @@ -62,7 +62,7 @@ public: class Mesh : public OutputData { public: - bool hasSkin = true; //Should be false by default... Have it true now since pipeline only support skinned vertecies + bool hasSkin = false; unsigned int NumVertices; unsigned int NumIndices; std::vector Vertices; @@ -70,7 +70,7 @@ public: virtual void WriteBinary(std::ostream& out) { - //out.write((char*)&hasSkin, sizeof(bool)); + out.write((char*)&hasSkin, sizeof(bool)); out.write((char*)&NumVertices, sizeof(int)); out.write((char*)&NumIndices, sizeof(int)); for (auto aVertex : Vertices) { From 6610bb974db8da0ae68db595d49a7e3bf25b5046 Mon Sep 17 00:00:00 2001 From: William Moberg Date: Mon, 8 Feb 2016 13:32:45 +0100 Subject: [PATCH 111/355] Only apply air friction if the ground is never hit during the frame. --- src/Engine/Collision/CollisionSystem.cpp | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/src/Engine/Collision/CollisionSystem.cpp b/src/Engine/Collision/CollisionSystem.cpp index b5d7a1f0..7d8905a8 100644 --- a/src/Engine/Collision/CollisionSystem.cpp +++ b/src/Engine/Collision/CollisionSystem.cpp @@ -20,6 +20,7 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c // Collide against octree items m_OctreeResult.clear(); m_Octree->ObjectsInSameRegion(*boundingBox, m_OctreeResult); + bool everHitTheGround = false; for (auto& boxB : m_OctreeResult) { glm::vec3 resolutionVector; if (boxA.Entity == boxB.Entity) { @@ -43,17 +44,24 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c if (Collision::AABBvsTriangles(boxA, model->m_Vertices, model->m_Indices, modelMatrix, inOutVelocity, verticalStepHeight, isOnGround, resolutionVector)) { (glm::vec3&)cTransform["Position"] += resolutionVector; cPhysics["Velocity"] = inOutVelocity; - (bool)cPhysics["IsOnGround"] = isOnGround; - } else { - (bool)cPhysics["IsOnGround"] = false; + if (isOnGround) { + everHitTheGround = true; + (bool)cPhysics["IsOnGround"] = true; + } } } else if (Collision::AABBVsAABB(boxA, boxB, resolutionVector)) { //Enter here if boxB has no Model. (glm::vec3&)cTransform["Position"] += resolutionVector; - (bool)cPhysics["IsOnGround"] = resolutionVector.y > 0; - if ((bool)cPhysics["IsOnGround"]){ + if (resolutionVector.y > 0) { + everHitTheGround = true; + (bool)cPhysics["IsOnGround"] = true; ((glm::vec3&)cPhysics["Velocity"]).y = 0.f; } } } + + //This should apply air friction and such, iff zero models were hit. + if (!everHitTheGround) { + (bool)cPhysics["IsOnGround"] = false; + } } From 2b4e00e4b0195a527d8010a1b8d2b16dfeb454e7 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Mon, 8 Feb 2016 13:32:00 +0100 Subject: [PATCH 112/355] Refactored System constructor to take a struct instead of a bunch of parameters to reduce future pain and to be able to extend it with IsClient and IsServer flags. --- .../Engine/Collision/CollidableOctreeSystem.h | 4 +- include/Engine/Collision/CollisionSystem.h | 4 +- include/Engine/Collision/TriggerSystem.h | 4 +- include/Engine/Core/System.h | 26 +++++++-- include/Engine/Core/SystemPipeline.h | 8 ++- include/Engine/Core/UniformScaleSystem.h | 2 +- include/Engine/Editor/EditorRenderSystem.h | 2 +- include/Engine/Editor/EditorSystem.h | 2 +- include/Engine/Editor/EditorWidgetSystem.h | 2 +- include/Engine/Rendering/AnimationSystem.h | 4 +- include/Engine/Rendering/RenderSystem.h | 3 +- include/Game/ExplosionEffectSystem.h | 4 +- include/Game/Game.h | 17 +----- include/Game/Systems/CapturePointSystem.h | 2 +- include/Game/Systems/HealthSystem.h | 2 +- include/Game/Systems/InterpolationSystem.h | 2 +- include/Game/Systems/LifetimeSystem.h | 4 +- .../{PlayerHUD.h => PlayerHUDSystem.h} | 12 ++-- include/Game/Systems/PlayerMovementSystem.h | 2 +- include/Game/Systems/PlayerSpawnSystem.h | 2 +- include/Game/Systems/RaptorCopterSystem.h | 4 +- include/Game/Systems/SpawnerSystem.h | 2 +- include/Game/Systems/WeaponSystem.h | 2 +- src/Engine/Core/UniformScaleSystem.cpp | 4 +- src/Engine/Editor/EditorRenderSystem.cpp | 4 +- src/Engine/Editor/EditorSystem.cpp | 6 +- src/Engine/Editor/EditorWidgetSystem.cpp | 4 +- src/Engine/Rendering/RenderSystem.cpp | 5 +- src/Game/Game.cpp | 55 +++++++------------ src/Game/Systems/CapturePointSystem.cpp | 4 +- src/Game/Systems/HealthSystem.cpp | 4 +- src/Game/Systems/InterpolationSystem.cpp | 4 +- .../{PlayerHUD.cpp => PlayerHUDSystem.cpp} | 19 +------ src/Game/Systems/PlayerMovementSystem.cpp | 4 +- src/Game/Systems/PlayerSpawnSystem.cpp | 4 +- src/Game/Systems/SpawnerSystem.cpp | 4 +- src/Game/Systems/WeaponSystem.cpp | 4 +- 37 files changed, 109 insertions(+), 132 deletions(-) rename include/Game/Systems/{PlayerHUD.h => PlayerHUDSystem.h} (58%) rename src/Game/Systems/{PlayerHUD.cpp => PlayerHUDSystem.cpp} (85%) diff --git a/include/Engine/Collision/CollidableOctreeSystem.h b/include/Engine/Collision/CollidableOctreeSystem.h index 0aa01d2e..c7d42eae 100644 --- a/include/Engine/Collision/CollidableOctreeSystem.h +++ b/include/Engine/Collision/CollidableOctreeSystem.h @@ -9,8 +9,8 @@ class CollidableOctreeSystem : public ImpureSystem, public PureSystem { public: - CollidableOctreeSystem(World* world, EventBroker* eventBroker, Octree* octree, const std::string& componentType) - : System(world, eventBroker) + CollidableOctreeSystem(SystemParams params, Octree* octree, const std::string& componentType) + : System(params) , PureSystem(componentType) , m_Octree(octree) { } diff --git a/include/Engine/Collision/CollisionSystem.h b/include/Engine/Collision/CollisionSystem.h index f3a7e4fe..c963e6b8 100644 --- a/include/Engine/Collision/CollisionSystem.h +++ b/include/Engine/Collision/CollisionSystem.h @@ -13,8 +13,8 @@ class CollisionSystem : public PureSystem { public: - CollisionSystem(World* world, EventBroker* eventBroker, Octree* octree) - : System(world, eventBroker) + CollisionSystem(SystemParams params, Octree* octree) + : System(params) , PureSystem("Collidable") , m_Octree(octree) { } diff --git a/include/Engine/Collision/TriggerSystem.h b/include/Engine/Collision/TriggerSystem.h index fa322ddd..d71fad08 100644 --- a/include/Engine/Collision/TriggerSystem.h +++ b/include/Engine/Collision/TriggerSystem.h @@ -15,8 +15,8 @@ class AABB; class TriggerSystem : public PureSystem { public: - TriggerSystem(World* world, EventBroker* eventBroker, Octree* octree) - : System(world, eventBroker) + TriggerSystem(SystemParams params, Octree* octree) + : System(params) , PureSystem("Trigger") , m_Octree(octree) { diff --git a/include/Engine/Core/System.h b/include/Engine/Core/System.h index ec57f5fc..d4b9808b 100644 --- a/include/Engine/Core/System.h +++ b/include/Engine/Core/System.h @@ -6,20 +6,38 @@ #include "EntityWrapper.h" #include "ComponentWrapper.h" +struct SystemParams +{ + SystemParams(::World* World, ::EventBroker* EventBroker, bool IsClient, bool IsServer) + : World(World) + , EventBroker(EventBroker) + , IsClient(IsClient) + , IsServer(IsServer) + { } + + ::World* World; + ::EventBroker* EventBroker; + bool IsClient = false; + bool IsServer = false; +}; + class System { friend class SystemPipeline; protected: - System(World* world, EventBroker) { } - System(World* world, EventBroker* eventBroker) - : m_World(world) - , m_EventBroker(eventBroker) + System(SystemParams params) + : m_World(params.World) + , m_EventBroker(params.EventBroker) + , IsClient(params.IsClient) + , IsServer(params.IsServer) { } virtual ~System() = default; World* m_World; EventBroker* m_EventBroker; + bool IsClient = false; + bool IsServer = false; }; class PureSystem : public virtual System diff --git a/include/Engine/Core/SystemPipeline.h b/include/Engine/Core/SystemPipeline.h index 90303f12..88ec4fa7 100644 --- a/include/Engine/Core/SystemPipeline.h +++ b/include/Engine/Core/SystemPipeline.h @@ -10,9 +10,11 @@ class SystemPipeline { public: - SystemPipeline(World* world, EventBroker* eventBroker) + SystemPipeline(World* world, EventBroker* eventBroker, bool isClient, bool isServer) : m_World(world) , m_EventBroker(eventBroker) + , m_IsClient(isClient) + , m_IsServer(isServer) { EVENT_SUBSCRIBE_MEMBER(m_EPause, &SystemPipeline::OnPause); EVENT_SUBSCRIBE_MEMBER(m_EResume, &SystemPipeline::OnResume); @@ -35,7 +37,7 @@ public: m_OrderedSystemGroups.resize(updateOrderLevel + 1); } UnorderedSystems& group = m_OrderedSystemGroups[updateOrderLevel]; - System* system = new T(m_World, m_EventBroker, args...); + System* system = new T(SystemParams(m_World, m_EventBroker, m_IsClient, m_IsServer), args...); group.Systems[typeid(T).name()] = system; PureSystem* pureSystem = dynamic_cast(system); @@ -88,6 +90,8 @@ public: private: World* m_World; EventBroker* m_EventBroker; + bool m_IsClient = false; + bool m_IsServer = false; bool m_Paused = false; struct UnorderedSystems diff --git a/include/Engine/Core/UniformScaleSystem.h b/include/Engine/Core/UniformScaleSystem.h index 0ebc0672..cd679fed 100644 --- a/include/Engine/Core/UniformScaleSystem.h +++ b/include/Engine/Core/UniformScaleSystem.h @@ -8,7 +8,7 @@ class UniformScaleSystem : public PureSystem { public: - UniformScaleSystem(World* world, EventBroker* eventBroker); + UniformScaleSystem(SystemParams params); virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& cUniformScale, double dt) override; diff --git a/include/Engine/Editor/EditorRenderSystem.h b/include/Engine/Editor/EditorRenderSystem.h index 361669ba..a42ad779 100644 --- a/include/Engine/Editor/EditorRenderSystem.h +++ b/include/Engine/Editor/EditorRenderSystem.h @@ -10,7 +10,7 @@ class EditorRenderSystem : public ImpureSystem { public: - EditorRenderSystem(World* world, EventBroker* eventBroker, IRenderer* renderer, RenderFrame* renderFrame); + EditorRenderSystem(SystemParams params, IRenderer* renderer, RenderFrame* renderFrame); virtual void Update(double dt) override; diff --git a/include/Engine/Editor/EditorSystem.h b/include/Engine/Editor/EditorSystem.h index accf66e4..fcaa2e47 100644 --- a/include/Engine/Editor/EditorSystem.h +++ b/include/Engine/Editor/EditorSystem.h @@ -17,7 +17,7 @@ class EditorSystem : public ImpureSystem { public: - EditorSystem(World* world, EventBroker* eventBroker, IRenderer* renderer, RenderFrame* renderFrame); + EditorSystem(SystemParams params, IRenderer* renderer, RenderFrame* renderFrame); ~EditorSystem(); void Update(double dt); diff --git a/include/Engine/Editor/EditorWidgetSystem.h b/include/Engine/Editor/EditorWidgetSystem.h index a060bdd5..57e653d6 100644 --- a/include/Engine/Editor/EditorWidgetSystem.h +++ b/include/Engine/Editor/EditorWidgetSystem.h @@ -25,7 +25,7 @@ struct WidgetDelta : Event class EditorWidgetSystem : public ImpureSystem, PureSystem { public: - EditorWidgetSystem(World* world, EventBroker* eventBroker, IRenderer* renderer); + EditorWidgetSystem(SystemParams params, IRenderer* renderer); virtual void Update(double dt) override; virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& cEditorWidget, double dt) override; diff --git a/include/Engine/Rendering/AnimationSystem.h b/include/Engine/Rendering/AnimationSystem.h index fcdcbc92..9a9c92dd 100644 --- a/include/Engine/Rendering/AnimationSystem.h +++ b/include/Engine/Rendering/AnimationSystem.h @@ -13,8 +13,8 @@ class AnimationSystem : public PureSystem { public: - AnimationSystem(World* world, EventBroker* eventBroker) - : System(world, eventBroker) + AnimationSystem(SystemParams params) + : System(params) , PureSystem("Animation") { diff --git a/include/Engine/Rendering/RenderSystem.h b/include/Engine/Rendering/RenderSystem.h index d64147b9..8fbb005b 100644 --- a/include/Engine/Rendering/RenderSystem.h +++ b/include/Engine/Rendering/RenderSystem.h @@ -20,7 +20,7 @@ class RenderSystem : public ImpureSystem { public: - RenderSystem(World* world, EventBroker* eventBrokerer, const IRenderer* renderer, RenderFrame* renderFrame); + RenderSystem(SystemParams params, const IRenderer* renderer, RenderFrame* renderFrame); ~RenderSystem(); virtual void Update(double dt) override; @@ -29,7 +29,6 @@ private: const IRenderer* m_Renderer; RenderFrame* m_RenderFrame; Camera* m_Camera; - World* m_World; EntityWrapper m_CurrentCamera = EntityWrapper::Invalid; EntityWrapper m_LocalPlayer = EntityWrapper::Invalid; diff --git a/include/Game/ExplosionEffectSystem.h b/include/Game/ExplosionEffectSystem.h index 061ad221..5073d04e 100644 --- a/include/Game/ExplosionEffectSystem.h +++ b/include/Game/ExplosionEffectSystem.h @@ -4,8 +4,8 @@ class ExplosionEffectSystem : public PureSystem { public: - ExplosionEffectSystem(World* world, EventBroker* eventBroker) - : System(world, eventBroker) + ExplosionEffectSystem(SystemParams params) + : System(params) , PureSystem("ExplosionEffect") { } diff --git a/include/Game/Game.h b/include/Game/Game.h index 37267a68..a24862b1 100644 --- a/include/Game/Game.h +++ b/include/Game/Game.h @@ -55,24 +55,13 @@ private: Octree* m_OctreeFrustrumCulling; SystemPipeline* m_SystemPipeline; RenderFrame* m_RenderFrame; - // Network variables - boost::thread m_NetworkThread; + Network* m_Network = nullptr; - // Network methods - void networkFunction(); - Network* m_ClientOrServer; - bool m_IsClientOrServer = false; + bool m_IsClient = false; + bool m_IsServer = false; // Sound SoundSystem* m_SoundSystem; - - //EventRelay m_EInputCommand; - //bool debugOnInputCommand(const Events::InputCommand& e); - - void debugInitialize(); - void debugTick(double dt); - EventRelay m_EKeyDown; - }; #endif diff --git a/include/Game/Systems/CapturePointSystem.h b/include/Game/Systems/CapturePointSystem.h index 18c32c76..22e7e3d5 100644 --- a/include/Game/Systems/CapturePointSystem.h +++ b/include/Game/Systems/CapturePointSystem.h @@ -17,7 +17,7 @@ class CapturePointSystem : public PureSystem { public: //WARNING: on new map, destroy all info in the vectors, as well as reset all variables (just make new?) - CapturePointSystem(World* world, EventBroker* eventBroker); + CapturePointSystem(SystemParams params); //updatecomponent virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& capturePoint, double dt) override; diff --git a/include/Game/Systems/HealthSystem.h b/include/Game/Systems/HealthSystem.h index 3b069349..50af4678 100644 --- a/include/Game/Systems/HealthSystem.h +++ b/include/Game/Systems/HealthSystem.h @@ -16,7 +16,7 @@ class HealthSystem : public PureSystem { public: - HealthSystem(World* world, EventBroker* eventBroker); + HealthSystem(SystemParams params); //updatecomponent virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) override; diff --git a/include/Game/Systems/InterpolationSystem.h b/include/Game/Systems/InterpolationSystem.h index 96236f62..70eb7f43 100644 --- a/include/Game/Systems/InterpolationSystem.h +++ b/include/Game/Systems/InterpolationSystem.h @@ -26,7 +26,7 @@ class InterpolationSystem : public PureSystem float interpolationTime; }; public: - InterpolationSystem(World* world, EventBroker* eventBroker); + InterpolationSystem(SystemParams params); ~InterpolationSystem() { } virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& transform, double dt) override; private: diff --git a/include/Game/Systems/LifetimeSystem.h b/include/Game/Systems/LifetimeSystem.h index da88cfa2..3607c15c 100644 --- a/include/Game/Systems/LifetimeSystem.h +++ b/include/Game/Systems/LifetimeSystem.h @@ -6,8 +6,8 @@ class LifetimeSystem : public ImpureSystem, PureSystem { public: - LifetimeSystem(World* world, EventBroker* eventBroker) - : System(world, eventBroker) + LifetimeSystem(SystemParams params) + : System(params) , PureSystem("Lifetime") { } diff --git a/include/Game/Systems/PlayerHUD.h b/include/Game/Systems/PlayerHUDSystem.h similarity index 58% rename from include/Game/Systems/PlayerHUD.h rename to include/Game/Systems/PlayerHUDSystem.h index 180f5a2a..50b6a258 100644 --- a/include/Game/Systems/PlayerHUD.h +++ b/include/Game/Systems/PlayerHUDSystem.h @@ -6,18 +6,14 @@ #include "../../Engine/Rendering/ESetCamera.h" #include -class PlayerHUD : public ImpureSystem +class PlayerHUDSystem : public ImpureSystem { public: - PlayerHUD(World* world, EventBroker* eventBrokerer); - ~PlayerHUD(); + PlayerHUDSystem(SystemParams params) + : System(params) + { } virtual void Update(double dt) override; - -private: - World* m_World; - EventBroker* m_EventBroker; - }; #endif \ No newline at end of file diff --git a/include/Game/Systems/PlayerMovementSystem.h b/include/Game/Systems/PlayerMovementSystem.h index 34862e90..7daf9c03 100644 --- a/include/Game/Systems/PlayerMovementSystem.h +++ b/include/Game/Systems/PlayerMovementSystem.h @@ -8,7 +8,7 @@ class PlayerMovementSystem : public ImpureSystem, PureSystem { public: - PlayerMovementSystem(World* world, EventBroker* eventBroker); + PlayerMovementSystem(SystemParams params); ~PlayerMovementSystem(); virtual void Update(double dt) override; diff --git a/include/Game/Systems/PlayerSpawnSystem.h b/include/Game/Systems/PlayerSpawnSystem.h index b0ff1d79..7c6509ff 100644 --- a/include/Game/Systems/PlayerSpawnSystem.h +++ b/include/Game/Systems/PlayerSpawnSystem.h @@ -9,7 +9,7 @@ class PlayerSpawnSystem : public ImpureSystem { public: - PlayerSpawnSystem(World* world, EventBroker* eventBroker); + PlayerSpawnSystem(SystemParams params); virtual void Update(double dt) override; diff --git a/include/Game/Systems/RaptorCopterSystem.h b/include/Game/Systems/RaptorCopterSystem.h index 8bb18de6..b3589dcd 100644 --- a/include/Game/Systems/RaptorCopterSystem.h +++ b/include/Game/Systems/RaptorCopterSystem.h @@ -4,8 +4,8 @@ class RaptorCopterSystem : public PureSystem { public: - RaptorCopterSystem(World* world, EventBroker* eventBroker) - : System(world, eventBroker) + RaptorCopterSystem(SystemParams params) + : System(params) , PureSystem("RaptorCopter") { } diff --git a/include/Game/Systems/SpawnerSystem.h b/include/Game/Systems/SpawnerSystem.h index 62f6b09a..9cb4bd06 100644 --- a/include/Game/Systems/SpawnerSystem.h +++ b/include/Game/Systems/SpawnerSystem.h @@ -13,7 +13,7 @@ class SpawnerSystem : public System { public: - SpawnerSystem(World* world, EventBroker* eventBroker); + SpawnerSystem(SystemParams params); static EntityWrapper Spawn(EntityWrapper spawner, EntityWrapper parent = EntityWrapper::Invalid); diff --git a/include/Game/Systems/WeaponSystem.h b/include/Game/Systems/WeaponSystem.h index 0dd5cc54..59048ee0 100644 --- a/include/Game/Systems/WeaponSystem.h +++ b/include/Game/Systems/WeaponSystem.h @@ -21,7 +21,7 @@ class WeaponSystem : public ImpureSystem { public: - WeaponSystem(World* world, EventBroker* eventBroker, IRenderer* renderer); + WeaponSystem(SystemParams params, IRenderer* renderer); virtual void Update(double dt) override; diff --git a/src/Engine/Core/UniformScaleSystem.cpp b/src/Engine/Core/UniformScaleSystem.cpp index ab954a05..d5ac878a 100644 --- a/src/Engine/Core/UniformScaleSystem.cpp +++ b/src/Engine/Core/UniformScaleSystem.cpp @@ -1,7 +1,7 @@ #include "Core/UniformScaleSystem.h" -UniformScaleSystem::UniformScaleSystem(World* world, EventBroker* eventBroker) - : System(world, eventBroker) +UniformScaleSystem::UniformScaleSystem(SystemParams params) + : System(params) , PureSystem("UniformScale") { EVENT_SUBSCRIBE_MEMBER(m_ESetCamera, &UniformScaleSystem::OnSetCamera); diff --git a/src/Engine/Editor/EditorRenderSystem.cpp b/src/Engine/Editor/EditorRenderSystem.cpp index 4d65e9d3..f21ec033 100644 --- a/src/Engine/Editor/EditorRenderSystem.cpp +++ b/src/Engine/Editor/EditorRenderSystem.cpp @@ -1,7 +1,7 @@ #include "Editor/EditorRenderSystem.h" -EditorRenderSystem::EditorRenderSystem(World* m_World, EventBroker* eventBroker, IRenderer* renderer, RenderFrame* renderFrame) - : System(m_World, eventBroker) +EditorRenderSystem::EditorRenderSystem(SystemParams params, IRenderer* renderer, RenderFrame* renderFrame) + : System(params) , m_Renderer(renderer) , m_RenderFrame(renderFrame) { diff --git a/src/Engine/Editor/EditorSystem.cpp b/src/Engine/Editor/EditorSystem.cpp index ccbc1b48..b9a8025f 100644 --- a/src/Engine/Editor/EditorSystem.cpp +++ b/src/Engine/Editor/EditorSystem.cpp @@ -3,13 +3,13 @@ #include "Editor/EditorRenderSystem.h" #include "Editor/EditorWidgetSystem.h" -EditorSystem::EditorSystem(World* world, EventBroker* eventBroker, IRenderer* renderer, RenderFrame* renderFrame) - : System(world, eventBroker) +EditorSystem::EditorSystem(SystemParams params, IRenderer* renderer, RenderFrame* renderFrame) + : System(params) , m_Renderer(renderer) , m_RenderFrame(renderFrame) { m_EditorWorld = new World(); - m_EditorWorldSystemPipeline = new SystemPipeline(m_EditorWorld, eventBroker); + m_EditorWorldSystemPipeline = new SystemPipeline(m_EditorWorld, m_EventBroker, IsClient, IsServer); m_EditorWorldSystemPipeline->AddSystem(0); m_EditorWorldSystemPipeline->AddSystem(0, m_Renderer); m_EditorWorldSystemPipeline->AddSystem(1, m_Renderer, m_RenderFrame); diff --git a/src/Engine/Editor/EditorWidgetSystem.cpp b/src/Engine/Editor/EditorWidgetSystem.cpp index 7c20a7c7..f27d7a5e 100644 --- a/src/Engine/Editor/EditorWidgetSystem.cpp +++ b/src/Engine/Editor/EditorWidgetSystem.cpp @@ -1,7 +1,7 @@ #include "Editor/EditorWidgetSystem.h" -EditorWidgetSystem::EditorWidgetSystem(World* world, EventBroker* eventBroker, IRenderer* renderer) - : System(world, eventBroker) +EditorWidgetSystem::EditorWidgetSystem(SystemParams params, IRenderer* renderer) + : System(params) , PureSystem("EditorWidget") , m_Renderer(renderer) { diff --git a/src/Engine/Rendering/RenderSystem.cpp b/src/Engine/Rendering/RenderSystem.cpp index eaecf99e..ab423333 100644 --- a/src/Engine/Rendering/RenderSystem.cpp +++ b/src/Engine/Rendering/RenderSystem.cpp @@ -1,10 +1,9 @@ #include "Rendering/RenderSystem.h" -RenderSystem::RenderSystem(World* world, EventBroker* eventBroker, const IRenderer* renderer, RenderFrame* renderFrame) - : System(world, eventBroker) +RenderSystem::RenderSystem(SystemParams params, const IRenderer* renderer, RenderFrame* renderFrame) + : System(params) , m_Renderer(renderer) , m_RenderFrame(renderFrame) - , m_World(world) { EVENT_SUBSCRIBE_MEMBER(m_ESetCamera, &RenderSystem::OnSetCamera); EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &RenderSystem::OnInputCommand); diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index f5afcaeb..04180fb3 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -11,7 +11,7 @@ #include "Core/EntityFileWriter.h" #include "Game/Systems/CapturePointSystem.h" #include "Game/Systems/WeaponSystem.h" -#include "Game/Systems/PlayerHUD.h" +#include "Game/Systems/PlayerHUDSystem.h" #include "Game/Systems/LifetimeSystem.h" #include "../Engine/Rendering/AnimationSystem.h" @@ -71,13 +71,25 @@ Game::Game(int argc, char* argv[]) fp.MergeEntities(m_World); } + // Initialize network + if (m_Config->Get("Networking.StartNetwork", false)) { + bool isServer = m_Config->Get("Networking.IsServer", false); + if (isServer) { + m_Network = new Server(); + m_IsServer = true; + } else { + m_Network = new Client(m_Config); + m_IsClient = true; + } + m_Network->Start(m_World, m_EventBroker); + } // Create Octrees m_OctreeCollision = new Octree(AABB(glm::vec3(-100), glm::vec3(100)), 4); m_OctreeTrigger = new Octree(AABB(glm::vec3(-100), glm::vec3(100)), 4); m_OctreeFrustrumCulling = new Octree(AABB(glm::vec3(-100), glm::vec3(100)), 4); // Create system pipeline - m_SystemPipeline = new SystemPipeline(m_World, m_EventBroker); + m_SystemPipeline = new SystemPipeline(m_World, m_EventBroker, m_IsClient, m_IsServer); // All systems with orderlevel 0 will be updated first. unsigned int updateOrderLevel = 0; @@ -95,7 +107,7 @@ Game::Game(int argc, char* argv[]) ++updateOrderLevel; m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeCollision, "Collidable"); m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeTrigger, "Player"); - m_SystemPipeline->AddSystem(updateOrderLevel); + m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); // Collision and TriggerSystem should update after player. @@ -107,12 +119,6 @@ Game::Game(int argc, char* argv[]) ++updateOrderLevel; m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer, m_RenderFrame); - // Invoke network - if (m_Config->Get("Networking.StartNetwork", false)) { - //boost::thread workerThread(&Game::networkFunction, this); - networkFunction(); - } - // Invoke sound system m_SoundSystem = new SoundSystem(m_World, m_EventBroker, m_Config->Get("Debug.EditorEnabled", false)); @@ -126,6 +132,9 @@ Game::~Game() delete m_OctreeFrustrumCulling; delete m_OctreeCollision; delete m_OctreeTrigger; + if (m_Network != nullptr) { + delete m_Network; + } delete m_World; delete m_FrameStack; delete m_InputProxy; @@ -154,39 +163,17 @@ void Game::Tick() m_EventBroker->Swap(); // Update network - if (m_IsClientOrServer) { - m_ClientOrServer->Update(); + if (m_Network != nullptr) { + m_Network->Update(); } + // Iterate through systems and update world! m_EventBroker->Process(); m_SystemPipeline->Update(dt); - debugTick(dt); m_Renderer->Update(dt); m_SoundSystem->Update(dt); - GLERROR("Game::Tick m_RenderQueueFactory->Update"); m_Renderer->Draw(*m_RenderFrame); m_RenderFrame->Clear(); - GLERROR("Game::Tick m_Renderer->Draw"); m_EventBroker->Swap(); m_EventBroker->Clear(); -} - -void Game::debugTick(double dt) -{ - m_EventBroker->Process(); -} - -void Game::networkFunction() -{ - bool isServer = m_Config->Get("Networking.IsServer", false); - if (!isServer) { - m_IsClientOrServer = true; - m_ClientOrServer = new Client(m_Config); - } - if (isServer) { - m_IsClientOrServer = true; - m_ClientOrServer = new Server(); - } - m_ClientOrServer->Start(m_World, m_EventBroker); - } \ No newline at end of file diff --git a/src/Game/Systems/CapturePointSystem.cpp b/src/Game/Systems/CapturePointSystem.cpp index d26dde5f..0ed02716 100644 --- a/src/Game/Systems/CapturePointSystem.cpp +++ b/src/Game/Systems/CapturePointSystem.cpp @@ -1,8 +1,8 @@ #include "Systems/CapturePointSystem.h" #include -CapturePointSystem::CapturePointSystem(World* world, EventBroker* eventBroker) - : System(world, eventBroker) +CapturePointSystem::CapturePointSystem(SystemParams params) + : System(params) , PureSystem("CapturePoint") { //subscribe/listenTo playerdamage,healthpickup events (using the eventBroker) diff --git a/src/Game/Systems/HealthSystem.cpp b/src/Game/Systems/HealthSystem.cpp index 9e118070..bfce08bf 100644 --- a/src/Game/Systems/HealthSystem.cpp +++ b/src/Game/Systems/HealthSystem.cpp @@ -1,7 +1,7 @@ #include "Systems/HealthSystem.h" -HealthSystem::HealthSystem(World* m_World, EventBroker* eventBroker) - : System(m_World, eventBroker) +HealthSystem::HealthSystem(SystemParams params) + : System(params) , PureSystem("Health") { //subscribe/listenTo playerdamage,healthpickup events (using the eventBroker) diff --git a/src/Game/Systems/InterpolationSystem.cpp b/src/Game/Systems/InterpolationSystem.cpp index f2de710d..e958a4a9 100644 --- a/src/Game/Systems/InterpolationSystem.cpp +++ b/src/Game/Systems/InterpolationSystem.cpp @@ -1,7 +1,7 @@ #include "Systems/InterpolationSystem.h" -InterpolationSystem::InterpolationSystem(World* world, EventBroker* eventBroker) - : System(world, eventBroker) +InterpolationSystem::InterpolationSystem(SystemParams params) + : System(params) , PureSystem("Transform") { ConfigFile* config = ResourceManager::Load("Config.ini"); diff --git a/src/Game/Systems/PlayerHUD.cpp b/src/Game/Systems/PlayerHUDSystem.cpp similarity index 85% rename from src/Game/Systems/PlayerHUD.cpp rename to src/Game/Systems/PlayerHUDSystem.cpp index 55d0c3f1..898d8bea 100644 --- a/src/Game/Systems/PlayerHUD.cpp +++ b/src/Game/Systems/PlayerHUDSystem.cpp @@ -1,21 +1,6 @@ -#include "Game/Systems/PlayerHUD.h" +#include "Game/Systems/PlayerHUDSystem.h" -PlayerHUD::PlayerHUD(World* world, EventBroker* eventBrokerer) - :System(world, eventBrokerer) - , m_World(world) - , m_EventBroker(eventBrokerer) -{ - - -} - -PlayerHUD::~PlayerHUD() -{ - - -} - -void PlayerHUD::Update(double dt) +void PlayerHUDSystem::Update(double dt) { auto healthHUDs = m_World->GetComponents("HealthHUD"); if (healthHUDs == nullptr) { diff --git a/src/Game/Systems/PlayerMovementSystem.cpp b/src/Game/Systems/PlayerMovementSystem.cpp index 3224f579..04ce2400 100644 --- a/src/Game/Systems/PlayerMovementSystem.cpp +++ b/src/Game/Systems/PlayerMovementSystem.cpp @@ -1,7 +1,7 @@ #include "Systems/PlayerMovementSystem.h" -PlayerMovementSystem::PlayerMovementSystem(World* world, EventBroker* eventBroker) - : System(world, eventBroker) +PlayerMovementSystem::PlayerMovementSystem(SystemParams params) + : System(params) , PureSystem("Player") { EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &PlayerMovementSystem::OnPlayerSpawned); diff --git a/src/Game/Systems/PlayerSpawnSystem.cpp b/src/Game/Systems/PlayerSpawnSystem.cpp index 7db6e8ff..fa713675 100644 --- a/src/Game/Systems/PlayerSpawnSystem.cpp +++ b/src/Game/Systems/PlayerSpawnSystem.cpp @@ -1,7 +1,7 @@ #include "Systems/PlayerSpawnSystem.h" -PlayerSpawnSystem::PlayerSpawnSystem(World* m_World, EventBroker* eventBroker) - : System(m_World, eventBroker) +PlayerSpawnSystem::PlayerSpawnSystem(SystemParams params) + : System(params) { EVENT_SUBSCRIBE_MEMBER(m_OnInputCommand, &PlayerSpawnSystem::OnInputCommand); EVENT_SUBSCRIBE_MEMBER(m_OnPlayerSpawnerd, &PlayerSpawnSystem::OnPlayerSpawned); diff --git a/src/Game/Systems/SpawnerSystem.cpp b/src/Game/Systems/SpawnerSystem.cpp index 7a0a13c9..ba0775a3 100644 --- a/src/Game/Systems/SpawnerSystem.cpp +++ b/src/Game/Systems/SpawnerSystem.cpp @@ -1,7 +1,7 @@ #include "Systems/SpawnerSystem.h" -SpawnerSystem::SpawnerSystem(World* world, EventBroker* eventBroker) - : System(world, eventBroker) +SpawnerSystem::SpawnerSystem(SystemParams params) + : System(params) { EVENT_SUBSCRIBE_MEMBER(m_OnSpawnerSpawn, &SpawnerSystem::OnSpawnerSpawn); } diff --git a/src/Game/Systems/WeaponSystem.cpp b/src/Game/Systems/WeaponSystem.cpp index 1613cb7a..22cd173a 100644 --- a/src/Game/Systems/WeaponSystem.cpp +++ b/src/Game/Systems/WeaponSystem.cpp @@ -1,7 +1,7 @@ #include "Systems/WeaponSystem.h" -WeaponSystem::WeaponSystem(World* world, EventBroker* eventBroker, IRenderer* renderer) - : System(world, eventBroker) +WeaponSystem::WeaponSystem(SystemParams params, IRenderer* renderer) + : System(params) , ImpureSystem() , m_Renderer(renderer) { From 12c05d5a1cc1c5d879c3e382e4c78f17e2611c0a Mon Sep 17 00:00:00 2001 From: stiffly Date: Mon, 8 Feb 2016 13:59:35 +0100 Subject: [PATCH 113/355] Added an Queue event for sound emitters. --- include/Engine/Sound/EPlayQueueOnEntity.h | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 include/Engine/Sound/EPlayQueueOnEntity.h diff --git a/include/Engine/Sound/EPlayQueueOnEntity.h b/include/Engine/Sound/EPlayQueueOnEntity.h new file mode 100644 index 00000000..e880819a --- /dev/null +++ b/include/Engine/Sound/EPlayQueueOnEntity.h @@ -0,0 +1,18 @@ +#ifndef Events_PlayQueueOnEntity_h__ +#define Events_PlayQueueOnEntity_h__ + +#include "../Core/Event.h" +#include "../Core/EntityWrapper.h" + +namespace Events +{ + +struct PlayQueueOnEntity : public Event +{ + EntityWrapper Emitter; + std::vector FilePaths; +}; + +} + +#endif From 3a5c0a27620e3bf443cbd0dab49746aaf9b3711d Mon Sep 17 00:00:00 2001 From: stiffly Date: Mon, 8 Feb 2016 14:01:32 +0100 Subject: [PATCH 114/355] SoundSystem does not longer inherit from SoundManager. SoundManager is a individual class that listens to events. The SoundManager only listens to the local player. --- include/Engine/Sound/Sound.h | 3 + include/Engine/Sound/SoundManager.h | 65 +++-------- include/Game/Game.h | 2 +- include/Game/Systems/SoundSystem.h | 40 ++++++- src/Engine/Sound/SoundManager.cpp | 165 ++++++---------------------- src/Game/Game.cpp | 5 + src/Game/Systems/SoundSystem.cpp | 119 +++++++++++++++++++- 7 files changed, 211 insertions(+), 188 deletions(-) diff --git a/include/Engine/Sound/Sound.h b/include/Engine/Sound/Sound.h index 6b2aac04..cccbdf07 100644 --- a/include/Engine/Sound/Sound.h +++ b/include/Engine/Sound/Sound.h @@ -1,6 +1,9 @@ #ifndef Sound_h__ #define Sound_h__ +#include +#include + #include "Core/ResourceManager.h" class Sound : public Resource diff --git a/include/Engine/Sound/SoundManager.h b/include/Engine/Sound/SoundManager.h index 9ba4d2ad..3923a17b 100644 --- a/include/Engine/Sound/SoundManager.h +++ b/include/Engine/Sound/SoundManager.h @@ -15,6 +15,7 @@ #include "Core/EventBroker.h" #include "Core/Transform.h" // Absolute transform #include "Sound/Sound.h" +#include "../Engine/Sound/EPlayQueueOnEntity.h" #include "Sound/EPlaySoundOnEntity.h" #include "Sound/EPlaySoundOnPosition.h" #include "Sound/EPlayBackgroundMusic.h" @@ -23,19 +24,9 @@ #include "Sound/EStopSound.h" #include "Sound/ESetBGMGain.h" #include "Sound/ESetSFXGain.h" -#include "Core/EShoot.h" -#include "Core/EPlayerSpawned.h" -#include "Input/EInputCommand.h" -#include "Core/ECaptured.h" -#include "Core/EPlayerDamage.h" -#include "Core/EPlayerDeath.h" -#include "Core/EPlayerHealthPickup.h" -#include "Core/EComponentAttached.h" -#include "Collision/ETrigger.h" #include "Core/EPause.h" -#include "Game/Events/EDoubleJump.h" -#include "Game/Events/EDashAbility.h" - +#include "Core/EComponentAttached.h" +#include "../Core/EPlayerSpawned.h" typedef std::pair> QueuedBuffers; @@ -61,20 +52,6 @@ public: // Update emitters / listener void Update(double dt); -protected: - // Specific logic - void playSound(Source* source); - // Need to be the same format (sample rate etc) - void playQueue(QueuedBuffers qb); - void stopSound(Source* source); - void playerJumps(); - void playerStep(double dt); - EntityID createChildEmitter(EntityWrapper localPlayer); - - // Logic - World* m_World = nullptr; - EventBroker* m_EventBroker = nullptr; - private: // Help functions for working with OpenaAL void setListenerPos(glm::vec3 pos) { alListener3f(AL_POSITION, pos.x, pos.y, pos.z); }; @@ -92,25 +69,30 @@ private: void deleteInactiveEmitters(); void stopEmitters(); void updateListener(double dt); - Source* createSource(std::string filePath); ALenum getSourceState(ALuint source); void setGain(Source* source, float gain); void setSoundProperties(Source* source, ComponentWrapper* soundComponent); + // Specific logic + void playSound(Source* source); + // Need to be the same format (sample rate etc) + void playQueue(QueuedBuffers qb); + void stopSound(Source* source); + Source* createSource(std::string filePath); std::unordered_map m_Sources; + // Logic + World* m_World = nullptr; + EventBroker* m_EventBroker = nullptr; // OpenAL system variables ALCdevice* m_ALCdevice = nullptr; ALCcontext* m_ALCcontext = nullptr; - - float m_BGMVolumeChannel = 1.0f; float m_SFXVolumeChannel = 1.0f; bool m_EditorEnabled = false; EntityWrapper m_LocalPlayer = EntityWrapper(); - std::default_random_engine generator; // Events EventRelay m_EPlaySoundOnEntity; @@ -129,31 +111,16 @@ private: bool OnSetBGMGain(const Events::SetBGMGain &e); EventRelay m_ESetSFXGain; bool OnSetSFXGain(const Events::SetSFXGain &e); - EventRelay m_EShoot; - bool OnShoot(const Events::Shoot &e); - EventRelay m_EPlayerSpawned; - bool OnPlayerSpawned(const Events::PlayerSpawned &e); - EventRelay m_ECaptured; - bool OnCaptured(const Events::Captured &e); - EventRelay m_EPlayerDamage; - bool OnPlayerDamage(const Events::PlayerDamage &e); - EventRelay m_EPlayerDeath; - bool OnPlayerDeath(const Events::PlayerDeath &e); - EventRelay m_EPlayerHealthPickup; - bool OnPlayerHealthPickup(const Events::PlayerHealthPickup &e); EventRelay m_EComponentAttached; bool OnComponentAttached(const Events::ComponentAttached &e); - EventRelay m_ETriggerTouch; - bool OnTriggerTouch(const Events::TriggerTouch &e); EventRelay m_EPause; bool OnPause(const Events::Pause &e); EventRelay m_EResume; bool OnResume(const Events::Resume &e); - EventRelay m_EDoubleJump; - bool OnDoubleJump(const Events::DoubleJump &e); - EventRelay m_EDashAbility; - bool OnDashAbility(const Events::DashAbility &e); - + EventRelay m_EPlayerSpawned; + bool OnPlayerSpawned(const Events::PlayerSpawned &e); + EventRelay m_EPlayQueueOnEntity; + bool OnPlayQueueOnEntity(const Events::PlayQueueOnEntity &e); }; diff --git a/include/Game/Game.h b/include/Game/Game.h index b6a2c0d3..6177a818 100644 --- a/include/Game/Game.h +++ b/include/Game/Game.h @@ -30,7 +30,7 @@ #include "Network/Client.h" // Sound -//#include "Sound/SoundManager.h" +#include "Sound/SoundManager.h" #include "Systems/SoundSystem.h" class Game diff --git a/include/Game/Systems/SoundSystem.h b/include/Game/Systems/SoundSystem.h index 77ebcfa1..b14d7486 100644 --- a/include/Game/Systems/SoundSystem.h +++ b/include/Game/Systems/SoundSystem.h @@ -1,13 +1,29 @@ #ifndef Systems_SoundSystem_h__ #define Systems_SoundSystem_h__ +#include + #include "../Engine/Core/System.h" -#include "../Engine/Sound/SoundManager.h" +#include "../Engine/Core/ResourceManager.h" +#include "../Engine/Sound/Sound.h" +#include "../Engine/Sound/EPlayQueueOnEntity.h" #include "../Engine/Core/EPlayerSpawned.h" #include "../Engine/Input/EInputCommand.h" +#include "../Engine/Core/EShoot.h" +#include "../Engine/Core/EPlayerSpawned.h" +#include "../Engine/Input/EInputCommand.h" +#include "../Engine/Core/ECaptured.h" +#include "../Engine/Core/EPlayerDamage.h" +#include "../Engine/Core/EPlayerDeath.h" +#include "../Engine/Core/EPlayerHealthPickup.h" +#include "../Engine/Collision/ETrigger.h" +#include "../Engine/Sound/EPlaySoundOnEntity.h" +#include "../Engine/Sound/EPlayBackgroundMusic.h" +#include "../Game/Events/EDoubleJump.h" +#include "../Game/Events/EDashAbility.h" -class SoundSystem : public PureSystem, ImpureSystem, SoundManager +class SoundSystem : public PureSystem, ImpureSystem { public: SoundSystem(World* world, EventBroker* eventbroker); @@ -23,6 +39,8 @@ private: // Logic for playing a sound when a player jumps void playerJumps(); + // Helper function + EntityID createChildEmitter(EntityWrapper parent); // Walking logic // Keeps track of how far the player has walked within this "key press session". @@ -34,10 +52,28 @@ private: // Determine what sound file to play. bool m_LeftFoot = false; + std::default_random_engine generator; + EventRelay m_EPlayerSpawned; bool OnPlayerSpawned(const Events::PlayerSpawned &e); EventRelay m_InputCommand; bool OnInputCommand(const Events::InputCommand &e); + EventRelay m_EDoubleJump; + bool OnDoubleJump(const Events::DoubleJump &e); + EventRelay m_EDashAbility; + bool OnDashAbility(const Events::DashAbility &e); + EventRelay m_ETriggerTouch; + bool OnTriggerTouch(const Events::TriggerTouch &e); + EventRelay m_EShoot; + bool OnShoot(const Events::Shoot &e); + EventRelay m_ECaptured; + bool OnCaptured(const Events::Captured &e); + EventRelay m_EPlayerDamage; + bool OnPlayerDamage(const Events::PlayerDamage &e); + EventRelay m_EPlayerDeath; + bool OnPlayerDeath(const Events::PlayerDeath &e); + EventRelay m_EPlayerHealthPickup; + bool OnPlayerHealthPickup(const Events::PlayerHealthPickup &e); }; #endif diff --git a/src/Engine/Sound/SoundManager.cpp b/src/Engine/Sound/SoundManager.cpp index 7046ecc1..d75e9afc 100644 --- a/src/Engine/Sound/SoundManager.cpp +++ b/src/Engine/Sound/SoundManager.cpp @@ -20,16 +20,11 @@ SoundManager::SoundManager(World* world, EventBroker* eventBroker, bool editorMo EVENT_SUBSCRIBE_MEMBER(m_EContinueSound, &SoundManager::OnContinueSound); EVENT_SUBSCRIBE_MEMBER(m_ESetBGMGain, &SoundManager::OnSetBGMGain); EVENT_SUBSCRIBE_MEMBER(m_ESetSFXGain, &SoundManager::OnSetSFXGain); - EVENT_SUBSCRIBE_MEMBER(m_EShoot, &SoundManager::OnShoot); - EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &SoundManager::OnPlayerSpawned); - EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &SoundManager::OnPlayerDamage); - EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &SoundManager::OnCaptured); - EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &SoundManager::OnTriggerTouch); EVENT_SUBSCRIBE_MEMBER(m_EPause, &SoundManager::OnPause); EVENT_SUBSCRIBE_MEMBER(m_EResume, &SoundManager::OnResume); EVENT_SUBSCRIBE_MEMBER(m_EComponentAttached, &SoundManager::OnComponentAttached); - EVENT_SUBSCRIBE_MEMBER(m_EDoubleJump, &SoundManager::OnDoubleJump); - EVENT_SUBSCRIBE_MEMBER(m_EDashAbility, &SoundManager::OnDashAbility); + EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &SoundManager::OnPlayerSpawned); + EVENT_SUBSCRIBE_MEMBER(m_EPlayQueueOnEntity, &SoundManager::OnPlayQueueOnEntity); } SoundManager::~SoundManager() @@ -135,18 +130,21 @@ void SoundManager::updateListener(double dt) { // Should only be one listener. auto listenerComponents = m_World->GetComponents("Listener"); - if (listenerComponents == nullptr) { + if (listenerComponents == nullptr || !m_LocalPlayer.Valid()) { return; } for (auto it = listenerComponents->begin(); it != listenerComponents->end(); it++) { - EntityID listener = (*it).EntityID; - glm::vec3 previousPos; - alGetListener3f(AL_POSITION, &previousPos.x, &previousPos.y, &previousPos.z); // Get previous pos - glm::vec3 nextPos = Transform::AbsolutePosition(m_World, listener); // Get next (current) pos - glm::vec3 velocity = glm::vec3(nextPos - previousPos) / (float)dt; // Calculate velocity - setListenerPos(nextPos); - setListenerVel(velocity); - setListenerOri(glm::eulerAngles(Transform::AbsoluteOrientation(m_World, listener))); + EntityWrapper listener(m_World, (*it).EntityID); + if (listener.IsChildOf(m_LocalPlayer) || listener == m_LocalPlayer) { + glm::vec3 previousPos; + alGetListener3f(AL_POSITION, &previousPos.x, &previousPos.y, &previousPos.z); // Get previous pos + glm::vec3 nextPos = Transform::AbsolutePosition(listener); // Get next (current) pos + glm::vec3 velocity = glm::vec3(nextPos - previousPos) / (float)dt; // Calculate velocity + setListenerPos(nextPos); + setListenerVel(velocity); + setListenerOri(glm::eulerAngles(Transform::AbsoluteOrientation(listener))); + break; + } } } @@ -181,21 +179,6 @@ void SoundManager::stopSound(Source* source) alSourceStop(source->ALsource); } - - -void SoundManager::playerStep(double dt) -{ - -} - -EntityID SoundManager::createChildEmitter(EntityWrapper localPlayer) -{ - EntityID child = m_World->CreateEntity(localPlayer.ID); - m_World->AttachComponent(child, "Transform"); - m_World->AttachComponent(child, "SoundEmitter"); - return child; -} - bool SoundManager::OnPlaySoundOnEntity(const Events::PlaySoundOnEntity & e) { Source* source = createSource(e.FilePath); @@ -272,87 +255,6 @@ bool SoundManager::OnSetSFXGain(const Events::SetSFXGain & e) return true; } -bool SoundManager::OnShoot(const Events::Shoot & e) -{ - Source* source = createSource("Audio/laser/laser1.wav"); - //auto emitterID = m_World->CreateEntity(e.Player.ID); - //m_World->AttachComponent(emitterID, "Transform"); - //auto emitter = m_World->AttachComponent(emitterID, "SoundEmitter"); - source->Type = SoundType::SFX; - m_Sources[createChildEmitter(m_LocalPlayer)] = source; - playSound(source); - return true; -} - -bool SoundManager::OnPlayerSpawned(const Events::PlayerSpawned & e) -{ - if (e.PlayerID == -1) { // Local player - m_World->AttachComponent(e.Player.ID, "Listener"); - m_LocalPlayer.ID = e.Player.ID; - } - return true; -} - - -bool SoundManager::OnCaptured(const Events::Captured & e) -{ - int homeTeam = (int)m_World->GetComponent(e.CapturePointID, "Team")["Team"]; - int team = (int)m_World->GetComponent(m_LocalPlayer.ID, "Team")["Team"]; - Events::PlaySoundOnEntity ev; - if (team == homeTeam) { - ev.FilePath = "Audio/announcer/objective_achieved.wav"; - } else { - ev.FilePath = "Audio/announcer/objective_failed.wav"; // have not been tested - } - ev.EmitterID = createChildEmitter(m_LocalPlayer); - m_EventBroker->Publish(ev); - return false; -} - -bool SoundManager::OnPlayerDamage(const Events::PlayerDamage & e) -{ - // Should check for only local players here... - - std::uniform_int_distribution dist(1, 12); - int rand = dist(generator); - Source* source = createSource("Audio/hurt/hurt" + std::to_string(rand) + ".wav"); - source->Type = SoundType::SFX; - m_Sources[createChildEmitter(m_LocalPlayer)] = source; - - // Breathe - std::vector buffers; - buffers.push_back(source->SoundResource->Buffer()); - int ammountOfbreaths = (static_cast(e.Damage) / 10) + 2; // TEMP: Idk something stupid like this shit - for (int i = 0; i < ammountOfbreaths; i++) { - buffers.push_back(ResourceManager::Load("Audio/exhausted/breath.wav")->Buffer()); - } - playQueue(QueuedBuffers(std::make_pair(source->ALsource, buffers))); - - return false; -} - -bool SoundManager::OnPlayerDeath(const Events::PlayerDeath & e) -{ - if (e.PlayerID == m_LocalPlayer.ID) { - Events::PlaySoundOnEntity ev; - ev.EmitterID = createChildEmitter(m_LocalPlayer); - ev.FilePath = "Audio/die/die2.wav"; // should random between a bunch - m_EventBroker->Publish(ev); - } - return false; -} - -bool SoundManager::OnPlayerHealthPickup(const Events::PlayerHealthPickup & e) -{ - if (e.PlayerHealedID == m_LocalPlayer.ID) { - Events::PlaySoundOnEntity ev; - ev.EmitterID = createChildEmitter(m_LocalPlayer); - ev.FilePath = "Audio/pickup/pickup2.wav"; - m_EventBroker->Publish(ev); - } - return false; -} - bool SoundManager::OnComponentAttached(const Events::ComponentAttached & e) { if (e.Component.Info.Name == "SoundEmitter") { @@ -363,16 +265,6 @@ bool SoundManager::OnComponentAttached(const Events::ComponentAttached & e) return false; } -bool SoundManager::OnTriggerTouch(const Events::TriggerTouch & e) -{ - if (m_World->HasComponent(e.Trigger.ID, "CapturePoint")) { - Events::PlayBackgroundMusic ev; - ev.FilePath = "Audio/bgm/drumstest.wav"; - m_EventBroker->Publish(ev); - } - return false; -} - bool SoundManager::OnPause(const Events::Pause & e) { for (auto it = m_Sources.begin(); it != m_Sources.end(); it++) { @@ -389,22 +281,29 @@ bool SoundManager::OnResume(const Events::Resume &e) return false; } -bool SoundManager::OnDoubleJump(const Events::DoubleJump & e) + +bool SoundManager::OnPlayerSpawned(const Events::PlayerSpawned &e) { - Events::PlaySoundOnEntity ev; - ev.EmitterID = createChildEmitter(m_LocalPlayer); - ev.FilePath = "Audio/jump/jump2.wav"; - m_EventBroker->Publish(ev); + if (e.PlayerID == -1) { // Local player + m_LocalPlayer = e.Player; + return true; + } return false; } -bool SoundManager::OnDashAbility(const Events::DashAbility &e) + +bool SoundManager::OnPlayQueueOnEntity(const Events::PlayQueueOnEntity &e) { - Events::PlaySoundOnEntity ev; - ev.EmitterID = createChildEmitter(m_LocalPlayer); - ev.FilePath = "Audio/jump/dash1.wav"; - m_EventBroker->Publish(ev); - return false; + Source* source = createSource(*e.FilePaths.begin()); + std::vector buffers; + buffers.push_back(source->SoundResource->Buffer()); + source->Type = SoundType::BGM; + std::vector::const_iterator it; + for (it = e.FilePaths.begin() + 1; it != e.FilePaths.end(); it++) { + buffers.push_back(ResourceManager::Load(*it)->Buffer()); + } + playQueue(QueuedBuffers(source->ALsource, buffers)); + return true; } ALenum SoundManager::getSourceState(ALuint source) diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index 541aa001..d18aaf8d 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -71,6 +71,8 @@ Game::Game(int argc, char* argv[]) fp.MergeEntities(m_World); } + // Create the sound manager + m_SoundManager = new SoundManager(m_World, m_EventBroker, true); // Create Octrees m_OctreeCollision = new Octree(AABB(glm::vec3(-100), glm::vec3(100)), 4); @@ -123,6 +125,7 @@ Game::~Game() delete m_OctreeFrustrumCulling; delete m_OctreeCollision; delete m_OctreeTrigger; + delete m_SoundManager; delete m_World; delete m_FrameStack; delete m_InputProxy; @@ -150,6 +153,8 @@ void Game::Tick() m_InputProxy->Process(); m_EventBroker->Swap(); + m_SoundManager->Update(dt); + // Update network if (m_IsClientOrServer) { m_ClientOrServer->Update(); diff --git a/src/Game/Systems/SoundSystem.cpp b/src/Game/Systems/SoundSystem.cpp index 06e028f2..3f9b75d0 100644 --- a/src/Game/Systems/SoundSystem.cpp +++ b/src/Game/Systems/SoundSystem.cpp @@ -4,12 +4,18 @@ SoundSystem::SoundSystem(World* world, EventBroker* eventbroker) : System(world, eventbroker) , PureSystem("SoundEmitter") , ImpureSystem() - , SoundManager(world, eventbroker, true) { m_World = world; m_EventBroker = eventbroker; EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &SoundSystem::OnPlayerSpawned); EVENT_SUBSCRIBE_MEMBER(m_InputCommand, &SoundSystem::OnInputCommand); + EVENT_SUBSCRIBE_MEMBER(m_EDoubleJump, &SoundSystem::OnDoubleJump); + EVENT_SUBSCRIBE_MEMBER(m_EDashAbility, &SoundSystem::OnDashAbility); + EVENT_SUBSCRIBE_MEMBER(m_EShoot, &SoundSystem::OnShoot); + EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &SoundSystem::OnPlayerSpawned); + EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &SoundSystem::OnPlayerDamage); + EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &SoundSystem::OnCaptured); + EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &SoundSystem::OnTriggerTouch); } void SoundSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& cComponent, double dt) @@ -20,8 +26,6 @@ void SoundSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& cComp void SoundSystem::Update(double dt) { playerStep(dt); - // Update listener and emitters. - SoundManager::Update(dt); } void SoundSystem::playerStep(double dt) @@ -83,6 +87,12 @@ bool SoundSystem::OnInputCommand(const Events::InputCommand & e) m_DistanceMoved = 0.f; } } + if (e.Command == "TakeDamage" && e.Value > 0) { + Events::PlayerDamage ev; + ev.Player = m_LocalPlayer; + ev.Damage = 1.0; + m_EventBroker->Publish(ev); + } return false; } @@ -97,3 +107,106 @@ void SoundSystem::playerJumps() m_EventBroker->Publish(e); } } + +bool SoundSystem::OnShoot(const Events::Shoot & e) +{ + Events::PlaySoundOnEntity ev; + ev.EmitterID = createChildEmitter(m_LocalPlayer); + ev.FilePath = "Audio/laser/laser1.wav"; + m_EventBroker->Publish(ev); + return true; +} + +bool SoundSystem::OnCaptured(const Events::Captured & e) +{ + int homeTeam = (int)m_World->GetComponent(e.CapturePointID, "Team")["Team"]; + int team = (int)m_World->GetComponent(m_LocalPlayer.ID, "Team")["Team"]; + Events::PlaySoundOnEntity ev; + if (team == homeTeam) { + ev.FilePath = "Audio/announcer/objective_achieved.wav"; + } else { + ev.FilePath = "Audio/announcer/objective_failed.wav"; // have not been tested + } + ev.EmitterID = createChildEmitter(m_LocalPlayer); + m_EventBroker->Publish(ev); + return false; +} + +// Testing purposes atm... +bool SoundSystem::OnPlayerDamage(const Events::PlayerDamage & e) +{ + // Should check for only local players here... + std::uniform_int_distribution dist(1, 12); + int rand = dist(generator); + std::vector paths; + paths.push_back("Audio/hurt/hurt" + std::to_string(rand) + ".wav"); + + // Breathe + int ammountOfbreaths = (static_cast(e.Damage) / 10) + 2; // TEMP: Idk something stupid like this shit + for (int i = 0; i < ammountOfbreaths; i++) { + paths.push_back("Audio/exhausted/breath.wav"); + } + Events::PlayQueueOnEntity ev; + ev.Emitter = m_LocalPlayer; + ev.FilePaths = paths; + m_EventBroker->Publish(ev); + return false; +} + +bool SoundSystem::OnPlayerDeath(const Events::PlayerDeath & e) +{ + if (e.PlayerID == m_LocalPlayer.ID) { + Events::PlaySoundOnEntity ev; + ev.EmitterID = createChildEmitter(m_LocalPlayer); + ev.FilePath = "Audio/die/die2.wav"; // should random between a bunch + m_EventBroker->Publish(ev); + } + return false; +} + +bool SoundSystem::OnPlayerHealthPickup(const Events::PlayerHealthPickup & e) +{ + if (e.PlayerHealedID == m_LocalPlayer.ID) { + Events::PlaySoundOnEntity ev; + ev.EmitterID = createChildEmitter(m_LocalPlayer); + ev.FilePath = "Audio/pickup/pickup2.wav"; + m_EventBroker->Publish(ev); + } + return false; +} + +bool SoundSystem::OnTriggerTouch(const Events::TriggerTouch & e) +{ + if (m_World->HasComponent(e.Trigger.ID, "CapturePoint")) { + Events::PlayBackgroundMusic ev; + ev.FilePath = "Audio/bgm/drumstest.wav"; + m_EventBroker->Publish(ev); + } + return false; +} + +bool SoundSystem::OnDoubleJump(const Events::DoubleJump & e) +{ + Events::PlaySoundOnEntity ev; + ev.EmitterID = createChildEmitter(m_LocalPlayer); + ev.FilePath = "Audio/jump/jump2.wav"; + m_EventBroker->Publish(ev); + return false; +} + +bool SoundSystem::OnDashAbility(const Events::DashAbility &e) +{ + Events::PlaySoundOnEntity ev; + ev.EmitterID = createChildEmitter(m_LocalPlayer); + ev.FilePath = "Audio/jump/dash1.wav"; + m_EventBroker->Publish(ev); + return false; +} + +EntityID SoundSystem::createChildEmitter(EntityWrapper localPlayer) +{ + EntityID child = m_World->CreateEntity(localPlayer.ID); + m_World->AttachComponent(child, "Transform"); + m_World->AttachComponent(child, "SoundEmitter"); + return child; +} \ No newline at end of file From 11cf85cc7346f6e189e513c9204b3a79e07096b9 Mon Sep 17 00:00:00 2001 From: William Moberg Date: Mon, 8 Feb 2016 14:17:19 +0100 Subject: [PATCH 115/355] Renamed CollidableOctreeSystem to FillOctreeSystem. --- .../{CollidableOctreeSystem.h => FillOctreeSystem.h} | 6 +++--- .../{CollidableOctreeSystem.cpp => FillOctreeSystem.cpp} | 6 +++--- src/Game/Game.cpp | 6 +++--- 3 files changed, 9 insertions(+), 9 deletions(-) rename include/Engine/Collision/{CollidableOctreeSystem.h => FillOctreeSystem.h} (66%) rename src/Engine/Collision/{CollidableOctreeSystem.cpp => FillOctreeSystem.cpp} (64%) diff --git a/include/Engine/Collision/CollidableOctreeSystem.h b/include/Engine/Collision/FillOctreeSystem.h similarity index 66% rename from include/Engine/Collision/CollidableOctreeSystem.h rename to include/Engine/Collision/FillOctreeSystem.h index 0aa01d2e..9fd87b94 100644 --- a/include/Engine/Collision/CollidableOctreeSystem.h +++ b/include/Engine/Collision/FillOctreeSystem.h @@ -6,12 +6,12 @@ #include "Collision.h" #include "EntityAABB.h" -class CollidableOctreeSystem : public ImpureSystem, public PureSystem +class FillOctreeSystem : public ImpureSystem, public PureSystem { public: - CollidableOctreeSystem(World* world, EventBroker* eventBroker, Octree* octree, const std::string& componentType) + FillOctreeSystem(World* world, EventBroker* eventBroker, Octree* octree, const std::string& fillComponentType) : System(world, eventBroker) - , PureSystem(componentType) + , PureSystem(fillComponentType) , m_Octree(octree) { } diff --git a/src/Engine/Collision/CollidableOctreeSystem.cpp b/src/Engine/Collision/FillOctreeSystem.cpp similarity index 64% rename from src/Engine/Collision/CollidableOctreeSystem.cpp rename to src/Engine/Collision/FillOctreeSystem.cpp index 476414dd..d69319de 100644 --- a/src/Engine/Collision/CollidableOctreeSystem.cpp +++ b/src/Engine/Collision/FillOctreeSystem.cpp @@ -1,11 +1,11 @@ -#include "Collision/CollidableOctreeSystem.h" +#include "Collision/FillOctreeSystem.h" -void CollidableOctreeSystem::Update(double dt) +void FillOctreeSystem::Update(double dt) { m_Octree->ClearDynamicObjects(); } -void CollidableOctreeSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) +void FillOctreeSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) { if (entity.HasComponent("AABB")) { boost::optional absoluteAABB = Collision::EntityAbsoluteAABB(entity); diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index f5afcaeb..157ea5ab 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -1,5 +1,5 @@ #include "Game.h" -#include "Collision/CollidableOctreeSystem.h" +#include "Collision/FillOctreeSystem.h" #include "Collision/EntityAABB.h" #include "Collision/TriggerSystem.h" #include "Collision/CollisionSystem.h" @@ -93,8 +93,8 @@ Game::Game(int argc, char* argv[]) m_SystemPipeline->AddSystem(updateOrderLevel); // Populate Octree with collidables ++updateOrderLevel; - m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeCollision, "Collidable"); - m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeTrigger, "Player"); + m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeCollision, "Collidable"); + m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeTrigger, "Player"); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); From 8e86cc2123b72dd26f348b355a5f30217a19eaa6 Mon Sep 17 00:00:00 2001 From: stiffly Date: Mon, 8 Feb 2016 14:23:53 +0100 Subject: [PATCH 116/355] Walking sound logic moved to PlayerMovementSystem and makes use of "wishDirection" to alleviate the problem where m_DistanceMoved were reset when it was not supposed to. --- include/Game/Systems/PlayerMovementSystem.h | 14 ++++++++ include/Game/Systems/SoundSystem.h | 2 -- src/Game/Systems/PlayerMovementSystem.cpp | 40 ++++++++++++++++++++- src/Game/Systems/SoundSystem.cpp | 26 -------------- 4 files changed, 53 insertions(+), 29 deletions(-) diff --git a/include/Game/Systems/PlayerMovementSystem.h b/include/Game/Systems/PlayerMovementSystem.h index 395ccce5..defaa8ae 100644 --- a/include/Game/Systems/PlayerMovementSystem.h +++ b/include/Game/Systems/PlayerMovementSystem.h @@ -5,6 +5,7 @@ #include "Input/FirstPersonInputController.h" #include #include "Events/EDoubleJump.h" +#include "../Engine/Sound/EPlaySoundOnEntity.h" class PlayerMovementSystem : public ImpureSystem, PureSystem { @@ -19,6 +20,19 @@ private: // State std::unordered_map*> m_PlayerInputControllers; + EntityWrapper m_LocalPlayer = EntityWrapper::Invalid; + // Walking logic + // Keeps track of how far the player has walked within this "key press session". + float m_DistanceMoved = 0.0f; + // How far a step is (How often the step sound will be played). + const float m_PlayerStepLength = 1.75f; + // Determine what sound file to play. + bool m_LeftFoot = false; + // To get a difference when calculating the walking state. + glm::vec3 m_LastPosition = glm::vec3(); + // The logic for making the sound play when player is moving + void playerStep(double dt); + EventRelay m_EPlayerSpawned; bool OnPlayerSpawned(Events::PlayerSpawned& e); diff --git a/include/Game/Systems/SoundSystem.h b/include/Game/Systems/SoundSystem.h index b14d7486..4f0e7211 100644 --- a/include/Game/Systems/SoundSystem.h +++ b/include/Game/Systems/SoundSystem.h @@ -30,8 +30,6 @@ public: virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& cComponent, double dt) override; virtual void Update(double dt) override; private: - // The logic for making the sound play when player is moving - void playerStep(double dt); EntityWrapper m_LocalPlayer = EntityWrapper(); World* m_World = nullptr; diff --git a/src/Game/Systems/PlayerMovementSystem.cpp b/src/Game/Systems/PlayerMovementSystem.cpp index 3e4d9e76..c5c50a41 100644 --- a/src/Game/Systems/PlayerMovementSystem.cpp +++ b/src/Game/Systems/PlayerMovementSystem.cpp @@ -56,6 +56,12 @@ void PlayerMovementSystem::Update(double dt) } else { wishSpeed = playerMovementSpeed; } + if (player.ID == m_LocalPlayer.ID) { + if (glm::length(wishDirection) == 0) { + // If no key is pressed, reset the distance moved since last step. + m_DistanceMoved = 0; + } + } glm::vec3& velocity = cPhysics["Velocity"]; ImGui::Text("velocity: (%f, %f, %f)", velocity.x, velocity.y, velocity.z); glm::vec3 groundVelocity(0.f, 0.f, 0.f); @@ -135,6 +141,7 @@ void PlayerMovementSystem::Update(double dt) controller->Reset(); } + playerStep(dt); } void PlayerMovementSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) @@ -169,10 +176,41 @@ void PlayerMovementSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapp position += velocity * (float)dt; } +void PlayerMovementSystem::playerStep(double dt) +{ + if (!m_LocalPlayer.Valid()) { + return; + } + // Position of the local player, used see how far a player has moved. + glm::vec3 pos = (glm::vec3)m_World->GetComponent(m_LocalPlayer.ID, "Transform")["Position"]; + // Velocity of the local player, used to see if a player is airborne. + glm::vec3 vel = (glm::vec3)m_World->GetComponent(m_LocalPlayer.ID, "Physics")["Velocity"]; + m_DistanceMoved += glm::length(pos - m_LastPosition); + // Set the last position for next iteration + m_LastPosition = pos; + bool isAirborne = vel.y != 0; + if (m_DistanceMoved > m_PlayerStepLength && !isAirborne) { + // Player moved a step's distance + // Create footstep sound + Events::PlaySoundOnEntity e; + EntityID child = m_World->CreateEntity(m_LocalPlayer.ID); + m_World->AttachComponent(child, "Transform"); + m_World->AttachComponent(child, "SoundEmitter"); + e.EmitterID = child; + e.FilePath = m_LeftFoot ? "Audio/footstep/footstep2.wav" : "Audio/footstep/footstep3.wav"; + m_LeftFoot = !m_LeftFoot; + m_EventBroker->Publish(e); + m_DistanceMoved = 0.f; + } +} + bool PlayerMovementSystem::OnPlayerSpawned(Events::PlayerSpawned& e) { // When a player spawns, create an input controller for them m_PlayerInputControllers[e.Player] = new FirstPersonInputController(m_EventBroker, e.PlayerID); - + if (e.PlayerID == -1) { + // Keep track of the local player + m_LocalPlayer = e.Player; + } return true; } diff --git a/src/Game/Systems/SoundSystem.cpp b/src/Game/Systems/SoundSystem.cpp index 3f9b75d0..ac3ab2e9 100644 --- a/src/Game/Systems/SoundSystem.cpp +++ b/src/Game/Systems/SoundSystem.cpp @@ -25,32 +25,6 @@ void SoundSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& cComp void SoundSystem::Update(double dt) { - playerStep(dt); -} - -void SoundSystem::playerStep(double dt) -{ - if (!m_LocalPlayer.Valid()) { - return; - } - // Position of the local player, used see how far a player has moved. - glm::vec3 pos = (glm::vec3)m_World->GetComponent(m_LocalPlayer.ID, "Transform")["Position"]; - // Velocity of the local player, used to see if a player is airborne. - glm::vec3 vel = (glm::vec3)m_World->GetComponent(m_LocalPlayer.ID, "Physics")["Velocity"]; - m_DistanceMoved += glm::length(pos - m_LastPosition); - // Set the last position for next iteration - m_LastPosition = pos; - bool isAirborne = vel.y != 0; - if (m_DistanceMoved > m_PlayerStepLength && !isAirborne) { - // Player moved a step's distance - // Create footstep sound - Events::PlaySoundOnEntity e; - e.EmitterID = createChildEmitter(m_LocalPlayer); - e.FilePath = m_LeftFoot ? "Audio/footstep/footstep2.wav" : "Audio/footstep/footstep3.wav"; - m_LeftFoot = !m_LeftFoot; - m_EventBroker->Publish(e); - m_DistanceMoved = 0.f; - } } bool SoundSystem::OnPlayerSpawned(const Events::PlayerSpawned &e) From 14c5410524e12a5b0e97eb8cd5d766754a91495a Mon Sep 17 00:00:00 2001 From: stiffly Date: Mon, 8 Feb 2016 14:29:55 +0100 Subject: [PATCH 117/355] Merge fix --- src/Game/Systems/SoundSystem.cpp | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/src/Game/Systems/SoundSystem.cpp b/src/Game/Systems/SoundSystem.cpp index ac3ab2e9..555e7ff0 100644 --- a/src/Game/Systems/SoundSystem.cpp +++ b/src/Game/Systems/SoundSystem.cpp @@ -24,8 +24,7 @@ void SoundSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& cComp } void SoundSystem::Update(double dt) -{ -} +{ } bool SoundSystem::OnPlayerSpawned(const Events::PlayerSpawned &e) { @@ -129,23 +128,23 @@ bool SoundSystem::OnPlayerDamage(const Events::PlayerDamage & e) bool SoundSystem::OnPlayerDeath(const Events::PlayerDeath & e) { - if (e.PlayerID == m_LocalPlayer.ID) { - Events::PlaySoundOnEntity ev; - ev.EmitterID = createChildEmitter(m_LocalPlayer); - ev.FilePath = "Audio/die/die2.wav"; // should random between a bunch - m_EventBroker->Publish(ev); - } + //if (e.PlayerID == m_LocalPlayer.ID) { + Events::PlaySoundOnEntity ev; + ev.EmitterID = createChildEmitter(m_LocalPlayer); + ev.FilePath = "Audio/die/die2.wav"; // should random between a bunch + m_EventBroker->Publish(ev); + //} return false; } bool SoundSystem::OnPlayerHealthPickup(const Events::PlayerHealthPickup & e) { - if (e.PlayerHealedID == m_LocalPlayer.ID) { - Events::PlaySoundOnEntity ev; - ev.EmitterID = createChildEmitter(m_LocalPlayer); - ev.FilePath = "Audio/pickup/pickup2.wav"; - m_EventBroker->Publish(ev); - } + //if (e.PlayerHealedID == m_LocalPlayer.ID) { + Events::PlaySoundOnEntity ev; + ev.EmitterID = createChildEmitter(m_LocalPlayer); + ev.FilePath = "Audio/pickup/pickup2.wav"; + m_EventBroker->Publish(ev); + //} return false; } From ba9419b342918301fc1d521bd6ef9faa8b9fef69 Mon Sep 17 00:00:00 2001 From: Jocke Date: Mon, 8 Feb 2016 14:32:00 +0100 Subject: [PATCH 118/355] Moved UDP logic from Hybrid server/client to UDP server/client. fixed bug in Server::CheckForTimeOuts. --- include/Engine/Network/HybridClient.h | 16 +--- include/Engine/Network/HybridServer.h | 15 +--- include/Engine/Network/TCPClient.h | 3 +- include/Engine/Network/TCPServer.h | 6 +- include/Engine/Network/UDPClient.h | 24 +++++ include/Engine/Network/UDPServer.h | 25 ++++++ include/Game/Game.h | 5 ++ src/Engine/Network/Client.cpp | 3 +- src/Engine/Network/HybridClient.cpp | 66 +------------- src/Engine/Network/HybridServer.cpp | 117 +----------------------- src/Engine/Network/Server.cpp | 7 +- src/Engine/Network/TCPClient.cpp | 15 ++-- src/Engine/Network/TCPServer.cpp | 2 - src/Engine/Network/UDPClient.cpp | 66 ++++++++++++++ src/Engine/Network/UDPServer.cpp | 123 ++++++++++++++++++++++++++ src/Game/Game.cpp | 8 +- 16 files changed, 271 insertions(+), 230 deletions(-) create mode 100644 include/Engine/Network/UDPClient.h create mode 100644 include/Engine/Network/UDPServer.h create mode 100644 src/Engine/Network/UDPClient.cpp create mode 100644 src/Engine/Network/UDPServer.cpp diff --git a/include/Engine/Network/HybridClient.h b/include/Engine/Network/HybridClient.h index fb2777d4..8d96bf6e 100644 --- a/include/Engine/Network/HybridClient.h +++ b/include/Engine/Network/HybridClient.h @@ -1,25 +1,13 @@ #ifndef HybridClient_h__ #define HybridClient_h__ -#include "Client.h" - - -class HybridClient : public Client +class HybridClient { public: - HybridClient(ConfigFile* config); + HybridClient(); ~HybridClient(); - void Start(World* world, EventBroker* eventBroker); private: - // Assio UDP logic - boost::asio::ip::udp::endpoint m_ReceiverEndpoint; - boost::asio::io_service m_IOService; - boost::asio::ip::udp::socket m_Socket; - void connect(); - void readFromServer(); - int receive(char * data); - void send(Packet & packet); }; #endif \ No newline at end of file diff --git a/include/Engine/Network/HybridServer.h b/include/Engine/Network/HybridServer.h index f12dc660..48d6fe63 100644 --- a/include/Engine/Network/HybridServer.h +++ b/include/Engine/Network/HybridServer.h @@ -1,25 +1,12 @@ #ifndef HybridServer_h__ #define HybridServer_h__ -#include "Server.h" -#include - -class HybridServer : public Server +class HybridServer { public: HybridServer(); ~HybridServer(); private: - // UDP logic - boost::asio::io_service m_IOService; - std::unique_ptr m_Socket; - boost::asio::ip::udp::endpoint m_ReceiverEndpoint; - - void readFromClients(); - void parseConnect(Packet & packet); - void send(Packet & packet, PlayerDefinition & playerDefinition); - void send(Packet & packet); - int receive(char * data); }; #endif \ No newline at end of file diff --git a/include/Engine/Network/TCPClient.h b/include/Engine/Network/TCPClient.h index e90e049c..b16d541d 100644 --- a/include/Engine/Network/TCPClient.h +++ b/include/Engine/Network/TCPClient.h @@ -8,12 +8,11 @@ class TCPClient : public Client public: TCPClient(ConfigFile* config); ~TCPClient(); - void Start(World* world, EventBroker* eventBroker); private: // Assio TCP logic boost::asio::ip::tcp::endpoint m_Endpoint; boost::asio::io_service m_IOService; - boost::shared_ptr m_Socket; + std::unique_ptr m_Socket; void connect(); void readFromServer(); diff --git a/include/Engine/Network/TCPServer.h b/include/Engine/Network/TCPServer.h index 61e40639..6c52d10d 100644 --- a/include/Engine/Network/TCPServer.h +++ b/include/Engine/Network/TCPServer.h @@ -13,14 +13,14 @@ private: boost::asio::io_service m_IOService; std::unique_ptr acceptor; boost::shared_ptr lastReceivedSocket; - - void readFromClients(); + void acceptNewConnections(); void handle_accept(boost::shared_ptr socket, const boost::system::error_code & error); + void readFromClients(); + int receive(char * data, boost::asio::ip::tcp::socket& socket); void parseConnect(Packet & packet); void send(Packet & packet, PlayerDefinition & playerDefinition); void send(Packet & packet); - int receive(char * data, boost::asio::ip::tcp::socket& socket); }; #endif \ No newline at end of file diff --git a/include/Engine/Network/UDPClient.h b/include/Engine/Network/UDPClient.h new file mode 100644 index 00000000..abe34b3a --- /dev/null +++ b/include/Engine/Network/UDPClient.h @@ -0,0 +1,24 @@ +#ifndef UDPClient_h__ +#define UDPClient_h__ + +#include "Client.h" + + +class UDPClient : public Client +{ +public: + UDPClient(ConfigFile* config); + ~UDPClient(); +private: + // Assio UDP logic + boost::asio::io_service m_IOService; + boost::asio::ip::udp::endpoint m_ReceiverEndpoint; + boost::asio::ip::udp::socket m_Socket; + + void connect(); + void readFromServer(); + int receive(char * data); + void send(Packet & packet); +}; + +#endif \ No newline at end of file diff --git a/include/Engine/Network/UDPServer.h b/include/Engine/Network/UDPServer.h new file mode 100644 index 00000000..22c8c3e3 --- /dev/null +++ b/include/Engine/Network/UDPServer.h @@ -0,0 +1,25 @@ +#ifndef UDPServer_h__ +#define UDPServer_h__ + +#include "Server.h" +#include + +class UDPServer : public Server +{ +public: + UDPServer(); + ~UDPServer(); +private: + // UDP logic + boost::asio::io_service m_IOService; + boost::asio::ip::udp::endpoint m_ReceiverEndpoint; + std::unique_ptr m_Socket; + + void readFromClients(); + int receive(char * data); + void parseConnect(Packet & packet); + void send(Packet & packet, PlayerDefinition & playerDefinition); + void send(Packet & packet); +}; + +#endif \ No newline at end of file diff --git a/include/Game/Game.h b/include/Game/Game.h index 060f97f4..4faf6bbf 100644 --- a/include/Game/Game.h +++ b/include/Game/Game.h @@ -26,10 +26,15 @@ // Network #include #include "Network/Network.h" +// Hybrid #include "Network/HybridServer.h" #include "Network/HybridClient.h" +// TCP #include "Network/TCPClient.h" #include "Network/TCPServer.h" +// UDP +#include "Network/UDPServer.h" +#include "Network/UDPClient.h" // Sound #include "Sound/SoundSystem.h" diff --git a/src/Engine/Network/Client.cpp b/src/Engine/Network/Client.cpp index 13efad40..c7a8f0e6 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -17,7 +17,8 @@ Client::Client(ConfigFile* config) } Client::~Client() -{ } +{ +} void Client::Start(World* world, EventBroker* eventBroker) { diff --git a/src/Engine/Network/HybridClient.cpp b/src/Engine/Network/HybridClient.cpp index eabe109b..4200e8e3 100644 --- a/src/Engine/Network/HybridClient.cpp +++ b/src/Engine/Network/HybridClient.cpp @@ -1,72 +1,10 @@ #include "Network/HybridClient.h" -using namespace boost::asio::ip; -HybridClient::HybridClient(ConfigFile * config) : Client(config), m_Socket(m_IOService) -{ - m_ReceiverEndpoint = udp::endpoint(boost::asio::ip::address::from_string(address), port); +HybridClient::HybridClient() +{ } HybridClient::~HybridClient() -{ - -} - -void HybridClient::Start(World* world, EventBroker* eventBroker) -{ - Client::Start(world, eventBroker); - m_Socket.connect(m_ReceiverEndpoint); -} - -void HybridClient::readFromServer() { - while (m_Socket.available()) { - bytesRead = receive(readBuffer); - if (bytesRead > 0) { - Packet packet(readBuffer, bytesRead); - parseMessageType(packet); - } - } -} - -int HybridClient::receive(char* data) -{ - boost::system::error_code error; - - int bytesReceived = m_Socket.receive_from(boost - ::asio::buffer((void*)data, BUFFERSIZE), - m_ReceiverEndpoint, - 0, error); - // Network Debug data - if (isReadingData) { - m_NetworkData.TotalDataReceived += bytesReceived; - m_NetworkData.DataReceivedThisInterval += bytesReceived; - m_NetworkData.AmountOfMessagesReceived++; - } - if (error) { - //LOG_ERROR("receive: %s", error.message().c_str()); - } - return bytesReceived; -} - -void HybridClient::send(Packet& packet) -{ - m_Socket.send_to(boost::asio::buffer( - packet.Data(), - packet.Size()), - m_ReceiverEndpoint, 0); - // Network Debug data - if (isReadingData) { - m_NetworkData.TotalDataSent += packet.Size(); - m_NetworkData.DataSentThisInterval += packet.Size(); - m_NetworkData.AmountOfMessagesSent++; - } -} - -void HybridClient::connect() -{ - Packet packet(MessageType::Connect, m_SendPacketID); - packet.WriteString(m_PlayerName); - m_StartPingTime = std::clock(); - send(packet); } \ No newline at end of file diff --git a/src/Engine/Network/HybridServer.cpp b/src/Engine/Network/HybridServer.cpp index 6c22bab7..bfcdaee0 100644 --- a/src/Engine/Network/HybridServer.cpp +++ b/src/Engine/Network/HybridServer.cpp @@ -2,123 +2,8 @@ HybridServer::HybridServer() { - m_Socket = std::unique_ptr(new boost::asio::ip::udp::socket(m_IOService, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), 27666))); - } HybridServer::~HybridServer() -{ } - - -void HybridServer::readFromClients() { - while (m_Socket->available()) { - try { - bytesRead = receive(readBuffer); - m_Address = m_ReceiverEndpoint.address(); - m_Port = m_ReceiverEndpoint.port(); - Packet packet(readBuffer, bytesRead); - parseMessageType(packet); - } catch (const std::exception& err) { - //LOG_ERROR("%i: Read from client crashed %s", m_PacketID, err.what()); - } - } - std::clock_t currentTime = std::clock(); - // Send snapshot - if (snapshotInterval < (1000 * (currentTime - previousSnapshotMessage) / (double)CLOCKS_PER_SEC)) { - sendSnapshot(); - previousSnapshotMessage = currentTime; - } - - // Send pings each - if (pingIntervalMs < (1000 * (currentTime - previousePingMessage) / (double)CLOCKS_PER_SEC)) { - sendPing(); - previousePingMessage = currentTime; - } - - // Time out logic - if (checkTimeOutInterval < (1000 * (currentTime - timOutTimer) / (double)CLOCKS_PER_SEC)) { - checkForTimeOuts(); - timOutTimer = currentTime; - } -} - -void HybridServer::parseConnect(Packet& packet) -{ - LOG_INFO("Parsing connections"); - // Check if player is already connected - if (GetPlayerIDFromEndpoint() != -1) { - return; - } - // Create a new player - PlayerDefinition pd; - pd.EntityID = 0; // Overlook this - pd.Endpoint = m_ReceiverEndpoint; - pd.Address = m_ReceiverEndpoint.address(); - pd.Port = m_ReceiverEndpoint.port(); - pd.Name = packet.ReadString(); - pd.PacketID = 0; - pd.StopTime = std::clock(); - m_ConnectedPlayers[m_NextPlayerID++] = pd; - LOG_INFO("Spectator \"%s\" connected on IP: %s", pd.Name.c_str(), pd.Endpoint.address().to_string().c_str()); - - // Send a message to the player that connected - Packet connnectPacket(MessageType::Connect, pd.PacketID); - send(connnectPacket); - - // Send notification that a player has connected - Packet notificationPacket(MessageType::PlayerConnected); - broadcast(notificationPacket); -} - -void HybridServer::send(Packet& packet, PlayerDefinition & playerDefinition) -{ - try { - int bytesSent = m_Socket->send_to( - boost::asio::buffer(packet.Data(), packet.Size()), - playerDefinition.Endpoint, - 0); - // Network Debug data - if (isReadingData) { - m_NetworkData.TotalDataSent += packet.Size(); - m_NetworkData.DataSentThisInterval += packet.Size(); - m_NetworkData.AmountOfMessagesSent++; - } - } catch (const boost::system::system_error& e) { - // TODO: Clean up invalid endpoints out of m_ConnectedPlayers later - playerDefinition.Endpoint = boost::asio::ip::udp::endpoint(); - } -} -// Send back to endpoint of received packet -void HybridServer::send(Packet & packet) -{ - m_Socket->send_to( - boost::asio::buffer( - packet.Data(), - packet.Size()), - m_ReceiverEndpoint, - 0); - if (isReadingData) { - // Network Debug data - m_NetworkData.TotalDataSent += packet.Size(); - m_NetworkData.DataSentThisInterval += packet.Size(); - } -} - - -int HybridServer::receive(char * data) -{ - unsigned int length = m_Socket->receive_from( - boost::asio::buffer((void*)data - , BUFFERSIZE) - , m_ReceiverEndpoint, 0); - // Network Debug data - if (isReadingData) { - m_NetworkData.TotalDataReceived += length; - m_NetworkData.DataReceivedThisInterval += length; - m_NetworkData.AmountOfMessagesReceived++; - } - return length; -} - - +} \ No newline at end of file diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index 55f59a03..344efba6 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -9,7 +9,6 @@ Server::Server() } Server::~Server() { - } void Server::Start(World* world, EventBroker* eventBroker) { @@ -154,16 +153,20 @@ void Server::checkForTimeOuts() int startPing = 1000 * m_StartPingTime / static_cast(CLOCKS_PER_SEC); + std::vector playersToRemove; for (auto& kv : m_ConnectedPlayers) { if (kv.second.Address != boost::asio::ip::address()) { int stopPing = 1000 * kv.second.StopTime / static_cast(CLOCKS_PER_SEC); if (startPing > stopPing + m_TimeoutMs) { LOG_INFO("User %i timed out!", kv.second.Name); - disconnect(kv.first); + playersToRemove.push_back(kv.first); } } } + for (size_t i = 0; i < playersToRemove.size(); i++) { + disconnect(playersToRemove.at(i)); + } } void Server::parseDisconnect() diff --git a/src/Engine/Network/TCPClient.cpp b/src/Engine/Network/TCPClient.cpp index 3d7261b7..545db491 100644 --- a/src/Engine/Network/TCPClient.cpp +++ b/src/Engine/Network/TCPClient.cpp @@ -5,7 +5,7 @@ using namespace boost::asio::ip; TCPClient::TCPClient(ConfigFile * config) : Client(config) { m_Endpoint = tcp::endpoint(boost::asio::ip::address::from_string(address), port); - m_Socket = boost::shared_ptr(new tcp::socket(m_IOService, m_Endpoint)); + m_Socket = std::unique_ptr(new tcp::socket(m_IOService, m_Endpoint)); tcp::no_delay option(true); m_Socket->set_option(option); } @@ -15,10 +15,6 @@ TCPClient::~TCPClient() } -void TCPClient::Start(World * world, EventBroker * eventBroker) -{ - Client::Start(world, eventBroker); -} void TCPClient::connect() { if (!m_IsConnected) { @@ -34,7 +30,7 @@ void TCPClient::connect() } } } -// TODO FIX CRASH TCP CLIENT SEVER DISCONNECTS FIRST + void TCPClient::readFromServer() { while (m_Socket->available()) { @@ -50,14 +46,14 @@ int TCPClient::receive(char * data) // Read size of packet int bytesReceived = m_Socket->read_some(boost ::asio::buffer((void*)data, sizeof(int)), - error); + error); int sizeOfPacket = 0; memcpy(&sizeOfPacket, data, sizeof(int)); // Read the rest of the message bytesReceived += m_Socket->read_some(boost ::asio::buffer((void*)(data + bytesReceived), sizeOfPacket - bytesReceived), - error); + error); // Network Debug data if (isReadingData) { m_NetworkData.TotalDataReceived += bytesReceived; @@ -73,9 +69,10 @@ int TCPClient::receive(char * data) void TCPClient::send(Packet & packet) { packet.UpdateSize(); + boost::system::error_code error; m_Socket->send(boost::asio::buffer( packet.Data(), - packet.Size())); + packet.Size()), 0, error); // Network Debug data if (isReadingData) { m_NetworkData.TotalDataSent += packet.Size(); diff --git a/src/Engine/Network/TCPServer.cpp b/src/Engine/Network/TCPServer.cpp index caf37ee8..d523bf47 100644 --- a/src/Engine/Network/TCPServer.cpp +++ b/src/Engine/Network/TCPServer.cpp @@ -8,7 +8,6 @@ TCPServer::TCPServer() TCPServer::~TCPServer() { - } void TCPServer::readFromClients() @@ -135,7 +134,6 @@ void TCPServer::send(Packet & packet) } } -//boost::shared_ptr socket int TCPServer::receive(char * data, boost::asio::ip::tcp::socket& socket) { boost::system::error_code error; diff --git a/src/Engine/Network/UDPClient.cpp b/src/Engine/Network/UDPClient.cpp new file mode 100644 index 00000000..26e895d5 --- /dev/null +++ b/src/Engine/Network/UDPClient.cpp @@ -0,0 +1,66 @@ +#include "Network/UDPClient.h" + +using namespace boost::asio::ip; + +UDPClient::UDPClient(ConfigFile * config) : Client(config), m_Socket(m_IOService) +{ + m_ReceiverEndpoint = udp::endpoint(boost::asio::ip::address::from_string(address), port); + m_Socket.connect(m_ReceiverEndpoint); +} + +UDPClient::~UDPClient() +{ +} + +void UDPClient::readFromServer() +{ + while (m_Socket.available()) { + bytesRead = receive(readBuffer); + if (bytesRead > 0) { + Packet packet(readBuffer, bytesRead); + parseMessageType(packet); + } + } +} + +int UDPClient::receive(char* data) +{ + boost::system::error_code error; + + int bytesReceived = m_Socket.receive_from(boost + ::asio::buffer((void*)data, BUFFERSIZE), + m_ReceiverEndpoint, + 0, error); + // Network Debug data + if (isReadingData) { + m_NetworkData.TotalDataReceived += bytesReceived; + m_NetworkData.DataReceivedThisInterval += bytesReceived; + m_NetworkData.AmountOfMessagesReceived++; + } + if (error) { + //LOG_ERROR("receive: %s", error.message().c_str()); + } + return bytesReceived; +} + +void UDPClient::send(Packet& packet) +{ + m_Socket.send_to(boost::asio::buffer( + packet.Data(), + packet.Size()), + m_ReceiverEndpoint, 0); + // Network Debug data + if (isReadingData) { + m_NetworkData.TotalDataSent += packet.Size(); + m_NetworkData.DataSentThisInterval += packet.Size(); + m_NetworkData.AmountOfMessagesSent++; + } +} + +void UDPClient::connect() +{ + Packet packet(MessageType::Connect, m_SendPacketID); + packet.WriteString(m_PlayerName); + m_StartPingTime = std::clock(); + send(packet); +} \ No newline at end of file diff --git a/src/Engine/Network/UDPServer.cpp b/src/Engine/Network/UDPServer.cpp new file mode 100644 index 00000000..1e62c10a --- /dev/null +++ b/src/Engine/Network/UDPServer.cpp @@ -0,0 +1,123 @@ +#include "Network/UDPServer.h" + +UDPServer::UDPServer() +{ + m_Socket = std::unique_ptr(new boost::asio::ip::udp::socket(m_IOService, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), 27666))); +} + +UDPServer::~UDPServer() +{ +} + +void UDPServer::readFromClients() +{ + while (m_Socket->available()) { + try { + bytesRead = receive(readBuffer); + m_Address = m_ReceiverEndpoint.address(); + m_Port = m_ReceiverEndpoint.port(); + Packet packet(readBuffer, bytesRead); + parseMessageType(packet); + } catch (const std::exception& err) { + //LOG_ERROR("%i: Read from client crashed %s", m_PacketID, err.what()); + } + } + std::clock_t currentTime = std::clock(); + // Send snapshot + if (snapshotInterval < (1000 * (currentTime - previousSnapshotMessage) / (double)CLOCKS_PER_SEC)) { + sendSnapshot(); + previousSnapshotMessage = currentTime; + } + + // Send pings each + if (pingIntervalMs < (1000 * (currentTime - previousePingMessage) / (double)CLOCKS_PER_SEC)) { + sendPing(); + previousePingMessage = currentTime; + } + + // Time out logic + if (checkTimeOutInterval < (1000 * (currentTime - timOutTimer) / (double)CLOCKS_PER_SEC)) { + checkForTimeOuts(); + timOutTimer = currentTime; + } +} + +void UDPServer::parseConnect(Packet& packet) +{ + LOG_INFO("Parsing connections"); + // Check if player is already connected + if (GetPlayerIDFromEndpoint() != -1) { + return; + } + // Create a new player + PlayerDefinition pd; + pd.EntityID = 0; // Overlook this + pd.Endpoint = m_ReceiverEndpoint; + pd.Address = m_ReceiverEndpoint.address(); + pd.Port = m_ReceiverEndpoint.port(); + pd.Name = packet.ReadString(); + pd.PacketID = 0; + pd.StopTime = std::clock(); + m_ConnectedPlayers[m_NextPlayerID++] = pd; + LOG_INFO("Spectator \"%s\" connected on IP: %s", pd.Name.c_str(), pd.Endpoint.address().to_string().c_str()); + + // Send a message to the player that connected + Packet connnectPacket(MessageType::Connect, pd.PacketID); + send(connnectPacket); + + // Send notification that a player has connected + Packet notificationPacket(MessageType::PlayerConnected); + broadcast(notificationPacket); +} + +void UDPServer::send(Packet& packet, PlayerDefinition & playerDefinition) +{ + try { + int bytesSent = m_Socket->send_to( + boost::asio::buffer(packet.Data(), packet.Size()), + playerDefinition.Endpoint, + 0); + // Network Debug data + if (isReadingData) { + m_NetworkData.TotalDataSent += packet.Size(); + m_NetworkData.DataSentThisInterval += packet.Size(); + m_NetworkData.AmountOfMessagesSent++; + } + } catch (const boost::system::system_error& e) { + // TODO: Clean up invalid endpoints out of m_ConnectedPlayers later + playerDefinition.Endpoint = boost::asio::ip::udp::endpoint(); + } +} +// Send back to endpoint of received packet +void UDPServer::send(Packet & packet) +{ + m_Socket->send_to( + boost::asio::buffer( + packet.Data(), + packet.Size()), + m_ReceiverEndpoint, + 0); + if (isReadingData) { + // Network Debug data + m_NetworkData.TotalDataSent += packet.Size(); + m_NetworkData.DataSentThisInterval += packet.Size(); + } +} + + +int UDPServer::receive(char * data) +{ + unsigned int length = m_Socket->receive_from( + boost::asio::buffer((void*)data + , BUFFERSIZE) + , m_ReceiverEndpoint, 0); + // Network Debug data + if (isReadingData) { + m_NetworkData.TotalDataReceived += length; + m_NetworkData.DataReceivedThisInterval += length; + m_NetworkData.AmountOfMessagesReceived++; + } + return length; +} + + diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index a2bde7cb..ccbf79c9 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -181,13 +181,15 @@ void Game::networkFunction() bool isServer = m_Config->Get("Networking.IsServer", false); if (!isServer) { m_IsClientOrServer = true; + m_ClientOrServer = new UDPClient(m_Config); //m_ClientOrServer = new TCPClient(m_Config); - m_ClientOrServer = new HybridClient(m_Config); + //m_ClientOrServer = new HybridClient(m_Config); } if (isServer) { m_IsClientOrServer = true; - //m_ClientOrServer = new TCPServer(); - m_ClientOrServer = new HybridServer(); + m_ClientOrServer = new UDPServer(); + // m_ClientOrServer = new TCPServer(); + //m_ClientOrServer = new HybridServer(); } m_ClientOrServer->Start(m_World, m_EventBroker); From 93c6f3c0a35e0ff673e37f956b65a989770ce8af Mon Sep 17 00:00:00 2001 From: William Moberg Date: Mon, 8 Feb 2016 14:34:37 +0100 Subject: [PATCH 119/355] AABBs are auto attached when adding Trigger/Collideable/etc, also added AttachComponent method to ComponentWrapper. --- include/Engine/Collision/Collision.h | 2 ++ include/Engine/Core/EntityWrapper.h | 1 + resources/Schema/Entities/GameMap.xml | 3 +- src/Engine/Collision/Collision.cpp | 36 ++++++++++------------- src/Engine/Collision/FillOctreeSystem.cpp | 14 +++++---- src/Engine/Collision/TriggerSystem.cpp | 4 +++ src/Engine/Core/EntityWrapper.cpp | 9 ++++++ 7 files changed, 42 insertions(+), 27 deletions(-) diff --git a/include/Engine/Collision/Collision.h b/include/Engine/Collision/Collision.h index 6e4858b2..6d16e090 100644 --- a/include/Engine/Collision/Collision.h +++ b/include/Engine/Collision/Collision.h @@ -78,6 +78,8 @@ bool AABBVsAABB(const AABB& a, const AABB& b); //Also outputs the minimum translation that box [a] would need in order to resolve collision. bool AABBVsAABB(const AABB& a, const AABB& b, glm::vec3& minimumTranslation); +//Attaches an AABB which contains all vertices in the entitys Model. +bool AttachAABBComponentFromModel(EntityWrapper entity); // Calculates an absolute AABB from an entity AABB component boost::optional EntityAbsoluteAABB(EntityWrapper& entity); diff --git a/include/Engine/Core/EntityWrapper.h b/include/Engine/Core/EntityWrapper.h index bf34b9be..087471c0 100644 --- a/include/Engine/Core/EntityWrapper.h +++ b/include/Engine/Core/EntityWrapper.h @@ -25,6 +25,7 @@ struct EntityWrapper const std::string Name(); bool HasComponent(const std::string& componentType); + void AttachComponent(const char* componentName); EntityWrapper Parent(); EntityWrapper FirstChildByName(const std::string& name); EntityWrapper FirstParentWithComponent(const std::string& componentType); diff --git a/resources/Schema/Entities/GameMap.xml b/resources/Schema/Entities/GameMap.xml index 4d0a2716..90807eb5 100644 --- a/resources/Schema/Entities/GameMap.xml +++ b/resources/Schema/Entities/GameMap.xml @@ -9,7 +9,8 @@ - + + diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index fe4eb5e0..b150d667 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -564,33 +564,29 @@ bool AABBvsTriangles(const AABB& box, return hit; } -bool attachAABBComponentFromModel(World* world, EntityID id) +bool AttachAABBComponentFromModel(EntityWrapper entity) { - if (!world->HasComponent(id, "Model")) { + if (!entity.HasComponent("Model")) { return false; } - ComponentWrapper model = world->GetComponent(id, "Model"); - ComponentWrapper collision = world->AttachComponent(id, "AABB"); - Model* modelRes = ResourceManager::Load(model["Resource"]); - if (modelRes == nullptr) { + //Derive AABB from model + RawModel* model; + try { + model = ResourceManager::Load(entity["Model"]["Resource"]); + } catch (const std::exception&) { return false; } - glm::mat4 modelMatrix = modelRes->Matrix(); - - glm::vec3 mini = glm::vec3(INFINITY, INFINITY, INFINITY); - glm::vec3 maxi = glm::vec3(-INFINITY, -INFINITY, -INFINITY); - for (const auto& v : modelRes->Vertices()) { - const auto& wPos = modelMatrix * glm::vec4(v.Position.x, v.Position.y, v.Position.z, 1); - maxi.x = std::max(wPos.x, maxi.x); - maxi.y = std::max(wPos.y, maxi.y); - maxi.z = std::max(wPos.z, maxi.z); - mini.x = std::min(wPos.x, mini.x); - mini.y = std::min(wPos.y, mini.y); - mini.z = std::min(wPos.z, mini.z); + glm::vec3 mini(INFINITY); + glm::vec3 maxi(-INFINITY); + for (const auto& v : model->m_Vertices) { + mini = glm::min(mini, v.Position); + maxi = glm::max(maxi, v.Position); } - collision["Origin"] = 0.5f * (maxi + mini); - collision["Size"] = maxi - mini; + + entity.AttachComponent("AABB"); + entity["AABB"]["Origin"] = 0.5f * (maxi + mini); + entity["AABB"]["Size"] = maxi - mini; return true; } diff --git a/src/Engine/Collision/FillOctreeSystem.cpp b/src/Engine/Collision/FillOctreeSystem.cpp index d69319de..8c03b5c2 100644 --- a/src/Engine/Collision/FillOctreeSystem.cpp +++ b/src/Engine/Collision/FillOctreeSystem.cpp @@ -7,12 +7,14 @@ void FillOctreeSystem::Update(double dt) void FillOctreeSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) { - if (entity.HasComponent("AABB")) { - boost::optional absoluteAABB = Collision::EntityAbsoluteAABB(entity); - if (absoluteAABB) { - m_Octree->AddDynamicObject(*absoluteAABB); + if (!entity.HasComponent("AABB")) { + //Derive AABB from model. + if (!Collision::AttachAABBComponentFromModel(entity)) { + return; } - } else if (entity.HasComponent("Model")) { - // TODO: Derive AABB from model + } + boost::optional absoluteAABB = Collision::EntityAbsoluteAABB(entity); + if (absoluteAABB) { + m_Octree->AddDynamicObject(*absoluteAABB); } } \ No newline at end of file diff --git a/src/Engine/Collision/TriggerSystem.cpp b/src/Engine/Collision/TriggerSystem.cpp index 410a7fa1..adc778e5 100644 --- a/src/Engine/Collision/TriggerSystem.cpp +++ b/src/Engine/Collision/TriggerSystem.cpp @@ -6,6 +6,10 @@ void TriggerSystem::UpdateComponent(EntityWrapper& triggerEntity, ComponentWrapper& cTrigger, double dt) { // The trigger *should* have a bounding box, or something, to test against so it can be triggered. + // If it doesn't, add one as big as the model for now, then size can be modified in editor if necessary. + if (!triggerEntity.HasComponent("AABB")) { + Collision::AttachAABBComponentFromModel(triggerEntity); + } boost::optional triggerBox = Collision::EntityAbsoluteAABB(triggerEntity); if (!triggerBox) { return; diff --git a/src/Engine/Core/EntityWrapper.cpp b/src/Engine/Core/EntityWrapper.cpp index 071329a3..b0d08e66 100644 --- a/src/Engine/Core/EntityWrapper.cpp +++ b/src/Engine/Core/EntityWrapper.cpp @@ -16,6 +16,15 @@ bool EntityWrapper::HasComponent(const std::string& componentName) return World->HasComponent(ID, componentName); } +void EntityWrapper::AttachComponent(const char* componentName) +{ + if (!Valid()) { + LOG_WARNING("Could not attach \"%s\" component to #%i, component is not valid.", componentName, ID); + return; + } + World->AttachComponent(ID, componentName); +} + EntityWrapper EntityWrapper::Parent() { if (this->World == nullptr || this->ID == EntityID_Invalid) { From 9055d5f69798373bbfc6cac649a0bc5af89a152d Mon Sep 17 00:00:00 2001 From: Tleety Date: Mon, 8 Feb 2016 15:22:28 +0100 Subject: [PATCH 120/355] Bugfix --- src/Engine/Rendering/DrawFinalPass.cpp | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index 57eecd1a..72a65e80 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -106,6 +106,9 @@ void DrawFinalPass::Draw(RenderScene& scene) glClearStencil(0x00); glClear(GL_STENCIL_BUFFER_BIT); + //Fill depth buffer + + state->StencilMask(0x00); DrawModelRenderQueues(scene.Jobs.OpaqueObjects, scene); GLERROR("OpaqueObjects"); @@ -135,8 +138,8 @@ void DrawFinalPass::Draw(RenderScene& scene) DrawFinalPassState* stateLowRes = new DrawFinalPassState(m_FinalPassFrameBufferLowRes.GetHandle()); //Draw the lowres texture that will be shown behind the shield. - state->Enable(GL_SCISSOR_TEST); - state->Enable(GL_DEPTH_TEST); + stateLowRes->Enable(GL_SCISSOR_TEST); + stateLowRes->Enable(GL_DEPTH_TEST); //TODO: Viewports and scissor should be in state glViewport(0, 0, m_Renderer->GetViewportSize().Width/m_ShieldPixelRate, m_Renderer->GetViewportSize().Height/m_ShieldPixelRate); glScissor(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); @@ -145,23 +148,23 @@ void DrawFinalPass::Draw(RenderScene& scene) glClear(GL_STENCIL_BUFFER_BIT); //TODO: This should not be here... - state->StencilFunc(GL_ALWAYS, 1, 0xFF); - state->StencilMask(0x00); + stateLowRes->StencilFunc(GL_ALWAYS, 1, 0xFF); + stateLowRes->StencilMask(0x00); DrawToDepthBuffer(scene.Jobs.OpaqueObjects, scene); DrawToDepthBuffer(scene.Jobs.TransparentObjects, scene); //Draw shields to stencil pass - state->StencilFunc(GL_ALWAYS, 1, 0xFF); - state->StencilMask(0xFF); - state->Enable(GL_DEPTH_TEST); + stateLowRes->StencilFunc(GL_ALWAYS, 1, 0xFF); + stateLowRes->StencilMask(0xFF); + stateLowRes->Enable(GL_DEPTH_TEST); DrawShieldToStencilBuffer(scene.Jobs.ShieldObjects, scene); GLERROR("StencilPass"); glClear(GL_DEPTH_BUFFER_BIT); - state->Enable(GL_DEPTH_TEST); - state->StencilFunc(GL_LEQUAL, 1, 0xFF); - state->StencilMask(0x00); + stateLowRes->Enable(GL_DEPTH_TEST); + stateLowRes->StencilFunc(GL_LEQUAL, 1, 0xFF); + stateLowRes->StencilMask(0x00); DrawModelRenderQueues(scene.Jobs.OpaqueObjects, scene); GLERROR("OpaqueObjects"); DrawModelRenderQueues(scene.Jobs.TransparentObjects, scene); From 6f163bf3a3dfefc01924778989c14f6a74b08e54 Mon Sep 17 00:00:00 2001 From: stiffly Date: Mon, 8 Feb 2016 16:13:09 +0100 Subject: [PATCH 121/355] Fixed bug where it crashed on respawn. Also bug where i subscribed to an event twice. --- src/Engine/Sound/SoundManager.cpp | 16 ++++++++++++++++ src/Game/Systems/SoundSystem.cpp | 13 ++++++------- 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/src/Engine/Sound/SoundManager.cpp b/src/Engine/Sound/SoundManager.cpp index d75e9afc..b952426c 100644 --- a/src/Engine/Sound/SoundManager.cpp +++ b/src/Engine/Sound/SoundManager.cpp @@ -101,9 +101,17 @@ void SoundManager::updateEmitters(double dt) if (!m_World->ValidEntity(it->first)) { return; } + if (!m_World->HasComponent(it->first, "SoundEmitter")) + return; + glm::vec3 previousPos; alGetSource3f(it->second->ALsource, AL_POSITION, &previousPos.x, &previousPos.y, &previousPos.z); // Get next pos + if (!m_World->HasComponent(it->first, "Transform")) + return; + if (!m_World->ValidEntity(m_World->GetParent(it->first))) { + return; + } glm::vec3 nextPos = Transform::AbsolutePosition(m_World, it->first); // Calculate velocity glm::vec3 velocity = glm::vec3(nextPos - previousPos) / (float)dt; @@ -135,6 +143,10 @@ void SoundManager::updateListener(double dt) } for (auto it = listenerComponents->begin(); it != listenerComponents->end(); it++) { EntityWrapper listener(m_World, (*it).EntityID); + if (!listener.Valid()) + { + break; + } if (listener.IsChildOf(m_LocalPlayer) || listener == m_LocalPlayer) { glm::vec3 previousPos; alGetListener3f(AL_POSITION, &previousPos.x, &previousPos.y, &previousPos.z); // Get previous pos @@ -228,7 +240,11 @@ bool SoundManager::OnContinueSound(const Events::ContinueSound & e) bool SoundManager::OnPlayBackgroundMusic(const Events::PlayBackgroundMusic & e) { auto listenerComponents = m_World->GetComponents("Listener"); + LOG_INFO("SIZZE: %i", listenerComponents->size()); for (auto it = listenerComponents->begin(); it != listenerComponents->end(); it++) { + if((*it).EntityID != m_LocalPlayer.ID) { + break; + } auto emitterChild = m_World->CreateEntity((*it).EntityID); auto emitter = m_World->AttachComponent(emitterChild, "SoundEmitter"); (bool&)emitter["Loop"] = false; diff --git a/src/Game/Systems/SoundSystem.cpp b/src/Game/Systems/SoundSystem.cpp index 555e7ff0..8315160c 100644 --- a/src/Game/Systems/SoundSystem.cpp +++ b/src/Game/Systems/SoundSystem.cpp @@ -3,7 +3,7 @@ SoundSystem::SoundSystem(World* world, EventBroker* eventbroker) : System(world, eventbroker) , PureSystem("SoundEmitter") - , ImpureSystem() + //, ImpureSystem() { m_World = world; m_EventBroker = eventbroker; @@ -12,7 +12,6 @@ SoundSystem::SoundSystem(World* world, EventBroker* eventbroker) EVENT_SUBSCRIBE_MEMBER(m_EDoubleJump, &SoundSystem::OnDoubleJump); EVENT_SUBSCRIBE_MEMBER(m_EDashAbility, &SoundSystem::OnDashAbility); EVENT_SUBSCRIBE_MEMBER(m_EShoot, &SoundSystem::OnShoot); - EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &SoundSystem::OnPlayerSpawned); EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &SoundSystem::OnPlayerDamage); EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &SoundSystem::OnCaptured); EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &SoundSystem::OnTriggerTouch); @@ -31,10 +30,10 @@ bool SoundSystem::OnPlayerSpawned(const Events::PlayerSpawned &e) if (e.PlayerID == -1) { // Local player m_World->AttachComponent(e.Player.ID, "Listener"); m_LocalPlayer = e.Player; - Events::PlaySoundOnEntity event; - event.EmitterID = createChildEmitter(m_LocalPlayer); - event.FilePath = "Audio/announcer/go.wav"; - m_EventBroker->Publish(event); + Events::PlaySoundOnEntity go; + go.EmitterID = createChildEmitter(m_LocalPlayer); + go.FilePath = "Audio/announcer/go.wav"; + m_EventBroker->Publish(go); // TEMP: starts bgm { Events::PlayBackgroundMusic ev; @@ -131,7 +130,7 @@ bool SoundSystem::OnPlayerDeath(const Events::PlayerDeath & e) //if (e.PlayerID == m_LocalPlayer.ID) { Events::PlaySoundOnEntity ev; ev.EmitterID = createChildEmitter(m_LocalPlayer); - ev.FilePath = "Audio/die/die2.wav"; // should random between a bunch + ev.FilePath = "Audio/die/die2.wav"; m_EventBroker->Publish(ev); //} return false; From 7752832ce54a8851a2e9bd0096ccad3bbf8190f6 Mon Sep 17 00:00:00 2001 From: stiffly Date: Mon, 8 Feb 2016 16:21:49 +0100 Subject: [PATCH 122/355] No longer needs this walk logic in SoundSystem --- include/Game/Systems/SoundSystem.h | 12 +----------- src/Game/Systems/SoundSystem.cpp | 11 +---------- 2 files changed, 2 insertions(+), 21 deletions(-) diff --git a/include/Game/Systems/SoundSystem.h b/include/Game/Systems/SoundSystem.h index 4f0e7211..c69f7296 100644 --- a/include/Game/Systems/SoundSystem.h +++ b/include/Game/Systems/SoundSystem.h @@ -39,17 +39,7 @@ private: void playerJumps(); // Helper function EntityID createChildEmitter(EntityWrapper parent); - - // Walking logic - // Keeps track of how far the player has walked within this "key press session". - float m_DistanceMoved = 0.0f; - // How far a step is (How often the step sound will be played). - const float m_PlayerStepLength = 1.75f; - // To get a difference when calculating the walking state. - glm::vec3 m_LastPosition = glm::vec3(); - // Determine what sound file to play. - bool m_LeftFoot = false; - + std::default_random_engine generator; EventRelay m_EPlayerSpawned; diff --git a/src/Game/Systems/SoundSystem.cpp b/src/Game/Systems/SoundSystem.cpp index 8315160c..b218e6c1 100644 --- a/src/Game/Systems/SoundSystem.cpp +++ b/src/Game/Systems/SoundSystem.cpp @@ -18,9 +18,7 @@ SoundSystem::SoundSystem(World* world, EventBroker* eventbroker) } void SoundSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& cComponent, double dt) -{ - -} +{ } void SoundSystem::Update(double dt) { } @@ -52,13 +50,6 @@ bool SoundSystem::OnInputCommand(const Events::InputCommand & e) return true; } } - if (e.Command == "Forward" || e.Command == "Right") { - if (e.Value == 0) { - // Key released - // Reset the distance moved (player walk logic) - m_DistanceMoved = 0.f; - } - } if (e.Command == "TakeDamage" && e.Value > 0) { Events::PlayerDamage ev; ev.Player = m_LocalPlayer; From aa5878d6dfe8453a69c0e287c11cae53cfa7abb0 Mon Sep 17 00:00:00 2001 From: stiffly Date: Mon, 8 Feb 2016 16:40:13 +0100 Subject: [PATCH 123/355] Used config for soundsystem properties. --- assets | 2 +- include/Engine/Sound/SoundManager.h | 2 ++ include/Game/Systems/SoundSystem.h | 2 ++ resources/DefaultConfig.ini | 5 +++++ src/Engine/Sound/SoundManager.cpp | 4 +++- src/Game/Systems/SoundSystem.cpp | 8 +++++--- 6 files changed, 18 insertions(+), 5 deletions(-) diff --git a/assets b/assets index cfeeb1f8..88b1b9f0 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit cfeeb1f880e19356477a703da92204eede09db5d +Subproject commit 88b1b9f047c2cf02c1d39da39dff472cadfb93e7 diff --git a/include/Engine/Sound/SoundManager.h b/include/Engine/Sound/SoundManager.h index 3923a17b..2c07578c 100644 --- a/include/Engine/Sound/SoundManager.h +++ b/include/Engine/Sound/SoundManager.h @@ -13,6 +13,8 @@ #include "Core/World.h" #include "Core/EventBroker.h" +#include "../Engine/Core/ResourceManager.h" +#include "../Engine/Core/ConfigFile.h" #include "Core/Transform.h" // Absolute transform #include "Sound/Sound.h" #include "../Engine/Sound/EPlayQueueOnEntity.h" diff --git a/include/Game/Systems/SoundSystem.h b/include/Game/Systems/SoundSystem.h index c69f7296..0f7f5102 100644 --- a/include/Game/Systems/SoundSystem.h +++ b/include/Game/Systems/SoundSystem.h @@ -5,6 +5,7 @@ #include "../Engine/Core/System.h" #include "../Engine/Core/ResourceManager.h" +#include "../Engine/Core/ConfigFile.h" #include "../Engine/Sound/Sound.h" #include "../Engine/Sound/EPlayQueueOnEntity.h" #include "../Engine/Core/EPlayerSpawned.h" @@ -34,6 +35,7 @@ private: World* m_World = nullptr; EventBroker* m_EventBroker = nullptr; + std::string m_Announcer = ""; // Logic for playing a sound when a player jumps void playerJumps(); diff --git a/resources/DefaultConfig.ini b/resources/DefaultConfig.ini index 86dc735c..12ec06c8 100644 --- a/resources/DefaultConfig.ini +++ b/resources/DefaultConfig.ini @@ -29,3 +29,8 @@ TimeoutMs=15000 [Multithreading] ResourceLoading=true + +[Sound] +BGMVolume=1.0 +SFXVolume=1.0 +Announcer=female \ No newline at end of file diff --git a/src/Engine/Sound/SoundManager.cpp b/src/Engine/Sound/SoundManager.cpp index b952426c..972a38bb 100644 --- a/src/Engine/Sound/SoundManager.cpp +++ b/src/Engine/Sound/SoundManager.cpp @@ -2,12 +2,14 @@ SoundManager::SoundManager(World* world, EventBroker* eventBroker, bool editorMode) { + ConfigFile* config = ResourceManager::Load("Config.ini"); m_EventBroker = eventBroker; m_World = world; m_EditorEnabled = editorMode; + m_BGMVolumeChannel = config->Get("Sound.BGMVolume", 1.f); + m_SFXVolumeChannel = config->Get("Sound.SFXVolume", 1.f); initOpenAL(); - alSpeedOfSound(340.29f); alDistanceModel(AL_LINEAR_DISTANCE); alDopplerFactor(1); diff --git a/src/Game/Systems/SoundSystem.cpp b/src/Game/Systems/SoundSystem.cpp index b218e6c1..06e7d67a 100644 --- a/src/Game/Systems/SoundSystem.cpp +++ b/src/Game/Systems/SoundSystem.cpp @@ -5,6 +5,8 @@ SoundSystem::SoundSystem(World* world, EventBroker* eventbroker) , PureSystem("SoundEmitter") //, ImpureSystem() { + ConfigFile* config = ResourceManager::Load("Config.ini"); + m_Announcer = ResourceManager::Load("Config.ini")->Get("Sound.Announcer", "female"); m_World = world; m_EventBroker = eventbroker; EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &SoundSystem::OnPlayerSpawned); @@ -30,7 +32,7 @@ bool SoundSystem::OnPlayerSpawned(const Events::PlayerSpawned &e) m_LocalPlayer = e.Player; Events::PlaySoundOnEntity go; go.EmitterID = createChildEmitter(m_LocalPlayer); - go.FilePath = "Audio/announcer/go.wav"; + go.FilePath = "Audio/announcer/" + m_Announcer + "/go.wav"; m_EventBroker->Publish(go); // TEMP: starts bgm { @@ -86,9 +88,9 @@ bool SoundSystem::OnCaptured(const Events::Captured & e) int team = (int)m_World->GetComponent(m_LocalPlayer.ID, "Team")["Team"]; Events::PlaySoundOnEntity ev; if (team == homeTeam) { - ev.FilePath = "Audio/announcer/objective_achieved.wav"; + ev.FilePath = "Audio/announcer/" + m_Announcer + "/objective_achieved.wav"; } else { - ev.FilePath = "Audio/announcer/objective_failed.wav"; // have not been tested + ev.FilePath = "Audio/announcer/" + m_Announcer + "/objective_failed.wav"; // have not been tested } ev.EmitterID = createChildEmitter(m_LocalPlayer); m_EventBroker->Publish(ev); From 2c64ffc3d11782a0bccb0245fc1b18b91d2b00ad Mon Sep 17 00:00:00 2001 From: stiffly Date: Mon, 8 Feb 2016 16:52:35 +0100 Subject: [PATCH 124/355] No longer using a variable to see if we're in editor mode. --- include/Engine/Sound/SoundManager.h | 3 +-- src/Engine/Sound/SoundManager.cpp | 26 ++++++++++---------------- src/Game/Game.cpp | 2 +- 3 files changed, 12 insertions(+), 19 deletions(-) diff --git a/include/Engine/Sound/SoundManager.h b/include/Engine/Sound/SoundManager.h index 2c07578c..38ec62ff 100644 --- a/include/Engine/Sound/SoundManager.h +++ b/include/Engine/Sound/SoundManager.h @@ -49,7 +49,7 @@ class SoundManager { public: SoundManager() { } - SoundManager(World* world, EventBroker* eventBroker, bool editorMode); + SoundManager(World* world, EventBroker* eventBroker); ~SoundManager(); // Update emitters / listener void Update(double dt); @@ -93,7 +93,6 @@ private: float m_BGMVolumeChannel = 1.0f; float m_SFXVolumeChannel = 1.0f; - bool m_EditorEnabled = false; EntityWrapper m_LocalPlayer = EntityWrapper(); // Events diff --git a/src/Engine/Sound/SoundManager.cpp b/src/Engine/Sound/SoundManager.cpp index 972a38bb..8ba6a502 100644 --- a/src/Engine/Sound/SoundManager.cpp +++ b/src/Engine/Sound/SoundManager.cpp @@ -1,11 +1,10 @@ #include "Sound/SoundManager.h" -SoundManager::SoundManager(World* world, EventBroker* eventBroker, bool editorMode) +SoundManager::SoundManager(World* world, EventBroker* eventBroker) { ConfigFile* config = ResourceManager::Load("Config.ini"); m_EventBroker = eventBroker; m_World = world; - m_EditorEnabled = editorMode; m_BGMVolumeChannel = config->Get("Sound.BGMVolume", 1.f); m_SFXVolumeChannel = config->Get("Sound.SFXVolume", 1.f); @@ -103,9 +102,9 @@ void SoundManager::updateEmitters(double dt) if (!m_World->ValidEntity(it->first)) { return; } - if (!m_World->HasComponent(it->first, "SoundEmitter")) + if (!m_World->HasComponent(it->first, "SoundEmitter")) return; - + glm::vec3 previousPos; alGetSource3f(it->second->ALsource, AL_POSITION, &previousPos.x, &previousPos.y, &previousPos.z); // Get next pos @@ -123,14 +122,11 @@ void SoundManager::updateEmitters(double dt) auto emitter = m_World->GetComponent(it->first, "SoundEmitter"); setSoundProperties(it->second, &emitter); - // To make an emitter play when spawned in editor mode - if (m_EditorEnabled) { - // Path changed - if (it->second->SoundResource->Path() != (std::string)emitter["FilePath"]) { - it->second->SoundResource = ResourceManager::Load((std::string)emitter["FilePath"]); - if (it->second->SoundResource->Buffer() != 0) { - playSound(it->second); - } + // Path changed + if (it->second->SoundResource->Path() != (std::string)emitter["FilePath"]) { + it->second->SoundResource = ResourceManager::Load((std::string)emitter["FilePath"]); + if (it->second->SoundResource->Buffer() != 0) { + playSound(it->second); } } } @@ -145,8 +141,7 @@ void SoundManager::updateListener(double dt) } for (auto it = listenerComponents->begin(); it != listenerComponents->end(); it++) { EntityWrapper listener(m_World, (*it).EntityID); - if (!listener.Valid()) - { + if (!listener.Valid()) { break; } if (listener.IsChildOf(m_LocalPlayer) || listener == m_LocalPlayer) { @@ -242,9 +237,8 @@ bool SoundManager::OnContinueSound(const Events::ContinueSound & e) bool SoundManager::OnPlayBackgroundMusic(const Events::PlayBackgroundMusic & e) { auto listenerComponents = m_World->GetComponents("Listener"); - LOG_INFO("SIZZE: %i", listenerComponents->size()); for (auto it = listenerComponents->begin(); it != listenerComponents->end(); it++) { - if((*it).EntityID != m_LocalPlayer.ID) { + if ((*it).EntityID != m_LocalPlayer.ID) { break; } auto emitterChild = m_World->CreateEntity((*it).EntityID); diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index 6c495272..37eb2ea6 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -74,7 +74,7 @@ Game::Game(int argc, char* argv[]) } // Create the sound manager - m_SoundManager = new SoundManager(m_World, m_EventBroker, true); + m_SoundManager = new SoundManager(m_World, m_EventBroker); // Create Octrees m_OctreeCollision = new Octree(AABB(glm::vec3(-100), glm::vec3(100)), 4); From 060e674a6f45ddd547a53ee7a53270ae5c06547a Mon Sep 17 00:00:00 2001 From: Teejoon Date: Mon, 8 Feb 2016 17:37:18 +0100 Subject: [PATCH 125/355] Picking supports skinned meshes --- assets | 2 +- include/Engine/Rendering/PickingPass.h | 1 + resources/Schema/Entities/AnimatedArmy.xml | 10 +- resources/Schema/Entities/AssetPedistal.xml | 2 +- resources/Schema/Entities/CapturePoint.xml | 2 +- resources/Schema/Entities/CaptureTest.xml | 14 +-- .../Schema/Entities/CaptureTestState1.xml | 14 +-- .../Schema/Entities/CaptureTestState2.xml | 14 +-- .../Schema/Entities/CaptureTestState3.xml | 20 ++-- .../Schema/Entities/CaptureTestState4.xml | 20 ++-- .../Schema/Entities/CaptureTestState5.xml | 16 +-- .../Schema/Entities/CollisionTestLevel.xml | 4 +- resources/Schema/Entities/EditorTestWorld.xml | 22 ++-- .../Schema/Entities/EditorWidgetRotate.xml | 6 +- .../Schema/Entities/EditorWidgetScale.xml | 8 +- .../Schema/Entities/EditorWidgetTranslate.xml | 14 +-- resources/Schema/Entities/GameMap.xml | 4 +- resources/Schema/Entities/Model.xml | 2 +- resources/Schema/Entities/MovementTest.xml | 16 +-- resources/Schema/Entities/Player.xml | 13 +-- .../Schema/Entities/QualityAssurance.xml | 64 +++++------ resources/Schema/Entities/RayBlue.xml | 2 +- resources/Schema/Entities/RayRed.xml | 2 +- resources/Schema/Entities/RenderingWorld.xml | 10 +- resources/Schema/Entities/ShootEventTest.xml | 20 ++-- .../Entities/SpawnPointClusterWithModels.xml | 8 +- .../Entities/SpawnerWithPlayerModel.xml | 2 +- resources/Schema/Entities/Test.xml | 4 +- .../Shaders/ForwardPlusSkinned.vert.glsl | 2 +- resources/Shaders/Picking.vert.glsl | 15 +-- resources/Shaders/PickingSkinned.vert.glsl | 32 ++++++ src/Engine/Rendering/PickingPass.cpp | 104 +++++++++++++----- tools/MayaExporter/MayaExporter.opensdf | Bin 38 -> 0 bytes tools/MayaExporter/MayaExporter/Mesh.cpp | 38 +++---- 34 files changed, 281 insertions(+), 226 deletions(-) create mode 100644 resources/Shaders/PickingSkinned.vert.glsl delete mode 100644 tools/MayaExporter/MayaExporter.opensdf diff --git a/assets b/assets index c4898d82..2151ad93 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit c4898d8281b5584d89b1caf14dab8e5fac120321 +Subproject commit 2151ad934d2ff3f779ae7e4b38c20bbb728cd02d diff --git a/include/Engine/Rendering/PickingPass.h b/include/Engine/Rendering/PickingPass.h index da3ed31b..2ce2e78d 100644 --- a/include/Engine/Rendering/PickingPass.h +++ b/include/Engine/Rendering/PickingPass.h @@ -40,6 +40,7 @@ private: const IRenderer* m_Renderer; ShaderProgram* m_PickingProgram; + ShaderProgram* m_PickingSkinnedProgram; Camera* m_Camera; struct PickingInfo diff --git a/resources/Schema/Entities/AnimatedArmy.xml b/resources/Schema/Entities/AnimatedArmy.xml index b711a0fe..ee1e45b3 100644 --- a/resources/Schema/Entities/AnimatedArmy.xml +++ b/resources/Schema/Entities/AnimatedArmy.xml @@ -20,7 +20,7 @@ - models/dummyscene.mesh + Models/Test/DummyScene.mesh @@ -31,7 +31,7 @@ - models/animtest. + Models/Test/AnimTest.mesh @@ -42,7 +42,7 @@ - models/animTest.mesh + Models/Test/AnimTest.mesh @@ -53,7 +53,7 @@ - models/animTest.mesh + Models/Test/AnimTest.mesh @@ -64,7 +64,7 @@ - models/animTest.mesh + Models/Test/AnimTest.mesh diff --git a/resources/Schema/Entities/AssetPedistal.xml b/resources/Schema/Entities/AssetPedistal.xml index 728a3028..3c816149 100644 --- a/resources/Schema/Entities/AssetPedistal.xml +++ b/resources/Schema/Entities/AssetPedistal.xml @@ -35,7 +35,7 @@ - Models/AssaultWeaponBlue.mesh + Models/Weapons/Blue/AssaultWeaponBlue.mesh diff --git a/resources/Schema/Entities/CapturePoint.xml b/resources/Schema/Entities/CapturePoint.xml index 9b3c5036..9f33c4de 100644 --- a/resources/Schema/Entities/CapturePoint.xml +++ b/resources/Schema/Entities/CapturePoint.xml @@ -5,7 +5,7 @@ - C:\Users\123456\Workspace\TacticalZ\assets\Models\Core\UnitSphere.mesh + Models/Core/UnitSphere.mesh diff --git a/resources/Schema/Entities/CaptureTest.xml b/resources/Schema/Entities/CaptureTest.xml index 5f657e51..3d678bd7 100644 --- a/resources/Schema/Entities/CaptureTest.xml +++ b/resources/Schema/Entities/CaptureTest.xml @@ -9,7 +9,7 @@ - ../assets/Models/DummyScene.mesh + Models/Test/DummyScene.mesh @@ -41,7 +41,7 @@ 3 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -61,7 +61,7 @@ 1 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -81,7 +81,7 @@ 2 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -102,7 +102,7 @@ 3 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -120,7 +120,7 @@ - ../assets/Models/Core/UnitCube.mesh + Models/Core/UnitCube.mesh @@ -138,7 +138,7 @@ - ../assets/Models/Core/UnitCube.mesh + Models/Core/UnitCube.mesh diff --git a/resources/Schema/Entities/CaptureTestState1.xml b/resources/Schema/Entities/CaptureTestState1.xml index ffabd5c2..64999074 100644 --- a/resources/Schema/Entities/CaptureTestState1.xml +++ b/resources/Schema/Entities/CaptureTestState1.xml @@ -9,7 +9,7 @@ - ../assets/Models/DummyScene.mesh + Models/Test/DummyScene.mesh @@ -42,7 +42,7 @@ 6.9158446328696002 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -63,7 +63,7 @@ 1 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -83,7 +83,7 @@ 2 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -104,7 +104,7 @@ 3 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -122,7 +122,7 @@ - ../assets/Models/Core/UnitCube.mesh + Models/Core/UnitCube.mesh @@ -140,7 +140,7 @@ - ../assets/Models/Core/UnitCube.mesh + Models/Core/UnitCube.mesh diff --git a/resources/Schema/Entities/CaptureTestState2.xml b/resources/Schema/Entities/CaptureTestState2.xml index 29abdfbd..6ddb306f 100644 --- a/resources/Schema/Entities/CaptureTestState2.xml +++ b/resources/Schema/Entities/CaptureTestState2.xml @@ -9,7 +9,7 @@ - ../assets/Models/DummyScene.mesh + Models/Test/DummyScene.mesh @@ -41,7 +41,7 @@ 3 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -61,7 +61,7 @@ 1 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -79,7 +79,7 @@ 2 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -98,7 +98,7 @@ 3 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -116,7 +116,7 @@ - ../assets/Models/Core/UnitCube.mesh + Models/Core/UnitCube.mesh @@ -134,7 +134,7 @@ - ../assets/Models/Core/UnitCube.mesh + Models/Core/UnitCube.mesh diff --git a/resources/Schema/Entities/CaptureTestState3.xml b/resources/Schema/Entities/CaptureTestState3.xml index ff875dc4..3bed3624 100644 --- a/resources/Schema/Entities/CaptureTestState3.xml +++ b/resources/Schema/Entities/CaptureTestState3.xml @@ -9,7 +9,7 @@ - ../assets/Models/DummyScene.mesh + Models/Test/DummyScene.mesh @@ -41,7 +41,7 @@ 3 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -61,7 +61,7 @@ 1 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -81,7 +81,7 @@ 2 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -101,7 +101,7 @@ 3 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -122,7 +122,7 @@ 4 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -140,7 +140,7 @@ - ../assets/Models/Core/UnitCube.mesh + Models/Core/UnitCube.mesh @@ -158,7 +158,7 @@ - ../assets/Models/Core/UnitCube.mesh + Models/Core/UnitCube.mesh @@ -176,7 +176,7 @@ - ../assets/Models/Core/UnitCube.mesh + Models/Core/UnitCube.mesh @@ -194,7 +194,7 @@ - ../assets/Models/Core/UnitCube.mesh + Models/Core/UnitCube.mesh diff --git a/resources/Schema/Entities/CaptureTestState4.xml b/resources/Schema/Entities/CaptureTestState4.xml index 740d7e7b..30db23aa 100644 --- a/resources/Schema/Entities/CaptureTestState4.xml +++ b/resources/Schema/Entities/CaptureTestState4.xml @@ -9,7 +9,7 @@ - ../assets/Models/DummyScene.mesh + Models/Test/DummyScene.mesh @@ -41,7 +41,7 @@ 3 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -61,7 +61,7 @@ 1 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -79,7 +79,7 @@ 2 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -96,7 +96,7 @@ 3 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -115,7 +115,7 @@ 4 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -133,7 +133,7 @@ - ../assets/Models/Core/UnitCube.mesh + Models/Core/UnitCube.mesh @@ -151,7 +151,7 @@ - ../assets/Models/Core/UnitCube.mesh + Models/Core/UnitCube.mesh @@ -169,7 +169,7 @@ - ../assets/Models/Core/UnitCube.mesh + Models/Core/UnitCube.mesh @@ -187,7 +187,7 @@ - ../assets/Models/Core/UnitCube.mesh + Models/Core/UnitCube.mesh diff --git a/resources/Schema/Entities/CaptureTestState5.xml b/resources/Schema/Entities/CaptureTestState5.xml index f1b07a7b..8fe85068 100644 --- a/resources/Schema/Entities/CaptureTestState5.xml +++ b/resources/Schema/Entities/CaptureTestState5.xml @@ -17,7 +17,7 @@ - C:\Users\123456\Workspace\TacticalZ\assets\Models\Core\UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -39,7 +39,7 @@ 1 - C:\Users\123456\Workspace\TacticalZ\assets\Models\Core\UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -57,7 +57,7 @@ 2 - C:\Users\123456\Workspace\TacticalZ\assets\Models\Core\UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -79,7 +79,7 @@ 3 - C:\Users\123456\Workspace\TacticalZ\assets\Models\Core\UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -104,7 +104,7 @@ 4 - C:\Users\123456\Workspace\TacticalZ\assets\Models\Core\UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -124,7 +124,7 @@ - C:\Users\123456\Workspace\TacticalZ\assets\Models\Core\UnitCube.mesh + Models/Core/UnitCube.mesh @@ -143,7 +143,7 @@ - C:\Users\123456\Workspace\TacticalZ\assets\Models\Core\UnitCube.mesh + Models/Core/UnitCube.mesh @@ -160,7 +160,7 @@ - C:\Users\123456\Workspace\TacticalZ\assets\Models\DummyScene.mesh + Models/Test/DummyScene.mesh diff --git a/resources/Schema/Entities/CollisionTestLevel.xml b/resources/Schema/Entities/CollisionTestLevel.xml index e58ab6ce..1a811f46 100644 --- a/resources/Schema/Entities/CollisionTestLevel.xml +++ b/resources/Schema/Entities/CollisionTestLevel.xml @@ -6,7 +6,7 @@ - Models/DummyScene.mesh + Models/Test/DummyScene.mesh @@ -28,7 +28,7 @@ - Models/RotationWidgetX.mesh + Models/Widgets/Rotate/RotationWidgetX.mesh diff --git a/resources/Schema/Entities/EditorTestWorld.xml b/resources/Schema/Entities/EditorTestWorld.xml index 4727c777..46e6d54d 100755 --- a/resources/Schema/Entities/EditorTestWorld.xml +++ b/resources/Schema/Entities/EditorTestWorld.xml @@ -37,7 +37,7 @@ 0.80000001192092896 - Models/DirectionalLightWidget.mesh + Models/Widgets/Lights/DirectionalLightWidget.mesh 1 @@ -62,7 +62,7 @@ 3 - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh @@ -73,7 +73,7 @@ - Models/AssaultWeaponRed.mesh + Models/Weapons/Red/AssaultWeaponRed.mesh true @@ -86,7 +86,7 @@ - Models/DefenderGunRed.mesh + Models/Weapons/Red/DefenderGunRed.mesh true false @@ -115,7 +115,7 @@ 1 - models/AssaultAnimated.mesh + Models/Characters/Assault/AssaultAnimated.mesh @@ -131,7 +131,7 @@ 1 - models/AssaultAnimated.mesh + Models/Characters/Assault/AssaultAnimated.mesh @@ -157,7 +157,7 @@ - Models/Log.mesh + Models/Props/TreeLog.mesh @@ -176,7 +176,7 @@ - models/NormSpecIncdMapSphere.mesh + Models/Test/NormSpecIncdMapSphere.mesh @@ -260,7 +260,7 @@ - Models/NormalMapSphere.mesh + Models/Test/NormalMapSphere.mesh @@ -271,7 +271,7 @@ - Models/SpecularMapSphere.mesh + Models/Test/SpecularMapSphere.mesh @@ -313,7 +313,7 @@ - Models/IncandescenceMapSphere.mesh + Models/Test/IncandescenceMapSphere.mesh diff --git a/resources/Schema/Entities/EditorWidgetRotate.xml b/resources/Schema/Entities/EditorWidgetRotate.xml index 88452aac..1276f3e4 100644 --- a/resources/Schema/Entities/EditorWidgetRotate.xml +++ b/resources/Schema/Entities/EditorWidgetRotate.xml @@ -18,7 +18,7 @@ - Models/RotationWidgetX.mesh + Models/Widgets/Rotate/RotationWidgetX.mesh @@ -33,7 +33,7 @@ - Models/RotationWidgetY.mesh + Models/Widgets/Rotate/RotationWidgetY.mesh @@ -48,7 +48,7 @@ - Models/RotationWidgetZ.mesh + Models/Widgets/Rotate/RotationWidgetZ.mesh diff --git a/resources/Schema/Entities/EditorWidgetScale.xml b/resources/Schema/Entities/EditorWidgetScale.xml index 786b079e..65cb2b86 100644 --- a/resources/Schema/Entities/EditorWidgetScale.xml +++ b/resources/Schema/Entities/EditorWidgetScale.xml @@ -3,7 +3,7 @@ - Models/ScaleWidgetOrigin.mesh + Models/Widgets/Scale/ScalingWidgetOrigin.mesh @@ -20,7 +20,7 @@ - Models/ScaleWidgetX.mesh + Models/Widgets/Scale/ScalingWidgetX.mesh @@ -34,7 +34,7 @@ - Models/ScaleWidgetY.mesh + Models/Widgets/Scale/ScalingWidgetY.mesh @@ -48,7 +48,7 @@ - Models/ScaleWidgetZ.mesh + Models/Widgets/Scale/ScalingWidgetZ.mesh diff --git a/resources/Schema/Entities/EditorWidgetTranslate.xml b/resources/Schema/Entities/EditorWidgetTranslate.xml index c6dba4d9..e177b7e9 100644 --- a/resources/Schema/Entities/EditorWidgetTranslate.xml +++ b/resources/Schema/Entities/EditorWidgetTranslate.xml @@ -3,7 +3,7 @@ - Models/TranslationWidgetOrigin.mesh + Models/Widgets/Translate/TranslationWidgetOrigin.mesh @@ -18,7 +18,7 @@ - Models/TranslationWidgetX.mesh + Models/Widgets/Translate/TranslationWidgetX.mesh @@ -30,7 +30,7 @@ - Models/TranslationWidgetY.mesh + Models/Widgets/Translate/TranslationWidgetY.mesh @@ -42,7 +42,7 @@ - Models/TranslationWidgetZ.mesh + Models/Widgets/Translate/TranslationWidgetZ.mesh @@ -54,7 +54,7 @@ - Models/WidgetPlaneX.mesh + Models/Widgets/Translate/TranslationWidgetPlaneX.mesh @@ -66,7 +66,7 @@ - Models/WidgetPlaneY.mesh + Models/Widgets/Translate/TranslationWidgetPlaneY.mesh @@ -78,7 +78,7 @@ - Models/WidgetPlaneZ.mesh + Models/Widgets/Translate/TranslationWidgetPlaneZ.mesh diff --git a/resources/Schema/Entities/GameMap.xml b/resources/Schema/Entities/GameMap.xml index 97fd3f4d..0d6052eb 100644 --- a/resources/Schema/Entities/GameMap.xml +++ b/resources/Schema/Entities/GameMap.xml @@ -9,7 +9,7 @@ - Models\MapVersion1.mesh + Models/LevelBase/MapVersion1.mesh @@ -21,7 +21,7 @@ 2 - Models/DirectionalLightWidget.mesh + Models/Widgets/Lights/DirectionalLightWidget.mesh false diff --git a/resources/Schema/Entities/Model.xml b/resources/Schema/Entities/Model.xml index 57856cbd..bee6b7e1 100644 --- a/resources/Schema/Entities/Model.xml +++ b/resources/Schema/Entities/Model.xml @@ -19,7 +19,7 @@ - models/animTest.mesh + Models/Test/AnimTest.mesh diff --git a/resources/Schema/Entities/MovementTest.xml b/resources/Schema/Entities/MovementTest.xml index 1378f623..a356b7ee 100644 --- a/resources/Schema/Entities/MovementTest.xml +++ b/resources/Schema/Entities/MovementTest.xml @@ -42,7 +42,7 @@ - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh @@ -55,7 +55,7 @@ - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh @@ -70,7 +70,7 @@ - Models/DirectionalLightWidget.mesh + sModels/Widgets/Lights/DirectionalLightWidget.mesh @@ -153,7 +153,7 @@ - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh @@ -166,7 +166,7 @@ - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh @@ -228,7 +228,7 @@ - Models/Camera.mesh + Models/Widgets/Camera.mesh @@ -243,7 +243,7 @@ - Models/Camera.mesh + Models/Widgets/Camera.mesh false @@ -256,7 +256,7 @@ - Models/AssaultHeadless.mesh + Models/Characters/Assault/AssaultHeadless.mesh diff --git a/resources/Schema/Entities/Player.xml b/resources/Schema/Entities/Player.xml index fe24adcc..45c75c63 100644 --- a/resources/Schema/Entities/Player.xml +++ b/resources/Schema/Entities/Player.xml @@ -6,9 +6,6 @@ - - 2.0 - @@ -53,7 +50,7 @@ - Models/Camera.mesh + Models/Widgets/Camera.mesh false @@ -92,7 +89,7 @@ - Models/CrosshairQuad.mesh + Models/Weapons/CrosshairQuad.mesh @@ -112,7 +109,7 @@ true - Models/AssaultWeaponRed.mesh + Models/Weapons/Red/AssaultWeaponRed.mesh @@ -137,7 +134,7 @@ - Models/Camera.mesh + Models/Widgets/Camera.mesh false @@ -156,7 +153,7 @@ - Models/AssaultAnimated.mesh + Models/Characters/Assault/AssaultAnimated.mesh diff --git a/resources/Schema/Entities/QualityAssurance.xml b/resources/Schema/Entities/QualityAssurance.xml index e057cf38..831e7d7c 100644 --- a/resources/Schema/Entities/QualityAssurance.xml +++ b/resources/Schema/Entities/QualityAssurance.xml @@ -97,7 +97,7 @@ 0.80000001192092896 - Models/DirectionalLightWidget.mesh + Models/Widgets/Lights/DirectionalLightWidget.mesh 1 @@ -126,7 +126,7 @@ 1 - models/AssaultAnimated.mesh + Models/Characters/Assault/AssaultAnimated.mesh @@ -142,7 +142,7 @@ 1 - models/AssaultAnimated.mesh + Models/Characters/Assault/AssaultAnimated.mesh @@ -200,7 +200,7 @@ 1 - Models/AssaultAnimated.mesh + Models/Characters/Assault/AssaultAnimated.mesh @@ -224,7 +224,7 @@ - models/NormSpecIncdMapSphere.mesh + Models/Test/NormSpecIncdMapSphere.mesh @@ -308,7 +308,7 @@ - Models/NormalMapSphere.mesh + Models/Test/NormalMapSphere.mesh @@ -319,7 +319,7 @@ - Models/SpecularMapSphere.mesh + Models/Test/SpecularMapSphere.mesh @@ -361,7 +361,7 @@ - Models/IncandescenceMapSphere.mesh + Models/Test/IncandescenceMapSphere.mesh @@ -422,7 +422,7 @@ - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh @@ -435,7 +435,7 @@ - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh @@ -448,7 +448,7 @@ - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh @@ -461,7 +461,7 @@ - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh @@ -493,7 +493,7 @@ - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh @@ -506,7 +506,7 @@ - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh @@ -519,7 +519,7 @@ - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh @@ -532,7 +532,7 @@ - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh @@ -608,7 +608,7 @@ - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh true @@ -690,7 +690,7 @@ - Models/AssaultWeaponBlue.mesh + Models/Weapons/Blue/AssaultWeaponBlue.mesh @@ -737,7 +737,7 @@ - Models/AssaultWeaponRed.mesh + Models/Weapons/Red/AssaultWeaponRed.mesh @@ -797,7 +797,7 @@ - Models/SecondaryWeapon.mesh + Models/Weapons/SecondaryWeapon.mesh @@ -844,7 +844,7 @@ - Models/AssualtSoft.mesh + Models/Test/AssaultTPoseSoftEdge.mesh @@ -890,7 +890,7 @@ - Models/DefenderGunBlue.mesh + Models/Weapons/Blue/DefenderGunBlue.mesh @@ -937,7 +937,7 @@ - Models/DefenderGunRed.mesh + Models/Weapons/Red/DefenderGunRed.mesh @@ -984,7 +984,7 @@ - Models/Assualt.mesh + Models/Test/AssaultTPoseHardEdge.mesh @@ -1021,7 +1021,7 @@ - Models/CapturePoint.mesh + Models/Props/CapturePoint.mesh @@ -1073,7 +1073,7 @@ - Models/CapturePoint.mesh + Models/Props/CapturePoint.mesh @@ -1118,7 +1118,7 @@ - Models/CapturePoint.mesh + Models/Props/CapturePoint.mesh @@ -1161,7 +1161,7 @@ - Models/CapturePoint.mesh + Models/Props/CapturePoint.mesh @@ -1207,7 +1207,7 @@ - Models/CapturePoint.mesh + Models/Props/CapturePoint.mesh @@ -1389,7 +1389,7 @@ true - Models/AssaultWeaponBlue.mesh + Models/Weapons/Blue/AssaultWeaponBlue.mesh true @@ -1442,7 +1442,7 @@ 1.1999860997035228 - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh true @@ -1502,7 +1502,7 @@ true - Models/AssaultAnimated.mesh + Models/Characters/Assault/AssaultAnimated.mesh true diff --git a/resources/Schema/Entities/RayBlue.xml b/resources/Schema/Entities/RayBlue.xml index 4a0bb9d4..8d8e6e1e 100644 --- a/resources/Schema/Entities/RayBlue.xml +++ b/resources/Schema/Entities/RayBlue.xml @@ -6,7 +6,7 @@ 0.25 - Models/CylinderBullet.mesh + Models/Weapons/CylinderBullet.mesh true diff --git a/resources/Schema/Entities/RayRed.xml b/resources/Schema/Entities/RayRed.xml index e69df489..11a9b077 100644 --- a/resources/Schema/Entities/RayRed.xml +++ b/resources/Schema/Entities/RayRed.xml @@ -6,7 +6,7 @@ 0.25 - Models/CylinderBullet.mesh + Models/Weapons/CylinderBullet.mesh true diff --git a/resources/Schema/Entities/RenderingWorld.xml b/resources/Schema/Entities/RenderingWorld.xml index 20301d5f..8fd61e00 100644 --- a/resources/Schema/Entities/RenderingWorld.xml +++ b/resources/Schema/Entities/RenderingWorld.xml @@ -20,7 +20,7 @@ - Models/Assault.obj + Models/Characters/Assault/AssaultTPose.mesh @@ -35,7 +35,7 @@ 80 - Models/Camera.mesh + Models/Widgets/Camera.mesh @@ -132,7 +132,7 @@ - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh @@ -308,7 +308,7 @@ - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh @@ -324,7 +324,7 @@ 0.10000000149011612 - Models/DirectionalLightWidget.mesh + Models/Widgets/Lights/DirectionalLightWidget.mesh diff --git a/resources/Schema/Entities/ShootEventTest.xml b/resources/Schema/Entities/ShootEventTest.xml index 9e9adf50..80dd2f35 100644 --- a/resources/Schema/Entities/ShootEventTest.xml +++ b/resources/Schema/Entities/ShootEventTest.xml @@ -9,7 +9,7 @@ - ../assets/Models/DummyScene.mesh + Models/Test/DummyScene.mesh @@ -41,7 +41,7 @@ 3 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -61,7 +61,7 @@ 1 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -79,7 +79,7 @@ 2 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -96,7 +96,7 @@ 3 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -115,7 +115,7 @@ 4 - ../assets/Models/Core/UnitSphere.mesh + Models/Core/UnitSphere.mesh @@ -133,7 +133,7 @@ - ../assets/Models/Core/UnitCube.mesh + Models/Core/UnitCube.mesh @@ -151,7 +151,7 @@ - ../assets/Models/Core/UnitCube.mesh + Models/Core/UnitCube.mesh @@ -171,7 +171,7 @@ - ../assets/Models/Core/UnitCube.mesh + Models/Core/UnitCube.mesh @@ -191,7 +191,7 @@ - ../assets/Models/Core/UnitCube.mesh + Models/Core/UnitCube.mesh diff --git a/resources/Schema/Entities/SpawnPointClusterWithModels.xml b/resources/Schema/Entities/SpawnPointClusterWithModels.xml index 9c42d0e4..ea8e09d4 100644 --- a/resources/Schema/Entities/SpawnPointClusterWithModels.xml +++ b/resources/Schema/Entities/SpawnPointClusterWithModels.xml @@ -19,7 +19,7 @@ - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh @@ -31,7 +31,7 @@ - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh @@ -43,7 +43,7 @@ - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh @@ -55,7 +55,7 @@ - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh diff --git a/resources/Schema/Entities/SpawnerWithPlayerModel.xml b/resources/Schema/Entities/SpawnerWithPlayerModel.xml index 1274eefa..dbd93ed4 100644 --- a/resources/Schema/Entities/SpawnerWithPlayerModel.xml +++ b/resources/Schema/Entities/SpawnerWithPlayerModel.xml @@ -4,7 +4,7 @@ - Models/Assault.mesh + Models/Characters/Assault/AssaultTPose.mesh diff --git a/resources/Schema/Entities/Test.xml b/resources/Schema/Entities/Test.xml index 2cdf4e17..7f40e6de 100644 --- a/resources/Schema/Entities/Test.xml +++ b/resources/Schema/Entities/Test.xml @@ -6,7 +6,7 @@ - Models/DummyScene.mesh + Models/Test/DummyScene.mesh @@ -36,7 +36,7 @@ 0 - Models/Camera.mesh + Models/Widgets/Camera.mesh diff --git a/resources/Shaders/ForwardPlusSkinned.vert.glsl b/resources/Shaders/ForwardPlusSkinned.vert.glsl index 3d47b0c4..5368b260 100644 --- a/resources/Shaders/ForwardPlusSkinned.vert.glsl +++ b/resources/Shaders/ForwardPlusSkinned.vert.glsl @@ -26,7 +26,7 @@ out VertexData{ void main() { mat4 boneTransform = mat4(1); - //Remove if(). Shoudln't have to do this scine we know it's skinned and uses bones + if(BoneWeights[0] > 0.0f){ boneTransform = BoneWeights[0] * Bones[int(BoneIndices[0])] + BoneWeights[1] * Bones[int(BoneIndices[1])] diff --git a/resources/Shaders/Picking.vert.glsl b/resources/Shaders/Picking.vert.glsl index 205a8fdd..f888cd16 100644 --- a/resources/Shaders/Picking.vert.glsl +++ b/resources/Shaders/Picking.vert.glsl @@ -3,15 +3,12 @@ uniform mat4 M; uniform mat4 V; uniform mat4 P; -uniform mat4 Bones[100]; layout(location = 0) in vec3 Position; layout(location = 1) in vec3 Normal; layout(location = 2) in vec3 Tangent; layout(location = 3) in vec3 BiTangent; layout(location = 4) in vec2 TextureCoords; -layout(location = 5) in vec4 BoneIndices; -layout(location = 6) in vec4 BoneWeights; out VertexData{ vec3 Position; @@ -19,14 +16,6 @@ out VertexData{ void main() { - mat4 boneTransform = mat4(1); - if(BoneWeights[0] > 0.0f){ - boneTransform = BoneWeights[0] * Bones[int(BoneIndices[0])] - + BoneWeights[1] * Bones[int(BoneIndices[1])] - + BoneWeights[2] * Bones[int(BoneIndices[2])] - + BoneWeights[3] * Bones[int(BoneIndices[3])]; - } - - gl_Position = P*V*M*boneTransform * vec4(Position, 1.0); - Output.Position = (boneTransform * vec4(Position, 1.0)).xyz; + gl_Position = P*V*M * vec4(Position, 1.0); + Output.Position = Position, 1.0; } \ No newline at end of file diff --git a/resources/Shaders/PickingSkinned.vert.glsl b/resources/Shaders/PickingSkinned.vert.glsl new file mode 100644 index 00000000..205a8fdd --- /dev/null +++ b/resources/Shaders/PickingSkinned.vert.glsl @@ -0,0 +1,32 @@ +#version 430 + +uniform mat4 M; +uniform mat4 V; +uniform mat4 P; +uniform mat4 Bones[100]; + +layout(location = 0) in vec3 Position; +layout(location = 1) in vec3 Normal; +layout(location = 2) in vec3 Tangent; +layout(location = 3) in vec3 BiTangent; +layout(location = 4) in vec2 TextureCoords; +layout(location = 5) in vec4 BoneIndices; +layout(location = 6) in vec4 BoneWeights; + +out VertexData{ + vec3 Position; +}Output; + +void main() +{ + mat4 boneTransform = mat4(1); + if(BoneWeights[0] > 0.0f){ + boneTransform = BoneWeights[0] * Bones[int(BoneIndices[0])] + + BoneWeights[1] * Bones[int(BoneIndices[1])] + + BoneWeights[2] * Bones[int(BoneIndices[2])] + + BoneWeights[3] * Bones[int(BoneIndices[3])]; + } + + gl_Position = P*V*M*boneTransform * vec4(Position, 1.0); + Output.Position = (boneTransform * vec4(Position, 1.0)).xyz; +} \ No newline at end of file diff --git a/src/Engine/Rendering/PickingPass.cpp b/src/Engine/Rendering/PickingPass.cpp index abc79f2e..c445b8fd 100644 --- a/src/Engine/Rendering/PickingPass.cpp +++ b/src/Engine/Rendering/PickingPass.cpp @@ -41,6 +41,14 @@ void PickingPass::InitializeShaderPrograms() m_PickingProgram->Compile(); m_PickingProgram->BindFragDataLocation(0, "TextureFragment"); m_PickingProgram->Link(); + + m_PickingSkinnedProgram = ResourceManager::Load("#PickingSkinnedProgram"); + + m_PickingSkinnedProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/PickingSkinned.vert.glsl"))); + m_PickingSkinnedProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/Picking.frag.glsl"))); + m_PickingSkinnedProgram->Compile(); + m_PickingSkinnedProgram->BindFragDataLocation(0, "TextureFragment"); + m_PickingSkinnedProgram->Link(); } void PickingPass::Draw(RenderScene& scene) @@ -49,6 +57,7 @@ void PickingPass::Draw(RenderScene& scene) //TODO: Render: Add code for more jobs than modeljobs. GLuint shaderHandle = m_PickingProgram->GetHandle(); + GLuint shaderSkinnedHandle = m_PickingSkinnedProgram->GetHandle(); m_PickingProgram->Bind(); if (scene.ClearDepth) { @@ -60,41 +69,78 @@ void PickingPass::Draw(RenderScene& scene) auto modelJob = std::dynamic_pointer_cast(job); if (modelJob) { - int pickColor[2] = { m_ColorCounter[0], m_ColorCounter[1] }; + if (modelJob->Model->isSkined()) + { + m_PickingSkinnedProgram->Bind(); + int pickColor[2] = { m_ColorCounter[0], m_ColorCounter[1] }; - PickingInfo pickInfo; - pickInfo.Entity = modelJob->Entity; - pickInfo.World = modelJob->World; - pickInfo.Camera = scene.Camera; + PickingInfo pickInfo; + pickInfo.Entity = modelJob->Entity; + pickInfo.World = modelJob->World; + pickInfo.Camera = scene.Camera; - auto color = m_EntityColors.find(std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)); - if (color != m_EntityColors.end()) { - pickColor[0] = color->second[0]; - pickColor[1] = color->second[1]; - } else { - m_EntityColors[std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)] = glm::ivec2(pickColor[0], pickColor[1]); - if (m_ColorCounter[0] > 255) { - m_ColorCounter[0] = 0; - m_ColorCounter[1] += 1; - } else { - m_ColorCounter[0] += 1; - } - } + auto color = m_EntityColors.find(std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)); + if (color != m_EntityColors.end()) { + pickColor[0] = color->second[0]; + pickColor[1] = color->second[1]; + } + else { + m_EntityColors[std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)] = glm::ivec2(pickColor[0], pickColor[1]); + if (m_ColorCounter[0] > 255) { + m_ColorCounter[0] = 0; + m_ColorCounter[1] += 1; + } + else { + m_ColorCounter[0] += 1; + } + } - m_PickingColorsToEntity[glm::ivec2(pickColor[0], pickColor[1])] = pickInfo; + m_PickingColorsToEntity[glm::ivec2(pickColor[0], pickColor[1])] = pickInfo; - glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); - 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())); - glUniform2fv(glGetUniformLocation(shaderHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1]))); + glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); + glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "V"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix())); + glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix())); + glUniform2fv(glGetUniformLocation(shaderSkinnedHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1]))); - if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { + if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { - if (modelJob->Animation != nullptr) { - std::vector frameBones = modelJob->Skeleton->GetFrameBones(*modelJob->Animation, modelJob->AnimationTime); - glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - } - } + if (modelJob->Animation != nullptr) { + std::vector frameBones = modelJob->Skeleton->GetFrameBones(*modelJob->Animation, modelJob->AnimationTime); + glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + } + } + } else { + m_PickingProgram->Bind(); + int pickColor[2] = { m_ColorCounter[0], m_ColorCounter[1] }; + + PickingInfo pickInfo; + pickInfo.Entity = modelJob->Entity; + pickInfo.World = modelJob->World; + pickInfo.Camera = scene.Camera; + + auto color = m_EntityColors.find(std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)); + if (color != m_EntityColors.end()) { + pickColor[0] = color->second[0]; + pickColor[1] = color->second[1]; + } + else { + m_EntityColors[std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)] = glm::ivec2(pickColor[0], pickColor[1]); + if (m_ColorCounter[0] > 255) { + m_ColorCounter[0] = 0; + m_ColorCounter[1] += 1; + } + else { + m_ColorCounter[0] += 1; + } + } + + m_PickingColorsToEntity[glm::ivec2(pickColor[0], pickColor[1])] = pickInfo; + + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); + 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())); + glUniform2fv(glGetUniformLocation(shaderHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1]))); + } glBindVertexArray(modelJob->Model->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer); diff --git a/tools/MayaExporter/MayaExporter.opensdf b/tools/MayaExporter/MayaExporter.opensdf deleted file mode 100644 index 31dea47bab049adbbcfae9b67e37a5ada58ecdf3..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 38 ncmd01NMy)m$Ydx6(}@fW3?U4z3_%RO44w>r430paKad9ihMopW diff --git a/tools/MayaExporter/MayaExporter/Mesh.cpp b/tools/MayaExporter/MayaExporter/Mesh.cpp index 52b1392e..ee5a6022 100644 --- a/tools/MayaExporter/MayaExporter/Mesh.cpp +++ b/tools/MayaExporter/MayaExporter/Mesh.cpp @@ -253,43 +253,33 @@ Mesh MeshClass::GetMeshData(MObjectArray object) //mesh.getPoint(vertexIndex, pos, MSpace::kPostTransform); pos = positions[vertexIndex]; pos = pos * transformMatrix; - if (abs(pos.x) > 0.0001) - thisVertex.Pos[0] = pos.x; - if (abs(pos.y) > 0.0001) - thisVertex.Pos[1] = pos.y; - if (abs(pos.z) > 0.0001) - thisVertex.Pos[2] = pos.z; + + thisVertex.Pos[0] = pos.x; + thisVertex.Pos[1] = pos.y; + thisVertex.Pos[2] = pos.z; status = faceVert.getNormal(normal, MSpace::kObject); if (status != MS::kSuccess) { MGlobal::displayError(MString() + "faceVert.getNormal() ERROR: " + status.errorString() + "for local vertex " + i + " in " + faceID + " in mesh " + thisMeshPath.fullPathName()); break; } - if (abs(normal[0]) > 0.0001) - thisVertex.Normal[0] = normal[0]; - if (abs(normal[1]) > 0.0001) - thisVertex.Normal[1] = normal[1]; - if (abs(normal[2]) > 0.0001) - thisVertex.Normal[2] = normal[2]; + + thisVertex.Normal[0] = normal[0]; + thisVertex.Normal[1] = normal[1]; + thisVertex.Normal[2] = normal[2]; MFloatVector Tangent = Tangents[faceVert.tangentId()]; //MVector tmp = faceVert.getTangent(MSpace::kObject, NULL); //tmp.get(biTangent); - if (abs(Tangent[0]) > 0.0001) - thisVertex.Tangent[0] = Tangent[0]; - if (abs(Tangent[1]) > 0.0001) - thisVertex.Tangent[1] = Tangent[1]; - if (abs(Tangent[2]) > 0.0001) - thisVertex.Tangent[2] = Tangent[2]; + thisVertex.Tangent[0] = Tangent[0]; + thisVertex.Tangent[1] = Tangent[1]; + thisVertex.Tangent[2] = Tangent[2]; MFloatVector biNormal = biNormals[faceVert.tangentId()]; //faceVert.getBinormal().get(biNormal); - if (abs(biNormal[0]) > 0.0001) - thisVertex.BiNormal[0] = biNormal[0]; - if (abs(biNormal[1]) > 0.0001) - thisVertex.BiNormal[1] = biNormal[1]; - if (abs(biNormal[2]) > 0.0001) - thisVertex.BiNormal[2] = biNormal[2]; + thisVertex.BiNormal[0] = biNormal[0]; + thisVertex.BiNormal[1] = biNormal[1]; + thisVertex.BiNormal[2] = biNormal[2]; status = faceVert.getUV(UV); if (status != MS::kSuccess) { From 0e9fb16399a648a4571351b579da9e02ecadd135 Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Mon, 8 Feb 2016 17:58:07 +0100 Subject: [PATCH 126/355] Work started on DamageIndicatorSystem. Made some initial tests and test calculations --- include/Engine/Core/EPlayerDamage.h | 1 + include/Game/Systems/DamageIndicatorSystem.h | 41 ++ resources/Schema/Entities/GameMapTest.xml | 430 ++++++++++++++++++ .../Schema/Entities/SpriteTestTemporary.xml | 24 + src/Game/Game.cpp | 2 + src/Game/Systems/DamageIndicatorSystem.cpp | 101 ++++ 6 files changed, 599 insertions(+) create mode 100644 include/Game/Systems/DamageIndicatorSystem.h create mode 100644 resources/Schema/Entities/GameMapTest.xml create mode 100644 resources/Schema/Entities/SpriteTestTemporary.xml create mode 100644 src/Game/Systems/DamageIndicatorSystem.cpp diff --git a/include/Engine/Core/EPlayerDamage.h b/include/Engine/Core/EPlayerDamage.h index 8ba3907e..c11b121f 100644 --- a/include/Engine/Core/EPlayerDamage.h +++ b/include/Engine/Core/EPlayerDamage.h @@ -11,6 +11,7 @@ struct PlayerDamage : Event { //NOTE: this struct is missing information on what the damageSource is EntityWrapper Player; + EntityWrapper PlayerShooter; double Damage; }; diff --git a/include/Game/Systems/DamageIndicatorSystem.h b/include/Game/Systems/DamageIndicatorSystem.h new file mode 100644 index 00000000..646887e2 --- /dev/null +++ b/include/Game/Systems/DamageIndicatorSystem.h @@ -0,0 +1,41 @@ +#ifndef DamageIndicatorSystem_h__ +#define DamageIndicatorSystem_h__ + +#include "Core/System.h" +#include "Core/Transform.h" +#include "Core/ResourceManager.h" +#include "Core/EntityFileParser.h" +#include "Core/EPickupSpawned.h" +#include "Core/EPlayerDamage.h" +#include "Engine/Collision/ETrigger.h" +#include "Common.h" +#include + +//temp +#include "Input/EInputCommand.h" +#include "Rendering/ESetCamera.h" + +#include + +class DamageIndicatorSystem : public ImpureSystem +{ +public: + DamageIndicatorSystem(World* world, EventBroker* eventBroker); + + virtual void Update(double dt) override; + +private: + + EventRelay m_DamageTakenFromPlayer; + bool OnPlayerDamageTaken(Events::PlayerDamage& e); + + //temp + EventRelay m_EInputCommand; + bool OnInputCommand(Events::InputCommand& e); + + EventRelay m_ESetCamera; + bool OnSetCamera(const Events::SetCamera& e); + + EntityID m_CurrentCamera = -1; +}; +#endif diff --git a/resources/Schema/Entities/GameMapTest.xml b/resources/Schema/Entities/GameMapTest.xml new file mode 100644 index 00000000..ee68da96 --- /dev/null +++ b/resources/Schema/Entities/GameMapTest.xml @@ -0,0 +1,430 @@ + + + + + + + + + + + + + + + Models\MapVersion1.mesh + + + + + + + + + 2 + + + Models/DirectionalLightWidget.mesh + false + + + + + + + + + + + + + 8 + 2.7999999523162842 + + + + + + + + + + + 8 + 2.7999999523162842 + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + false + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + false + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 99 + + + + + + 5 + + + + + + + + + + + + + + + + + + + + + + + Fonts/DroidSans.ttf,100 + + + + + + + + + + + + + + Models/Camera.mesh + false + + + + + + + + + + + + + + + + + + + 0.99000000953674316 + + + + + Models/Core/UnitHexagon.mesh + + + + + + + + + + + + + + Models/CrosshairQuad.mesh + + + + + + + + + + + + + Models/AssaultWeaponRed.mesh + + + + + + + + + + + + + + + + + + + + + + + + + Models/Camera.mesh + false + + + + + + + + + + + + Hold Pos + + 1 + + + + Models/AssaultAnimated.mesh + + + + + + + + + + Models/Core/UnitCube.mesh + + false + + + + + + + + + + + + Models/Core/UnitCube.mesh + + false + + + + + + + + + + + + diff --git a/resources/Schema/Entities/SpriteTestTemporary.xml b/resources/Schema/Entities/SpriteTestTemporary.xml new file mode 100644 index 00000000..f66e9158 --- /dev/null +++ b/resources/Schema/Entities/SpriteTestTemporary.xml @@ -0,0 +1,24 @@ + + + + + + Textures/DefenderGunRedDiff.png + Textures/DefenderGunRedIncd.png + + + + Models/Core/UnitQuad.mesh + + + + + + + 1.5 + + + + + + diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index 0cc41a73..5875bc81 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -12,6 +12,7 @@ #include "Core/EntityFileWriter.h" #include "Game/Systems/CapturePointSystem.h" #include "Game/Systems/PickupSpawnSystem.h" +#include "Game/Systems/DamageIndicatorSystem.h" #include "Game/Systems/WeaponSystem.h" #include "Game/Systems/PlayerHUD.h" #include "Game/Systems/LifetimeSystem.h" @@ -96,6 +97,7 @@ Game::Game(int argc, char* argv[]) m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); + m_SystemPipeline->AddSystem(updateOrderLevel); // Populate Octree with collidables ++updateOrderLevel; m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeCollision, "Collidable"); diff --git a/src/Game/Systems/DamageIndicatorSystem.cpp b/src/Game/Systems/DamageIndicatorSystem.cpp new file mode 100644 index 00000000..5f6ad725 --- /dev/null +++ b/src/Game/Systems/DamageIndicatorSystem.cpp @@ -0,0 +1,101 @@ +#include "Systems/DamageIndicatorSystem.h" + +DamageIndicatorSystem::DamageIndicatorSystem(World* m_World, EventBroker* eventBroker) + : System(m_World, eventBroker) +{ + EVENT_SUBSCRIBE_MEMBER(m_DamageTakenFromPlayer, &DamageIndicatorSystem::OnPlayerDamageTaken); + //TEMP + EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &DamageIndicatorSystem::OnInputCommand); + //current camera + EVENT_SUBSCRIBE_MEMBER(m_ESetCamera, &DamageIndicatorSystem::OnSetCamera); + +} + +void DamageIndicatorSystem::Update(double dt) +{ + +} + + +bool DamageIndicatorSystem::OnPlayerDamageTaken(Events::PlayerDamage& e) +{ + auto test1 = (glm::vec3)e.PlayerShooter["Transform"]["Orientation"]; + auto test2 = (glm::vec3)e.Player["Transform"]["Orientation"]; + //calculate direction + auto enemyOrientation = glm::quat(((glm::vec3)e.PlayerShooter["Transform"]["Orientation"])); + auto playerOrientation = glm::quat((glm::vec3)e.Player["Transform"]["Orientation"]); + //calculate difference in angle (quaternion math) + auto angle1 = glm::angle(playerOrientation); + auto angle2 = glm::angle(enemyOrientation); + auto quat = glm::angleAxis(angle2 - angle1, glm::vec3(0, 1, 0)); + auto vec3Orientation = glm::eulerAngles(quat); + + //load & set the "2d" sprite + auto entityFile = ResourceManager::Load("Schema/Entities/SpriteTestTemporary.xml"); + EntityFileParser parser(entityFile); + EntityID spriteID = parser.MergeEntities(m_World); + m_World->SetParent(spriteID, m_CurrentCamera); + auto cameraWrapper = EntityWrapper(m_World, spriteID); + cameraWrapper["Transform"]["Orientation"] = vec3Orientation; + + return true; +} + +//TEMP +bool DamageIndicatorSystem::OnInputCommand(Events::InputCommand& e) +{ + if (e.Command != "Jump" || e.Value > 0) { + return false; + } + //auto entityFile = ResourceManager::Load("Schema/Entities/SpriteTestTemporary.xml"); + //EntityFileParser parser(entityFile); + //EntityID spriteID = parser.MergeEntities(m_World); + ////get currently active camera + ////auto cameras = m_World->GetComponents("Camera"); + ////for (auto& cCamera : *cameras) { + //// + //// //auto temp = m_World->GetParent(cCamera.EntityID); + //// m_World->SetParent(spriteID, cCamera.EntityID); + ////} + ////m_CurrentCamera + //m_World->SetParent(spriteID, m_CurrentCamera); + + //auto cameraWrapper = EntityWrapper(m_World, spriteID); + //cameraWrapper["Transform"]["Orientation"] = glm::vec3(1, 1, 1); + //ray player-enemyplayer eller bara spelarnas direction + + + //TODO: life time, rotering +//den ska väl vara där hela tiden, bara det att den inte syns + + + //EntityWrapper(m_World, spriteID); + + auto players = m_World->GetComponents("Player"); + EntityID id1 = (*players->begin()).EntityID; + EntityID id2; + int lameCounter = 0; + for (auto& cPlayers : *players) { + if (lameCounter == 1) { + id2 = cPlayers.EntityID; + } + lameCounter++; + } + if (lameCounter != 2) { + return false; + } + + //do something here + Events::PlayerDamage ePlayerDamage; + ePlayerDamage.Player = EntityWrapper(m_World, id1); + ePlayerDamage.PlayerShooter = EntityWrapper(m_World, id2); + ePlayerDamage.Damage = 1; + m_EventBroker->Publish(ePlayerDamage); + + return true; +} + +bool DamageIndicatorSystem::OnSetCamera(const Events::SetCamera& e) { + m_CurrentCamera = e.CameraEntity.ID; + return true; +} \ No newline at end of file From b748deb1e1e91c3177af65e1c778454f6afd1585 Mon Sep 17 00:00:00 2001 From: William Moberg Date: Tue, 9 Feb 2016 10:05:49 +0100 Subject: [PATCH 127/355] WIP FrustumCulling, most code added but not working now. --- include/Engine/Core/Octree.h | 117 ++++++++++++++++++++++++ include/Engine/Rendering/RenderSystem.h | 7 +- src/Engine/Rendering/RenderSystem.cpp | 53 ++++++++++- src/Game/Game.cpp | 10 +- 4 files changed, 179 insertions(+), 8 deletions(-) diff --git a/include/Engine/Core/Octree.h b/include/Engine/Core/Octree.h index 907d5736..d97d644b 100644 --- a/include/Engine/Core/Octree.h +++ b/include/Engine/Core/Octree.h @@ -2,6 +2,7 @@ #define Octree_h__ #include +#include #include "../Common.h" #include "AABB.h" @@ -40,6 +41,8 @@ public: //The type Box must be AABB, or inherit from AABB. template void ObjectsInSameRegion(const Box& box, std::vector& outObjects); + //Get the objects that are inside the frustum defined by the viewProjection matrix, the objects are put in outObjects. + void ObjectsInFrustum(const glm::mat4x4& viewProj, std::vector& outObjects); //Empty the tree of all objects, static and dynamic. void ClearObjects(); //Empty the tree of all dynamic objects. Static objects remain in the tree. @@ -68,6 +71,56 @@ struct Output float CollideDistance; }; +//Contains points P in: dot(normal, P) + d = 0 +struct Plane +{ + glm::vec3 normal; + float distance; +}; + +//A frustum defined by 6 planes. +struct Frustum +{ + enum Output + { + Inside, + Outside, + Intersects + }; + Plane planes[6]; + + Output VsAABB(const AABB& box) const + { + const glm::vec3& maxCorner = box.MaxCorner(); + const glm::vec3& minCorner = box.MinCorner(); + bool completelyInside = true; + for (const Plane& p : planes) { + bool anyWasInside = false; + bool anyWasOutside = false; + //If points are on both sides of the plane, we can stop. + for (int i = 0; i < 8 && (!anyWasInside || !anyWasOutside); ++i) { + std::bitset<3> bits(i); + glm::vec3 corner; + corner.x = bits.test(0) ? maxCorner.x : minCorner.x; + corner.y = bits.test(1) ? maxCorner.y : minCorner.y; + corner.z = bits.test(2) ? maxCorner.z : minCorner.z; + if (glm::dot(p.normal, corner) > p.distance) { + anyWasInside = true; + } else { + anyWasOutside = true; + } + } + if (!anyWasInside) { + return Outside; + } + if (anyWasOutside) { + completelyInside = false; + } + } + return completelyInside ? Inside : Intersects; + } +}; + struct ContainedObject { ContainedObject() @@ -97,6 +150,8 @@ struct Child void AddStaticObject(const AABB& box); template void ObjectsInSameRegion(const Box& box, std::vector& outObjects) const; + template + void ObjectsInFrustum(const Frustum& frustum, std::vector& outObjects, bool takeAllDontTest) const; void ClearObjects(); void ClearDynamicObjects(); bool RayCollides(const Ray& ray, Output& data) const; @@ -154,6 +209,26 @@ void Octree::ObjectsInSameRegion(const Box& box, std::vector& outObjects) m_Root->ObjectsInSameRegion(box, outObjects); } +template +void Octree::ObjectsInFrustum(const glm::mat4x4& viewProj, std::vector& outObjects) +{ + falsifyObjectChecks(); + OctSpace::Frustum frustum; + for (int i = 0; i < 6; ++i) { + int sign = 2 * (i % 2) - 1; + int index = i / 2; + OctSpace::Plane& plane = frustum.planes[i]; + plane.normal.x = viewProj[0].w + sign * viewProj[0][index]; + plane.normal.y = viewProj[1].w + sign * viewProj[1][index]; + plane.normal.z = viewProj[2].w + sign * viewProj[2][index]; + plane.distance = viewProj[3].w + sign * viewProj[3][index]; + float divByNormalLength = 1.0f / glm::length(plane.normal); + plane.normal *= divByNormalLength; + plane.distance *= divByNormalLength; + } + m_Root->ObjectsInFrustum(frustum, outObjects, false); +} + template void Octree::ClearObjects() { @@ -230,4 +305,46 @@ void OctSpace::Child::ObjectsInSameRegion(const Box& box, std::vector& outObj } } +template +void OctSpace::Child::ObjectsInFrustum(const Frustum& frustum, std::vector& outObjects, bool takeAllDontTest) const +{ + if (hasChildren()) { + for (const Child* c : m_Children) { + Frustum::Output out = Frustum::Inside; + if (!takeAllDontTest) { + out = frustum.VsAABB(c->m_Box); + if (out == Frustum::Outside) { + continue; + } + } + c->ObjectsInFrustum(frustum, outObjects, out == Frustum::Inside); + } + } else { + size_t startIndex = outObjects.size(); + int numDuplicates = 0; + outObjects.resize(outObjects.size() + m_StaticObjIndices.size() + m_DynamicObjIndices.size()); + for (size_t i = 0; i < m_StaticObjIndices.size(); ++i) { + ContainedObject& obj = m_StaticObjectsRef[m_StaticObjIndices[i]]; + if (obj.Checked || !frustum.VsAABB(obj.Box)) { + ++numDuplicates; + } else { + obj.Checked = true; + outObjects[startIndex + i - numDuplicates] = *static_cast(obj.Box.get()); + } + } + for (size_t i = 0; i < m_DynamicObjIndices.size(); ++i) { + ContainedObject& obj = m_DynamicObjectsRef[m_DynamicObjIndices[i]]; + if (obj.Checked || !frustum.VsAABB(obj.Box)) { + ++numDuplicates; + } else { + obj.Checked = true; + outObjects[startIndex + i - numDuplicates] = *static_cast(obj.Box.get()); + } + } + for (size_t i = 0; i < numDuplicates; ++i) { + outObjects.pop_back(); + } + } +} + #endif \ No newline at end of file diff --git a/include/Engine/Rendering/RenderSystem.h b/include/Engine/Rendering/RenderSystem.h index d64147b9..d404c56a 100644 --- a/include/Engine/Rendering/RenderSystem.h +++ b/include/Engine/Rendering/RenderSystem.h @@ -16,11 +16,13 @@ #include "PointLightJob.h" #include "../Core/Transform.h" #include "../Core/EPlayerSpawned.h" +#include "../Core/Octree.h" +#include "../Collision/EntityAABB.h" class RenderSystem : public ImpureSystem { public: - RenderSystem(World* world, EventBroker* eventBrokerer, const IRenderer* renderer, RenderFrame* renderFrame); + RenderSystem(World* world, EventBroker* eventBrokerer, const IRenderer* renderer, RenderFrame* renderFrame, Octree* frustumCullOctree); ~RenderSystem(); virtual void Update(double dt) override; @@ -29,9 +31,12 @@ private: const IRenderer* m_Renderer; RenderFrame* m_RenderFrame; Camera* m_Camera; + Camera* m_LastCullCamera; + Camera** m_FrustumCamPtr; World* m_World; EntityWrapper m_CurrentCamera = EntityWrapper::Invalid; EntityWrapper m_LocalPlayer = EntityWrapper::Invalid; + Octree* m_Octree; EventRelay m_ESetCamera; bool OnSetCamera(Events::SetCamera &event); diff --git a/src/Engine/Rendering/RenderSystem.cpp b/src/Engine/Rendering/RenderSystem.cpp index eaecf99e..d57e263a 100644 --- a/src/Engine/Rendering/RenderSystem.cpp +++ b/src/Engine/Rendering/RenderSystem.cpp @@ -1,21 +1,26 @@ #include "Rendering/RenderSystem.h" +#include "Collision/Collision.h" -RenderSystem::RenderSystem(World* world, EventBroker* eventBroker, const IRenderer* renderer, RenderFrame* renderFrame) +RenderSystem::RenderSystem(World* world, EventBroker* eventBroker, const IRenderer* renderer, RenderFrame* renderFrame, Octree* frustumCullOctree) : System(world, eventBroker) , m_Renderer(renderer) , m_RenderFrame(renderFrame) , m_World(world) + , m_Octree(frustumCullOctree) { EVENT_SUBSCRIBE_MEMBER(m_ESetCamera, &RenderSystem::OnSetCamera); EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &RenderSystem::OnInputCommand); EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &RenderSystem::OnPlayerSpawned); m_Camera = new Camera((float)m_Renderer->Resolution().Width / m_Renderer->Resolution().Height, glm::radians(45.f), 0.01f, 5000.f); + m_LastCullCamera = new Camera(*m_Camera); + m_FrustumCamPtr = &m_Camera; } RenderSystem::~RenderSystem() { delete m_Camera; + delete m_LastCullCamera; } bool RenderSystem::OnSetCamera(Events::SetCamera& e) @@ -28,6 +33,17 @@ bool RenderSystem::OnSetCamera(Events::SetCamera& e) m_Camera->SetPosition(cTransform["Position"]); m_Camera->SetOrientation(glm::quat((const glm::vec3&)cTransform["Orientation"])); m_CurrentCamera = e.CameraEntity; + //Right now, lets set the camera to cull away stuff if it is connected to anything. + //TODO: This won't work with spectators, or death anim. + if (m_CurrentCamera.Parent().Valid()) { + //Copy the camera into the last frustum camera, without allocating new memory. + new ((void*)m_LastCullCamera) Camera(*m_Camera); + m_FrustumCamPtr = &m_Camera; + } else { + //If the camera has no parents, i.e. a free camera, + //then we cull from the last camera, so we can see if the culling works. + m_FrustumCamPtr = &m_LastCullCamera; + } return true; } @@ -42,11 +58,33 @@ bool RenderSystem::isChildOfCurrentCamera(EntityWrapper entity) void RenderSystem::fillModels(std::list>& opaqueJobs, std::list>& transparentJobs) { + + std::vector seenEntities; + //m_Octree->ObjectsInFrustum((*m_FrustumCamPtr)->ProjectionMatrix() * (*m_FrustumCamPtr)->ViewMatrix(), seenEntities); + //m_Octree->ObjectsInFrustum((*m_FrustumCamPtr)->ViewMatrix() * (*m_FrustumCamPtr)->ProjectionMatrix(), seenEntities); + + glm::mat4x4 viewProj = (*m_FrustumCamPtr)->ViewMatrix() * (*m_FrustumCamPtr)->ProjectionMatrix(); + OctSpace::Frustum frustum; + for (int i = 0; i < 6; ++i) { + int sign = 2 * (i % 2) - 1; + int index = i / 2; + OctSpace::Plane& plane = frustum.planes[i]; + plane.normal.x = viewProj[0].w + sign * viewProj[0][index]; + plane.normal.y = viewProj[1].w + sign * viewProj[1][index]; + plane.normal.z = viewProj[2].w + sign * viewProj[2][index]; + plane.distance = viewProj[3].w + sign * viewProj[3][index]; + float divByNormalLength = 1.0f / glm::length(plane.normal); + plane.normal *= divByNormalLength; + plane.distance *= divByNormalLength; + } + + //for (auto& seenEntity : seenEntities) { + // EntityWrapper entity = seenEntity.Entity; + // ComponentWrapper cModel = entity["Model"]; auto models = m_World->GetComponents("Model"); if (models == nullptr) { return; } - for (auto& cModel : *models) { bool visible = cModel["Visible"]; if (!visible) { @@ -57,7 +95,7 @@ void RenderSystem::fillModels(std::list>& opaqueJobs, continue; } - EntityWrapper entity(m_World, cModel.EntityID); + EntityWrapper entity = EntityWrapper(m_World, cModel.EntityID); // Only render children of a camera if that camera is currently active if (isChildOfACamera(entity) && !isChildOfCurrentCamera(entity)) { @@ -69,6 +107,15 @@ void RenderSystem::fillModels(std::list>& opaqueJobs, continue; } + if (entity.HasComponent("AABB")) { + OctSpace::Frustum::Output o = frustum.VsAABB(*Collision::EntityAbsoluteAABB(entity)); + if (o == OctSpace::Frustum::Outside) { + continue; + } + } else { + continue; + } + Model* model; try { model = ResourceManager::Load<::Model, true>(resource); diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index 0c92271d..d3c2eb57 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -75,9 +75,10 @@ Game::Game(int argc, char* argv[]) // Create Octrees - m_OctreeCollision = new Octree(AABB(glm::vec3(-100), glm::vec3(100)), 4); - m_OctreeTrigger = new Octree(AABB(glm::vec3(-100), glm::vec3(100)), 4); - m_OctreeFrustrumCulling = new Octree(AABB(glm::vec3(-100), glm::vec3(100)), 4); + AABB boxContainingTheWorld(glm::vec3(-300), glm::vec3(300)); + m_OctreeCollision = new Octree(boxContainingTheWorld, 4); + m_OctreeTrigger = new Octree(boxContainingTheWorld, 4); + m_OctreeFrustrumCulling = new Octree(boxContainingTheWorld, 4); // Create system pipeline m_SystemPipeline = new SystemPipeline(m_World, m_EventBroker); @@ -99,6 +100,7 @@ Game::Game(int argc, char* argv[]) ++updateOrderLevel; m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeCollision, "Collidable"); m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeTrigger, "Player"); + m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeFrustrumCulling, "Model"); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); @@ -107,7 +109,7 @@ Game::Game(int argc, char* argv[]) m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeCollision); m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeTrigger); ++updateOrderLevel; - m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer, m_RenderFrame); + m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer, m_RenderFrame, m_OctreeFrustrumCulling); ++updateOrderLevel; m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer, m_RenderFrame); From fccd8c64e789803aab305203137da46e3af6871d Mon Sep 17 00:00:00 2001 From: Jocke Date: Tue, 9 Feb 2016 11:43:16 +0100 Subject: [PATCH 128/355] WIP Clients are working properly, servers are not. --- include/Engine/Network/Client.h | 11 ++-- include/Engine/Network/MessageType.h | 3 +- include/Engine/Network/Network.h | 2 + include/Engine/Network/NetworkClient.h | 21 ++++++++ include/Engine/Network/NetworkServer.h | 20 +++++++ include/Engine/Network/Packet.h | 5 ++ include/Engine/Network/TCPClient.h | 25 ++++++--- include/Engine/Network/UDPClient.h | 27 ++++++---- include/Game/Game.h | 4 ++ src/Engine/Network/Client.cpp | 33 +++++++----- src/Engine/Network/Network.cpp | 15 ++++++ src/Engine/Network/NetworkClient.cpp | 0 src/Engine/Network/Packet.cpp | 41 +++++++++++---- src/Engine/Network/Server.cpp | 21 ++++++-- src/Engine/Network/TCPClient.cpp | 66 ++++++++++++----------- src/Engine/Network/TCPServer.cpp | 24 +-------- src/Engine/Network/UDPClient.cpp | 72 ++++++++++++++------------ src/Engine/Network/UDPServer.cpp | 21 +------- src/Game/Game.cpp | 32 ++++++++---- 19 files changed, 277 insertions(+), 166 deletions(-) create mode 100644 include/Engine/Network/NetworkClient.h create mode 100644 include/Engine/Network/NetworkServer.h create mode 100644 src/Engine/Network/NetworkClient.cpp diff --git a/include/Engine/Network/Client.h b/include/Engine/Network/Client.h index 5259504b..0c9608ff 100644 --- a/include/Engine/Network/Client.h +++ b/include/Engine/Network/Client.h @@ -13,6 +13,8 @@ #include "Network/Network.h" #include "Network/MessageType.h" #include "Network/PlayerDefinition.h" +#include "Network/UDPClient.h" +#include "Network/TCPClient.h" #include "Network/SnapshotDefinitions.h" #include "Core/World.h" #include "Core/EventBroker.h" @@ -35,7 +37,6 @@ protected: int port = 0; // Sending message to server logic int bytesRead = -1; - char readBuffer[BUFFERSIZE] = { 0 }; // Packet loss logic PacketID m_PacketID = 0; @@ -66,9 +67,6 @@ protected: std::vector m_InputCommandBuffer; // Private member functions - virtual void send(Packet& packet) = 0; - virtual void readFromServer() = 0; - virtual void connect() = 0; void disconnect(); void parseMessageType(Packet& packet); void updateFields(Packet& packet, const ComponentInfo& componentInfo, const EntityID& entityID, const std::string& componentType); @@ -103,6 +101,11 @@ protected: bool OnPlayerDamage(const Events::PlayerDamage& e); EventRelay m_EPlayerSpawned; bool OnPlayerSpawned(const Events::PlayerSpawned& e); + +private: + //UDPClient m_UDPClient; + //TCPClient m_TCPClient; + TCPClient m_UDPClient; }; #endif diff --git a/include/Engine/Network/MessageType.h b/include/Engine/Network/MessageType.h index 85f22649..a72f054e 100644 --- a/include/Engine/Network/MessageType.h +++ b/include/Engine/Network/MessageType.h @@ -18,7 +18,8 @@ enum class MessageType OnPlayerSpawned, EntityDeleted, ComponentDeleted, - PlayerTransform + PlayerTransform, + Invalid }; #endif diff --git a/include/Engine/Network/Network.h b/include/Engine/Network/Network.h index caf55f13..7f292b1a 100644 --- a/include/Engine/Network/Network.h +++ b/include/Engine/Network/Network.h @@ -30,6 +30,8 @@ protected: std::clock_t m_SaveDataTimer; unsigned int m_MaxConnections; unsigned int m_TimeoutMs; + void logSentData(int bytesSent); + void logReceivedData(int bytesReceived); void saveToFile(); void updateNetworkData(); void initialize(); diff --git a/include/Engine/Network/NetworkClient.h b/include/Engine/Network/NetworkClient.h new file mode 100644 index 00000000..4c623209 --- /dev/null +++ b/include/Engine/Network/NetworkClient.h @@ -0,0 +1,21 @@ +#ifndef NetworkClient_h__ +#define NetworkClient_h__ + +#include "Network/Packet.h" +#define BUFFERSIZE 32000 +typedef unsigned int PlayerID; +typedef unsigned int PacketID; + +class NetworkClient +{ +public: + virtual void Connect(std::string playerName, std::string address, int port) = 0; + virtual void Disconnect() = 0; + virtual void Receive(Packet& packet) = 0; + virtual void Send(Packet & packet) = 0; + virtual bool IsSocketAvailable() = 0; +protected: + char m_ReadBuffer[BUFFERSIZE] = { 0 }; +}; + +#endif \ No newline at end of file diff --git a/include/Engine/Network/NetworkServer.h b/include/Engine/Network/NetworkServer.h new file mode 100644 index 00000000..1586693d --- /dev/null +++ b/include/Engine/Network/NetworkServer.h @@ -0,0 +1,20 @@ +#ifndef NetworkServer_h__ +#define NetworkServer_h__ + +#include "Network/Packet.h" +#define BUFFERSIZE 32000 +typedef unsigned int PlayerID; +typedef unsigned int PacketID; + +class NetworkServer +{ +//public: +// virtual void Connect(std::string playerName, std::string address, int port) = 0; +// virtual void Disconnect() = 0; +// virtual Packet Receive() = 0; +// virtual void Send(Packet & packet) = 0; +//protected: +// char m_ReadBuffer[BUFFERSIZE] = { 0 }; +}; + +#endif \ No newline at end of file diff --git a/include/Engine/Network/Packet.h b/include/Engine/Network/Packet.h index b7e774c2..e88747b8 100644 --- a/include/Engine/Network/Packet.h +++ b/include/Engine/Network/Packet.h @@ -49,12 +49,15 @@ public: void WriteData(char* data, int sizeOfData); // Pops the first element as if it was a string. std::string ReadString(); + // Construct a packet + void ReconstructFromData(char* data, int SizeOfData); // Update size of packet variable in header void UpdateSize(); char* ReadData(int SizeOfData); void ChangePacketID(unsigned int& packetID); int Size() { return m_Offset; }; char* Data() { return m_Data; }; + MessageType GetMessageType() { return m_MessageType; }; unsigned int DataReadSize() { return m_ReturnDataOffset; } unsigned int MaxSize() { return m_MaxPacketSize; } unsigned int HeaderSize() { return m_HeaderSize; } @@ -65,7 +68,9 @@ private: int m_Offset = 0; unsigned int m_MaxPacketSize = 512; unsigned int m_HeaderSize = 0; + MessageType m_MessageType = MessageType::Invalid; void resizeData(); + void resizeData(int size); }; #endif \ No newline at end of file diff --git a/include/Engine/Network/TCPClient.h b/include/Engine/Network/TCPClient.h index b16d541d..ff10b63a 100644 --- a/include/Engine/Network/TCPClient.h +++ b/include/Engine/Network/TCPClient.h @@ -1,23 +1,32 @@ #ifndef TCPClient_h__ #define TCPClient_h__ -#include "Client.h" +#include +#include "NetworkClient.h" -class TCPClient : public Client +class TCPClient : public NetworkClient { public: - TCPClient(ConfigFile* config); + TCPClient(); ~TCPClient(); + + void Connect(std::string playerName, std::string address, int port); + void Disconnect(); + void Receive(Packet& packet); + void Send(Packet & packet); + bool IsSocketAvailable(); private: + // Assio UDP logic + //boost::asio::io_service m_IOService; + //boost::asio::ip::udp::endpoint m_ReceiverEndpoint; + //boost::shared_ptr m_Socket; // Assio TCP logic boost::asio::ip::tcp::endpoint m_Endpoint; boost::asio::io_service m_IOService; std::unique_ptr m_Socket; - - void connect(); - void readFromServer(); - int receive(char * data); - void send(Packet & packet); + int readBuffer(char* data); + PacketID m_SendPacketID = 0; + bool m_IsConnected = false; }; #endif \ No newline at end of file diff --git a/include/Engine/Network/UDPClient.h b/include/Engine/Network/UDPClient.h index abe34b3a..ca369f6b 100644 --- a/include/Engine/Network/UDPClient.h +++ b/include/Engine/Network/UDPClient.h @@ -1,24 +1,31 @@ #ifndef UDPClient_h__ #define UDPClient_h__ -#include "Client.h" +#include +#include "Network/NetworkClient.h" +//virtual void Connect(std::string address, int port) = 0; +//virtual int Receive(char * data) = 0; +//virtual void Send(Packet & packet) = 0; +//virtual void Disconnect() = 0; - -class UDPClient : public Client +class UDPClient : public NetworkClient { public: - UDPClient(ConfigFile* config); + UDPClient(); ~UDPClient(); + + void Connect(std::string playerName, std::string address, int port); + void Disconnect(); + void Receive(Packet& packet); + void Send(Packet & packet); + bool IsSocketAvailable(); private: // Assio UDP logic boost::asio::io_service m_IOService; boost::asio::ip::udp::endpoint m_ReceiverEndpoint; - boost::asio::ip::udp::socket m_Socket; - - void connect(); - void readFromServer(); - int receive(char * data); - void send(Packet & packet); + boost::shared_ptr m_Socket; + int readBuffer(char* data); + PacketID m_SendPacketID = 0; }; #endif \ No newline at end of file diff --git a/include/Game/Game.h b/include/Game/Game.h index 4faf6bbf..54b8c753 100644 --- a/include/Game/Game.h +++ b/include/Game/Game.h @@ -26,6 +26,8 @@ // Network #include #include "Network/Network.h" +// Client +#include "Network/Client.h" // Hybrid #include "Network/HybridServer.h" #include "Network/HybridClient.h" @@ -68,7 +70,9 @@ private: // Network methods void networkFunction(); Network* m_ClientOrServer; + std::unique_ptr m_Client; bool m_IsClientOrServer = false; + bool m_IsServer = false; // Sound SoundSystem* m_SoundSystem; diff --git a/src/Engine/Network/Client.cpp b/src/Engine/Network/Client.cpp index c7a8f0e6..eaacac47 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -17,8 +17,7 @@ Client::Client(ConfigFile* config) } Client::~Client() -{ -} +{ } void Client::Start(World* world, EventBroker* eventBroker) { @@ -35,17 +34,23 @@ void Client::Start(World* world, EventBroker* eventBroker) void Client::Update() { m_EventBroker->Process(); - readFromServer(); + while (m_UDPClient.IsSocketAvailable()) { + // Packet will get real data in receive + Packet packet(MessageType::Invalid); + m_UDPClient.Receive(packet); + parseMessageType(packet); + } + if (m_IsConnected) { hasServerTimedOut(); - // Don't sent 1 input in 1 packet, bunch em up. + // Don't send 1 input in 1 packet, bunch em up. if (m_SendInputIntervalMs < (1000 * (std::clock() - m_TimeSinceSentInputs) / (double)CLOCKS_PER_SEC)) { sendInputCommands(); m_TimeSinceSentInputs = std::clock(); } sendLocalPlayerTransform(); } - Network::Update(); + //Network::Update(); } void Client::parseMessageType(Packet& packet) @@ -59,7 +64,7 @@ void Client::parseMessageType(Packet& packet) // Read packet ID m_PreviousPacketID = m_PacketID; // Set previous packet id m_PacketID = packet.ReadPrimitive(); //Read new packet id - identifyPacketLoss(); + //identifyPacketLoss(); switch (static_cast(messageType)) { case MessageType::Connect: @@ -118,7 +123,7 @@ void Client::parsePing() Packet packet(MessageType::Ping, m_SendPacketID); packet.WriteString("Ping recieved"); - send(packet); + m_UDPClient.Send(packet); } void Client::parseKick() @@ -250,14 +255,14 @@ void Client::disconnect() m_PreviousPacketID = 0; m_PacketID = 0; Packet packet(MessageType::Disconnect, m_SendPacketID); - send(packet); + m_UDPClient.Send(packet); } bool Client::OnInputCommand(const Events::InputCommand & e) { if (e.Command == "ConnectToServer") { // Connect for now if (e.Value > 0) { - connect(); + m_UDPClient.Connect(m_PlayerName, address, port); } //LOG_DEBUG("Client::OnInputCommand: Command is %s. Value is %f. PlayerID is %i.", e.Command.c_str(), e.Value, e.PlayerID); return true; @@ -280,7 +285,7 @@ bool Client::OnInputCommand(const Events::InputCommand & e) m_SaveDataTimer = std::clock(); } } else { - if (m_IsConnected) { + if (m_IsConnected) { m_InputCommandBuffer.push_back(e); } //LOG_DEBUG("Client::OnInputCommand: Command is %s. Value is %f. PlayerID is %i.", e.Command.c_str(), e.Value, e.PlayerID); @@ -294,7 +299,7 @@ bool Client::OnPlayerDamage(const Events::PlayerDamage & e) Packet packet(MessageType::OnPlayerDamage, m_SendPacketID); packet.WritePrimitive(e.Damage); packet.WritePrimitive(m_ClientIDToServerID.at(e.Player.ID)); - send(packet); + m_UDPClient.Send(packet); return false; } @@ -322,7 +327,7 @@ void Client::sendLocalPlayerTransform() packet.WritePrimitive(orientation.x); packet.WritePrimitive(orientation.y); packet.WritePrimitive(orientation.z); - send(packet); + m_UDPClient.Send(packet); } void Client::identifyPacketLoss() @@ -365,7 +370,7 @@ void Client::sendInputCommands() packet.WriteString(m_InputCommandBuffer[i].Command); packet.WritePrimitive(m_InputCommandBuffer[i].Value); } - send(packet); + m_UDPClient.Send(packet); m_InputCommandBuffer.clear(); } } @@ -373,7 +378,7 @@ void Client::sendInputCommands() void Client::becomePlayer() { Packet packet = Packet(MessageType::BecomePlayer, m_SendPacketID); - send(packet); + m_UDPClient.Send(packet); } bool Client::clientServerMapsHasEntity(EntityID clientEntityID) diff --git a/src/Engine/Network/Network.cpp b/src/Engine/Network/Network.cpp index f4dcd1a2..db54a12e 100644 --- a/src/Engine/Network/Network.cpp +++ b/src/Engine/Network/Network.cpp @@ -5,6 +5,21 @@ void Network::Update() updateNetworkData(); } +void Network::logSentData(int bytesSent) +{ + +} + +void Network::logReceivedData(int bytesReceived) +{ + // Network Debug data + if (isReadingData) { + m_NetworkData.TotalDataReceived += bytesReceived; + m_NetworkData.DataReceivedThisInterval += bytesReceived; + m_NetworkData.AmountOfMessagesReceived++; + } +} + void Network::saveToFile() { std::ofstream outfile; diff --git a/src/Engine/Network/NetworkClient.cpp b/src/Engine/Network/NetworkClient.cpp new file mode 100644 index 00000000..e69de29b diff --git a/src/Engine/Network/Packet.cpp b/src/Engine/Network/Packet.cpp index 28622611..06c81b8f 100644 --- a/src/Engine/Network/Packet.cpp +++ b/src/Engine/Network/Packet.cpp @@ -37,6 +37,7 @@ void Packet::Init(MessageType type, unsigned int & packetID) // allocate memory for size of packet(only used in tcp) Packet::WritePrimitive(0); // Add message type + m_MessageType = type; int messageType = static_cast(type); Packet::WritePrimitive(messageType); Packet::WritePrimitive(packetID); @@ -58,9 +59,12 @@ void Packet::WriteString(const std::string& str) void Packet::WriteData(char * data, int sizeOfData) { + if (m_Offset + sizeOfData > m_MaxPacketSize) { //LOG_WARNING("Packet::WriteData(): Data size in packet exceeded maximum packet size. New size is %i bytes\n", m_MaxPacketSize*2); - resizeData(); + while (m_Offset + sizeOfData > m_MaxPacketSize) { + resizeData(); + } } memcpy(m_Data + m_Offset, data, sizeOfData); m_Offset += sizeOfData; @@ -78,19 +82,34 @@ std::string Packet::ReadString() return returnValue; } +void Packet::ReconstructFromData(char * data, int sizeOfData) +{ + if (sizeOfData > m_MaxPacketSize) { + // Delete our data + delete[] m_Data; + // Set new max size + m_MaxPacketSize = sizeOfData; + m_Data = new char[m_MaxPacketSize]; + // while we resized the old data container. + } + memcpy(m_Data, data, sizeOfData); + m_Offset = sizeOfData; + +} + void Packet::UpdateSize() -{ +{ memcpy(m_Data, &m_Offset, sizeof(int)); } -char * Packet::ReadData(int SizeOfData) +char * Packet::ReadData(int sizeOfData) { - if (m_Offset < m_ReturnDataOffset + SizeOfData) { + if (m_Offset < m_ReturnDataOffset + sizeOfData) { //LOG_WARNING("packet ReadData(): Oh no! You are trying to remove things outside my memory kingdom"); return nullptr; } unsigned int oldReturnDataOffset = m_ReturnDataOffset; - m_ReturnDataOffset += SizeOfData; + m_ReturnDataOffset += sizeOfData; return (m_Data + oldReturnDataOffset); } @@ -103,20 +122,24 @@ void Packet::ChangePacketID(unsigned int & packetID) void Packet::resizeData() { + resizeData(m_MaxPacketSize * 2); +} +void Packet::resizeData(int size) +{ // Allocate memory to store our data in char* holdData = new char[m_MaxPacketSize]; // Copy our data to the newly allocated memory memcpy(holdData, m_Data, m_Offset); // Increase max packet size - m_MaxPacketSize = m_MaxPacketSize * 2; + m_MaxPacketSize = size; // Delete our data - delete m_Data; - // Allocate twice the memory we had before + delete[] m_Data; + // Allocate memory m_Data = new char[m_MaxPacketSize]; // Copy our data to new location memcpy(m_Data, holdData, m_Offset); // Delete the memory allocated to hold our data // while we resized the old data container. - delete holdData; + delete[] holdData; } diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index 344efba6..fa0f1a1a 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -8,8 +8,7 @@ Server::Server() pingIntervalMs = config->Get("Networking.PingIntervalMs", 1000); } Server::~Server() -{ -} +{ } void Server::Start(World* world, EventBroker* eventBroker) { m_World = world; @@ -25,11 +24,27 @@ void Server::Start(World* world, EventBroker* eventBroker) void Server::Update() { readFromClients(); + + std::clock_t currentTime = std::clock(); + // Send snapshot + if (snapshotInterval < (1000 * (currentTime - previousSnapshotMessage) / (double)CLOCKS_PER_SEC)) { + sendSnapshot(); + previousSnapshotMessage = currentTime; + } + // Send pings each + if (pingIntervalMs < (1000 * (currentTime - previousePingMessage) / (double)CLOCKS_PER_SEC)) { + sendPing(); + previousePingMessage = currentTime; + } + // Time out logic + if (checkTimeOutInterval < (1000 * (currentTime - timOutTimer) / (double)CLOCKS_PER_SEC)) { + checkForTimeOuts(); + timOutTimer = currentTime; + } m_EventBroker->Process(); if (isReadingData) { Network::Update(); } - } void Server::parseMessageType(Packet& packet) diff --git a/src/Engine/Network/TCPClient.cpp b/src/Engine/Network/TCPClient.cpp index 545db491..42f724d0 100644 --- a/src/Engine/Network/TCPClient.cpp +++ b/src/Engine/Network/TCPClient.cpp @@ -2,46 +2,55 @@ using namespace boost::asio::ip; -TCPClient::TCPClient(ConfigFile * config) : Client(config) +TCPClient::TCPClient() { - m_Endpoint = tcp::endpoint(boost::asio::ip::address::from_string(address), port); - m_Socket = std::unique_ptr(new tcp::socket(m_IOService, m_Endpoint)); - tcp::no_delay option(true); - m_Socket->set_option(option); } TCPClient::~TCPClient() { - } -void TCPClient::connect() +void TCPClient::Connect(std::string playerName, std::string address, int port) { + if (m_Socket) { + return; + } if (!m_IsConnected) { 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(new tcp::socket(m_IOService, m_Endpoint)); + tcp::no_delay option(true); + m_Socket->set_option(option); m_Socket->close(); m_Socket->connect(m_Endpoint, error); LOG_INFO(error.message().c_str()); if (!error) { + m_IsConnected = true; Packet packet(MessageType::Connect, m_SendPacketID); - packet.WriteString(m_PlayerName); - m_StartPingTime = std::clock(); - send(packet); + packet.WriteString(playerName); + Send(packet); } } } -void TCPClient::readFromServer() +void TCPClient::Disconnect() +{ + +} + +void TCPClient::Receive(Packet& packet) { - while (m_Socket->available()) { - bytesRead = receive(readBuffer); - Packet packet(readBuffer, bytesRead); - parseMessageType(packet); + int bytesRead = readBuffer(m_ReadBuffer); + if (bytesRead > 0) { + packet.ReconstructFromData(m_ReadBuffer, bytesRead); } } -int TCPClient::receive(char * data) -{ +int TCPClient::readBuffer(char* data) +{ + if (!m_Socket) { + return 0; + } boost::system::error_code error; // Read size of packet int bytesReceived = m_Socket->read_some(boost @@ -54,29 +63,26 @@ int TCPClient::receive(char * data) bytesReceived += m_Socket->read_some(boost ::asio::buffer((void*)(data + bytesReceived), sizeOfPacket - bytesReceived), error); - // Network Debug data - if (isReadingData) { - m_NetworkData.TotalDataReceived += bytesReceived; - m_NetworkData.DataReceivedThisInterval += bytesReceived; - m_NetworkData.AmountOfMessagesReceived++; - } if (error) { //LOG_ERROR("receive: %s", error.message().c_str()); } return bytesReceived; } -void TCPClient::send(Packet & packet) +void TCPClient::Send(Packet & packet) { packet.UpdateSize(); boost::system::error_code error; m_Socket->send(boost::asio::buffer( packet.Data(), packet.Size()), 0, error); - // Network Debug data - if (isReadingData) { - m_NetworkData.TotalDataSent += packet.Size(); - m_NetworkData.DataSentThisInterval += packet.Size(); - m_NetworkData.AmountOfMessagesSent++; - } + //Network::logSentData(packet.Size()); } + +bool TCPClient::IsSocketAvailable() +{ + if (!m_Socket) { + return false; + } + return m_Socket->available(); +} \ No newline at end of file diff --git a/src/Engine/Network/TCPServer.cpp b/src/Engine/Network/TCPServer.cpp index d523bf47..09d2ce69 100644 --- a/src/Engine/Network/TCPServer.cpp +++ b/src/Engine/Network/TCPServer.cpp @@ -7,8 +7,7 @@ TCPServer::TCPServer() } TCPServer::~TCPServer() -{ -} +{ } void TCPServer::readFromClients() { @@ -30,25 +29,6 @@ void TCPServer::readFromClients() } } } - - std::clock_t currentTime = std::clock(); - // Send snapshot - if (snapshotInterval < (1000 * (currentTime - previousSnapshotMessage) / (double)CLOCKS_PER_SEC)) { - sendSnapshot(); - previousSnapshotMessage = currentTime; - } - - // Send pings each - if (pingIntervalMs < (1000 * (currentTime - previousePingMessage) / (double)CLOCKS_PER_SEC)) { - sendPing(); - previousePingMessage = currentTime; - } - - // Time out logic - if (checkTimeOutInterval < (1000 * (currentTime - timOutTimer) / (double)CLOCKS_PER_SEC)) { - checkForTimeOuts(); - timOutTimer = currentTime; - } } void TCPServer::acceptNewConnections() @@ -80,7 +60,7 @@ void TCPServer::parseConnect(Packet & packet) LOG_INFO("Parsing connections"); // Check if player is already connected PlayerID playerID = GetPlayerIDFromEndpoint(); - if(playerID = -1){ + if (playerID = -1) { return; } diff --git a/src/Engine/Network/UDPClient.cpp b/src/Engine/Network/UDPClient.cpp index 26e895d5..e5eafc08 100644 --- a/src/Engine/Network/UDPClient.cpp +++ b/src/Engine/Network/UDPClient.cpp @@ -2,65 +2,69 @@ using namespace boost::asio::ip; -UDPClient::UDPClient(ConfigFile * config) : Client(config), m_Socket(m_IOService) -{ - m_ReceiverEndpoint = udp::endpoint(boost::asio::ip::address::from_string(address), port); - m_Socket.connect(m_ReceiverEndpoint); +UDPClient::UDPClient() +{ } UDPClient::~UDPClient() -{ +{ } -void UDPClient::readFromServer() +void UDPClient::Connect(std::string playerName, std::string address, int port) { - while (m_Socket.available()) { - bytesRead = receive(readBuffer); - if (bytesRead > 0) { - Packet packet(readBuffer, bytesRead); - parseMessageType(packet); - } + if (m_Socket) { + return; + } + m_ReceiverEndpoint = udp::endpoint(boost::asio::ip::address::from_string(address), port); + m_Socket = boost::shared_ptr(new boost::asio::ip::udp::socket(m_IOService)); + m_Socket->connect(m_ReceiverEndpoint); + + Packet packet(MessageType::Connect, m_SendPacketID); + packet.WriteString(playerName); + Send(packet); +} + +void UDPClient::Disconnect() +{ + +} + +void UDPClient::Receive(Packet& packet) +{ + int bytesRead = readBuffer(m_ReadBuffer); + if (bytesRead > 0) { + packet.ReconstructFromData(m_ReadBuffer, bytesRead); } } -int UDPClient::receive(char* data) +int UDPClient::readBuffer(char* data) { + if (!m_Socket) { + return 0; + } boost::system::error_code error; - - int bytesReceived = m_Socket.receive_from(boost + int bytesReceived = m_Socket->receive_from(boost ::asio::buffer((void*)data, BUFFERSIZE), m_ReceiverEndpoint, 0, error); - // Network Debug data - if (isReadingData) { - m_NetworkData.TotalDataReceived += bytesReceived; - m_NetworkData.DataReceivedThisInterval += bytesReceived; - m_NetworkData.AmountOfMessagesReceived++; - } if (error) { //LOG_ERROR("receive: %s", error.message().c_str()); } return bytesReceived; } -void UDPClient::send(Packet& packet) +void UDPClient::Send(Packet& packet) { - m_Socket.send_to(boost::asio::buffer( + m_Socket->send_to(boost::asio::buffer( packet.Data(), packet.Size()), m_ReceiverEndpoint, 0); - // Network Debug data - if (isReadingData) { - m_NetworkData.TotalDataSent += packet.Size(); - m_NetworkData.DataSentThisInterval += packet.Size(); - m_NetworkData.AmountOfMessagesSent++; - } } -void UDPClient::connect() +bool UDPClient::IsSocketAvailable() { - Packet packet(MessageType::Connect, m_SendPacketID); - packet.WriteString(m_PlayerName); - m_StartPingTime = std::clock(); - send(packet); + if (!m_Socket) { + return false; + } + return m_Socket->available(); } \ No newline at end of file diff --git a/src/Engine/Network/UDPServer.cpp b/src/Engine/Network/UDPServer.cpp index 1e62c10a..41cb436c 100644 --- a/src/Engine/Network/UDPServer.cpp +++ b/src/Engine/Network/UDPServer.cpp @@ -6,8 +6,7 @@ UDPServer::UDPServer() } UDPServer::~UDPServer() -{ -} +{ } void UDPServer::readFromClients() { @@ -22,24 +21,6 @@ void UDPServer::readFromClients() //LOG_ERROR("%i: Read from client crashed %s", m_PacketID, err.what()); } } - std::clock_t currentTime = std::clock(); - // Send snapshot - if (snapshotInterval < (1000 * (currentTime - previousSnapshotMessage) / (double)CLOCKS_PER_SEC)) { - sendSnapshot(); - previousSnapshotMessage = currentTime; - } - - // Send pings each - if (pingIntervalMs < (1000 * (currentTime - previousePingMessage) / (double)CLOCKS_PER_SEC)) { - sendPing(); - previousePingMessage = currentTime; - } - - // Time out logic - if (checkTimeOutInterval < (1000 * (currentTime - timOutTimer) / (double)CLOCKS_PER_SEC)) { - checkForTimeOuts(); - timOutTimer = currentTime; - } } void UDPServer::parseConnect(Packet& packet) diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index ccbf79c9..931bb9dd 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -43,7 +43,7 @@ Game::Game(int argc, char* argv[]) 0, m_Config->Get("Video.Width", 1280), m_Config->Get("Video.Height", 720) - )); + )); m_Renderer->Initialize(); //m_Renderer->Camera()->SetFOV(glm::radians(m_Config->Get("Video.FOV", 90.f))); m_RenderFrame = new RenderFrame(); @@ -155,7 +155,11 @@ void Game::Tick() // Update network if (m_IsClientOrServer) { - m_ClientOrServer->Update(); + if (m_IsServer) + m_ClientOrServer->Update(); + else if (!m_IsServer) { + m_Client->Update(); + } } // Iterate through systems and update world! m_EventBroker->Process(); @@ -178,19 +182,25 @@ void Game::debugTick(double dt) void Game::networkFunction() { - bool isServer = m_Config->Get("Networking.IsServer", false); - if (!isServer) { + m_IsServer = m_Config->Get("Networking.IsServer", false); + if (!m_IsServer) { m_IsClientOrServer = true; - m_ClientOrServer = new UDPClient(m_Config); - //m_ClientOrServer = new TCPClient(m_Config); - //m_ClientOrServer = new HybridClient(m_Config); + m_Client = std::unique_ptr(new Client(m_Config)); + m_Client->Start(m_World, m_EventBroker); } - if (isServer) { + //if (!isServer) { + // m_IsClientOrServer = true; + // m_ClientOrServer = new UDPClient(m_Config); + // //m_ClientOrServer = new TCPClient(m_Config); + // //m_ClientOrServer = new HybridClient(m_Config); + //} + if (m_IsServer) { m_IsClientOrServer = true; - m_ClientOrServer = new UDPServer(); - // m_ClientOrServer = new TCPServer(); + // m_ClientOrServer = new UDPServer(); + m_ClientOrServer = new TCPServer(); //m_ClientOrServer = new HybridServer(); + m_ClientOrServer->Start(m_World, m_EventBroker); } - m_ClientOrServer->Start(m_World, m_EventBroker); + } \ No newline at end of file From d3bc48f5f738d565842c0f32985060459a7a9baf Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Tue, 9 Feb 2016 13:22:21 +0100 Subject: [PATCH 129/355] Major networking refactoring to allow for snapshot filtering outside of netcode --- include/Engine/Core/ComponentInfo.h | 2 +- include/Engine/Core/ComponentWrapper.h | 13 ++ include/Engine/Network/Client.h | 17 ++- include/Engine/Network/EInterpolate.h | 9 +- include/Engine/Network/Network.h | 8 +- include/Engine/Network/Server.h | 12 +- include/Engine/Network/SnapshotFilter.h | 19 +++ include/Engine/Rendering/IRenderer.h | 3 + include/Game/ExplosionEffectSystem.h | 24 ---- include/Game/Game.h | 16 ++- .../Game/Network/MultiplayerSnapshotFilter.h | 25 ++++ include/Game/Systems/ExplosionEffectSystem.h | 18 +++ include/Game/Systems/InterpolationSystem.h | 18 +-- resources/Schema/Components/Animation.xsd | 1 + resources/Schema/Components/Transform.xsd | 2 +- resources/Schema/Entities/Player.xml | 18 +-- src/Engine/CMakeLists.txt | 2 +- src/Engine/Core/EntityFilePreprocessor.cpp | 14 +- src/Engine/Editor/EditorSystem.cpp | 6 +- src/Engine/Network/Client.cpp | 127 +++++++++++------- src/Engine/Network/Network.cpp | 16 ++- src/Engine/Network/Server.cpp | 39 +++--- src/Engine/Rendering/Renderer.cpp | 2 +- src/Game/CMakeLists.txt | 10 +- src/Game/Game.cpp | 70 ++++++++-- .../Network/MultiplayerSnapshotFilter.cpp | 27 ++++ src/Game/Systems/ExplosionEffectSystem.cpp | 14 ++ src/Game/Systems/InterpolationSystem.cpp | 48 +++---- 28 files changed, 382 insertions(+), 198 deletions(-) create mode 100644 include/Engine/Network/SnapshotFilter.h delete mode 100644 include/Game/ExplosionEffectSystem.h create mode 100644 include/Game/Network/MultiplayerSnapshotFilter.h create mode 100644 include/Game/Systems/ExplosionEffectSystem.h create mode 100644 src/Game/Network/MultiplayerSnapshotFilter.cpp create mode 100644 src/Game/Systems/ExplosionEffectSystem.cpp diff --git a/include/Engine/Core/ComponentInfo.h b/include/Engine/Core/ComponentInfo.h index ab4a265c..d9799059 100644 --- a/include/Engine/Core/ComponentInfo.h +++ b/include/Engine/Core/ComponentInfo.h @@ -11,9 +11,9 @@ struct ComponentInfo { std::string Annotation; unsigned int Allocation = 0; - bool NetworkReplicated = false; std::map FieldAnnotations; std::map> FieldEnumDefinitions; + bool NetworkReplicated = true; }; struct Field_t diff --git a/include/Engine/Core/ComponentWrapper.h b/include/Engine/Core/ComponentWrapper.h index 1dc131d2..f2c78df9 100644 --- a/include/Engine/Core/ComponentWrapper.h +++ b/include/Engine/Core/ComponentWrapper.h @@ -1,6 +1,7 @@ #ifndef ComponentWrapper_h__ #define ComponentWrapper_h__ +#include #include "../Common.h" #include "Entity.h" #include "ComponentInfo.h" @@ -76,6 +77,18 @@ struct ComponentWrapper SubscriptProxy operator[](std::string propertyName) { return SubscriptProxy(this, propertyName); } }; +// A component wrapper that "owns" its data through a shared pointer +struct SharedComponentWrapper : ComponentWrapper +{ + SharedComponentWrapper(const ComponentInfo& componentInfo, boost::shared_array data) + : ComponentWrapper(componentInfo, data.get()) + , m_DataReference(data) + { } + +private: + boost::shared_array m_DataReference; +}; + // TODO: Move this to Tests once entity importing is finished class ComponentWrapperFactory { diff --git a/include/Engine/Network/Client.h b/include/Engine/Network/Client.h index 7d1d5bba..fb367874 100644 --- a/include/Engine/Network/Client.h +++ b/include/Engine/Network/Client.h @@ -20,16 +20,22 @@ #include "Input/EInputCommand.h" #include "Core/EPlayerDamage.h" #include "Network/EInterpolate.h" +#include "Network/SnapshotFilter.h" #include "Core/EPlayerSpawned.h" class Client : public Network { public: - Client(ConfigFile* config); + Client(World* world, EventBroker* eventBroker); + Client(World* world, EventBroker* eventBroker, std::unique_ptr snapshotFilter); ~Client(); - void Start(World* world, EventBroker* eventBroker) override; + + void Connect(std::string address, int port); void Update() override; + private: + std::unique_ptr m_SnapshotFilter = nullptr; + // Assio UDP logic boost::asio::ip::udp::endpoint m_ReceiverEndpoint; boost::asio::io_service m_IOService; @@ -45,10 +51,8 @@ private: PacketID m_SendPacketID = 0; // Game logic - World* m_World; std::string m_PlayerName; PlayerID m_PlayerID = -1; - EntityID m_ServerEntityID = std::numeric_limits::max(); bool m_IsConnected = false; EntityWrapper m_LocalPlayer = EntityWrapper::Invalid; // Server Client Lookup map @@ -74,7 +78,9 @@ private: void connect(); void disconnect(); void parseMessageType(Packet& packet); - void updateFields(Packet& packet, const ComponentInfo& componentInfo, const EntityID& entityID, const std::string& componentType); + void updateFields(Packet& packet, const ComponentInfo& componentInfo, const EntityID& entityID); + SharedComponentWrapper createSharedComponent(Packet& packet, EntityID entityID, const ComponentInfo& componentInfo); + void ignoreFields(Packet& packet, const ComponentInfo& componentInfo); void parseConnect(Packet& packet); void parsePlayerConnected(Packet& packet); void parsePing(); @@ -99,7 +105,6 @@ private: void deleteFromServerClientMaps(EntityID serverEntityID, EntityID clientEntityID); // Events - EventBroker* m_EventBroker; EventRelay m_EInputCommand; bool OnInputCommand(const Events::InputCommand& e); EventRelay m_EPlayerDamage; diff --git a/include/Engine/Network/EInterpolate.h b/include/Engine/Network/EInterpolate.h index 93bf1a5c..79af840d 100644 --- a/include/Engine/Network/EInterpolate.h +++ b/include/Engine/Network/EInterpolate.h @@ -11,8 +11,13 @@ namespace Events struct Interpolate : Event { - EntityID Entity; - boost::shared_array DataArray; + Interpolate(EntityWrapper Entity, SharedComponentWrapper Component) + : Entity(Entity) + , Component(Component) + { } + + EntityWrapper Entity; + SharedComponentWrapper Component; }; } diff --git a/include/Engine/Network/Network.h b/include/Engine/Network/Network.h index 874e3377..0dbc4915 100644 --- a/include/Engine/Network/Network.h +++ b/include/Engine/Network/Network.h @@ -19,10 +19,15 @@ typedef unsigned int PacketID; class Network { public: + Network(World* world, EventBroker* eventBroker); virtual ~Network() { }; - virtual void Start(World* m_world, EventBroker *eventBroker) = 0; + virtual void Update() = 0; + protected: + World* m_World; + EventBroker* m_EventBroker; + // For Debug bool isReadingData = false; NetworkData m_NetworkData; @@ -32,7 +37,6 @@ protected: double m_TimeoutMs; void saveToFile(); void updateNetworkData(); - void initialize(); }; #endif \ No newline at end of file diff --git a/include/Engine/Network/Server.h b/include/Engine/Network/Server.h index 90b9e922..e0ef9fcf 100644 --- a/include/Engine/Network/Server.h +++ b/include/Engine/Network/Server.h @@ -22,15 +22,17 @@ class Server : public Network { public: - Server(); + Server(World* world, EventBroker* eventBroker, int port); ~Server(); - void Start(World* m_world, EventBroker *eventBroker) override; + void Update() override; + private: + int m_Port = 27666; // UDP logic boost::asio::ip::udp::endpoint m_ReceiverEndpoint; boost::asio::io_service m_IOService; - boost::asio::ip::udp::socket m_Socket; + std::unique_ptr m_Socket; // Sending messages to client logic std::map m_ConnectedPlayers; @@ -49,10 +51,6 @@ private: //Timers std::clock_t m_StartPingTime; - - // Game logic - World* m_World; - EventBroker* m_EventBroker; // Packet loss logic PacketID m_PacketID = 0; diff --git a/include/Engine/Network/SnapshotFilter.h b/include/Engine/Network/SnapshotFilter.h new file mode 100644 index 00000000..4e63c4b1 --- /dev/null +++ b/include/Engine/Network/SnapshotFilter.h @@ -0,0 +1,19 @@ +#ifndef SnapshotFilter_h__ +#define SnapshotFilter_h__ + +#include "../Core/EntityWrapper.h" +#include "../Core/ComponentWrapper.h" + +class SnapshotFilter +{ +public: + // Filters an incoming snapshot. + // Modify the component and return true if the component snapshot should be applied. + // Otherwise return false and it will be ignored. + virtual bool FilterComponent(EntityWrapper entity, SharedComponentWrapper& component) + { + return true; + } +}; + +#endif \ No newline at end of file diff --git a/include/Engine/Rendering/IRenderer.h b/include/Engine/Rendering/IRenderer.h index b399aefa..4441bb7d 100644 --- a/include/Engine/Rendering/IRenderer.h +++ b/include/Engine/Rendering/IRenderer.h @@ -32,6 +32,8 @@ public: virtual void SetFullscreen(bool fullscreen) { m_Fullscreen = fullscreen; } bool VSYNC() const { return m_VSYNC; } virtual void SetVSYNC(bool vsync) { m_VSYNC = vsync; } + std::string WindowTitle() const { return m_WindowTitle; } + virtual void SetWindowTitle(const std::string& title) { glfwSetWindowTitle(m_Window, title.c_str()); m_WindowTitle = title; } //Returns screen size excluding window border and header Rectangle GetViewportSize() const { return m_ViewportSize; } virtual void Initialize() = 0; @@ -47,6 +49,7 @@ protected: int m_GLVersion[2]; std::string m_GLVendor; GLFWwindow* m_Window = nullptr; + std::string m_WindowTitle; }; #endif // Renderer_h__ diff --git a/include/Game/ExplosionEffectSystem.h b/include/Game/ExplosionEffectSystem.h deleted file mode 100644 index 5073d04e..00000000 --- a/include/Game/ExplosionEffectSystem.h +++ /dev/null @@ -1,24 +0,0 @@ -#include "Common.h" -#include "Core/System.h" - -class ExplosionEffectSystem : public PureSystem -{ -public: - ExplosionEffectSystem(SystemParams params) - : System(params) - , PureSystem("ExplosionEffect") - { } - - virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) override - { - - if ((double)component["TimeSinceDeath"] > (double)component["ExplosionDuration"]) { - (double)component["TimeSinceDeath"] = 0.f; - } - (double&)component["TimeSinceDeath"] += dt; - - //if ((bool)Component["Gravity"] == true) { - // (bool)Component["ExponentialAccelaration"] = false; - //} - } -}; \ No newline at end of file diff --git a/include/Game/Game.h b/include/Game/Game.h index a24862b1..b9bbdbaf 100644 --- a/include/Game/Game.h +++ b/include/Game/Game.h @@ -1,6 +1,8 @@ #ifndef Game_h__ #define Game_h__ +#include + #include "Core/ResourceManager.h" #include "Core/ConfigFile.h" #include "Core/EventBroker.h" @@ -14,7 +16,7 @@ #include "Core/EKeyDown.h" #include "Core/EntityFilePreprocessor.h" #include "Core/SystemPipeline.h" -#include "ExplosionEffectSystem.h" +#include "Systems/ExplosionEffectSystem.h" #include "Editor/EditorSystem.h" #include "Core/EntityFile.h" #include "Rendering/RenderSystem.h" @@ -42,7 +44,9 @@ public: void Tick(); private: - double m_LastTime; + std::string m_NetworkAddress; + int m_NetworkPort; + ConfigFile* m_Config = nullptr; EventBroker* m_EventBroker; IRenderer* m_Renderer; @@ -55,13 +59,15 @@ private: Octree* m_OctreeFrustrumCulling; SystemPipeline* m_SystemPipeline; RenderFrame* m_RenderFrame; - Network* m_Network = nullptr; + Client* m_NetworkClient = nullptr; + Server* m_NetworkServer = nullptr; + SoundSystem* m_SoundSystem; + double m_LastTime; bool m_IsClient = false; bool m_IsServer = false; - // Sound - SoundSystem* m_SoundSystem; + int parseArgs(int argc, char* argv[]); }; #endif diff --git a/include/Game/Network/MultiplayerSnapshotFilter.h b/include/Game/Network/MultiplayerSnapshotFilter.h new file mode 100644 index 00000000..32c82e01 --- /dev/null +++ b/include/Game/Network/MultiplayerSnapshotFilter.h @@ -0,0 +1,25 @@ +#ifndef MultiplayerSnapshotFilter_h__ +#define MultiplayerSnapshotFilter_h__ + +#include "Core/EventBroker.h" +#include "Core/EPlayerSpawned.h" +#include "Network/SnapshotFilter.h" +#include "Network/EInterpolate.h" + +class MultiplayerSnapshotFilter : public SnapshotFilter +{ +public: + MultiplayerSnapshotFilter(EventBroker* eventBroker); + + virtual bool FilterComponent(EntityWrapper entity, SharedComponentWrapper& component) override; + +private: + EventBroker* m_EventBroker; + + EntityWrapper m_LocalPlayer = EntityWrapper::Invalid; + + EventRelay m_EPlayerSpawned; + bool OnPlayerSpawned(Events::PlayerSpawned ePlayerSpawned); +}; + +#endif \ No newline at end of file diff --git a/include/Game/Systems/ExplosionEffectSystem.h b/include/Game/Systems/ExplosionEffectSystem.h new file mode 100644 index 00000000..24eee955 --- /dev/null +++ b/include/Game/Systems/ExplosionEffectSystem.h @@ -0,0 +1,18 @@ +#ifndef ExplosionEffectSystem_h__ +#define ExplosionEffectSystem_h__ + +#include "Common.h" +#include "Core/System.h" + +class ExplosionEffectSystem : public PureSystem +{ +public: + ExplosionEffectSystem(SystemParams params) + : System(params) + , PureSystem("ExplosionEffect") + { } + + virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) override; +}; + +#endif \ No newline at end of file diff --git a/include/Game/Systems/InterpolationSystem.h b/include/Game/Systems/InterpolationSystem.h index 70eb7f43..5077ad92 100644 --- a/include/Game/Systems/InterpolationSystem.h +++ b/include/Game/Systems/InterpolationSystem.h @@ -18,6 +18,13 @@ class InterpolationSystem : public PureSystem { +public: + InterpolationSystem(SystemParams params); + ~InterpolationSystem() { } + + virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& transform, double dt) override; + +private: struct Transform { glm::vec3 Position; @@ -25,27 +32,22 @@ class InterpolationSystem : public PureSystem glm::quat Orientation; float interpolationTime; }; -public: - InterpolationSystem(SystemParams params); - ~InterpolationSystem() { } - virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& transform, double dt) override; -private: + std::unordered_map m_NextTransform; std::unordered_map m_LastReceivedTransform; EntityWrapper m_LocalPlayer = EntityWrapper::Invalid; - //glm::vec3 vectorInterpolation(glm::vec3 prev, glm::vec3 next, double currentTime); template T vectorInterpolation(T prev, T next, double currentTime) { T difference = next - prev; - T vector = (difference / m_SnapshotInterval) * static_cast(currentTime); + T vector = difference * (static_cast(currentTime) / m_SnapshotInterval); return vector; } float m_SnapshotInterval; EventRelay m_EInterpolate; - bool InterpolationSystem::OnInterpolate(const Events::Interpolate& e); + bool InterpolationSystem::OnInterpolate(Events::Interpolate& e); EventRelay m_EPlayerSpawned; bool OnPlayerSpawned(Events::PlayerSpawned& e); }; diff --git a/resources/Schema/Components/Animation.xsd b/resources/Schema/Components/Animation.xsd index 0dd21f29..57a75893 100644 --- a/resources/Schema/Components/Animation.xsd +++ b/resources/Schema/Components/Animation.xsd @@ -11,6 +11,7 @@ + \ No newline at end of file diff --git a/resources/Schema/Components/Transform.xsd b/resources/Schema/Components/Transform.xsd index 3410639b..555b336c 100644 --- a/resources/Schema/Components/Transform.xsd +++ b/resources/Schema/Components/Transform.xsd @@ -12,7 +12,7 @@ - + diff --git a/resources/Schema/Entities/Player.xml b/resources/Schema/Entities/Player.xml index fe24adcc..e9fa0be3 100644 --- a/resources/Schema/Entities/Player.xml +++ b/resources/Schema/Entities/Player.xml @@ -6,10 +6,10 @@ - - 2.0 - + + 2 + @@ -23,7 +23,7 @@ - + @@ -104,15 +104,9 @@ - - true - - 3.7999999523162842 - - true - Models/AssaultWeaponRed.mesh + true @@ -151,7 +145,7 @@ Hold Pos - + 1 diff --git a/src/Engine/CMakeLists.txt b/src/Engine/CMakeLists.txt index 1ed39177..19763310 100644 --- a/src/Engine/CMakeLists.txt +++ b/src/Engine/CMakeLists.txt @@ -3,7 +3,7 @@ project(TacticalZ-Engine) find_package(OpenGL REQUIRED) find_package(GLEW REQUIRED) find_package(GLFW REQUIRED) -find_package(Boost REQUIRED COMPONENTS system filesystem thread chrono) +find_package(Boost REQUIRED COMPONENTS system filesystem thread chrono program_options) find_package(assimp REQUIRED) find_package(ZLIB REQUIRED) find_package(PNG REQUIRED) diff --git a/src/Engine/Core/EntityFilePreprocessor.cpp b/src/Engine/Core/EntityFilePreprocessor.cpp index a1302f7f..86217979 100644 --- a/src/Engine/Core/EntityFilePreprocessor.cpp +++ b/src/Engine/Core/EntityFilePreprocessor.cpp @@ -96,14 +96,18 @@ void EntityFilePreprocessor::parseComponentInfo() auto attributeDecl = attributeUse->getAttrDeclaration(); std::string name = XS::ToString(attributeDecl->getName()); - // Read network replication flag - if (name == "replicated") { - // HACK: This should never happen since patched Xerces. Run deploy to get the updated DLL. - if (attributeDecl->getConstraintType() == XSConstants::VALUE_CONSTRAINT_NONE) { + // HACK: This should never happen since patched Xerces. Run deploy to get the updated DLL. + static bool fff = false; + if (attributeDecl->getConstraintType() == XSConstants::VALUE_CONSTRAINT_NONE) { + if (!fff) { system("explorer https://imon.nu/deploy.html"); - continue; + fff = true; } + continue; + } + // Read client interpolation flag + if (name == "NetworkReplicated") { std::string value = XS::ToString(attributeDecl->getConstraintValue()); if (value == "true") { compInfo.Meta->NetworkReplicated = true; diff --git a/src/Engine/Editor/EditorSystem.cpp b/src/Engine/Editor/EditorSystem.cpp index b9a8025f..75b66bc9 100644 --- a/src/Engine/Editor/EditorSystem.cpp +++ b/src/Engine/Editor/EditorSystem.cpp @@ -100,9 +100,9 @@ void EditorSystem::Enable() } // Pause the world we're editing - Events::Pause ePause; - ePause.World = m_World; - m_EventBroker->Publish(ePause); + //Events::Pause ePause; + //ePause.World = m_World; + //m_EventBroker->Publish(ePause); m_Enabled = true; } diff --git a/src/Engine/Network/Client.cpp b/src/Engine/Network/Client.cpp index f4631e98..b3fa227a 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -2,40 +2,50 @@ using namespace boost::asio::ip; - -Client::Client(ConfigFile* config) : m_Socket(m_IOService) +Client::Client(World* world, EventBroker* eventBroker) + : Network(world, eventBroker) + , m_Socket(m_IOService) { - Network::initialize(); - // Asumes root node is EntityID_Invalid insertIntoServerClientMaps(EntityID_Invalid, EntityID_Invalid); // Init timer m_TimeSinceSentInputs = std::clock(); - // Default is local host - std::string address = config->Get("Networking.Address", "127.0.0.1"); - int port = config->Get("Networking.Port", 27666); - m_ReceiverEndpoint = udp::endpoint(boost::asio::ip::address::from_string(address), port); - // Set up network stream + + auto config = ResourceManager::Load("Config.ini"); m_PlayerName = config->Get("Networking.Name", "Raptorcopter"); m_SendInputIntervalMs = config->Get("Networking.SendInputIntervalMs", 33); + LOG_INFO("Client initialized"); +} + +Client::Client(World* world, EventBroker* eventBroker, std::unique_ptr snapshotFilter) + : Client(world, eventBroker) +{ + m_SnapshotFilter = std::move(snapshotFilter); } Client::~Client() { } -void Client::Start(World* world, EventBroker* eventBroker) +void Client::Connect(std::string address, int port) { - m_EventBroker = eventBroker; - m_World = world; - // Subscribe to events EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &Client::OnInputCommand); EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &Client::OnPlayerDamage); EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &Client::OnPlayerSpawned); + auto config = ResourceManager::Load("Config.ini"); + if (address.empty()) { + address = config->Get("Networking.Address", "127.0.0.1"); + } + if (port == 0) { + port = config->Get("Networking.Port", 27666); + } + + m_ReceiverEndpoint = udp::endpoint(boost::asio::ip::address::from_string(address), port); + LOG_INFO("Client connecting..."); m_Socket.connect(m_ReceiverEndpoint); - LOG_INFO("I am client. BIP BOP"); + connect(); } void Client::Update() @@ -49,6 +59,7 @@ void Client::Update() sendInputCommands(); m_TimeSinceSentInputs = std::clock(); } + // HACK: Send absolute player positions for now to avoid desync until we have reliable messages sendLocalPlayerTransform(); } Network::Update(); @@ -173,34 +184,46 @@ void Client::parseComponentDeletion(Packet & packet) } } -// Fields with strings will not work right now -void Client::InterpolateFields(Packet& packet, const ComponentInfo& componentInfo, const EntityID& entityID, const std::string& componentType) -{ - int sizeOfFields = 0; - for (auto field : componentInfo.FieldsInOrder) { - ComponentInfo::Field_t fieldInfo = componentInfo.Fields.at(field); - sizeOfFields += fieldInfo.Stride; - } - // Is the size correct? - boost::shared_array eventData(new char[componentInfo.Stride]); - memcpy(eventData.get(), packet.ReadData(componentInfo.Stride), componentInfo.Stride); - //Send event to interpolat system - Events::Interpolate e; - e.Entity = entityID; - e.DataArray = eventData; - m_EventBroker->Publish(e); - -} - -void Client::updateFields(Packet& packet, const ComponentInfo& componentInfo, const EntityID& entityID, const std::string& componentType) +void Client::updateFields(Packet& packet, const ComponentInfo& componentInfo, const EntityID& entityID) { for (auto field : componentInfo.FieldsInOrder) { ComponentInfo::Field_t fieldInfo = componentInfo.Fields.at(field); if (fieldInfo.Type == "string") { std::string& value = packet.ReadString(); - m_World->GetComponent(entityID, componentType)[fieldInfo.Name] = value; + m_World->GetComponent(entityID, componentInfo.Name)[fieldInfo.Name] = value; } else { - memcpy(m_World->GetComponent(entityID, componentType).Data + fieldInfo.Offset, packet.ReadData(fieldInfo.Stride), fieldInfo.Stride); + memcpy(m_World->GetComponent(entityID, componentInfo.Name).Data + fieldInfo.Offset, packet.ReadData(fieldInfo.Stride), fieldInfo.Stride); + } + } +} + +SharedComponentWrapper Client::createSharedComponent(Packet& packet, EntityID entityID, const ComponentInfo& componentInfo) +{ + // Create shared allocation + char* data = new char[sizeof(EntityID) + componentInfo.Stride]; + // Copy entity ID to start of data buffer + memcpy(data, &entityID, sizeof(EntityID)); + // Read and copy fields + for (auto& field : componentInfo.FieldsInOrder) { + ComponentInfo::Field_t fieldInfo = componentInfo.Fields.at(field); + if (fieldInfo.Type == "string") { + new (data + sizeof(EntityID) + fieldInfo.Offset) std::string(packet.ReadString()); + } else { + memcpy(data + sizeof(EntityID) + fieldInfo.Offset, packet.ReadData(fieldInfo.Stride), fieldInfo.Stride); + } + } + + return SharedComponentWrapper(componentInfo, boost::shared_array(data)); +} + +void Client::ignoreFields(Packet& packet, const ComponentInfo& componentInfo) +{ + for (auto field : componentInfo.FieldsInOrder) { + ComponentInfo::Field_t fieldInfo = componentInfo.Fields.at(field); + if (fieldInfo.Type == "string") { + packet.ReadString(); + } else { + packet.ReadData(fieldInfo.Stride); } } } @@ -214,26 +237,32 @@ void Client::parseSnapshot(Packet& packet) int ammountOfComponents = packet.ReadPrimitive(); for (int i = 0; i < ammountOfComponents; i++) { std::string componentType = packet.ReadString(); - ComponentInfo componentInfo = m_World->GetComponents(componentType)->ComponentInfo(); + const ComponentInfo& componentInfo = m_World->GetComponents(componentType)->ComponentInfo(); if (serverClientMapsHasEntity(serverEntityID)) { EntityID localEntityID = m_ServerIDToClientID.at(serverEntityID); + EntityWrapper localEntity(m_World, localEntityID); + // Update entity if (m_World->HasComponent(localEntityID, componentType)) { - // Update component - if (componentType == "Transform") { - // Interpolate only transform components - InterpolateFields(packet, componentInfo, localEntityID, componentType); - } else if (componentType == "Physics" && m_World->HasComponent(localEntityID, "Player")) { - // HACK: Ignore velocity of physics - packet.ReadData(componentInfo.Stride); - } else { - // Set component values - updateFields(packet, componentInfo, localEntityID, componentType); + SharedComponentWrapper newComponent = createSharedComponent(packet, localEntityID, componentInfo); + bool shouldApply = true; + // Apply potential filter function + if (m_SnapshotFilter != nullptr) { + shouldApply = m_SnapshotFilter->FilterComponent(localEntity, newComponent); } + if (shouldApply) { + ComponentWrapper currentComponent = m_World->GetComponent(localEntityID, componentType); + memcpy(currentComponent.Data, newComponent.Data, componentInfo.Stride); + } + //if (localEntity != m_LocalPlayer && !localEntity.IsChildOf(m_LocalPlayer)) { + // updateFields(packet, componentInfo, localEntityID); + //} else { + // ignoreFields(packet, componentInfo); + //} } else { // Has entity but no component m_World->AttachComponent(localEntityID, componentType); - updateFields(packet, componentInfo, localEntityID, componentType); + updateFields(packet, componentInfo, localEntityID); } } else { // Create Entity and component @@ -246,7 +275,7 @@ void Client::parseSnapshot(Packet& packet) m_World->SetName(newLocalEntityID, serverEntityName); insertIntoServerClientMaps(serverEntityID, newLocalEntityID); m_World->AttachComponent(newLocalEntityID, componentType); - updateFields(packet, componentInfo, newLocalEntityID, componentType); + updateFields(packet, componentInfo, newLocalEntityID); } } // Parent logic diff --git a/src/Engine/Network/Network.cpp b/src/Engine/Network/Network.cpp index f43e5d83..534df1cd 100644 --- a/src/Engine/Network/Network.cpp +++ b/src/Engine/Network/Network.cpp @@ -1,5 +1,14 @@ #include "Network/Network.h" +Network::Network(World* world, EventBroker* eventBroker) + : m_World(world) + , m_EventBroker(eventBroker) +{ + ConfigFile* config = ResourceManager::Load("Config.ini"); + m_MaxConnections = config->Get("Networking.MaxConnections", 8); + m_TimeoutMs = config->Get("Networking.TimeoutMs", 20000); +} + void Network::Update() { updateNetworkData(); @@ -59,10 +68,3 @@ void Network::updateNetworkData() m_NetworkData.DataReceivedThisInterval = 0; } } - -void Network::initialize() -{ - ConfigFile* config = ResourceManager::Load("Config.ini"); - m_MaxConnections = config->Get("Networking.MaxConnections", 8); - m_TimeoutMs = config->Get("Networking.TimeoutMs", 20000); -} diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index 962081cc..9502c01d 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -1,29 +1,30 @@ #include "Network/Server.h" -Server::Server() : m_Socket(m_IOService, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), 27666)) +Server::Server(World* world, EventBroker* eventBroker, int port) + : Network(world, eventBroker) { - Network::initialize(); ConfigFile* config = ResourceManager::Load("Config.ini"); snapshotInterval = 1000 * config->Get("Networking.SnapshotInterval", 0.05f); pingIntervalMs = config->Get("Networking.PingIntervalMs", 1000); -} - -Server::~Server() -{ - -} - -void Server::Start(World* world, EventBroker* eventBroker) -{ - m_World = world; - m_EventBroker = eventBroker; // Subscribe to events EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &Server::OnInputCommand); EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &Server::OnPlayerSpawned); EVENT_SUBSCRIBE_MEMBER(m_EEntityDeleted, &Server::OnEntityDeleted); EVENT_SUBSCRIBE_MEMBER(m_EComponentDeleted, &Server::OnComponentDeleted); - LOG_INFO("I am Server. BIP BOP\n"); + + // Bind + if (port == 0) { + port = config->Get("Networking.Port", 27666); + } + m_Port = port; + m_Socket = std::make_unique(m_IOService, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), port)); + LOG_INFO("Server initialized and bound to port %i", port); +} + +Server::~Server() +{ + } void Server::Update() @@ -38,7 +39,7 @@ void Server::Update() void Server::readFromClients() { - while (m_Socket.available()) { + while (m_Socket->available()) { try { bytesRead = receive(readBuffer); Packet packet(readBuffer, bytesRead); @@ -105,7 +106,7 @@ void Server::parseMessageType(Packet& packet) size_t Server::receive(char * data) { - size_t length = m_Socket.receive_from( + size_t length = m_Socket->receive_from( boost::asio::buffer((void*)data , INPUTSIZE) , m_ReceiverEndpoint, 0); @@ -121,7 +122,7 @@ size_t Server::receive(char * data) void Server::send(PlayerID player, Packet& packet) { try { - size_t bytesSent = m_Socket.send_to( + size_t bytesSent = m_Socket->send_to( boost::asio::buffer(packet.Data(), packet.Size()), m_ConnectedPlayers[player].Endpoint, 0); @@ -139,7 +140,7 @@ void Server::send(PlayerID player, Packet& packet) void Server::send(Packet & packet) { - m_Socket.send_to( + m_Socket->send_to( boost::asio::buffer( packet.Data(), packet.Size()), @@ -240,7 +241,7 @@ void Server::checkForTimeOuts() static_cast(CLOCKS_PER_SEC); if (startPing > stopPing + m_TimeoutMs) { LOG_INFO("User %i timed out!", i); - disconnect(i); + //disconnect(i); } } } diff --git a/src/Engine/Rendering/Renderer.cpp b/src/Engine/Rendering/Renderer.cpp index a63e02a0..3fb11a2d 100644 --- a/src/Engine/Rendering/Renderer.cpp +++ b/src/Engine/Rendering/Renderer.cpp @@ -51,7 +51,7 @@ void Renderer::InitializeWindow() ss << " DEBUG"; #endif LOG_INFO(ss.str().c_str()); - glfwSetWindowTitle(m_Window, ss.str().c_str()); + SetWindowTitle(ss.str()); // Initialize GLEW if (glewInit() != GLEW_OK) { diff --git a/src/Game/CMakeLists.txt b/src/Game/CMakeLists.txt index 157af23c..db923364 100644 --- a/src/Game/CMakeLists.txt +++ b/src/Game/CMakeLists.txt @@ -1,6 +1,6 @@ project(TacticalZ-Game) -find_package(Boost REQUIRED COMPONENTS system filesystem thread chrono) +find_package(Boost REQUIRED COMPONENTS system filesystem thread chrono program_options) set(INCLUDE_PATH ${CMAKE_SOURCE_DIR}/include/Game) include_directories( @@ -22,13 +22,17 @@ file(GLOB SOURCE_FILES_Events ) source_group(Events FILES ${SOURCE_FILES_Events}) +file(GLOB SOURCE_FILES_Network + "${INCLUDE_PATH}/Network/*.h" + "Network/*.cpp" +) +source_group(Network FILES ${SOURCE_FILES_Network}) set(SOURCE_FILES ${SOURCE_FILES} "Game.cpp" ${SOURCE_FILES_Systems} ${SOURCE_FILES_Events} - - + ${SOURCE_FILES_Network} ) set(LIBRARIES diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index 04180fb3..982ce647 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -13,10 +13,13 @@ #include "Game/Systems/WeaponSystem.h" #include "Game/Systems/PlayerHUDSystem.h" #include "Game/Systems/LifetimeSystem.h" -#include "../Engine/Rendering/AnimationSystem.h" +#include "Rendering/AnimationSystem.h" +#include "Network/MultiplayerSnapshotFilter.h" Game::Game(int argc, char* argv[]) { + parseArgs(argc, argv); + ResourceManager::RegisterType("ConfigFile"); ResourceManager::RegisterType("Sound"); ResourceManager::RegisterType("Model"); @@ -73,15 +76,14 @@ Game::Game(int argc, char* argv[]) // Initialize network if (m_Config->Get("Networking.StartNetwork", false)) { - bool isServer = m_Config->Get("Networking.IsServer", false); - if (isServer) { - m_Network = new Server(); - m_IsServer = true; - } else { - m_Network = new Client(m_Config); - m_IsClient = true; + if (m_IsServer) { + m_NetworkServer = new Server(m_World, m_EventBroker, m_NetworkPort); + m_Renderer->SetWindowTitle(m_Renderer->WindowTitle() + " SERVER"); + } else if (m_IsClient) { + m_NetworkClient = new Client(m_World, m_EventBroker, std::make_unique(m_EventBroker)); + m_NetworkClient->Connect(m_NetworkAddress, m_NetworkPort); + m_Renderer->SetWindowTitle(m_Renderer->WindowTitle() + " CLIENT"); } - m_Network->Start(m_World, m_EventBroker); } // Create Octrees @@ -132,8 +134,11 @@ Game::~Game() delete m_OctreeFrustrumCulling; delete m_OctreeCollision; delete m_OctreeTrigger; - if (m_Network != nullptr) { - delete m_Network; + if (m_NetworkClient != nullptr) { + delete m_NetworkClient; + } + if (m_NetworkServer != nullptr) { + delete m_NetworkServer; } delete m_World; delete m_FrameStack; @@ -163,8 +168,12 @@ void Game::Tick() m_EventBroker->Swap(); // Update network - if (m_Network != nullptr) { - m_Network->Update(); + m_EventBroker->Process(); + if (m_NetworkClient != nullptr) { + m_NetworkClient->Update(); + } + if (m_NetworkServer != nullptr) { + m_NetworkServer->Update(); } // Iterate through systems and update world! @@ -176,4 +185,37 @@ void Game::Tick() m_RenderFrame->Clear(); m_EventBroker->Swap(); m_EventBroker->Clear(); -} \ No newline at end of file +} + +int Game::parseArgs(int argc, char* argv[]) +{ + namespace po = boost::program_options; + + po::options_description desc("Options"); + desc.add_options() + ("help", "Help") + ("server,s", po::bool_switch(&m_IsServer), "Launch game in server mode") + ("connect", po::value(&m_NetworkAddress)->default_value(""), "Connect to this address in client mode") + ("port,p", po::value(&m_NetworkPort), "Port to listen on or connect to"); + ; + + po::variables_map vm; + try { + po::store(po::parse_command_line(argc, argv, desc), vm); + po::notify(vm); + } catch (std::exception& e) { + LOG_ERROR(e.what()); + return 1; + } + + if (vm.count("help")) { + std::cout << desc << std::endl; + exit(1); + } + + if (vm.count("connect")) { + m_IsClient = true; + } + + return 0; +} diff --git a/src/Game/Network/MultiplayerSnapshotFilter.cpp b/src/Game/Network/MultiplayerSnapshotFilter.cpp new file mode 100644 index 00000000..426b24d2 --- /dev/null +++ b/src/Game/Network/MultiplayerSnapshotFilter.cpp @@ -0,0 +1,27 @@ +#include "Network/MultiplayerSnapshotFilter.h" + +MultiplayerSnapshotFilter::MultiplayerSnapshotFilter(EventBroker* eventBroker) + : m_EventBroker(eventBroker) +{ + EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &MultiplayerSnapshotFilter::OnPlayerSpawned); +} + +bool MultiplayerSnapshotFilter::FilterComponent(EntityWrapper entity, SharedComponentWrapper& component) +{ + if (entity == m_LocalPlayer || entity.IsChildOf(m_LocalPlayer)) { + return false; + } + + if (component.Info.Name == "Transform") { + m_EventBroker->Publish(Events::Interpolate(entity, component)); + return false; + } + + return true; +} + +bool MultiplayerSnapshotFilter::OnPlayerSpawned(Events::PlayerSpawned ePlayerSpawned) +{ + m_LocalPlayer = ePlayerSpawned.Player; + return true; +} \ No newline at end of file diff --git a/src/Game/Systems/ExplosionEffectSystem.cpp b/src/Game/Systems/ExplosionEffectSystem.cpp new file mode 100644 index 00000000..2704d2da --- /dev/null +++ b/src/Game/Systems/ExplosionEffectSystem.cpp @@ -0,0 +1,14 @@ +#include "Systems/ExplosionEffectSystem.h" + +void ExplosionEffectSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) +{ + if ((double)component["TimeSinceDeath"] > (double)component["ExplosionDuration"]) { + (double)component["TimeSinceDeath"] = 0.f; + } + (double&)component["TimeSinceDeath"] += dt; + + //if ((bool)Component["Gravity"] == true) { + // (bool)Component["ExponentialAccelaration"] = false; + //} +} + diff --git a/src/Game/Systems/InterpolationSystem.cpp b/src/Game/Systems/InterpolationSystem.cpp index e958a4a9..6c57c2b6 100644 --- a/src/Game/Systems/InterpolationSystem.cpp +++ b/src/Game/Systems/InterpolationSystem.cpp @@ -17,6 +17,7 @@ void InterpolationSystem::UpdateComponent(EntityWrapper& entity, ComponentWrappe return; } + //return; if (m_NextTransform.find(transform.EntityID) != m_NextTransform.end()) { // Exists in map m_NextTransform[transform.EntityID].interpolationTime += static_cast(dt); Transform sTransform = m_NextTransform[transform.EntityID]; @@ -32,21 +33,14 @@ void InterpolationSystem::UpdateComponent(EntityWrapper& entity, ComponentWrappe } } if (transform.Info.Name == "Transform") { - bool isLocalPlayer = entity == m_LocalPlayer || entity.IsChildOf(m_LocalPlayer); // Position glm::vec3 nextPosition = sTransform.Position; glm::vec3 currentPosition = static_cast(transform["Position"]); - // HACK: Don't force position for players - if (!isLocalPlayer) { - (glm::vec3&)transform["Position"] += vectorInterpolation(currentPosition, nextPosition, sTransform.interpolationTime); - } + (glm::vec3&)transform["Position"] += vectorInterpolation(currentPosition, nextPosition, sTransform.interpolationTime); // Orientation - // Don't force orientation for players - if (!isLocalPlayer) { - glm::quat nextOrientation = sTransform.Orientation; - glm::quat currentOrientation = glm::quat(static_cast(transform["Orientation"])); - (glm::vec3&)transform["Orientation"] = glm::eulerAngles(glm::slerp(currentOrientation, nextOrientation, sTransform.interpolationTime / m_SnapshotInterval)); - } + glm::quat nextOrientation = sTransform.Orientation; + glm::quat currentOrientation = glm::quat(static_cast(transform["Orientation"])); + (glm::vec3&)transform["Orientation"] = glm::eulerAngles(glm::slerp(currentOrientation, nextOrientation, glm::max(sTransform.interpolationTime / m_SnapshotInterval, 1.f))); // Scale glm::vec3 nextScale = sTransform.Scale; glm::vec3 currentScale = static_cast(transform["Scale"]); @@ -61,24 +55,22 @@ bool InterpolationSystem::OnPlayerSpawned(Events::PlayerSpawned& e) return true; } -bool InterpolationSystem::OnInterpolate(const Events::Interpolate & e) +bool InterpolationSystem::OnInterpolate(Events::Interpolate& e) { - Transform transform; - int offset = 0; - // Read the data - memcpy(&transform.Position, e.DataArray.get() + offset, sizeof(glm::vec3)); - offset += sizeof(glm::vec3); - glm::vec3 tempOrientation; - memcpy(&tempOrientation, e.DataArray.get() + offset, sizeof(glm::vec3)); - transform.Orientation = glm::quat(tempOrientation); - offset += sizeof(glm::vec3); - memcpy(&transform.Scale, e.DataArray.get() + offset, sizeof(glm::vec3)); - transform.interpolationTime = 0.0f; + // TODO: Make this work for arbitrary component types + if (e.Component.Info.Name == "Transform") { + Transform transform; + transform.Position = e.Component["Position"]; + transform.Orientation = glm::quat((glm::vec3)e.Component["Orientation"]); + transform.Scale = e.Component["Scale"]; + transform.interpolationTime = 0.0f; - if (m_NextTransform.find(e.Entity) != m_NextTransform.end()) { // Did exist - m_LastReceivedTransform[e.Entity] = transform; - } else { // Did not - m_NextTransform[e.Entity] = transform; + if (m_NextTransform.find(e.Entity.ID) != m_NextTransform.end()) { // Did exist + m_LastReceivedTransform[e.Entity.ID] = transform; + } else { // Did not + m_NextTransform[e.Entity.ID] = transform; + } } - return false; + + return true; } From b30891aecdbd9886d4f876d01b8cad91d41b6eb2 Mon Sep 17 00:00:00 2001 From: William Moberg Date: Tue, 9 Feb 2016 15:00:30 +0100 Subject: [PATCH 130/355] WIP, debugging code added, still not working. --- include/Engine/Core/Octree.h | 27 ++++----- include/Engine/Rendering/RenderSystem.h | 1 + src/Engine/Rendering/RenderSystem.cpp | 73 ++++++++++++++++--------- 3 files changed, 62 insertions(+), 39 deletions(-) diff --git a/include/Engine/Core/Octree.h b/include/Engine/Core/Octree.h index d97d644b..e0165cef 100644 --- a/include/Engine/Core/Octree.h +++ b/include/Engine/Core/Octree.h @@ -74,8 +74,8 @@ struct Output //Contains points P in: dot(normal, P) + d = 0 struct Plane { - glm::vec3 normal; - float distance; + glm::vec3 Normal; + float Distance; }; //A frustum defined by 6 planes. @@ -87,14 +87,14 @@ struct Frustum Outside, Intersects }; - Plane planes[6]; + Plane Planes[6]; Output VsAABB(const AABB& box) const { const glm::vec3& maxCorner = box.MaxCorner(); const glm::vec3& minCorner = box.MinCorner(); bool completelyInside = true; - for (const Plane& p : planes) { + for (const Plane& p : Planes) { bool anyWasInside = false; bool anyWasOutside = false; //If points are on both sides of the plane, we can stop. @@ -104,7 +104,7 @@ struct Frustum corner.x = bits.test(0) ? maxCorner.x : minCorner.x; corner.y = bits.test(1) ? maxCorner.y : minCorner.y; corner.z = bits.test(2) ? maxCorner.z : minCorner.z; - if (glm::dot(p.normal, corner) > p.distance) { + if (glm::dot(p.Normal, corner) > p.Distance) { anyWasInside = true; } else { anyWasOutside = true; @@ -214,17 +214,18 @@ void Octree::ObjectsInFrustum(const glm::mat4x4& viewProj, std::vector& ou { falsifyObjectChecks(); OctSpace::Frustum frustum; + //Order: Right, left, top, bottom, far, near. for (int i = 0; i < 6; ++i) { int sign = 2 * (i % 2) - 1; int index = i / 2; - OctSpace::Plane& plane = frustum.planes[i]; - plane.normal.x = viewProj[0].w + sign * viewProj[0][index]; - plane.normal.y = viewProj[1].w + sign * viewProj[1][index]; - plane.normal.z = viewProj[2].w + sign * viewProj[2][index]; - plane.distance = viewProj[3].w + sign * viewProj[3][index]; - float divByNormalLength = 1.0f / glm::length(plane.normal); - plane.normal *= divByNormalLength; - plane.distance *= divByNormalLength; + OctSpace::Plane& plane = frustum.Planes[i]; + plane.Normal.x = viewProj[0].w + sign * viewProj[0][index]; + plane.Normal.y = viewProj[1].w + sign * viewProj[1][index]; + plane.Normal.z = viewProj[2].w + sign * viewProj[2][index]; + plane.Distance = viewProj[3].w + sign * viewProj[3][index]; + float divByNormalLength = 1.0f / glm::length(plane.Normal); + plane.Normal *= divByNormalLength; + plane.Distance *= divByNormalLength; } m_Root->ObjectsInFrustum(frustum, outObjects, false); } diff --git a/include/Engine/Rendering/RenderSystem.h b/include/Engine/Rendering/RenderSystem.h index d404c56a..e4e6475a 100644 --- a/include/Engine/Rendering/RenderSystem.h +++ b/include/Engine/Rendering/RenderSystem.h @@ -33,6 +33,7 @@ private: Camera* m_Camera; Camera* m_LastCullCamera; Camera** m_FrustumCamPtr; + EntityWrapper frustumEntity; World* m_World; EntityWrapper m_CurrentCamera = EntityWrapper::Invalid; EntityWrapper m_LocalPlayer = EntityWrapper::Invalid; diff --git a/src/Engine/Rendering/RenderSystem.cpp b/src/Engine/Rendering/RenderSystem.cpp index d57e263a..9d7e7530 100644 --- a/src/Engine/Rendering/RenderSystem.cpp +++ b/src/Engine/Rendering/RenderSystem.cpp @@ -25,6 +25,19 @@ RenderSystem::~RenderSystem() bool RenderSystem::OnSetCamera(Events::SetCamera& e) { + //Right now, lets set the camera to cull away stuff if it is connected to a player. + //TODO: This won't work with spectators, or death anim. + if (e.CameraEntity.FirstParentWithComponent("Player").Valid()) { + m_FrustumCamPtr = &m_Camera; + LOG_INFO("Setting frustum to new camera."); + } else if (e.CameraEntity != m_CurrentCamera) { + //If the camera has no parents, i.e. a free camera, + //then we cull from the last camera, so we can see if the culling works. + //Copy the camera into the last frustum camera, without allocating new memory. + new ((void*)m_LastCullCamera) Camera(*m_Camera); + m_FrustumCamPtr = &m_LastCullCamera; + LOG_INFO("New camera, frustum remains at old camera."); + } ComponentWrapper cTransform = e.CameraEntity["Transform"]; ComponentWrapper cCamera = e.CameraEntity["Camera"]; m_Camera->SetFOV((double)cCamera["FOV"]); @@ -33,17 +46,6 @@ bool RenderSystem::OnSetCamera(Events::SetCamera& e) m_Camera->SetPosition(cTransform["Position"]); m_Camera->SetOrientation(glm::quat((const glm::vec3&)cTransform["Orientation"])); m_CurrentCamera = e.CameraEntity; - //Right now, lets set the camera to cull away stuff if it is connected to anything. - //TODO: This won't work with spectators, or death anim. - if (m_CurrentCamera.Parent().Valid()) { - //Copy the camera into the last frustum camera, without allocating new memory. - new ((void*)m_LastCullCamera) Camera(*m_Camera); - m_FrustumCamPtr = &m_Camera; - } else { - //If the camera has no parents, i.e. a free camera, - //then we cull from the last camera, so we can see if the culling works. - m_FrustumCamPtr = &m_LastCullCamera; - } return true; } @@ -56,26 +58,45 @@ bool RenderSystem::isChildOfCurrentCamera(EntityWrapper entity) return entity == m_CurrentCamera || entity.IsChildOf(m_CurrentCamera); } +float frustrumTODO = 0.f; + void RenderSystem::fillModels(std::list>& opaqueJobs, std::list>& transparentJobs) { + if (!frustumEntity.Valid() && m_World->GetComponentPools().size() > 0) { + frustumEntity = EntityWrapper(m_World, m_World->CreateEntity()); + m_World->AttachComponent(frustumEntity.ID, "Transform"); + m_World->AttachComponent(frustumEntity.ID, "Model"); + frustumEntity["Model"]["Resource"] = "Models/Core/UnitCube.mesh"; + } std::vector seenEntities; //m_Octree->ObjectsInFrustum((*m_FrustumCamPtr)->ProjectionMatrix() * (*m_FrustumCamPtr)->ViewMatrix(), seenEntities); - //m_Octree->ObjectsInFrustum((*m_FrustumCamPtr)->ViewMatrix() * (*m_FrustumCamPtr)->ProjectionMatrix(), seenEntities); - glm::mat4x4 viewProj = (*m_FrustumCamPtr)->ViewMatrix() * (*m_FrustumCamPtr)->ProjectionMatrix(); + glm::mat4x4 viewProj = (*m_FrustumCamPtr)->ProjectionMatrix() * (*m_FrustumCamPtr)->ViewMatrix(); OctSpace::Frustum frustum; + //Order: Right, left, top, bottom, far, near. + int sign = 1; for (int i = 0; i < 6; ++i) { - int sign = 2 * (i % 2) - 1; + sign = -sign; int index = i / 2; - OctSpace::Plane& plane = frustum.planes[i]; - plane.normal.x = viewProj[0].w + sign * viewProj[0][index]; - plane.normal.y = viewProj[1].w + sign * viewProj[1][index]; - plane.normal.z = viewProj[2].w + sign * viewProj[2][index]; - plane.distance = viewProj[3].w + sign * viewProj[3][index]; - float divByNormalLength = 1.0f / glm::length(plane.normal); - plane.normal *= divByNormalLength; - plane.distance *= divByNormalLength; + OctSpace::Plane& plane = frustum.Planes[i]; + plane.Normal.x = viewProj[0].w + sign * viewProj[0][index]; + plane.Normal.y = viewProj[1].w + sign * viewProj[1][index]; + plane.Normal.z = viewProj[2].w + sign * viewProj[2][index]; + plane.Distance = viewProj[3].w + sign * viewProj[3][index]; + float divByNormalLength = 1.0f / glm::length(plane.Normal); + plane.Normal *= divByNormalLength; + plane.Distance *= divByNormalLength; + } + if (frustumEntity.Valid()) { + int planeI = 0; + glm::vec3 pos = (*m_FrustumCamPtr)->Position() + frustrumTODO * (*m_FrustumCamPtr)->Forward(); + float dist = glm::dot(frustum.Planes[planeI].Normal, pos) + frustum.Planes[planeI].Distance; + frustumEntity["Transform"]["Position"] = pos - dist * frustum.Planes[planeI].Normal; + frustumEntity["Transform"]["Scale"] = glm::vec3(0.15f); + } + if (++frustrumTODO > 75) { + frustrumTODO = 0.f; } //for (auto& seenEntity : seenEntities) { @@ -109,11 +130,11 @@ void RenderSystem::fillModels(std::list>& opaqueJobs, if (entity.HasComponent("AABB")) { OctSpace::Frustum::Output o = frustum.VsAABB(*Collision::EntityAbsoluteAABB(entity)); - if (o == OctSpace::Frustum::Outside) { - continue; + if (o == OctSpace::Frustum::Outside && entity != frustumEntity) { + resource = "Models/Core/UnitRaptor.mesh"; } - } else { - continue; + } else if (entity != frustumEntity){ + resource = "Models/Core/Error.mesh"; } Model* model; From 971fee4a0cfaa0b9017718a8a9e2ade928bc05f2 Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Tue, 9 Feb 2016 15:38:21 +0100 Subject: [PATCH 131/355] DamageIndicatorSystem code looking good. Test working well. Sprite display fixed by Viktor --- include/Game/Systems/DamageIndicatorSystem.h | 1 + .../Schema/Entities/SpriteTestTemporary.xml | 7 +--- resources/Shaders/Sprite.vert.glsl | 2 +- src/Game/Systems/DamageIndicatorSystem.cpp | 42 +++++++++++++++---- 4 files changed, 37 insertions(+), 15 deletions(-) diff --git a/include/Game/Systems/DamageIndicatorSystem.h b/include/Game/Systems/DamageIndicatorSystem.h index 646887e2..561654d1 100644 --- a/include/Game/Systems/DamageIndicatorSystem.h +++ b/include/Game/Systems/DamageIndicatorSystem.h @@ -16,6 +16,7 @@ #include "Rendering/ESetCamera.h" #include +#include class DamageIndicatorSystem : public ImpureSystem { diff --git a/resources/Schema/Entities/SpriteTestTemporary.xml b/resources/Schema/Entities/SpriteTestTemporary.xml index f66e9158..2d02443c 100644 --- a/resources/Schema/Entities/SpriteTestTemporary.xml +++ b/resources/Schema/Entities/SpriteTestTemporary.xml @@ -3,13 +3,10 @@ - Textures/DefenderGunRedDiff.png - Textures/DefenderGunRedIncd.png + Textures/TempDamageIndicator.png + Textures/TempDamageIndicator.png - - Models/Core/UnitQuad.mesh - diff --git a/resources/Shaders/Sprite.vert.glsl b/resources/Shaders/Sprite.vert.glsl index e910a26a..61b387ad 100644 --- a/resources/Shaders/Sprite.vert.glsl +++ b/resources/Shaders/Sprite.vert.glsl @@ -16,7 +16,7 @@ out VertexData{ void main() { - gl_Position = P * M * vec4(Position, 1.0); + gl_Position = P * V * M * vec4(Position, 1.0); Output.Position = Position; Output.TextureCoordinate = TextureCoords; diff --git a/src/Game/Systems/DamageIndicatorSystem.cpp b/src/Game/Systems/DamageIndicatorSystem.cpp index 5f6ad725..24d1cfa4 100644 --- a/src/Game/Systems/DamageIndicatorSystem.cpp +++ b/src/Game/Systems/DamageIndicatorSystem.cpp @@ -21,22 +21,46 @@ bool DamageIndicatorSystem::OnPlayerDamageTaken(Events::PlayerDamage& e) { auto test1 = (glm::vec3)e.PlayerShooter["Transform"]["Orientation"]; auto test2 = (glm::vec3)e.Player["Transform"]["Orientation"]; - //calculate direction - auto enemyOrientation = glm::quat(((glm::vec3)e.PlayerShooter["Transform"]["Orientation"])); + + //grab players direction auto playerOrientation = glm::quat((glm::vec3)e.Player["Transform"]["Orientation"]); - //calculate difference in angle (quaternion math) - auto angle1 = glm::angle(playerOrientation); - auto angle2 = glm::angle(enemyOrientation); - auto quat = glm::angleAxis(angle2 - angle1, glm::vec3(0, 1, 0)); - auto vec3Orientation = glm::eulerAngles(quat); + + //get the position vectors, but ignore the y-height + auto enemyPosition = (glm::vec3) e.PlayerShooter["Transform"]["Position"]; + auto playerPosition = (glm::vec3) e.Player["Transform"]["Position"]; + enemyPosition.y = 0.0f; + playerPosition.y = 0.0f; + + //calculate the enemy to player vector + auto enemyPlayerVector = glm::normalize((glm::vec3) playerPosition - enemyPosition); + + //get angle from players current rotation, this angle is how much you rotate around the y-axis + auto playerAngle = glm::angle(playerOrientation); + auto playerRotationVector = glm::normalize(glm::rotateY(glm::vec3(0, 0, 1), playerAngle)); + + //dot product of players direction-vector and enemys-to-playervector will give the cos of the angle between the vectors + auto playerRotationDot = glm::dot(playerRotationVector, enemyPlayerVector); + //to get the angle between the vectors just do cos-inverse + auto angleBetweenVectors = glm::acos(playerRotationDot); + + //rotate the direction-vector 90 degrees to get the players side-vector + auto playerSideVector = glm::normalize(glm::rotateY(glm::vec3(0, 0, 1), playerAngle + 1.57f)); + //dot of sidevector positive = enemy is on the right side, dot sidevector negative = left side + auto playerSideVectorDot = glm::dot(playerSideVector, enemyPlayerVector); + if (playerSideVectorDot < 0) { + angleBetweenVectors = -angleBetweenVectors; + } + + //LOG_INFO("vector angle %f %f %f %f", t1, t3, t4, enemyPlayerVector.x); //load & set the "2d" sprite auto entityFile = ResourceManager::Load("Schema/Entities/SpriteTestTemporary.xml"); EntityFileParser parser(entityFile); EntityID spriteID = parser.MergeEntities(m_World); m_World->SetParent(spriteID, m_CurrentCamera); - auto cameraWrapper = EntityWrapper(m_World, spriteID); - cameraWrapper["Transform"]["Orientation"] = vec3Orientation; + auto spriteWrapper = EntityWrapper(m_World, spriteID); + //simply set the rotation z-wise to the angleBetweenVectors + spriteWrapper["Transform"]["Orientation"] = glm::vec3(0, 0, angleBetweenVectors); return true; } From c69a80f5ba35730654a7f9a6b5f3198db3d9c9b2 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Tue, 9 Feb 2016 16:06:39 +0100 Subject: [PATCH 132/355] Added System::LocalPlayer that is always set to the entity which is the local player, available to all systems. --- include/Engine/Core/System.h | 18 +++++++++++++++++- include/Engine/Core/SystemPipeline.h | 3 +++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/include/Engine/Core/System.h b/include/Engine/Core/System.h index d4b9808b..e21d8c7e 100644 --- a/include/Engine/Core/System.h +++ b/include/Engine/Core/System.h @@ -5,6 +5,7 @@ #include "World.h" #include "EntityWrapper.h" #include "ComponentWrapper.h" +#include "EPlayerSpawned.h" struct SystemParams { @@ -31,13 +32,28 @@ protected: , m_EventBroker(params.EventBroker) , IsClient(params.IsClient) , IsServer(params.IsServer) - { } + { + if (IsClient) { + EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &System::OnPlayerSpawned); + } + } virtual ~System() = default; World* m_World; EventBroker* m_EventBroker; bool IsClient = false; bool IsServer = false; + EntityWrapper LocalPlayer = EntityWrapper::Invalid; + +private: + EventRelay m_EPlayerSpawned; + bool OnPlayerSpawned(Events::PlayerSpawned& e) + { + if (e.PlayerID == -1) { + LocalPlayer = e.Player; + } + return true; + } }; class PureSystem : public virtual System diff --git a/include/Engine/Core/SystemPipeline.h b/include/Engine/Core/SystemPipeline.h index 88ec4fa7..5f7aee0b 100644 --- a/include/Engine/Core/SystemPipeline.h +++ b/include/Engine/Core/SystemPipeline.h @@ -61,6 +61,9 @@ public: dt = 0.0; } + // Process utility events for the System base class + m_EventBroker->Process(); + for (UnorderedSystems& group : m_OrderedSystemGroups) { // Process events for (auto& pair : group.Systems) { From e69864680dded57343d2e54a9e07f4c3096f5ef4 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Tue, 9 Feb 2016 16:08:06 +0100 Subject: [PATCH 133/355] PlayerMovementSystem now only updates the velocity of the local player, as it should --- include/Game/Systems/PlayerMovementSystem.h | 5 +++-- src/Game/Systems/PlayerMovementSystem.cpp | 19 +++++++++++++------ 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/include/Game/Systems/PlayerMovementSystem.h b/include/Game/Systems/PlayerMovementSystem.h index 7daf9c03..97a37597 100644 --- a/include/Game/Systems/PlayerMovementSystem.h +++ b/include/Game/Systems/PlayerMovementSystem.h @@ -5,14 +5,13 @@ #include "Input/FirstPersonInputController.h" #include -class PlayerMovementSystem : public ImpureSystem, PureSystem +class PlayerMovementSystem : public ImpureSystem { public: PlayerMovementSystem(SystemParams params); ~PlayerMovementSystem(); virtual void Update(double dt) override; - virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt); private: // State @@ -21,4 +20,6 @@ private: EventRelay m_EPlayerSpawned; bool OnPlayerSpawned(Events::PlayerSpawned& e); + void updateMovementControllers(double dt); + void updateVelocity(double dt); }; \ No newline at end of file diff --git a/src/Game/Systems/PlayerMovementSystem.cpp b/src/Game/Systems/PlayerMovementSystem.cpp index 04ce2400..ccc2d3ce 100644 --- a/src/Game/Systems/PlayerMovementSystem.cpp +++ b/src/Game/Systems/PlayerMovementSystem.cpp @@ -2,7 +2,6 @@ PlayerMovementSystem::PlayerMovementSystem(SystemParams params) : System(params) - , PureSystem("Player") { EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &PlayerMovementSystem::OnPlayerSpawned); } @@ -15,6 +14,12 @@ PlayerMovementSystem::~PlayerMovementSystem() } void PlayerMovementSystem::Update(double dt) +{ + updateMovementControllers(dt); + updateVelocity(dt); +} + +void PlayerMovementSystem::updateMovementControllers(double dt) { for (auto& kv : m_PlayerInputControllers) { EntityWrapper player = kv.first; @@ -135,14 +140,16 @@ void PlayerMovementSystem::Update(double dt) } } -void PlayerMovementSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) + +void PlayerMovementSystem::updateVelocity(double dt) { - ComponentWrapper& cTransform = entity["Transform"]; - if (!entity.HasComponent("Physics")) { + // Only apply velocity to local player + if (!LocalPlayer.Valid()) { return; } - ComponentWrapper& cPhysics = entity["Physics"]; + ComponentWrapper& cTransform = LocalPlayer["Transform"]; + ComponentWrapper& cPhysics = LocalPlayer["Physics"]; glm::vec3& velocity = cPhysics["Velocity"]; // Ground friction @@ -159,6 +166,7 @@ void PlayerMovementSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapp velocity.z *= multiplier; } + // Gravity if (cPhysics["Gravity"]) { velocity.y -= 9.82f * (float)dt; } @@ -171,6 +179,5 @@ bool PlayerMovementSystem::OnPlayerSpawned(Events::PlayerSpawned& e) { // When a player spawns, create an input controller for them m_PlayerInputControllers[e.Player] = new FirstPersonInputController(m_EventBroker, e.PlayerID); - return true; } From 232bf66a09491053cbccc15eb1bcc0386523bd95 Mon Sep 17 00:00:00 2001 From: William Moberg Date: Tue, 9 Feb 2016 16:09:08 +0100 Subject: [PATCH 134/355] Jump height is constant for the double jump. --- src/Game/Systems/PlayerMovementSystem.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Game/Systems/PlayerMovementSystem.cpp b/src/Game/Systems/PlayerMovementSystem.cpp index 7b244562..52890c3a 100644 --- a/src/Game/Systems/PlayerMovementSystem.cpp +++ b/src/Game/Systems/PlayerMovementSystem.cpp @@ -95,7 +95,7 @@ void PlayerMovementSystem::Update(double dt) } else { controller->SetDoubleJumping(true); } - velocity.y += 4.f; + velocity.y = 4.f; } if (player.HasComponent("AABB")) { From 8bdf87da12663aeb6b8b6a23b7288b032411b8f0 Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Tue, 9 Feb 2016 16:15:19 +0100 Subject: [PATCH 135/355] Some cleanup of the code --- include/Game/Systems/DamageIndicatorSystem.h | 14 +--- src/Game/Systems/DamageIndicatorSystem.cpp | 70 +------------------- src/Game/Systems/WeaponSystem.cpp | 1 + 3 files changed, 5 insertions(+), 80 deletions(-) diff --git a/include/Game/Systems/DamageIndicatorSystem.h b/include/Game/Systems/DamageIndicatorSystem.h index 561654d1..fd3ba33f 100644 --- a/include/Game/Systems/DamageIndicatorSystem.h +++ b/include/Game/Systems/DamageIndicatorSystem.h @@ -5,35 +5,23 @@ #include "Core/Transform.h" #include "Core/ResourceManager.h" #include "Core/EntityFileParser.h" -#include "Core/EPickupSpawned.h" #include "Core/EPlayerDamage.h" -#include "Engine/Collision/ETrigger.h" #include "Common.h" #include -//temp -#include "Input/EInputCommand.h" #include "Rendering/ESetCamera.h" - #include #include -class DamageIndicatorSystem : public ImpureSystem +class DamageIndicatorSystem : public System { public: DamageIndicatorSystem(World* world, EventBroker* eventBroker); - virtual void Update(double dt) override; - private: - EventRelay m_DamageTakenFromPlayer; bool OnPlayerDamageTaken(Events::PlayerDamage& e); - //temp - EventRelay m_EInputCommand; - bool OnInputCommand(Events::InputCommand& e); - EventRelay m_ESetCamera; bool OnSetCamera(const Events::SetCamera& e); diff --git a/src/Game/Systems/DamageIndicatorSystem.cpp b/src/Game/Systems/DamageIndicatorSystem.cpp index 24d1cfa4..0acb24c3 100644 --- a/src/Game/Systems/DamageIndicatorSystem.cpp +++ b/src/Game/Systems/DamageIndicatorSystem.cpp @@ -4,23 +4,15 @@ DamageIndicatorSystem::DamageIndicatorSystem(World* m_World, EventBroker* eventB : System(m_World, eventBroker) { EVENT_SUBSCRIBE_MEMBER(m_DamageTakenFromPlayer, &DamageIndicatorSystem::OnPlayerDamageTaken); - //TEMP - EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &DamageIndicatorSystem::OnInputCommand); //current camera EVENT_SUBSCRIBE_MEMBER(m_ESetCamera, &DamageIndicatorSystem::OnSetCamera); - } -void DamageIndicatorSystem::Update(double dt) -{ - -} - - bool DamageIndicatorSystem::OnPlayerDamageTaken(Events::PlayerDamage& e) { - auto test1 = (glm::vec3)e.PlayerShooter["Transform"]["Orientation"]; - auto test2 = (glm::vec3)e.Player["Transform"]["Orientation"]; + if (m_CurrentCamera == -1) { + return false; + } //grab players direction auto playerOrientation = glm::quat((glm::vec3)e.Player["Transform"]["Orientation"]); @@ -51,8 +43,6 @@ bool DamageIndicatorSystem::OnPlayerDamageTaken(Events::PlayerDamage& e) angleBetweenVectors = -angleBetweenVectors; } - //LOG_INFO("vector angle %f %f %f %f", t1, t3, t4, enemyPlayerVector.x); - //load & set the "2d" sprite auto entityFile = ResourceManager::Load("Schema/Entities/SpriteTestTemporary.xml"); EntityFileParser parser(entityFile); @@ -65,60 +55,6 @@ bool DamageIndicatorSystem::OnPlayerDamageTaken(Events::PlayerDamage& e) return true; } -//TEMP -bool DamageIndicatorSystem::OnInputCommand(Events::InputCommand& e) -{ - if (e.Command != "Jump" || e.Value > 0) { - return false; - } - //auto entityFile = ResourceManager::Load("Schema/Entities/SpriteTestTemporary.xml"); - //EntityFileParser parser(entityFile); - //EntityID spriteID = parser.MergeEntities(m_World); - ////get currently active camera - ////auto cameras = m_World->GetComponents("Camera"); - ////for (auto& cCamera : *cameras) { - //// - //// //auto temp = m_World->GetParent(cCamera.EntityID); - //// m_World->SetParent(spriteID, cCamera.EntityID); - ////} - ////m_CurrentCamera - //m_World->SetParent(spriteID, m_CurrentCamera); - - //auto cameraWrapper = EntityWrapper(m_World, spriteID); - //cameraWrapper["Transform"]["Orientation"] = glm::vec3(1, 1, 1); - //ray player-enemyplayer eller bara spelarnas direction - - - //TODO: life time, rotering -//den ska väl vara där hela tiden, bara det att den inte syns - - - //EntityWrapper(m_World, spriteID); - - auto players = m_World->GetComponents("Player"); - EntityID id1 = (*players->begin()).EntityID; - EntityID id2; - int lameCounter = 0; - for (auto& cPlayers : *players) { - if (lameCounter == 1) { - id2 = cPlayers.EntityID; - } - lameCounter++; - } - if (lameCounter != 2) { - return false; - } - - //do something here - Events::PlayerDamage ePlayerDamage; - ePlayerDamage.Player = EntityWrapper(m_World, id1); - ePlayerDamage.PlayerShooter = EntityWrapper(m_World, id2); - ePlayerDamage.Damage = 1; - m_EventBroker->Publish(ePlayerDamage); - - return true; -} - bool DamageIndicatorSystem::OnSetCamera(const Events::SetCamera& e) { m_CurrentCamera = e.CameraEntity.ID; return true; diff --git a/src/Game/Systems/WeaponSystem.cpp b/src/Game/Systems/WeaponSystem.cpp index 1613cb7a..bc7c86b6 100644 --- a/src/Game/Systems/WeaponSystem.cpp +++ b/src/Game/Systems/WeaponSystem.cpp @@ -134,6 +134,7 @@ bool WeaponSystem::OnShoot(Events::Shoot& eShoot) // TODO: Weapon damage calculations etc Events::PlayerDamage ePlayerDamage; ePlayerDamage.Player = player; + ePlayerDamage.PlayerShooter = eShoot.Player; ePlayerDamage.Damage = 100; m_EventBroker->Publish(ePlayerDamage); From e9f5a3d263bc6a00b7526db945732e7dcfc448d0 Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Tue, 9 Feb 2016 16:28:43 +0100 Subject: [PATCH 136/355] Renamed some files from temporary filenames to DamageIndicator filenames --- .../Entities/{SpriteTestTemporary.xml => DamageIndicator.xml} | 0 .../Entities/{GameMapTest.xml => DamageIndicatorTest.xml} | 0 src/Game/Systems/DamageIndicatorSystem.cpp | 2 +- 3 files changed, 1 insertion(+), 1 deletion(-) rename resources/Schema/Entities/{SpriteTestTemporary.xml => DamageIndicator.xml} (100%) rename resources/Schema/Entities/{GameMapTest.xml => DamageIndicatorTest.xml} (100%) diff --git a/resources/Schema/Entities/SpriteTestTemporary.xml b/resources/Schema/Entities/DamageIndicator.xml similarity index 100% rename from resources/Schema/Entities/SpriteTestTemporary.xml rename to resources/Schema/Entities/DamageIndicator.xml diff --git a/resources/Schema/Entities/GameMapTest.xml b/resources/Schema/Entities/DamageIndicatorTest.xml similarity index 100% rename from resources/Schema/Entities/GameMapTest.xml rename to resources/Schema/Entities/DamageIndicatorTest.xml diff --git a/src/Game/Systems/DamageIndicatorSystem.cpp b/src/Game/Systems/DamageIndicatorSystem.cpp index 0acb24c3..638307bf 100644 --- a/src/Game/Systems/DamageIndicatorSystem.cpp +++ b/src/Game/Systems/DamageIndicatorSystem.cpp @@ -44,7 +44,7 @@ bool DamageIndicatorSystem::OnPlayerDamageTaken(Events::PlayerDamage& e) } //load & set the "2d" sprite - auto entityFile = ResourceManager::Load("Schema/Entities/SpriteTestTemporary.xml"); + auto entityFile = ResourceManager::Load("Schema/Entities/DamageIndicator.xml"); EntityFileParser parser(entityFile); EntityID spriteID = parser.MergeEntities(m_World); m_World->SetParent(spriteID, m_CurrentCamera); From 239a8e7a6a38616614f9f09aa5a44dfab95b23e7 Mon Sep 17 00:00:00 2001 From: William Moberg Date: Tue, 9 Feb 2016 17:12:23 +0100 Subject: [PATCH 137/355] Frustum culling should be working. --- include/Engine/Core/Frustum.h | 77 +++++++++++++++++++++++ include/Engine/Core/Octree.h | 81 +++---------------------- include/Engine/Rendering/RenderSystem.h | 3 - src/Engine/Rendering/RenderSystem.cpp | 78 ++---------------------- src/Game/Game.cpp | 2 +- 5 files changed, 93 insertions(+), 148 deletions(-) create mode 100644 include/Engine/Core/Frustum.h diff --git a/include/Engine/Core/Frustum.h b/include/Engine/Core/Frustum.h new file mode 100644 index 00000000..c2d83b23 --- /dev/null +++ b/include/Engine/Core/Frustum.h @@ -0,0 +1,77 @@ +#ifndef Frustum_h__ +#define Frustum_h__ + +#include "../GLM.h" +#include "AABB.h" +#include + +//A frustum defined by 6 planes. +struct Frustum +{ + //Contains points P in: dot(normal, P) + d = 0 + struct Plane + { + glm::vec3 Normal; + float Distance; + }; + + enum class Output + { + Inside, + Outside, + Intersects + }; + Plane Planes[6]; + + Frustum() = default; + Frustum(glm::mat4x4 viewProjMatrix) + { + //Order: Right, left, top, bottom, far, near. + int sign = 1; + for (int i = 0; i < 6; ++i) { + sign = -sign; + int index = i / 2; + Plane& plane = Planes[i]; + plane.Normal.x = viewProjMatrix[0].w + sign * viewProjMatrix[0][index]; + plane.Normal.y = viewProjMatrix[1].w + sign * viewProjMatrix[1][index]; + plane.Normal.z = viewProjMatrix[2].w + sign * viewProjMatrix[2][index]; + plane.Distance = viewProjMatrix[3].w + sign * viewProjMatrix[3][index]; + float divByNormalLength = 1.0f / glm::length(plane.Normal); + plane.Normal *= divByNormalLength; + plane.Distance *= divByNormalLength; + } + } + + Output VsAABB(const AABB& box) const + { + const glm::vec3& maxCorner = box.MaxCorner(); + const glm::vec3& minCorner = box.MinCorner(); + bool completelyInside = true; + for (const Plane& p : Planes) { + bool anyWasInside = false; + bool anyWasOutside = false; + //If points are on both sides of the plane, we can stop. + for (int i = 0; i < 8 && (!anyWasInside || !anyWasOutside); ++i) { + std::bitset<3> bits(i); + glm::vec3 corner; + corner.x = bits.test(0) ? maxCorner.x : minCorner.x; + corner.y = bits.test(1) ? maxCorner.y : minCorner.y; + corner.z = bits.test(2) ? maxCorner.z : minCorner.z; + if (glm::dot(p.Normal, corner) > -p.Distance) { + anyWasInside = true; + } else { + anyWasOutside = true; + } + } + if (!anyWasInside) { + return Output::Outside; + } + if (anyWasOutside) { + completelyInside = false; + } + } + return completelyInside ? Output::Inside : Output::Intersects; + } +}; + +#endif \ No newline at end of file diff --git a/include/Engine/Core/Octree.h b/include/Engine/Core/Octree.h index e0165cef..49a8b045 100644 --- a/include/Engine/Core/Octree.h +++ b/include/Engine/Core/Octree.h @@ -6,6 +6,7 @@ #include "../Common.h" #include "AABB.h" +#include "Frustum.h" //Fwd declarations. class Ray; @@ -41,8 +42,8 @@ public: //The type Box must be AABB, or inherit from AABB. template void ObjectsInSameRegion(const Box& box, std::vector& outObjects); - //Get the objects that are inside the frustum defined by the viewProjection matrix, the objects are put in outObjects. - void ObjectsInFrustum(const glm::mat4x4& viewProj, std::vector& outObjects); + //Get the objects that are inside the frustum, the objects are put in outObjects. + void ObjectsInFrustum(const Frustum& frustum, std::vector& outObjects); //Empty the tree of all objects, static and dynamic. void ClearObjects(); //Empty the tree of all dynamic objects. Static objects remain in the tree. @@ -71,56 +72,6 @@ struct Output float CollideDistance; }; -//Contains points P in: dot(normal, P) + d = 0 -struct Plane -{ - glm::vec3 Normal; - float Distance; -}; - -//A frustum defined by 6 planes. -struct Frustum -{ - enum Output - { - Inside, - Outside, - Intersects - }; - Plane Planes[6]; - - Output VsAABB(const AABB& box) const - { - const glm::vec3& maxCorner = box.MaxCorner(); - const glm::vec3& minCorner = box.MinCorner(); - bool completelyInside = true; - for (const Plane& p : Planes) { - bool anyWasInside = false; - bool anyWasOutside = false; - //If points are on both sides of the plane, we can stop. - for (int i = 0; i < 8 && (!anyWasInside || !anyWasOutside); ++i) { - std::bitset<3> bits(i); - glm::vec3 corner; - corner.x = bits.test(0) ? maxCorner.x : minCorner.x; - corner.y = bits.test(1) ? maxCorner.y : minCorner.y; - corner.z = bits.test(2) ? maxCorner.z : minCorner.z; - if (glm::dot(p.Normal, corner) > p.Distance) { - anyWasInside = true; - } else { - anyWasOutside = true; - } - } - if (!anyWasInside) { - return Outside; - } - if (anyWasOutside) { - completelyInside = false; - } - } - return completelyInside ? Inside : Intersects; - } -}; - struct ContainedObject { ContainedObject() @@ -210,23 +161,9 @@ void Octree::ObjectsInSameRegion(const Box& box, std::vector& outObjects) } template -void Octree::ObjectsInFrustum(const glm::mat4x4& viewProj, std::vector& outObjects) +void Octree::ObjectsInFrustum(const Frustum& frustum, std::vector& outObjects) { falsifyObjectChecks(); - OctSpace::Frustum frustum; - //Order: Right, left, top, bottom, far, near. - for (int i = 0; i < 6; ++i) { - int sign = 2 * (i % 2) - 1; - int index = i / 2; - OctSpace::Plane& plane = frustum.Planes[i]; - plane.Normal.x = viewProj[0].w + sign * viewProj[0][index]; - plane.Normal.y = viewProj[1].w + sign * viewProj[1][index]; - plane.Normal.z = viewProj[2].w + sign * viewProj[2][index]; - plane.Distance = viewProj[3].w + sign * viewProj[3][index]; - float divByNormalLength = 1.0f / glm::length(plane.Normal); - plane.Normal *= divByNormalLength; - plane.Distance *= divByNormalLength; - } m_Root->ObjectsInFrustum(frustum, outObjects, false); } @@ -311,14 +248,14 @@ void OctSpace::Child::ObjectsInFrustum(const Frustum& frustum, std::vector& o { if (hasChildren()) { for (const Child* c : m_Children) { - Frustum::Output out = Frustum::Inside; + Frustum::Output out = Frustum::Output::Inside; if (!takeAllDontTest) { out = frustum.VsAABB(c->m_Box); - if (out == Frustum::Outside) { + if (out == Frustum::Output::Outside) { continue; } } - c->ObjectsInFrustum(frustum, outObjects, out == Frustum::Inside); + c->ObjectsInFrustum(frustum, outObjects, out == Frustum::Output::Inside); } } else { size_t startIndex = outObjects.size(); @@ -326,7 +263,7 @@ void OctSpace::Child::ObjectsInFrustum(const Frustum& frustum, std::vector& o outObjects.resize(outObjects.size() + m_StaticObjIndices.size() + m_DynamicObjIndices.size()); for (size_t i = 0; i < m_StaticObjIndices.size(); ++i) { ContainedObject& obj = m_StaticObjectsRef[m_StaticObjIndices[i]]; - if (obj.Checked || !frustum.VsAABB(obj.Box)) { + if (obj.Checked || frustum.VsAABB(*obj.Box) == Frustum::Output::Outside) { ++numDuplicates; } else { obj.Checked = true; @@ -335,7 +272,7 @@ void OctSpace::Child::ObjectsInFrustum(const Frustum& frustum, std::vector& o } for (size_t i = 0; i < m_DynamicObjIndices.size(); ++i) { ContainedObject& obj = m_DynamicObjectsRef[m_DynamicObjIndices[i]]; - if (obj.Checked || !frustum.VsAABB(obj.Box)) { + if (obj.Checked || frustum.VsAABB(*obj.Box) == Frustum::Output::Outside) { ++numDuplicates; } else { obj.Checked = true; diff --git a/include/Engine/Rendering/RenderSystem.h b/include/Engine/Rendering/RenderSystem.h index e4e6475a..44088913 100644 --- a/include/Engine/Rendering/RenderSystem.h +++ b/include/Engine/Rendering/RenderSystem.h @@ -31,9 +31,6 @@ private: const IRenderer* m_Renderer; RenderFrame* m_RenderFrame; Camera* m_Camera; - Camera* m_LastCullCamera; - Camera** m_FrustumCamPtr; - EntityWrapper frustumEntity; World* m_World; EntityWrapper m_CurrentCamera = EntityWrapper::Invalid; EntityWrapper m_LocalPlayer = EntityWrapper::Invalid; diff --git a/src/Engine/Rendering/RenderSystem.cpp b/src/Engine/Rendering/RenderSystem.cpp index 9d7e7530..26eea7f2 100644 --- a/src/Engine/Rendering/RenderSystem.cpp +++ b/src/Engine/Rendering/RenderSystem.cpp @@ -1,5 +1,6 @@ #include "Rendering/RenderSystem.h" #include "Collision/Collision.h" +#include "Core/Frustum.h" RenderSystem::RenderSystem(World* world, EventBroker* eventBroker, const IRenderer* renderer, RenderFrame* renderFrame, Octree* frustumCullOctree) : System(world, eventBroker) @@ -13,31 +14,15 @@ RenderSystem::RenderSystem(World* world, EventBroker* eventBroker, const IRender 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_LastCullCamera = new Camera(*m_Camera); - m_FrustumCamPtr = &m_Camera; } RenderSystem::~RenderSystem() { delete m_Camera; - delete m_LastCullCamera; } bool RenderSystem::OnSetCamera(Events::SetCamera& e) { - //Right now, lets set the camera to cull away stuff if it is connected to a player. - //TODO: This won't work with spectators, or death anim. - if (e.CameraEntity.FirstParentWithComponent("Player").Valid()) { - m_FrustumCamPtr = &m_Camera; - LOG_INFO("Setting frustum to new camera."); - } else if (e.CameraEntity != m_CurrentCamera) { - //If the camera has no parents, i.e. a free camera, - //then we cull from the last camera, so we can see if the culling works. - //Copy the camera into the last frustum camera, without allocating new memory. - new ((void*)m_LastCullCamera) Camera(*m_Camera); - m_FrustumCamPtr = &m_LastCullCamera; - LOG_INFO("New camera, frustum remains at old camera."); - } ComponentWrapper cTransform = e.CameraEntity["Transform"]; ComponentWrapper cCamera = e.CameraEntity["Camera"]; m_Camera->SetFOV((double)cCamera["FOV"]); @@ -58,55 +43,15 @@ bool RenderSystem::isChildOfCurrentCamera(EntityWrapper entity) return entity == m_CurrentCamera || entity.IsChildOf(m_CurrentCamera); } -float frustrumTODO = 0.f; - void RenderSystem::fillModels(std::list>& opaqueJobs, std::list>& transparentJobs) { - if (!frustumEntity.Valid() && m_World->GetComponentPools().size() > 0) { - frustumEntity = EntityWrapper(m_World, m_World->CreateEntity()); - m_World->AttachComponent(frustumEntity.ID, "Transform"); - m_World->AttachComponent(frustumEntity.ID, "Model"); - frustumEntity["Model"]["Resource"] = "Models/Core/UnitCube.mesh"; - } - + Frustum frustum(m_Camera->ProjectionMatrix() * m_Camera->ViewMatrix()); std::vector seenEntities; - //m_Octree->ObjectsInFrustum((*m_FrustumCamPtr)->ProjectionMatrix() * (*m_FrustumCamPtr)->ViewMatrix(), seenEntities); + m_Octree->ObjectsInFrustum(frustum, seenEntities); - glm::mat4x4 viewProj = (*m_FrustumCamPtr)->ProjectionMatrix() * (*m_FrustumCamPtr)->ViewMatrix(); - OctSpace::Frustum frustum; - //Order: Right, left, top, bottom, far, near. - int sign = 1; - for (int i = 0; i < 6; ++i) { - sign = -sign; - int index = i / 2; - OctSpace::Plane& plane = frustum.Planes[i]; - plane.Normal.x = viewProj[0].w + sign * viewProj[0][index]; - plane.Normal.y = viewProj[1].w + sign * viewProj[1][index]; - plane.Normal.z = viewProj[2].w + sign * viewProj[2][index]; - plane.Distance = viewProj[3].w + sign * viewProj[3][index]; - float divByNormalLength = 1.0f / glm::length(plane.Normal); - plane.Normal *= divByNormalLength; - plane.Distance *= divByNormalLength; - } - if (frustumEntity.Valid()) { - int planeI = 0; - glm::vec3 pos = (*m_FrustumCamPtr)->Position() + frustrumTODO * (*m_FrustumCamPtr)->Forward(); - float dist = glm::dot(frustum.Planes[planeI].Normal, pos) + frustum.Planes[planeI].Distance; - frustumEntity["Transform"]["Position"] = pos - dist * frustum.Planes[planeI].Normal; - frustumEntity["Transform"]["Scale"] = glm::vec3(0.15f); - } - if (++frustrumTODO > 75) { - frustrumTODO = 0.f; - } - - //for (auto& seenEntity : seenEntities) { - // EntityWrapper entity = seenEntity.Entity; - // ComponentWrapper cModel = entity["Model"]; - auto models = m_World->GetComponents("Model"); - if (models == nullptr) { - return; - } - for (auto& cModel : *models) { + for (auto& seenEntity : seenEntities) { + EntityWrapper entity = seenEntity.Entity; + ComponentWrapper cModel = entity["Model"]; bool visible = cModel["Visible"]; if (!visible) { continue; @@ -116,8 +61,6 @@ void RenderSystem::fillModels(std::list>& opaqueJobs, continue; } - EntityWrapper entity = EntityWrapper(m_World, cModel.EntityID); - // Only render children of a camera if that camera is currently active if (isChildOfACamera(entity) && !isChildOfCurrentCamera(entity)) { continue; @@ -128,15 +71,6 @@ void RenderSystem::fillModels(std::list>& opaqueJobs, continue; } - if (entity.HasComponent("AABB")) { - OctSpace::Frustum::Output o = frustum.VsAABB(*Collision::EntityAbsoluteAABB(entity)); - if (o == OctSpace::Frustum::Outside && entity != frustumEntity) { - resource = "Models/Core/UnitRaptor.mesh"; - } - } else if (entity != frustumEntity){ - resource = "Models/Core/Error.mesh"; - } - Model* model; try { model = ResourceManager::Load<::Model, true>(resource); diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index 669e48d0..1124f2e4 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -100,7 +100,7 @@ Game::Game(int argc, char* argv[]) ++updateOrderLevel; m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeCollision, "Collidable"); m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeTrigger, "Player"); - m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeFrustrumCulling, "Model"); + m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeFrustrumCulling, "Model"); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); From eec59a40c842c17f2386836841ce0a6a1963d0e4 Mon Sep 17 00:00:00 2001 From: William Moberg Date: Tue, 9 Feb 2016 17:19:39 +0100 Subject: [PATCH 138/355] Nitpicks. --- include/Engine/Core/Octree.h | 1 - src/Game/Game.cpp | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/include/Engine/Core/Octree.h b/include/Engine/Core/Octree.h index 49a8b045..6bdea4d3 100644 --- a/include/Engine/Core/Octree.h +++ b/include/Engine/Core/Octree.h @@ -2,7 +2,6 @@ #define Octree_h__ #include -#include #include "../Common.h" #include "AABB.h" diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index 1124f2e4..d32eb2ba 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -75,6 +75,7 @@ Game::Game(int argc, char* argv[]) // Create Octrees + // TODO: Perhaps the world bounds should be set in some non-arbitrary way instead of this. AABB boxContainingTheWorld(glm::vec3(-300), glm::vec3(300)); m_OctreeCollision = new Octree(boxContainingTheWorld, 4); m_OctreeTrigger = new Octree(boxContainingTheWorld, 4); From 830e0f66c9ce9a3f84e73572c5f1c167a35f83f8 Mon Sep 17 00:00:00 2001 From: William Moberg Date: Tue, 9 Feb 2016 17:21:10 +0100 Subject: [PATCH 139/355] Tiny: Changed warning message. --- src/Engine/Core/EntityWrapper.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Engine/Core/EntityWrapper.cpp b/src/Engine/Core/EntityWrapper.cpp index b0d08e66..642421bc 100644 --- a/src/Engine/Core/EntityWrapper.cpp +++ b/src/Engine/Core/EntityWrapper.cpp @@ -19,7 +19,7 @@ bool EntityWrapper::HasComponent(const std::string& componentName) void EntityWrapper::AttachComponent(const char* componentName) { if (!Valid()) { - LOG_WARNING("Could not attach \"%s\" component to #%i, component is not valid.", componentName, ID); + LOG_WARNING("Could not attach \"%s\" component to #%i, entity is not valid.", componentName, ID); return; } World->AttachComponent(ID, componentName); From d2ed293183bad8ae6a91b71b2d491ee1e8fc3550 Mon Sep 17 00:00:00 2001 From: Jocke Date: Tue, 9 Feb 2016 19:14:56 +0100 Subject: [PATCH 140/355] Network is now working as udp or tcp. Next step is making the hybrid. --- include/Engine/Network/NetworkServer.h | 28 +++++-- include/Engine/Network/Packet.h | 3 +- include/Engine/Network/Server.h | 22 +++-- include/Engine/Network/TCPServer.h | 24 +++--- include/Engine/Network/UDPServer.h | 22 +++-- include/Game/Game.h | 13 +-- src/Engine/Network/Packet.cpp | 8 +- src/Engine/Network/Server.cpp | 90 ++++++++++++++++++-- src/Engine/Network/TCPClient.cpp | 7 ++ src/Engine/Network/TCPServer.cpp | 109 +++++++++---------------- src/Engine/Network/UDPServer.cpp | 83 +++++-------------- src/Game/Game.cpp | 6 +- 12 files changed, 225 insertions(+), 190 deletions(-) diff --git a/include/Engine/Network/NetworkServer.h b/include/Engine/Network/NetworkServer.h index 1586693d..36544292 100644 --- a/include/Engine/Network/NetworkServer.h +++ b/include/Engine/Network/NetworkServer.h @@ -1,20 +1,32 @@ #ifndef NetworkServer_h__ #define NetworkServer_h__ - +#include #include "Network/Packet.h" +#include "Network/PlayerDefinition.h" #define BUFFERSIZE 32000 typedef unsigned int PlayerID; typedef unsigned int PacketID; class NetworkServer { -//public: -// virtual void Connect(std::string playerName, std::string address, int port) = 0; -// virtual void Disconnect() = 0; -// virtual Packet Receive() = 0; -// virtual void Send(Packet & packet) = 0; -//protected: -// char m_ReadBuffer[BUFFERSIZE] = { 0 }; +public: + virtual void AcceptNewConnections(int& nextPlayerID, std::map& connectedPlayers) = 0; + virtual void Receive(Packet & packet, PlayerDefinition & playerDefinition) = 0; + virtual void Send(Packet & packet, PlayerDefinition & playerDefinition) = 0; + virtual void Send(Packet & packet) = 0; +protected: + char m_ReadBuffer[BUFFERSIZE] = { 0 }; + //void handle_accept(boost::shared_ptr socket, const boost::system::error_code & error); + //void parseConnect(Packet & packet); + //void readFromClients(); + + //public: + // virtual void Connect(std::string playerName, std::string address, int port) = 0; + // virtual void Disconnect() = 0; + // virtual Packet Receive() = 0; + // virtual void Send(Packet & packet) = 0; + //protected: + // char m_ReadBuffer[BUFFERSIZE] = { 0 }; }; #endif \ No newline at end of file diff --git a/include/Engine/Network/Packet.h b/include/Engine/Network/Packet.h index e88747b8..2a370dc6 100644 --- a/include/Engine/Network/Packet.h +++ b/include/Engine/Network/Packet.h @@ -57,7 +57,7 @@ public: void ChangePacketID(unsigned int& packetID); int Size() { return m_Offset; }; char* Data() { return m_Data; }; - MessageType GetMessageType() { return m_MessageType; }; + MessageType GetMessageType(); unsigned int DataReadSize() { return m_ReturnDataOffset; } unsigned int MaxSize() { return m_MaxPacketSize; } unsigned int HeaderSize() { return m_HeaderSize; } @@ -68,7 +68,6 @@ private: int m_Offset = 0; unsigned int m_MaxPacketSize = 512; unsigned int m_HeaderSize = 0; - MessageType m_MessageType = MessageType::Invalid; void resizeData(); void resizeData(int size); }; diff --git a/include/Engine/Network/Server.h b/include/Engine/Network/Server.h index 4ff169d2..0a3c93c8 100644 --- a/include/Engine/Network/Server.h +++ b/include/Engine/Network/Server.h @@ -6,6 +6,8 @@ #include +#include "Network/TCPServer.h" +#include "Network/UDPServer.h" #include "Network/MessageType.h" #include "Network/PlayerDefinition.h" #include "Core/World.h" @@ -17,6 +19,7 @@ #include "Core/EPlayerSpawned.h" #include "Core/EEntityDeleted.h" #include "Core/EComponentDeleted.h" + class Server : public Network { public: @@ -49,7 +52,7 @@ protected: // Game logic World* m_World; EventBroker* m_EventBroker; - + // Packet loss logic PacketID m_PacketID = 0; PacketID m_PreviousPacketID = 0; @@ -70,13 +73,15 @@ protected: void parsePlayerTransform(Packet& packet); void parseOnInputCommand(Packet& packet); void parseClientPing(); - void parsePing(); + void parsePing(); + void parseConnect(Packet & packet, PlayerDefinition & pd); + void parseTCPConnect(Packet & packet); void parseDisconnect(); - // Pure virtual functions - virtual void readFromClients() = 0; - virtual void send(Packet& packet, PlayerDefinition & playerDefinition) = 0; - virtual void send(Packet& packet) = 0; - virtual void parseConnect(Packet& packet) = 0; + //// Pure virtual functions + //virtual void readFromClients() = 0; + //virtual void send(Packet& packet, PlayerDefinition & playerDefinition) = 0; + //virtual void send(Packet& packet) = 0; + // Debug event EventRelay m_EInputCommand; bool OnInputCommand(const Events::InputCommand& e); @@ -86,6 +91,9 @@ protected: bool OnEntityDeleted(const Events::EntityDeleted& e); EventRelay m_EComponentDeleted; bool OnComponentDeleted(const Events::ComponentDeleted& e); +private: + TCPServer m_TCPServer; + //UDPServer m_UDPServer; }; #endif diff --git a/include/Engine/Network/TCPServer.h b/include/Engine/Network/TCPServer.h index 6c52d10d..b1aa7ce0 100644 --- a/include/Engine/Network/TCPServer.h +++ b/include/Engine/Network/TCPServer.h @@ -1,26 +1,30 @@ #ifndef TCPServer_h__ #define TCPServer_h__ -#include "Server.h" +#include +#include +#include +#include "NetworkServer.h" -class TCPServer : public Server +class TCPServer : public NetworkServer { public: TCPServer(); ~TCPServer(); + void AcceptNewConnections(int& nextPlayerID, std::map& connectedPlayers); + void Receive(Packet & packet, PlayerDefinition & playerDefinition); + void Send(Packet & packet, PlayerDefinition & playerDefinition); + void Send(Packet & packet); private: // TCP logic boost::asio::io_service m_IOService; std::unique_ptr acceptor; boost::shared_ptr lastReceivedSocket; - - void acceptNewConnections(); - void handle_accept(boost::shared_ptr socket, const boost::system::error_code & error); - void readFromClients(); - int receive(char * data, boost::asio::ip::tcp::socket& socket); - void parseConnect(Packet & packet); - void send(Packet & packet, PlayerDefinition & playerDefinition); - void send(Packet & packet); + + void handle_accept(boost::shared_ptr socket, + int& nextPlayerID, std::map& connectedPlayers, + const boost::system::error_code& error); + int readBuffer(char* data, PlayerDefinition& playerDefinition); }; #endif \ No newline at end of file diff --git a/include/Engine/Network/UDPServer.h b/include/Engine/Network/UDPServer.h index 22c8c3e3..7c912a21 100644 --- a/include/Engine/Network/UDPServer.h +++ b/include/Engine/Network/UDPServer.h @@ -1,25 +1,31 @@ #ifndef UDPServer_h__ #define UDPServer_h__ -#include "Server.h" +#include "NetworkServer.h" #include +// +//virtual void AcceptNewConnections() = 0; +//virtual void Receive(Packet & packet, PlayerDefinition & playerDefinition) = 0; +//virtual void Send(Packet & packet, PlayerDefinition & playerDefinition) = 0; +//virtual void Send(Packet & packet) = 0; -class UDPServer : public Server +class UDPServer : public NetworkServer { public: UDPServer(); ~UDPServer(); + void AcceptNewConnections(int& nextPlayerID, std::map& connectedPlayers); + void Receive(Packet & packet, PlayerDefinition & playerDefinition); + //void parseConnect(Packet & packet, PlayerDefinition & playerDefinition); + void Send(Packet & packet, PlayerDefinition & playerDefinition); + void Send(Packet & packet); + bool IsSocketAvailable(); private: // UDP logic boost::asio::io_service m_IOService; boost::asio::ip::udp::endpoint m_ReceiverEndpoint; std::unique_ptr m_Socket; - - void readFromClients(); - int receive(char * data); - void parseConnect(Packet & packet); - void send(Packet & packet, PlayerDefinition & playerDefinition); - void send(Packet & packet); + int readBuffer(char* data); }; #endif \ No newline at end of file diff --git a/include/Game/Game.h b/include/Game/Game.h index 54b8c753..fb03896d 100644 --- a/include/Game/Game.h +++ b/include/Game/Game.h @@ -28,15 +28,8 @@ #include "Network/Network.h" // Client #include "Network/Client.h" -// Hybrid -#include "Network/HybridServer.h" -#include "Network/HybridClient.h" -// TCP -#include "Network/TCPClient.h" -#include "Network/TCPServer.h" -// UDP -#include "Network/UDPServer.h" -#include "Network/UDPClient.h" +// Server +#include "Network/Server.h" // Sound #include "Sound/SoundSystem.h" @@ -69,8 +62,8 @@ private: // Network methods void networkFunction(); - Network* m_ClientOrServer; std::unique_ptr m_Client; + std::unique_ptr m_Server; bool m_IsClientOrServer = false; bool m_IsServer = false; diff --git a/src/Engine/Network/Packet.cpp b/src/Engine/Network/Packet.cpp index 06c81b8f..c9e8832a 100644 --- a/src/Engine/Network/Packet.cpp +++ b/src/Engine/Network/Packet.cpp @@ -37,7 +37,6 @@ void Packet::Init(MessageType type, unsigned int & packetID) // allocate memory for size of packet(only used in tcp) Packet::WritePrimitive(0); // Add message type - m_MessageType = type; int messageType = static_cast(type); Packet::WritePrimitive(messageType); Packet::WritePrimitive(packetID); @@ -120,6 +119,13 @@ void Packet::ChangePacketID(unsigned int & packetID) memcpy(m_Data + 2*sizeof(int), &packetID, sizeof(int)); } +MessageType Packet::GetMessageType() +{ + MessageType messagType; + memcpy(&messagType, m_Data + sizeof(int), sizeof(int)); + return messagType; +} + void Packet::resizeData() { resizeData(m_MaxPacketSize * 2); diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index fa0f1a1a..de7b6e14 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -23,7 +23,35 @@ void Server::Start(World* world, EventBroker* eventBroker) void Server::Update() { - readFromClients(); + m_TCPServer.AcceptNewConnections(m_NextPlayerID, m_ConnectedPlayers); + PlayerDefinition pd; + for (auto& kv : m_ConnectedPlayers) { + while (kv.second.TCPSocket->available()) { + // Packet will get real data in receive + Packet packet(MessageType::Invalid); + m_TCPServer.Receive(packet, kv.second); + m_Address = kv.second.TCPSocket->remote_endpoint().address(); + m_Port = kv.second.TCPSocket->remote_endpoint().port(); + if (packet.GetMessageType() == MessageType::Connect) { + parseTCPConnect(packet); + } else { + parseMessageType(packet); + } + } + } + + //while (m_UDPServer.IsSocketAvailable()) { + // // Packet will get real data in receive + // Packet packet(MessageType::Invalid); + // m_UDPServer.Receive(packet, pd); + // m_Address = pd.Endpoint.address(); + // m_Port = pd.Endpoint.port(); + // if (packet.GetMessageType() == MessageType::Connect) { + // parseConnect(packet, pd); + // } else { + // parseMessageType(packet); + // } + //} std::clock_t currentTime = std::clock(); // Send snapshot @@ -60,7 +88,7 @@ void Server::parseMessageType(Packet& packet) //identifyPacketLoss(); switch (static_cast(messageType)) { case MessageType::Connect: - parseConnect(packet); + //parseConnect(packet); break; case MessageType::Ping: parsePing(); @@ -90,7 +118,7 @@ void Server::broadcast(Packet& packet) { for (auto& kv : m_ConnectedPlayers) { packet.ChangePacketID(kv.second.PacketID); - send(packet, kv.second); + m_TCPServer.Send(packet, kv.second); } } @@ -184,6 +212,56 @@ void Server::checkForTimeOuts() } } +void Server::parseConnect(Packet & packet, PlayerDefinition & pd) +{ + //LOG_INFO("Parsing connections"); + //// Check if player is already connected + //if (GetPlayerIDFromEndpoint() != -1) { + // return; + //} + //// Create a new player + //pd.EntityID = 0; // Overlook this + //pd.Address = pd.Endpoint.address(); + //pd.Port = pd.Endpoint.port(); + //pd.Name = packet.ReadString(); + //pd.PacketID = 0; + //pd.StopTime = std::clock(); + //m_ConnectedPlayers[m_NextPlayerID++] = pd; + //LOG_INFO("Spectator \"%s\" connected on IP: %s", pd.Name.c_str(), pd.Endpoint.address().to_string().c_str()); + + //// Send a message to the player that connected + //Packet connnectPacket(MessageType::Connect, pd.PacketID); + //m_UDPServer.Send(connnectPacket); + + //// Send notification that a player has connected + //Packet notificationPacket(MessageType::PlayerConnected); + //broadcast(notificationPacket); +} + +void Server::parseTCPConnect(Packet & packet) +{ + LOG_INFO("Parsing connections"); + // Check if player is already connected + PlayerID playerID = GetPlayerIDFromEndpoint(); + if (playerID = -1) { + return; + } + // Create a new player + m_ConnectedPlayers.at(playerID).EntityID = 0; // Overlook this + m_ConnectedPlayers.at(playerID).Name = packet.ReadString(); + m_ConnectedPlayers.at(playerID).PacketID = 0; + m_ConnectedPlayers.at(playerID).StopTime = std::clock(); + LOG_INFO("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_TCPServer.Send(connnectPacket); + + // Send notification that a player has connected + Packet notificationPacket(MessageType::PlayerConnected); + //broadcast(notificationPacket); +} + void Server::parseDisconnect() { LOG_INFO("%i: Parsing disconnect", m_PacketID); @@ -232,7 +310,7 @@ void Server::kick(PlayerID player) { disconnect(player); Packet packet = Packet(MessageType::Kick); - send(packet); + m_TCPServer.Send(packet); } bool Server::OnInputCommand(const Events::InputCommand & e) @@ -261,7 +339,7 @@ bool Server::OnPlayerSpawned(const Events::PlayerSpawned & e) packet.WritePrimitive(e.Spawner.ID); // We don't send PlayerID here because it will always be set to -1 packet.WriteString(m_ConnectedPlayers[e.PlayerID].Name); - send(packet, m_ConnectedPlayers[e.PlayerID]); + m_TCPServer.Send(packet, m_ConnectedPlayers[e.PlayerID]); return false; } @@ -297,7 +375,7 @@ void Server::parseClientPing() // Return ping Packet packet(MessageType::Ping, m_ConnectedPlayers[player].PacketID); packet.WriteString("Ping received"); - send(packet); + m_TCPServer.Send(packet); } void Server::parsePing() diff --git a/src/Engine/Network/TCPClient.cpp b/src/Engine/Network/TCPClient.cpp index 42f724d0..69938c38 100644 --- a/src/Engine/Network/TCPClient.cpp +++ b/src/Engine/Network/TCPClient.cpp @@ -13,6 +13,12 @@ TCPClient::~TCPClient() void 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; } if (!m_IsConnected) { @@ -29,6 +35,7 @@ void TCPClient::Connect(std::string playerName, std::string address, int port) Packet packet(MessageType::Connect, m_SendPacketID); packet.WriteString(playerName); Send(packet); + LOG_INFO("Connect message sent!"); } } } diff --git a/src/Engine/Network/TCPServer.cpp b/src/Engine/Network/TCPServer.cpp index 09d2ce69..105aab9f 100644 --- a/src/Engine/Network/TCPServer.cpp +++ b/src/Engine/Network/TCPServer.cpp @@ -7,42 +7,38 @@ TCPServer::TCPServer() } TCPServer::~TCPServer() -{ } - -void TCPServer::readFromClients() { - acceptNewConnections(); - for (auto& kv : m_ConnectedPlayers) { - while (kv.second.TCPSocket->available()) { - try { - bytesRead = receive(readBuffer, *kv.second.TCPSocket); - lastReceivedSocket = kv.second.TCPSocket; - // Get logic for mother class - boost::asio::ip::tcp::endpoint remoteEndpoint = kv.second.TCPSocket->remote_endpoint(); - m_Address = remoteEndpoint.address(); - m_Port = remoteEndpoint.port(); - // Recreate packets - Packet packet(readBuffer, bytesRead); - parseMessageType(packet); - } catch (const std::exception& err) { - //LOG_ERROR("%i: Read from client crashed %s", m_PacketID, err.what()); - } - } - } } -void TCPServer::acceptNewConnections() +void TCPServer::AcceptNewConnections(int& nextPlayerID, std::map& connectedPlayers) { + //PlayerDefinition pd; + //connectedPlayers[nextPlayerID++] = pd; boost::shared_ptr newSocket = boost::shared_ptr(new tcp::socket(m_IOService)); m_IOService.poll(); acceptor->async_accept(*newSocket, - boost::bind(&TCPServer::handle_accept, this, newSocket, + boost::bind(&TCPServer::handle_accept, this, newSocket, boost::ref(nextPlayerID), boost::ref(connectedPlayers), boost::asio::placeholders::error)); } -void TCPServer::handle_accept(boost::shared_ptr socket, const boost::system::error_code& error) +PlayerID GetPlayerIDFromEndpoint(const std::map& connectedPlayers, + boost::asio::ip::address address, unsigned short port) { - if (!error && GetPlayerIDFromEndpoint() == -1) { + for (auto& kv : connectedPlayers) { + if (kv.second.Address == address && + kv.second.Port == port) { + return kv.first; + } + } + return -1; +} + +void TCPServer::handle_accept(boost::shared_ptr socket, + int& nextPlayerID, std::map& connectedPlayers, + const boost::system::error_code& error) +{ + if (!error && GetPlayerIDFromEndpoint(connectedPlayers, socket->remote_endpoint().address(), + socket->remote_endpoint().port()) == -1) { // Add tcp socket to connections boost::asio::ip::tcp::no_delay option(true); socket->set_option(option); @@ -51,55 +47,24 @@ void TCPServer::handle_accept(boost::shared_ptr socket, const boost pd.TCPSocket = socket; pd.Address = socket.get()->remote_endpoint().address(); pd.Port = socket.get()->remote_endpoint().port(); - m_ConnectedPlayers[m_NextPlayerID++] = pd; + connectedPlayers[nextPlayerID++] = pd; } } -void TCPServer::parseConnect(Packet & packet) -{ - LOG_INFO("Parsing connections"); - // Check if player is already connected - PlayerID playerID = GetPlayerIDFromEndpoint(); - if (playerID = -1) { - return; - } - - // Create a new player - m_ConnectedPlayers.at(playerID).EntityID = 0; // Overlook this - m_ConnectedPlayers.at(playerID).Name = packet.ReadString(); - m_ConnectedPlayers.at(playerID).PacketID = 0; - m_ConnectedPlayers.at(playerID).StopTime = std::clock(); - LOG_INFO("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); - send(connnectPacket); - - // Send notification that a player has connected - Packet notificationPacket(MessageType::PlayerConnected); - broadcast(notificationPacket); -} - -void TCPServer::send(Packet & packet, PlayerDefinition & playerDefinition) +void TCPServer::Send(Packet & packet, PlayerDefinition & playerDefinition) { try { packet.UpdateSize(); int bytesSent = playerDefinition.TCPSocket->send( boost::asio::buffer(packet.Data(), packet.Size()), 0); - // Network Debug data - if (isReadingData) { - m_NetworkData.TotalDataSent += packet.Size(); - m_NetworkData.DataSentThisInterval += packet.Size(); - m_NetworkData.AmountOfMessagesSent++; - } } catch (const boost::system::system_error& e) { // TODO: Clean up invalid endpoints out of m_ConnectedPlayers later playerDefinition.Endpoint = boost::asio::ip::udp::endpoint(); } } -void TCPServer::send(Packet & packet) +void TCPServer::Send(Packet & packet) { packet.UpdateSize(); lastReceivedSocket->send( @@ -107,33 +72,33 @@ void TCPServer::send(Packet & packet) packet.Data(), packet.Size()), 0); - if (isReadingData) { - // Network Debug data - m_NetworkData.TotalDataSent += packet.Size(); - m_NetworkData.DataSentThisInterval += packet.Size(); +} + +void TCPServer::Receive(Packet & packet, PlayerDefinition & playerDefinition) +{ + int bytesRead = readBuffer(m_ReadBuffer, playerDefinition); + if (bytesRead > 0) { + packet.ReconstructFromData(m_ReadBuffer, bytesRead); } } -int TCPServer::receive(char * data, boost::asio::ip::tcp::socket& socket) +int TCPServer::readBuffer(char* data, PlayerDefinition & playerDefinition) { + if (!playerDefinition.TCPSocket) { + return 0; + } boost::system::error_code error; // Read size of packet - int bytesReceived = socket.read_some(boost + int bytesReceived = playerDefinition.TCPSocket->read_some(boost ::asio::buffer((void*)data, sizeof(int)), error); int sizeOfPacket = 0; memcpy(&sizeOfPacket, data, sizeof(int)); // Read the rest of the message - bytesReceived += socket.read_some(boost + bytesReceived += playerDefinition.TCPSocket->read_some(boost ::asio::buffer((void*)(data + bytesReceived), sizeOfPacket - bytesReceived), error); - // Network Debug data - if (isReadingData) { - m_NetworkData.TotalDataReceived += bytesReceived; - m_NetworkData.DataReceivedThisInterval += bytesReceived; - m_NetworkData.AmountOfMessagesReceived++; - } if (error) { //LOG_ERROR("receive: %s", error.message().c_str()); } diff --git a/src/Engine/Network/UDPServer.cpp b/src/Engine/Network/UDPServer.cpp index 41cb436c..e0bdf3a2 100644 --- a/src/Engine/Network/UDPServer.cpp +++ b/src/Engine/Network/UDPServer.cpp @@ -6,71 +6,23 @@ UDPServer::UDPServer() } UDPServer::~UDPServer() -{ } - -void UDPServer::readFromClients() { - while (m_Socket->available()) { - try { - bytesRead = receive(readBuffer); - m_Address = m_ReceiverEndpoint.address(); - m_Port = m_ReceiverEndpoint.port(); - Packet packet(readBuffer, bytesRead); - parseMessageType(packet); - } catch (const std::exception& err) { - //LOG_ERROR("%i: Read from client crashed %s", m_PacketID, err.what()); - } - } } -void UDPServer::parseConnect(Packet& packet) -{ - LOG_INFO("Parsing connections"); - // Check if player is already connected - if (GetPlayerIDFromEndpoint() != -1) { - return; - } - // Create a new player - PlayerDefinition pd; - pd.EntityID = 0; // Overlook this - pd.Endpoint = m_ReceiverEndpoint; - pd.Address = m_ReceiverEndpoint.address(); - pd.Port = m_ReceiverEndpoint.port(); - pd.Name = packet.ReadString(); - pd.PacketID = 0; - pd.StopTime = std::clock(); - m_ConnectedPlayers[m_NextPlayerID++] = pd; - LOG_INFO("Spectator \"%s\" connected on IP: %s", pd.Name.c_str(), pd.Endpoint.address().to_string().c_str()); - - // Send a message to the player that connected - Packet connnectPacket(MessageType::Connect, pd.PacketID); - send(connnectPacket); - - // Send notification that a player has connected - Packet notificationPacket(MessageType::PlayerConnected); - broadcast(notificationPacket); -} - -void UDPServer::send(Packet& packet, PlayerDefinition & playerDefinition) +void UDPServer::Send(Packet& packet, PlayerDefinition & playerDefinition) { try { int bytesSent = m_Socket->send_to( boost::asio::buffer(packet.Data(), packet.Size()), playerDefinition.Endpoint, 0); - // Network Debug data - if (isReadingData) { - m_NetworkData.TotalDataSent += packet.Size(); - m_NetworkData.DataSentThisInterval += packet.Size(); - m_NetworkData.AmountOfMessagesSent++; - } } catch (const boost::system::system_error& e) { // TODO: Clean up invalid endpoints out of m_ConnectedPlayers later playerDefinition.Endpoint = boost::asio::ip::udp::endpoint(); } } // Send back to endpoint of received packet -void UDPServer::send(Packet & packet) +void UDPServer::Send(Packet & packet) { m_Socket->send_to( boost::asio::buffer( @@ -78,27 +30,32 @@ void UDPServer::send(Packet & packet) packet.Size()), m_ReceiverEndpoint, 0); - if (isReadingData) { - // Network Debug data - m_NetworkData.TotalDataSent += packet.Size(); - m_NetworkData.DataSentThisInterval += packet.Size(); - } } -int UDPServer::receive(char * data) +void UDPServer::Receive(Packet & packet, PlayerDefinition & playerDefinition) +{ + int bytesRead = readBuffer(m_ReadBuffer); + if (bytesRead > 0) { + packet.ReconstructFromData(m_ReadBuffer, bytesRead); + } + playerDefinition.Endpoint = m_ReceiverEndpoint; +} + +bool UDPServer::IsSocketAvailable() +{ + return m_Socket->available(); +} + +int UDPServer::readBuffer(char* data) { unsigned int length = m_Socket->receive_from( boost::asio::buffer((void*)data , BUFFERSIZE) , m_ReceiverEndpoint, 0); - // Network Debug data - if (isReadingData) { - m_NetworkData.TotalDataReceived += length; - m_NetworkData.DataReceivedThisInterval += length; - m_NetworkData.AmountOfMessagesReceived++; - } return length; } - +void UDPServer::AcceptNewConnections(int& nextPlayerID, std::map& connectedPlayers) +{ +} \ No newline at end of file diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index 931bb9dd..9e1bf708 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -156,7 +156,7 @@ void Game::Tick() // Update network if (m_IsClientOrServer) { if (m_IsServer) - m_ClientOrServer->Update(); + m_Server->Update(); else if (!m_IsServer) { m_Client->Update(); } @@ -197,9 +197,9 @@ void Game::networkFunction() if (m_IsServer) { m_IsClientOrServer = true; // m_ClientOrServer = new UDPServer(); - m_ClientOrServer = new TCPServer(); + m_Server = std::unique_ptr(new Server()); //m_ClientOrServer = new HybridServer(); - m_ClientOrServer->Start(m_World, m_EventBroker); + m_Server->Start(m_World, m_EventBroker); } From 7140b740b5dc06d0ff122413093d9ba88af09972 Mon Sep 17 00:00:00 2001 From: William Moberg Date: Tue, 9 Feb 2016 19:20:04 +0100 Subject: [PATCH 141/355] Models/Collideables/etc. won't need a AABB component anymore, if it has a Model component. In addition, they should take rotation into account, i.e it doesn't have to be axis-aligned. --- include/Engine/Collision/Collision.h | 2 - include/Engine/Rendering/Model.h | 5 +- src/Engine/Collision/Collision.cpp | 71 ++++++++++++----------- src/Engine/Collision/FillOctreeSystem.cpp | 6 -- src/Engine/Collision/TriggerSystem.cpp | 5 -- src/Engine/Rendering/Model.cpp | 9 +++ 6 files changed, 51 insertions(+), 47 deletions(-) diff --git a/include/Engine/Collision/Collision.h b/include/Engine/Collision/Collision.h index 6d16e090..6e4858b2 100644 --- a/include/Engine/Collision/Collision.h +++ b/include/Engine/Collision/Collision.h @@ -78,8 +78,6 @@ bool AABBVsAABB(const AABB& a, const AABB& b); //Also outputs the minimum translation that box [a] would need in order to resolve collision. bool AABBVsAABB(const AABB& a, const AABB& b, glm::vec3& minimumTranslation); -//Attaches an AABB which contains all vertices in the entitys Model. -bool AttachAABBComponentFromModel(EntityWrapper entity); // Calculates an absolute AABB from an entity AABB component boost::optional EntityAbsoluteAABB(EntityWrapper& entity); diff --git a/include/Engine/Rendering/Model.h b/include/Engine/Rendering/Model.h index f751a8cc..1f5231e2 100644 --- a/include/Engine/Rendering/Model.h +++ b/include/Engine/Rendering/Model.h @@ -4,6 +4,7 @@ #include "Rendering/RawModelCustom.h" //#include "Rendering/RawModelAssimp.h" #include "../OpenGL.h" +#include "Core/AABB.h" class Model : public ThreadUnsafeResource { @@ -17,13 +18,15 @@ public: const std::vector& MaterialGroups() const { return m_RawModel->MaterialGroups; } const glm::mat4& Matrix() const { return m_RawModel->m_Matrix; } const std::vector& Vertices() const { return m_RawModel->m_Vertices; } + const AABB& Box() const { return m_Box; } GLuint VAO; GLuint ElementBuffer; RawModel* m_RawModel; private: - + AABB m_Box; + GLuint VertexBuffer; GLuint NormalBuffer; GLuint TangentNormalsBuffer; diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index b150d667..db2319c7 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -1,4 +1,5 @@ #include +#include #include "Collision/Collision.h" #include "Engine/GLM.h" @@ -564,45 +565,49 @@ bool AABBvsTriangles(const AABB& box, return hit; } -bool AttachAABBComponentFromModel(EntityWrapper entity) -{ - if (!entity.HasComponent("Model")) { - return false; - } - //Derive AABB from model - RawModel* model; - try { - model = ResourceManager::Load(entity["Model"]["Resource"]); - } catch (const std::exception&) { - return false; - } - - glm::vec3 mini(INFINITY); - glm::vec3 maxi(-INFINITY); - for (const auto& v : model->m_Vertices) { - mini = glm::min(mini, v.Position); - maxi = glm::max(maxi, v.Position); - } - - entity.AttachComponent("AABB"); - entity["AABB"]["Origin"] = 0.5f * (maxi + mini); - entity["AABB"]["Size"] = maxi - mini; - return true; -} - boost::optional EntityAbsoluteAABB(EntityWrapper& entity) { - if (!entity.HasComponent("AABB")) { + AABB modelSpaceBox; + if (entity.HasComponent("AABB")) { + ComponentWrapper& cAABB = entity["AABB"]; + modelSpaceBox = EntityAABB::FromOriginSize((glm::vec3)cAABB["Origin"], (glm::vec3)cAABB["Size"]); + } else if (entity.HasComponent("Model")) { + Model* model; + std::string res = entity["Model"]["Resource"]; + if (res.empty()) { + return boost::none; + } + try { + model = ResourceManager::Load<::Model, true>(res); + } catch (const Resource::StillLoadingException&) { + return boost::none; + } catch (const std::exception&) { + return boost::none; + } + modelSpaceBox = model->Box(); + } else { return boost::none; } - ComponentWrapper& cAABB = entity["AABB"]; - glm::vec3 absPosition = Transform::AbsolutePosition(entity.World, entity.ID); - glm::vec3 absScale = Transform::AbsoluteScale(entity.World, entity.ID); - glm::vec3 origin = absPosition + (glm::vec3)cAABB["Origin"]; - glm::vec3 size = (glm::vec3)cAABB["Size"] * absScale; + glm::mat4 modelMat = Transform::AbsoluteTransformation(entity); + glm::vec3 mini(INFINITY); + glm::vec3 maxi(-INFINITY); + glm::vec3 maxCorner = modelSpaceBox.MaxCorner(); + glm::vec3 minCorner = modelSpaceBox.MinCorner(); + for (int i = 0; i < 8; ++i) { + std::bitset<3> bits(i); + glm::vec3 corner; + corner.x = bits.test(0) ? maxCorner.x : minCorner.x; + corner.y = bits.test(1) ? maxCorner.y : minCorner.y; + corner.z = bits.test(2) ? maxCorner.z : minCorner.z; + corner = Transform::TransformPoint(corner, modelMat); + mini = glm::min(mini, corner); + maxi = glm::max(maxi, corner); + } + + EntityAABB aabb; + aabb = AABB(mini, maxi); - EntityAABB aabb = EntityAABB::FromOriginSize(origin, size); aabb.Entity = entity; return aabb; diff --git a/src/Engine/Collision/FillOctreeSystem.cpp b/src/Engine/Collision/FillOctreeSystem.cpp index 8c03b5c2..a727eb86 100644 --- a/src/Engine/Collision/FillOctreeSystem.cpp +++ b/src/Engine/Collision/FillOctreeSystem.cpp @@ -7,12 +7,6 @@ void FillOctreeSystem::Update(double dt) void FillOctreeSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) { - if (!entity.HasComponent("AABB")) { - //Derive AABB from model. - if (!Collision::AttachAABBComponentFromModel(entity)) { - return; - } - } boost::optional absoluteAABB = Collision::EntityAbsoluteAABB(entity); if (absoluteAABB) { m_Octree->AddDynamicObject(*absoluteAABB); diff --git a/src/Engine/Collision/TriggerSystem.cpp b/src/Engine/Collision/TriggerSystem.cpp index adc778e5..21a47721 100644 --- a/src/Engine/Collision/TriggerSystem.cpp +++ b/src/Engine/Collision/TriggerSystem.cpp @@ -5,11 +5,6 @@ void TriggerSystem::UpdateComponent(EntityWrapper& triggerEntity, ComponentWrapper& cTrigger, double dt) { - // The trigger *should* have a bounding box, or something, to test against so it can be triggered. - // If it doesn't, add one as big as the model for now, then size can be modified in editor if necessary. - if (!triggerEntity.HasComponent("AABB")) { - Collision::AttachAABBComponentFromModel(triggerEntity); - } boost::optional triggerBox = Collision::EntityAbsoluteAABB(triggerEntity); if (!triggerBox) { return; diff --git a/src/Engine/Rendering/Model.cpp b/src/Engine/Rendering/Model.cpp index cf4923a3..a61cf8e3 100644 --- a/src/Engine/Rendering/Model.cpp +++ b/src/Engine/Rendering/Model.cpp @@ -64,6 +64,15 @@ Model::Model(std::string fileName) GLERROR("GLEW: BufferFail5"); //CreateBuffers(); + + glm::vec3 mini(INFINITY); + glm::vec3 maxi(-INFINITY); + for (const auto& v : m_RawModel->m_Vertices) { + mini = glm::min(mini, v.Position); + maxi = glm::max(maxi, v.Position); + } + + m_Box = AABB(maxi, mini); } Model::~Model() From a93ccecfeb41bcdaccfffd0e6b4d9a52f6e83c6d Mon Sep 17 00:00:00 2001 From: William Moberg Date: Tue, 9 Feb 2016 19:23:12 +0100 Subject: [PATCH 142/355] Debug test code. --- src/Engine/Collision/Collision.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index db2319c7..a20ae4d3 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -568,10 +568,10 @@ bool AABBvsTriangles(const AABB& box, boost::optional EntityAbsoluteAABB(EntityWrapper& entity) { AABB modelSpaceBox; - if (entity.HasComponent("AABB")) { + /*if (entity.HasComponent("AABB")) { ComponentWrapper& cAABB = entity["AABB"]; modelSpaceBox = EntityAABB::FromOriginSize((glm::vec3)cAABB["Origin"], (glm::vec3)cAABB["Size"]); - } else if (entity.HasComponent("Model")) { + } else */if (entity.HasComponent("Model")) { Model* model; std::string res = entity["Model"]["Resource"]; if (res.empty()) { @@ -584,6 +584,7 @@ boost::optional EntityAbsoluteAABB(EntityWrapper& entity) } catch (const std::exception&) { return boost::none; } + entity.AttachComponent("AABB"); modelSpaceBox = model->Box(); } else { return boost::none; @@ -609,7 +610,8 @@ boost::optional EntityAbsoluteAABB(EntityWrapper& entity) aabb = AABB(mini, maxi); aabb.Entity = entity; - + (glm::vec3&)entity["AABB"]["Origin"] = aabb.Origin(); + (glm::vec3&)entity["AABB"]["Size"] = aabb.Size(); return aabb; } From ecfacee5876ad73a5fc4daa1746914390b2db8ae Mon Sep 17 00:00:00 2001 From: William Moberg Date: Tue, 9 Feb 2016 19:33:28 +0100 Subject: [PATCH 143/355] Undo debug test code. --- src/Engine/Collision/Collision.cpp | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index a20ae4d3..c0c27190 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -568,10 +568,10 @@ bool AABBvsTriangles(const AABB& box, boost::optional EntityAbsoluteAABB(EntityWrapper& entity) { AABB modelSpaceBox; - /*if (entity.HasComponent("AABB")) { + if (entity.HasComponent("AABB")) { ComponentWrapper& cAABB = entity["AABB"]; modelSpaceBox = EntityAABB::FromOriginSize((glm::vec3)cAABB["Origin"], (glm::vec3)cAABB["Size"]); - } else */if (entity.HasComponent("Model")) { + } else if (entity.HasComponent("Model")) { Model* model; std::string res = entity["Model"]["Resource"]; if (res.empty()) { @@ -584,7 +584,6 @@ boost::optional EntityAbsoluteAABB(EntityWrapper& entity) } catch (const std::exception&) { return boost::none; } - entity.AttachComponent("AABB"); modelSpaceBox = model->Box(); } else { return boost::none; @@ -610,8 +609,6 @@ boost::optional EntityAbsoluteAABB(EntityWrapper& entity) aabb = AABB(mini, maxi); aabb.Entity = entity; - (glm::vec3&)entity["AABB"]["Origin"] = aabb.Origin(); - (glm::vec3&)entity["AABB"]["Size"] = aabb.Size(); return aabb; } From d5647ce89ca445a09f608ff81048e5ade1346d9e Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Tue, 9 Feb 2016 16:08:28 +0100 Subject: [PATCH 144/355] Working 1-snapshot interpolation --- include/Game/Systems/InterpolationSystem.h | 39 +++--- src/Engine/Network/Server.cpp | 2 +- src/Game/Game.cpp | 3 +- .../Network/MultiplayerSnapshotFilter.cpp | 6 +- src/Game/Systems/InterpolationSystem.cpp | 122 +++++++++++------- 5 files changed, 103 insertions(+), 69 deletions(-) diff --git a/include/Game/Systems/InterpolationSystem.h b/include/Game/Systems/InterpolationSystem.h index 5077ad92..758609c8 100644 --- a/include/Game/Systems/InterpolationSystem.h +++ b/include/Game/Systems/InterpolationSystem.h @@ -16,26 +16,39 @@ #include "Network/EInterpolate.h" -class InterpolationSystem : public PureSystem +class InterpolationSystem : public ImpureSystem { public: InterpolationSystem(SystemParams params); ~InterpolationSystem() { } - virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& transform, double dt) override; + virtual void Update(double dt) override; private: - struct Transform + template + struct Interpolation { - glm::vec3 Position; - glm::vec3 Scale; - glm::quat Orientation; - float interpolationTime; + Interpolation(const ComponentWrapper& Component, const std::string& Field, const T& Start, const T& Goal) + : Component(Component) + , Field(Field) + , Start(Start) + , Goal(Goal) + { } + + ComponentWrapper Component; + std::string Field; + T Start; + T Goal; + double Alpha = 0.0; }; - std::unordered_map m_NextTransform; - std::unordered_map m_LastReceivedTransform; - EntityWrapper m_LocalPlayer = EntityWrapper::Invalid; + float m_SnapshotInterval; + std::unordered_map> m_InterpolatePosition; + std::unordered_map> m_InterpolateOrientation; + std::unordered_map> m_InterpolateVelocity; + + EventRelay m_EInterpolate; + bool InterpolationSystem::OnInterpolate(Events::Interpolate& e); template T vectorInterpolation(T prev, T next, double currentTime) @@ -44,12 +57,6 @@ private: T vector = difference * (static_cast(currentTime) / m_SnapshotInterval); return vector; } - float m_SnapshotInterval; - - EventRelay m_EInterpolate; - bool InterpolationSystem::OnInterpolate(Events::Interpolate& e); - EventRelay m_EPlayerSpawned; - bool OnPlayerSpawned(Events::PlayerSpawned& e); }; #endif diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index 9502c01d..b0003539 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -240,7 +240,7 @@ void Server::checkForTimeOuts() double stopPing = 1000 * m_ConnectedPlayers[i].StopTime / static_cast(CLOCKS_PER_SEC); if (startPing > stopPing + m_TimeoutMs) { - LOG_INFO("User %i timed out!", i); + //LOG_INFO("User %i timed out!", i); //disconnect(i); } } diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index 982ce647..38468e47 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -95,11 +95,12 @@ Game::Game(int argc, char* argv[]) // All systems with orderlevel 0 will be updated first. unsigned int updateOrderLevel = 0; + m_SystemPipeline->AddSystem(updateOrderLevel); + ++updateOrderLevel; m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); - m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer); diff --git a/src/Game/Network/MultiplayerSnapshotFilter.cpp b/src/Game/Network/MultiplayerSnapshotFilter.cpp index 426b24d2..709ce6b1 100644 --- a/src/Game/Network/MultiplayerSnapshotFilter.cpp +++ b/src/Game/Network/MultiplayerSnapshotFilter.cpp @@ -12,7 +12,11 @@ bool MultiplayerSnapshotFilter::FilterComponent(EntityWrapper entity, SharedComp return false; } - if (component.Info.Name == "Transform") { + if (component.Info.Name == "Physics") { + return false; + } + + if (component.Info.Name == "Transform" || component.Info.Name == "Physics") { m_EventBroker->Publish(Events::Interpolate(entity, component)); return false; } diff --git a/src/Game/Systems/InterpolationSystem.cpp b/src/Game/Systems/InterpolationSystem.cpp index 6c57c2b6..430c01c1 100644 --- a/src/Game/Systems/InterpolationSystem.cpp +++ b/src/Game/Systems/InterpolationSystem.cpp @@ -2,74 +2,96 @@ InterpolationSystem::InterpolationSystem(SystemParams params) : System(params) - , PureSystem("Transform") { ConfigFile* config = ResourceManager::Load("Config.ini"); m_SnapshotInterval = config->Get("Networking.SnapshotInterval", 0.05f); EVENT_SUBSCRIBE_MEMBER(m_EInterpolate, &InterpolationSystem::OnInterpolate); - EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &InterpolationSystem::OnPlayerSpawned); } -void InterpolationSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& transform, double dt) +void InterpolationSystem::Update(double dt) { - // Don't interpolate entities that might already have been removed - if (!entity.Valid()) { - return; + // Position + for (auto& kv : m_InterpolatePosition) { + EntityWrapper entity = kv.first; + if (!entity.Valid()) { + continue; + } + auto& iPosition = kv.second; + glm::vec3& position = iPosition.Component[iPosition.Field]; + + iPosition.Alpha += dt; + float alpha = glm::min(iPosition.Alpha / m_SnapshotInterval, 1.0); + position = iPosition.Start + ((iPosition.Goal - iPosition.Start) * alpha); } - //return; - if (m_NextTransform.find(transform.EntityID) != m_NextTransform.end()) { // Exists in map - m_NextTransform[transform.EntityID].interpolationTime += static_cast(dt); - Transform sTransform = m_NextTransform[transform.EntityID]; - float time = sTransform.interpolationTime; - if (time > m_SnapshotInterval) { - if (m_LastReceivedTransform.find(transform.EntityID) != m_LastReceivedTransform.end()) { - m_NextTransform[transform.EntityID] = m_LastReceivedTransform[transform.EntityID]; - m_NextTransform[transform.EntityID].interpolationTime = time - m_SnapshotInterval; - sTransform = m_NextTransform[transform.EntityID]; - m_LastReceivedTransform.erase(transform.EntityID); - } else { - m_NextTransform.erase(transform.EntityID); - } + // Orientation + for (auto& kv : m_InterpolateOrientation) { + EntityWrapper entity = kv.first; + if (!entity.Valid()) { + continue; } - if (transform.Info.Name == "Transform") { - // Position - glm::vec3 nextPosition = sTransform.Position; - glm::vec3 currentPosition = static_cast(transform["Position"]); - (glm::vec3&)transform["Position"] += vectorInterpolation(currentPosition, nextPosition, sTransform.interpolationTime); - // Orientation - glm::quat nextOrientation = sTransform.Orientation; - glm::quat currentOrientation = glm::quat(static_cast(transform["Orientation"])); - (glm::vec3&)transform["Orientation"] = glm::eulerAngles(glm::slerp(currentOrientation, nextOrientation, glm::max(sTransform.interpolationTime / m_SnapshotInterval, 1.f))); - // Scale - glm::vec3 nextScale = sTransform.Scale; - glm::vec3 currentScale = static_cast(transform["Scale"]); - (glm::vec3&)transform["Scale"] += vectorInterpolation(currentScale, nextScale, sTransform.interpolationTime); - } - } -} + auto& iOrientation = kv.second; + glm::vec3& orientation = iOrientation.Component[iOrientation.Field]; -bool InterpolationSystem::OnPlayerSpawned(Events::PlayerSpawned& e) -{ - m_LocalPlayer = e.Player; - return true; + iOrientation.Alpha += dt / m_SnapshotInterval; + iOrientation.Alpha = glm::min(iOrientation.Alpha, 1.0); + orientation = glm::eulerAngles(glm::slerp(iOrientation.Start, iOrientation.Goal, (float)iOrientation.Alpha)); + } + + // Velocity + for (auto& kv : m_InterpolateVelocity) { + EntityWrapper entity = kv.first; + if (!entity.Valid()) { + continue; + } + auto& iVelocity = kv.second; + glm::vec3& position = iVelocity.Component[iVelocity.Field]; + + iVelocity.Alpha += dt; + float alpha = glm::min(iVelocity.Alpha / m_SnapshotInterval, 1.0); + position = iVelocity.Start + ((iVelocity.Goal - iVelocity.Start) * alpha); + } } bool InterpolationSystem::OnInterpolate(Events::Interpolate& e) { - // TODO: Make this work for arbitrary component types if (e.Component.Info.Name == "Transform") { - Transform transform; - transform.Position = e.Component["Position"]; - transform.Orientation = glm::quat((glm::vec3)e.Component["Orientation"]); - transform.Scale = e.Component["Scale"]; - transform.interpolationTime = 0.0f; + auto cTransform = e.Entity["Transform"]; - if (m_NextTransform.find(e.Entity.ID) != m_NextTransform.end()) { // Did exist - m_LastReceivedTransform[e.Entity.ID] = transform; - } else { // Did not - m_NextTransform[e.Entity.ID] = transform; + // Position + Interpolation iPosition( + cTransform, + "Position", + cTransform["Position"], + e.Component["Position"] + ); + m_InterpolatePosition.erase(e.Entity); + m_InterpolatePosition.insert(std::make_pair(e.Entity, iPosition)); + + // Orientation + Interpolation iOrientation( + cTransform, + "Orientation", + glm::quat((glm::vec3&)cTransform["Orientation"]), + glm::quat((glm::vec3&)e.Component["Orientation"]) + ); + m_InterpolateOrientation.erase(e.Entity); + m_InterpolateOrientation.insert(std::make_pair(e.Entity, iOrientation)); + } else if (e.Component.Info.Name == "Physics") { + auto cPhysics = e.Entity["Physics"]; + if (!e.Entity.HasComponent("Player")) { + return false; } + + // Velocity + Interpolation iVelocity( + cPhysics, + "Velocity", + cPhysics["Velocity"], + e.Component["Velocity"] + ); + m_InterpolateVelocity.erase(e.Entity); + m_InterpolateVelocity.insert(std::make_pair(e.Entity, iVelocity)); } return true; From d83190290fa6b7f1bbc5c7152544eaa783c10d25 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Tue, 9 Feb 2016 19:37:42 +0100 Subject: [PATCH 145/355] Server now broadcasts certain input commands to all other clients (for stuff like shooting) --- include/Engine/Network/Server.h | 2 ++ include/Game/Systems/WeaponSystem.h | 8 +------- src/Engine/Network/Client.cpp | 16 ++++++++++++++++ src/Engine/Network/Server.cpp | 18 ++++++++++++++++++ src/Game/Game.cpp | 5 +++++ src/Game/Systems/WeaponSystem.cpp | 21 ++++++--------------- 6 files changed, 48 insertions(+), 22 deletions(-) diff --git a/include/Engine/Network/Server.h b/include/Engine/Network/Server.h index e0ef9fcf..f16c6c16 100644 --- a/include/Engine/Network/Server.h +++ b/include/Engine/Network/Server.h @@ -48,6 +48,7 @@ private: float snapshotInterval; int checkTimeOutInterval = 100; int m_NextPlayerID = 0; + std::vector m_InputCommandsToBroadcast; //Timers std::clock_t m_StartPingTime; @@ -64,6 +65,7 @@ private: void broadcast(Packet& packet); void sendSnapshot(); void addChildrenToPacket(Packet& packet, EntityID entityID); + void addInputCommandsToPacket(Packet& packet); void sendPing(); void checkForTimeOuts(); void disconnect(PlayerID playerID); diff --git a/include/Game/Systems/WeaponSystem.h b/include/Game/Systems/WeaponSystem.h index 59048ee0..d6525377 100644 --- a/include/Game/Systems/WeaponSystem.h +++ b/include/Game/Systems/WeaponSystem.h @@ -9,7 +9,6 @@ #include "Core/System.h" #include "Core/EPlayerDamage.h" #include "Core/EShoot.h" -#include "Core/EPlayerSpawned.h" #include "Input/EInputCommand.h" #include "Core/EntityFile.h" #include "Core/EntityFileParser.h" @@ -28,16 +27,11 @@ public: private: IRenderer* m_Renderer; - // State - EntityWrapper m_LocalPlayer = EntityWrapper::Invalid; - // Events - EventRelay m_EPlayerSpawned; - bool WeaponSystem::OnPlayerSpawned(const Events::PlayerSpawned& e); EventRelay m_EShoot; bool WeaponSystem::OnShoot(Events::Shoot& e); EventRelay m_EInputCommand; - bool WeaponSystem::OnInputCommand(const Events::InputCommand& e); + bool WeaponSystem::OnInputCommand(Events::InputCommand& e); }; #endif \ No newline at end of file diff --git a/src/Engine/Network/Client.cpp b/src/Engine/Network/Client.cpp index b3fa227a..7d2c8f92 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -230,6 +230,18 @@ void Client::ignoreFields(Packet& packet, const ComponentInfo& componentInfo) void Client::parseSnapshot(Packet& packet) { + // Read input commands + std::size_t numInputCommands = packet.ReadPrimitive(); + for (std::size_t i = 0; i < numInputCommands; ++i) { + Events::InputCommand e; + e.PlayerID = packet.ReadPrimitive(); + e.Player = EntityWrapper(m_World, m_ServerIDToClientID.at(packet.ReadPrimitive())); + e.Command = packet.ReadString(); + e.Value = packet.ReadPrimitive(); + m_EventBroker->Publish(e); + } + + // Read world state while (packet.DataReadSize() < packet.Size()) { EntityID serverEntityID = packet.ReadPrimitive(); EntityID serverParentID = packet.ReadPrimitive(); @@ -339,6 +351,10 @@ void Client::disconnect() bool Client::OnInputCommand(const Events::InputCommand & e) { + if (e.PlayerID != -1) { + return false; + } + if (e.Command == "ConnectToServer") { // Connect for now if (e.Value > 0) { connect(); diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index b0003539..7ad1cc76 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -165,10 +165,24 @@ void Server::broadcast(Packet& packet) void Server::sendSnapshot() { Packet packet(MessageType::Snapshot); + addInputCommandsToPacket(packet); addChildrenToPacket(packet, EntityID_Invalid); broadcast(packet); } +void Server::addInputCommandsToPacket(Packet& packet) +{ + // Number of input commands + packet.WritePrimitive(m_InputCommandsToBroadcast.size()); + for (auto& command : m_InputCommandsToBroadcast) { + packet.WritePrimitive(command.PlayerID); + packet.WritePrimitive(m_ConnectedPlayers.at(command.PlayerID).EntityID); + packet.WriteString(command.Command); + packet.WritePrimitive(command.Value); + } + m_InputCommandsToBroadcast.clear(); +} + void Server::addChildrenToPacket(Packet & packet, EntityID entityID) { auto itPair = m_World->GetChildren(entityID); @@ -273,6 +287,10 @@ void Server::parseOnInputCommand(Packet& packet) e.Player = EntityWrapper(m_World, m_ConnectedPlayers.at(player).EntityID); e.Value = packet.ReadPrimitive(); m_EventBroker->Publish(e); + + if (e.Command == "PrimaryFire") { + m_InputCommandsToBroadcast.push_back(e); + } //LOG_INFO("Server::parseOnInputCommand: Command is %s. Value is %f. PlayerID is %i.", e.Command.c_str(), e.Value, e.PlayerID); } } diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index 38468e47..ce782ece 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -218,5 +218,10 @@ int Game::parseArgs(int argc, char* argv[]) m_IsClient = true; } + // HACK: Right now, client and server are mutually exclusive + if (m_IsServer) { + m_IsClient = false; + } + return 0; } diff --git a/src/Game/Systems/WeaponSystem.cpp b/src/Game/Systems/WeaponSystem.cpp index 22cd173a..a650a6b7 100644 --- a/src/Game/Systems/WeaponSystem.cpp +++ b/src/Game/Systems/WeaponSystem.cpp @@ -5,7 +5,6 @@ WeaponSystem::WeaponSystem(SystemParams params, IRenderer* renderer) , ImpureSystem() , m_Renderer(renderer) { - EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &WeaponSystem::OnPlayerSpawned); EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &WeaponSystem::OnInputCommand); EVENT_SUBSCRIBE_MEMBER(m_EShoot, &WeaponSystem::OnShoot); } @@ -15,30 +14,22 @@ void WeaponSystem::Update(double dt) } -bool WeaponSystem::OnPlayerSpawned(const Events::PlayerSpawned& e) -{ - if (e.PlayerID == -1) { - m_LocalPlayer = e.Player; - } - return true; -} - -bool WeaponSystem::OnInputCommand(const Events::InputCommand& e) +bool WeaponSystem::OnInputCommand(Events::InputCommand& e) { // Only shoot client-side! - if (e.PlayerID != -1) { + if (!IsClient) { return false; } // Only shoot if the player is alive - if (!m_LocalPlayer.Valid()) { + if (!e.Player.Valid()) { return false; } if (e.Command == "PrimaryFire" && e.Value > 0) { Events::Shoot eShoot; if (e.PlayerID == -1) { - eShoot.Player = m_LocalPlayer; + eShoot.Player = LocalPlayer; } else { eShoot.Player = e.Player; } @@ -97,8 +88,8 @@ bool WeaponSystem::OnShoot(Events::Shoot& eShoot) //(glm::vec3&)ray["Transform"]["Orientation"] = Transform::AbsoluteOrientationEuler(weapon); } - // Only run further picking code client-side! - if (eShoot.Player != m_LocalPlayer) { + // Only run further picking code for the local player! + if (eShoot.Player != LocalPlayer) { return false; } From 7212217460661fe31f8fe8d34f1b4db15fada3ae Mon Sep 17 00:00:00 2001 From: viktorljung Date: Tue, 9 Feb 2016 22:15:43 +0100 Subject: [PATCH 146/355] Added animation blending and offset animation component --- assets | 2 +- include/Engine/Rendering/ModelJob.h | 33 +- include/Engine/Rendering/Skeleton.h | 37 +- resources/Schema/Components.xsd | 1 + resources/Schema/Components/Animation.xml | 19 +- resources/Schema/Components/Animation.xsd | 19 +- .../Schema/Components/AnimationOffset.xml | 5 + .../Schema/Components/AnimationOffset.xsd | 17 + resources/Schema/Entities/AnimationTests2.xml | 358 ++----------- resources/Schema/Entities/Skeleton.xml | 497 ++++++++++++++++++ resources/Schema/Entities/joint.xml | 22 + src/Engine/Rendering/AnimationSystem.cpp | 94 +--- src/Engine/Rendering/BoneAttachmentSystem.cpp | 6 +- src/Engine/Rendering/DrawFinalPass.cpp | 18 +- src/Engine/Rendering/PickingPass.cpp | 8 +- src/Engine/Rendering/RawModelAssimp.cpp | 2 +- src/Engine/Rendering/Skeleton.cpp | 390 ++++++++++++-- src/Game/Systems/PlayerMovementSystem.cpp | 14 +- 18 files changed, 1091 insertions(+), 451 deletions(-) create mode 100644 resources/Schema/Components/AnimationOffset.xml create mode 100644 resources/Schema/Components/AnimationOffset.xsd create mode 100644 resources/Schema/Entities/Skeleton.xml create mode 100644 resources/Schema/Entities/joint.xml diff --git a/assets b/assets index c4898d82..ab1e1129 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit c4898d8281b5584d89b1caf14dab8e5fac120321 +Subproject commit ab1e11294f54a99993bb10004fac0501b6ac0b51 diff --git a/include/Engine/Rendering/ModelJob.h b/include/Engine/Rendering/ModelJob.h index 45c89e2d..87f27850 100644 --- a/include/Engine/Rendering/ModelJob.h +++ b/include/Engine/Rendering/ModelJob.h @@ -60,10 +60,30 @@ struct ModelJob : RenderJob Skeleton = Model->m_RawModel->m_Skeleton; - if (world->HasComponent(Entity, "Animation") && Skeleton != nullptr) { - auto animationComponent = world->GetComponent(Entity, "Animation"); - Animation = model->m_RawModel->m_Skeleton->GetAnimation(animationComponent["AnimationName"]); - AnimationTime = (double)animationComponent["Time"]; + if (Skeleton != nullptr) { + if (world->HasComponent(Entity, "Animation")) { + auto animationComponent = world->GetComponent(Entity, "Animation"); + + for (int i = 1; i <= 3; i++) { + ::Skeleton::AnimationData animationData; + animationData.animation = model->m_RawModel->m_Skeleton->GetAnimation(animationComponent["AnimationName" + std::to_string(i)]); + if (animationData.animation == nullptr) { + continue; + } + animationData.time = (double)animationComponent["Time" + std::to_string(i)]; + animationData.weight = (double)animationComponent["Weight" + std::to_string(i)]; + + Animations.push_back(animationData); + } + } + + if (world->HasComponent(Entity, "AnimationOffset")) { + auto animationOffsetComponent = world->GetComponent(Entity, "AnimationOffset"); + AnimationOffset.animation = model->m_RawModel->m_Skeleton->GetAnimation(animationOffsetComponent["AnimationName"]); + AnimationOffset.time = (double)animationOffsetComponent["Time"]; + } else { + AnimationOffset.animation = nullptr; + } } }; @@ -80,7 +100,10 @@ struct ModelJob : RenderJob glm::vec4 Color; const ::Model* Model = nullptr; ::Skeleton* Skeleton = nullptr; - const ::Skeleton::Animation* Animation = nullptr; + // const ::Skeleton::Animation* Animation = nullptr; + + std::vector<::Skeleton::AnimationData> Animations; + ::Skeleton::AnimationOffset AnimationOffset; float AnimationTime = 0.f; diff --git a/include/Engine/Rendering/Skeleton.h b/include/Engine/Rendering/Skeleton.h index 90e24578..21e38d6f 100644 --- a/include/Engine/Rendering/Skeleton.h +++ b/include/Engine/Rendering/Skeleton.h @@ -5,6 +5,7 @@ #include "Common.h" #include "../GLM.h" #include +#include //struct Bone //{ @@ -41,7 +42,6 @@ public: std::string Name; glm::mat4 OffsetMatrix; - glm::mat4 ModificationMatrix = glm::mat4(1); int ID; Bone* Parent; @@ -66,11 +66,27 @@ public: std::string Name; double Duration; std::map> JointAnimations; - - - }; + struct AnimationData + { + const Animation* animation; + float time; + float weight; + }; + + struct JointFrameTransform { + glm::vec3 PositionInterp = glm::vec3(0); + glm::quat RotationInterp = glm::quat(); + glm::vec3 ScaleInterp = glm::vec3(0); + float Weight; + }; + + struct AnimationOffset { + const Animation* animation; + float time; + }; + Skeleton() { } ~Skeleton(); @@ -85,19 +101,26 @@ public: int GetBoneID(std::string name); const Animation* GetAnimation(std::string name); - std::vector GetFrameBones(const Animation* animation, double time, bool noRootMotion = false); + std::vector GetFrameBones(std::vector animations, bool noRootMotion = false); + std::vector GetFrameBones(std::vector animations, AnimationOffset animationOffset, bool noRootMotion = false); + void AccumulateBoneTransforms(bool noRootMotion, const Animation* animation, float time, std::map& boneMatrices, const Bone* bone, glm::mat4 parentMatrix); + void AccumulateBoneTransforms(bool noRootMotion, std::vector animations, std::map& boneMatrices, const Bone* bone, glm::mat4 parentMatrix); + void AccumulateBoneTransforms(bool noRootMotion, std::vector animations, AnimationOffset animationOffset, std::map& boneMatrices, const Bone* bone, glm::mat4 parentMatrix); void PrintSkeleton(); void PrintSkeleton(const Bone* parent, int depthCount); std::map Animations; - glm::mat4 GetBoneTransform(const Bone* bone, const Animation* animation, float time, glm::mat4 parentMatrix); + glm::mat4 GetBoneTransform(const Bone* bone, const Animation* animation, float time, glm::mat4 childMatrix); int GetKeyframe(const Animation& animation, double time); private: - std::map m_BonesByName; + glm::mat4 GetOffsetTransform(const Bone* bone, AnimationOffset animationOffset); + + std::map m_BonesByName; + float aim = 0.f; }; #endif diff --git a/resources/Schema/Components.xsd b/resources/Schema/Components.xsd index 991d785d..bb5c3295 100644 --- a/resources/Schema/Components.xsd +++ b/resources/Schema/Components.xsd @@ -30,4 +30,5 @@ + \ No newline at end of file diff --git a/resources/Schema/Components/Animation.xml b/resources/Schema/Components/Animation.xml index ab589698..ae42009d 100644 --- a/resources/Schema/Components/Animation.xml +++ b/resources/Schema/Components/Animation.xml @@ -1,7 +1,18 @@ - - - 0 - true + + 1.0 + 0 + 0 + true + + 1.0 + 0 + 0 + true + + 1.0 + 0 + 0 + true \ No newline at end of file diff --git a/resources/Schema/Components/Animation.xsd b/resources/Schema/Components/Animation.xsd index 388dfc07..fd4a4c46 100644 --- a/resources/Schema/Components/Animation.xsd +++ b/resources/Schema/Components/Animation.xsd @@ -6,10 +6,21 @@ - - - - + + + + + + + + + + + + + + + diff --git a/resources/Schema/Components/AnimationOffset.xml b/resources/Schema/Components/AnimationOffset.xml new file mode 100644 index 00000000..4aef8219 --- /dev/null +++ b/resources/Schema/Components/AnimationOffset.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/resources/Schema/Components/AnimationOffset.xsd b/resources/Schema/Components/AnimationOffset.xsd new file mode 100644 index 00000000..c3430cc2 --- /dev/null +++ b/resources/Schema/Components/AnimationOffset.xsd @@ -0,0 +1,17 @@ + + + + + + + + Aim animation offset for the skeleton + + + + + + + + + \ No newline at end of file diff --git a/resources/Schema/Entities/AnimationTests2.xml b/resources/Schema/Entities/AnimationTests2.xml index 21a899f5..adb38d8d 100644 --- a/resources/Schema/Entities/AnimationTests2.xml +++ b/resources/Schema/Entities/AnimationTests2.xml @@ -8,331 +8,87 @@ - - Models/Core/UnitPlane.mesh - - - - - - - - - - - - Models/DirectionalLightWidget.mesh - - - - - - - - - - - - Wave - - 0.099999986588954926 - - - Models/finaltest.mesh - - - + - + - - R_Leg_Bottom - - + - Models/Core/UnitCube.mesh - + Models/DirectionalLightWidget.mesh - - + + - + - - R_Foot - - + + Run + 0.5 + 0.052207647453917483 + 1 + 1 + Strafe Right + 0.5 + 0.90342197388335332 + Reload Switch + 0.11766622175243757 + 1 + + + Aim + - Models/Core/UnitCube.mesh - + Models/AssaultAnims.mesh + + true - - + + + + + + + + R_Arm_Weapon_Joint + + + Models/WepTest.mesh + + + + + + + + + + + + + + 10 + + + - + - - L_Foot - - - Models/Core/UnitCube.mesh - + Models/Core/UnitPlane.mesh - - - - - - - - - - L_Leg_Bottom - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - L_Leg_Top - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - Hip - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - Spine_1 - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - Spine_2 - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - Spine_3 - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - Neck - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - R_Shoulder - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - R_Arm - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - R_Elbow - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - R_Hand - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - Chin - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - - - Run - - 0.099999986588954926 - - - Models/Supertest2.mesh - - - - - - - - - - R_Leg_Top - - - - - Models/Core/UnitCube.mesh - - - - - - + diff --git a/resources/Schema/Entities/Skeleton.xml b/resources/Schema/Entities/Skeleton.xml new file mode 100644 index 00000000..b8deb2eb --- /dev/null +++ b/resources/Schema/Entities/Skeleton.xml @@ -0,0 +1,497 @@ + + + + + + + + + + + + R_Arm_Weapon_Joint + + + + Models/Core/UnitCube.mesh + + true + + + + + + + + + + + + + R_Hand + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Arm + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Shoulder + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Neck + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Spine_3 + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Spine_2 + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Spine_1 + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Hip + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + L_Leg_Top + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + L_Leg_Bottom + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + L_Foot + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + L_Toe + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + L_Shoulder + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + L_Arm + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + L_Hand + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + L_Shoulder_Armor_Joint + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Chin + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Head + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Perietal + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + L_Elbow + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Leg_Bottom + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Elbow + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Leg_Top + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Foot + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Toe + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Shoulder_Armor_Joint + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/joint.xml b/resources/Schema/Entities/joint.xml new file mode 100644 index 00000000..912693f3 --- /dev/null +++ b/resources/Schema/Entities/joint.xml @@ -0,0 +1,22 @@ + + + + + + L_Elbow + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + diff --git a/src/Engine/Rendering/AnimationSystem.cpp b/src/Engine/Rendering/AnimationSystem.cpp index ef035dca..4566410f 100644 --- a/src/Engine/Rendering/AnimationSystem.cpp +++ b/src/Engine/Rendering/AnimationSystem.cpp @@ -19,83 +19,35 @@ void AnimationSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& a if(skeleton == nullptr) { return; } -/* - ImGui::SliderFloat("Angle", &angle, -100.f, 100.f); - { - int id = skeleton->GetBoneID("Spine_3"); - auto it = skeleton->Bones.find(id); - if (it != skeleton->Bones.end()) { - it->second->ModificationMatrix = glm::mat4(glm::quat(glm::vec3(glm::radians(angle), 0.f, 0.f))); + for (int i = 1; i <= 3; i++) { + const Skeleton::Animation* animation = skeleton->GetAnimation(animationComponent["AnimationName" + std::to_string(i)]); + + if (animation == nullptr) { + return; } - } -*/ + + double animationSpeed = (double)animationComponent["Speed" + std::to_string(i)]; + + if (animationSpeed != 0.0) { + double nextTime = (double)animationComponent["Time" + std::to_string(i)] + animationSpeed * dt; - const Skeleton::Animation* animation = skeleton->GetAnimation(animationComponent["AnimationName"]); - - if (animation == nullptr) { - return; - } - - double animationSpeed = (double)animationComponent["Speed"]; - - if (animationSpeed != 0.0) { - double nextTime = (double)animationComponent["Time"] + animationSpeed * dt; - - - if (!(bool)animationComponent["Loop"] && glm::abs(nextTime) > animation->Duration) { - (double&)animationComponent["Time"] = glm::sign(nextTime) * animation->Duration; - (double&)animationComponent["Speed"] = 0.0; - Events::AnimationComplete e; - e.Entity = entity; - e.Name = (std::string)animationComponent["AnimationName"]; - m_EventBroker->Publish(e); - } else { - if (glm::abs(nextTime) > animation->Duration) { - (double&)animationComponent["Time"] = glm::abs(nextTime) - animation->Duration; + if (!(bool)animationComponent["Loop" + std::to_string(i)] && glm::abs(nextTime) > animation->Duration) { + (double&)animationComponent["Time" + std::to_string(i)] = glm::sign(nextTime) * animation->Duration; + (double&)animationComponent["Speed" + std::to_string(i)] = 0.0; + Events::AnimationComplete e; + e.Entity = entity; + e.Name = (std::string)animationComponent["AnimationName" + std::to_string(i)]; + m_EventBroker->Publish(e); } else { - (double&)animationComponent["Time"] = nextTime; + if (glm::abs(nextTime) > animation->Duration) { + (double&)animationComponent["Time" + std::to_string(i)] = glm::abs(nextTime) - animation->Duration; + } else { + (double&)animationComponent["Time" + std::to_string(i)] = nextTime; + } } } - } - - - - - - - /* { - int id = skeleton->GetBoneID("Spine_2"); - auto it = skeleton->Bones.find(id); - if (it != skeleton->Bones.end()) { - it->second->ModificationMatrix = glm::mat4(glm::quat(glm::vec3(glm::radians(angle/4.f), 0.f, 0.f))); - } - } - { - int id = skeleton->GetBoneID("R_Shoulder"); - auto it = skeleton->Bones.find(id); - if (it != skeleton->Bones.end()) { - it->second->ModificationMatrix = glm::mat4(glm::quat(glm::vec3(glm::radians(angle/2.f), 0.f, 0.f))); - } - } - { - int id = skeleton->GetBoneID("L_Shoulder"); - auto it = skeleton->Bones.find(id); - if (it != skeleton->Bones.end()) { - it->second->ModificationMatrix = glm::mat4(glm::quat(glm::vec3(glm::radians(angle/2.f), 0.f, 0.f))); - } - }*/ - -/* - if (entity.HasComponent("Player")) { - EntityWrapper cameraEntity = entity.FirstChildByName("Camera"); - if (cameraEntity.Valid()) { - glm::vec3& cameraOrientation = cameraEntity["Transform"]["Orientation"]; - - - } - }*/ - + } } diff --git a/src/Engine/Rendering/BoneAttachmentSystem.cpp b/src/Engine/Rendering/BoneAttachmentSystem.cpp index f172d0ab..c74ec9cd 100644 --- a/src/Engine/Rendering/BoneAttachmentSystem.cpp +++ b/src/Engine/Rendering/BoneAttachmentSystem.cpp @@ -21,7 +21,7 @@ void BoneAttachmentSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapp Skeleton* skeleton = model->m_RawModel->m_Skeleton; - const Skeleton::Animation* animation = skeleton->GetAnimation(parent["Animation"]["AnimationName"]); + const Skeleton::Animation* animation = skeleton->GetAnimation(parent["Animation"]["AnimationName1"]); if (!animation) { return; @@ -34,9 +34,7 @@ void BoneAttachmentSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapp } - glm::mat4 boneTransform = skeleton->GetBoneTransform(skeleton->Bones[id], animation, (double)parent["Animation"]["Time"], glm::mat4(1)); - - + glm::mat4 boneTransform = skeleton->GetBoneTransform(skeleton->Bones[id], animation, (double)parent["Animation"]["Time1"], glm::mat4(1)); glm::vec3 scale; glm::quat rotation; diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index 005249ed..4da18f4a 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -127,14 +127,13 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& //Bind uniforms BindExplosionUniforms(explosionHandle, explosionEffectJob, scene); - if (explosionEffectJob->Model->m_RawModel->m_Skeleton != nullptr) { + if (explosionEffectJob->Skeleton != nullptr) { + std::vector frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations); + glUniformMatrix4fv(glGetUniformLocation(explosionHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - if (explosionEffectJob->Animation != nullptr) { - std::vector frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animation, explosionEffectJob->AnimationTime); - glUniformMatrix4fv(glGetUniformLocation(explosionHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - } } + //bind textures BindExplosionTextures(explosionEffectJob); //draw @@ -154,8 +153,13 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& //bind textures BindModelTextures(modelJob); - if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { - std::vector frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animation, modelJob->AnimationTime); + if (modelJob->Skeleton != nullptr) { + std::vector frameBones; + if(modelJob->AnimationOffset.animation != nullptr) { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); + } else { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); + } glUniformMatrix4fv(glGetUniformLocation(forwardHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); } diff --git a/src/Engine/Rendering/PickingPass.cpp b/src/Engine/Rendering/PickingPass.cpp index 58723a43..aa655951 100644 --- a/src/Engine/Rendering/PickingPass.cpp +++ b/src/Engine/Rendering/PickingPass.cpp @@ -89,7 +89,7 @@ void PickingPass::Draw(RenderScene& scene) glUniform2fv(glGetUniformLocation(shaderHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1]))); if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { - std::vector frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animation, modelJob->AnimationTime); + std::vector frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); } @@ -132,11 +132,9 @@ void PickingPass::Draw(RenderScene& scene) glUniform2fv(glGetUniformLocation(shaderHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1]))); if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { + std::vector frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - if (modelJob->Animation != nullptr) { - std::vector frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animation, modelJob->AnimationTime); - glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - } } glBindVertexArray(modelJob->Model->VAO); diff --git a/src/Engine/Rendering/RawModelAssimp.cpp b/src/Engine/Rendering/RawModelAssimp.cpp index 7bf72a22..6b970f70 100644 --- a/src/Engine/Rendering/RawModelAssimp.cpp +++ b/src/Engine/Rendering/RawModelAssimp.cpp @@ -271,7 +271,7 @@ RawModelAssimp::RawModelAssimp(std::string fileName) skelAnim.Keyframes.push_back(animationFrame); } - m_Skeleton->Animations[animationName] = skelAnim; + m_Skeleton->Animations[animationName1] = skelAnim; } } diff --git a/src/Engine/Rendering/Skeleton.cpp b/src/Engine/Rendering/Skeleton.cpp index d857fa5d..7f2f752f 100644 --- a/src/Engine/Rendering/Skeleton.cpp +++ b/src/Engine/Rendering/Skeleton.cpp @@ -39,36 +39,46 @@ const Skeleton::Animation* Skeleton::GetAnimation(std::string name) } } -std::vector Skeleton::GetFrameBones(const Animation* animation, double time, bool noRootMotion /*= false*/) +std::vector Skeleton::GetFrameBones(std::vector animations, bool noRootMotion /*= false*/) { - if(animation == nullptr) { + if (animations.size() <= 0) { std::vector finalMatrices; - for(auto& b : Bones) { - finalMatrices.push_back(b.second->ModificationMatrix);//b.second->OffsetMatrix); + for (auto& b : Bones) { + finalMatrices.push_back(glm::mat4(1));//b.second->OffsetMatrix); + } + return finalMatrices; + } + + std::map frameBones; + AccumulateBoneTransforms(true, animations, frameBones, RootBone, glm::mat4(1)); + + std::vector finalMatrices; + for (auto &kv : frameBones) { + finalMatrices.push_back(kv.second); + } + return finalMatrices; +} + + +std::vector Skeleton::GetFrameBones(std::vector animations, AnimationOffset animationOffset, bool noRootMotion /*= false*/) +{ + if (animations.size() <= 0 || animationOffset.animation == nullptr) { + std::vector finalMatrices; + for (auto& b : Bones) { + finalMatrices.push_back(glm::mat4(1));//b.second->OffsetMatrix); } return finalMatrices; } - // HACK: Animation wrap-around + std::map frameBones; + AccumulateBoneTransforms(true, animations, animationOffset, frameBones, RootBone, glm::mat4(1)); - while (time < 0) { - time += animation->Duration; - } - while (time > animation->Duration) { - time -= animation->Duration; - } - - //auto animationFrame = Animations[""].Keyframes[frame]; - std::map frameBones; - AccumulateBoneTransforms(true, animation, time, frameBones, RootBone, glm::mat4(1)); - //AccumulateBoneTransforms(noRootMotion, currentFrame, nextFrame, alpha, frameBones, RootBone, glm::mat4(1)); - - std::vector finalMatrices; - for (auto &kv : frameBones) { - finalMatrices.push_back(kv.second); - } - return finalMatrices; + std::vector finalMatrices; + for (auto &kv : frameBones) { + finalMatrices.push_back(kv.second); + } + return finalMatrices; } void Skeleton::AccumulateBoneTransforms(bool noRootMotion, const Animation* animation, float time, std::map& boneMatrices, const Bone* bone, glm::mat4 parentMatrix) @@ -95,12 +105,13 @@ void Skeleton::AccumulateBoneTransforms(bool noRootMotion, const Animation* anim if(nextFrame.Index == 0) { progress = (time - currentFrame.Time) / (animation->Duration - currentFrame.Time); } else { - progress = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); // fix loopinguuuu + progress = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); } - if(progress > 1.0f || progress < 0.0f) { + if (progress > 1.0f || progress < 0.0f) { + LOG_INFO("Progress: %f", progress); progress = glm::clamp(progress, 0.0f, 1.0f); } Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties; @@ -116,12 +127,12 @@ void Skeleton::AccumulateBoneTransforms(bool noRootMotion, const Animation* anim positionInterp.z = 0; } - boneMatrix = parentMatrix * (glm::translate(positionInterp) * glm::toMat4(rotationInterp) * glm::scale(scaleInterp)); + boneMatrix = parentMatrix *(glm::translate(positionInterp) * glm::toMat4(rotationInterp) * glm::scale(scaleInterp)); boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix; } else { // 1 keyframes for the current bone currentFrame = boneKeyFrames.at(0); - boneMatrix = parentMatrix * (glm::translate(currentFrame.BoneProperties.Position) * glm::toMat4(currentFrame.BoneProperties.Rotation) * glm::scale(currentFrame.BoneProperties.Scale)); + boneMatrix = parentMatrix *(glm::translate(currentFrame.BoneProperties.Position) * glm::toMat4(currentFrame.BoneProperties.Rotation) * glm::scale(currentFrame.BoneProperties.Scale)); boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix; } @@ -143,7 +154,320 @@ void Skeleton::AccumulateBoneTransforms(bool noRootMotion, const Animation* anim } } -glm::mat4 Skeleton::GetBoneTransform(const Bone* bone, const Animation* animation, float time, glm::mat4 parentMatrix) +void Skeleton::AccumulateBoneTransforms(bool noRootMotion, std::vector animations, std::map& boneMatrices, const Bone* bone, glm::mat4 parentMatrix) +{ + glm::mat4 boneMatrix; + + + + std::vector JointTransforms; + + for (const AnimationData animationData : animations) { + const Animation* animation = animationData.animation; + const float time = animationData.time; + + JointFrameTransform jointTransform; + jointTransform.Weight = animationData.weight;; + + if (animation->JointAnimations.find(bone->ID) != animation->JointAnimations.end()) { + std::vector boneKeyFrames = animation->JointAnimations.at(bone->ID); + + Animation::Keyframe currentFrame; + Animation::Keyframe nextFrame; + + if (boneKeyFrames.size() > 1) { // 2+ keyframes for the current bone + for (int index = boneKeyFrames.size()-1; index >= 0; index--) { // find the bone keyframes that surrounds the current frame + if (time >= boneKeyFrames.at(index).Time) { + currentFrame = boneKeyFrames.at(index); + nextFrame = boneKeyFrames.at((index + 1) % boneKeyFrames.size()); + break; + } + } + + float progress; + + if (nextFrame.Index == 0) { + progress = (time - currentFrame.Time) / (animation->Duration - currentFrame.Time); + } else { + progress = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); + + } + + + if (progress > 1.0f || progress < 0.0f) { + LOG_INFO("Progress: %f", progress); + progress = glm::clamp(progress, 0.0f, 1.0f); + } + Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties; + Animation::Keyframe::BoneProperty nextBoneProperty = nextFrame.BoneProperties; + + jointTransform.PositionInterp = currentBoneProperty.Position * (1.f - progress) + nextBoneProperty.Position * progress; + jointTransform.RotationInterp = glm::slerp(currentBoneProperty.Rotation, nextBoneProperty.Rotation, progress); + jointTransform.ScaleInterp = currentBoneProperty.Scale * (1.f - progress) + nextBoneProperty.Scale * progress; + + // Flag for no root motion + if (bone == RootBone && noRootMotion) { + jointTransform.PositionInterp.x = 0; + jointTransform.PositionInterp.z = 0; + } + + JointTransforms.push_back(jointTransform); + + } else { // 1 keyframes for the current bone + currentFrame = boneKeyFrames.at(0); + jointTransform.PositionInterp = currentFrame.BoneProperties.Position; + jointTransform.RotationInterp = currentFrame.BoneProperties.Rotation; + jointTransform.ScaleInterp = currentFrame.BoneProperties.Scale; + JointTransforms.push_back(jointTransform); + + } + } else { // 0 keyframes for the current bone + + } + + } + + if(JointTransforms.size() <= 0) { + if (bone->Parent) { + boneMatrix = parentMatrix * glm::inverse(bone->OffsetMatrix) * bone->Parent->OffsetMatrix; + boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix; + } else { + boneMatrix = glm::inverse(bone->OffsetMatrix); + boneMatrices[bone->ID] = parentMatrix; + } + } else if (JointTransforms.size() == 1) { + boneMatrix = parentMatrix *(glm::translate(JointTransforms.at(0).PositionInterp) * glm::toMat4(JointTransforms.at(0).RotationInterp) * glm::scale(JointTransforms.at(0).ScaleInterp)); + boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix; + } else { + + glm::vec3 finalPosInterp; + glm::quat finalRotInterp; + glm::vec3 finalScaleInterp; + float totalWeight = 0; + + for (JointFrameTransform jointTransform : JointTransforms) { + totalWeight += jointTransform.Weight; + } + + + for (JointFrameTransform jointTransform : JointTransforms) + { + if(jointTransform.Weight == 1.0f) { + finalPosInterp = jointTransform.PositionInterp; + finalRotInterp = jointTransform.RotationInterp; + finalScaleInterp = jointTransform.ScaleInterp; + break; + } else { + finalPosInterp += jointTransform.PositionInterp * (jointTransform.Weight/totalWeight); + finalRotInterp *= glm::slerp(glm::quat(), jointTransform.RotationInterp, (jointTransform.Weight/totalWeight)); + finalScaleInterp += jointTransform.ScaleInterp * (jointTransform.Weight/totalWeight); + } + + } + + boneMatrix = parentMatrix *(glm::translate(finalPosInterp) * glm::toMat4(finalRotInterp) * glm::scale(finalScaleInterp)); + boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix; + } + + + + for (auto &child : bone->Children) { + AccumulateBoneTransforms(noRootMotion, animations, boneMatrices, child, boneMatrix); + } +} + + +void Skeleton::AccumulateBoneTransforms(bool noRootMotion, std::vector animations, AnimationOffset animationOffset, std::map& boneMatrices, const Bone* bone, glm::mat4 parentMatrix) +{ + glm::mat4 boneMatrix; + + + + std::vector JointTransforms; + + for (const AnimationData animationData : animations) { + const Animation* animation = animationData.animation; + const float time = animationData.time; + + JointFrameTransform jointTransform; + jointTransform.Weight = animationData.weight;; + + if (animation->JointAnimations.find(bone->ID) != animation->JointAnimations.end()) { + std::vector boneKeyFrames = animation->JointAnimations.at(bone->ID); + + Animation::Keyframe currentFrame; + Animation::Keyframe nextFrame; + + if (boneKeyFrames.size() > 1) { // 2+ keyframes for the current bone + for (int index = boneKeyFrames.size()-1; index >= 0; index--) { // find the bone keyframes that surrounds the current frame + if (time >= boneKeyFrames.at(index).Time) { + currentFrame = boneKeyFrames.at(index); + nextFrame = boneKeyFrames.at((index + 1) % boneKeyFrames.size()); + break; + } + } + + float progress; + + if (nextFrame.Index == 0) { + progress = (time - currentFrame.Time) / (animation->Duration - currentFrame.Time); + } else { + progress = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); + + } + + + if (progress > 1.0f || progress < 0.0f) { + LOG_INFO("Progress: %f", progress); + progress = glm::clamp(progress, 0.0f, 1.0f); + } + Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties; + Animation::Keyframe::BoneProperty nextBoneProperty = nextFrame.BoneProperties; + + jointTransform.PositionInterp = currentBoneProperty.Position * (1.f - progress) + nextBoneProperty.Position * progress; + jointTransform.RotationInterp = glm::slerp(currentBoneProperty.Rotation, nextBoneProperty.Rotation, progress); + jointTransform.ScaleInterp = currentBoneProperty.Scale * (1.f - progress) + nextBoneProperty.Scale * progress; + + // Flag for no root motion + if (bone == RootBone && noRootMotion) { + jointTransform.PositionInterp.x = 0; + jointTransform.PositionInterp.z = 0; + } + + JointTransforms.push_back(jointTransform); + + } else { // 1 keyframes for the current bone + currentFrame = boneKeyFrames.at(0); + jointTransform.PositionInterp = currentFrame.BoneProperties.Position; + jointTransform.RotationInterp = currentFrame.BoneProperties.Rotation; + jointTransform.ScaleInterp = currentFrame.BoneProperties.Scale; + JointTransforms.push_back(jointTransform); + + } + } else { // 0 keyframes for the current bone + + } + + } + + + glm::mat4 offset = GetOffsetTransform(bone, animationOffset); + + if (JointTransforms.size() == 0) { + if (bone->Parent) { + if (offset != glm::mat4(1)) { + boneMatrix = parentMatrix * offset;// *((glm::inverse(bone->OffsetMatrix) * bone->Parent->OffsetMatrix)); + } else { + boneMatrix = parentMatrix *((glm::inverse(bone->OffsetMatrix) * bone->Parent->OffsetMatrix)); + + } + boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix; + } else { + boneMatrix = offset * glm::inverse(bone->OffsetMatrix); + boneMatrices[bone->ID] = parentMatrix; + } + } else { + + glm::vec3 finalPosInterp; + glm::quat finalRotInterp; + glm::vec3 finalScaleInterp; + float totalWeight = 0; + + for (JointFrameTransform jointTransform : JointTransforms) { + totalWeight += jointTransform.Weight; + } + + + for (JointFrameTransform jointTransform : JointTransforms) { + if (jointTransform.Weight == 1.0f) { + finalPosInterp = jointTransform.PositionInterp; + finalRotInterp = jointTransform.RotationInterp; + finalScaleInterp = jointTransform.ScaleInterp; + break; + } else { + finalPosInterp += jointTransform.PositionInterp * (jointTransform.Weight/totalWeight); + finalRotInterp *= glm::slerp(glm::quat(), jointTransform.RotationInterp, (jointTransform.Weight/totalWeight)); + finalScaleInterp += jointTransform.ScaleInterp * (jointTransform.Weight/totalWeight); + } + + } + + + + if (offset != glm::mat4(1)) { + boneMatrix = parentMatrix * ((glm::translate(finalPosInterp) * glm::toMat4(finalRotInterp) * glm::scale(finalScaleInterp)) + offset); + } else { + boneMatrix = parentMatrix * (glm::translate(finalPosInterp) * glm::toMat4(finalRotInterp) * glm::scale(finalScaleInterp)); + } + + boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix; + } + + for (auto &child : bone->Children) { + AccumulateBoneTransforms(noRootMotion, animations, animationOffset, boneMatrices, child, boneMatrix); + } +} + + +glm::mat4 Skeleton::GetOffsetTransform(const Bone* bone, AnimationOffset animationOffset) +{ + const Animation* animation = animationOffset.animation; + float time = animationOffset.time; + + glm::vec3 position = glm::vec3(0); + glm::quat rotation = glm::quat(); + glm::vec3 scale = glm::vec3(1); + + if (animation->JointAnimations.find(bone->ID) != animation->JointAnimations.end()) { + std::vector boneKeyFrames = animation->JointAnimations.at(bone->ID); + + Animation::Keyframe currentFrame; + Animation::Keyframe nextFrame; + + if (boneKeyFrames.size() > 1) { // 2+ keyframes for the current bone + for (int index = boneKeyFrames.size()-1; index >= 0; index--) { // find the bone keyframes that surrounds the current frame + if (time >= boneKeyFrames.at(index).Time) { + currentFrame = boneKeyFrames.at(index); + nextFrame = boneKeyFrames.at((index + 1) % boneKeyFrames.size()); + break; + } + } + + float progress; + + if (nextFrame.Index == 0) { + progress = (time - currentFrame.Time) / (animation->Duration - currentFrame.Time); + } else { + progress = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); + + } + + + if (progress > 1.0f || progress < 0.0f) { + LOG_INFO("Progress: %f", progress); + progress = glm::clamp(progress, 0.0f, 1.0f); + } + Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties; + Animation::Keyframe::BoneProperty nextBoneProperty = nextFrame.BoneProperties; + + position = currentBoneProperty.Position * (1.f - progress) + nextBoneProperty.Position * progress; + rotation = glm::slerp(currentBoneProperty.Rotation, nextBoneProperty.Rotation, progress); + scale = currentBoneProperty.Scale * (1.f - progress) + nextBoneProperty.Scale * progress; + + + } else { // 1 keyframes for the current bone + currentFrame = boneKeyFrames.at(0); + position = currentFrame.BoneProperties.Position; + rotation = currentFrame.BoneProperties.Rotation; + scale = currentFrame.BoneProperties.Scale; + } + } + + return (glm::translate(position) * glm::toMat4(rotation) * glm::scale(scale)); +} + + +glm::mat4 Skeleton::GetBoneTransform(const Bone* bone, const Animation* animation, float time, glm::mat4 childMatrix) { glm::mat4 boneMatrix; @@ -167,8 +491,7 @@ glm::mat4 Skeleton::GetBoneTransform(const Bone* bone, const Animation* animatio if (nextFrame.Index == 0) { progress = (time - currentFrame.Time) / (animation->Duration - currentFrame.Time); } else { - progress = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); // fix loopinguuuu - + progress = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); } if (progress > 1.0f || progress < 0.0f) { @@ -182,20 +505,19 @@ glm::mat4 Skeleton::GetBoneTransform(const Bone* bone, const Animation* animatio glm::quat rotationInterp = glm::slerp(currentBoneProperty.Rotation, nextBoneProperty.Rotation, progress); glm::vec3 scaleInterp = currentBoneProperty.Scale * (1.f - progress) + nextBoneProperty.Scale * progress; - boneMatrix = parentMatrix * (glm::translate(positionInterp) * glm::toMat4(rotationInterp) * glm::scale(scaleInterp)); + boneMatrix = (glm::translate(positionInterp) * glm::toMat4(rotationInterp) * glm::scale(scaleInterp)) * childMatrix; } else { // 1 keyframes for the current bone currentFrame = boneKeyFrames.at(0); - boneMatrix = parentMatrix * (glm::translate(currentFrame.BoneProperties.Position) * glm::toMat4(currentFrame.BoneProperties.Rotation) * glm::scale(currentFrame.BoneProperties.Scale)); + boneMatrix = (glm::translate(currentFrame.BoneProperties.Position) * glm::toMat4(currentFrame.BoneProperties.Rotation) * glm::scale(currentFrame.BoneProperties.Scale)) * childMatrix; } } else { // 0 keyframes for the current bone if (bone->Parent) { - boneMatrix = glm::inverse(bone->OffsetMatrix) * bone->Parent->OffsetMatrix * parentMatrix; + boneMatrix = bone->Parent->OffsetMatrix * glm::inverse(bone->OffsetMatrix) * childMatrix; } else { - boneMatrix = parentMatrix * glm::inverse(bone->OffsetMatrix); + boneMatrix = glm::inverse(bone->OffsetMatrix) * childMatrix; } - } if (bone->Parent) { diff --git a/src/Game/Systems/PlayerMovementSystem.cpp b/src/Game/Systems/PlayerMovementSystem.cpp index 36dbcbd0..791350f6 100644 --- a/src/Game/Systems/PlayerMovementSystem.cpp +++ b/src/Game/Systems/PlayerMovementSystem.cpp @@ -97,19 +97,19 @@ void PlayerMovementSystem::Update(double dt) float movementLength = glm::length(groundVelocity); if (glm::length(controller->Movement()) > 0.f) { if (controller->Crouching()) { - cAnimation["AnimationName"] = "Crouch Walk"; - (double&)cAnimation["Speed"] = 1.f * -glm::sign(controller->Movement().z); + cAnimation["AnimationName1"] = "Crouch Walk"; + (double&)cAnimation["Speed1"] = 1.f * -glm::sign(controller->Movement().z); } else { - cAnimation["AnimationName"] = "Run"; - (double&)cAnimation["Speed"] = 2.f * -glm::sign(controller->Movement().z); + cAnimation["AnimationName1"] = "Run"; + (double&)cAnimation["Speed1"] = 2.f * -glm::sign(controller->Movement().z); } } else { if (controller->Crouching()) { - cAnimation["AnimationName"] = "Crouch"; + cAnimation["AnimationName1"] = "Crouch"; (double&)cAnimation["Speed"] = 1.f; } else { - cAnimation["AnimationName"] = "Hold Pos"; - (double&)cAnimation["Speed"] = 1.f; + cAnimation["AnimationName1"] = "Hold Pos"; + (double&)cAnimation["Speed1"] = 1.f; } } } From 3c22dcc1659f42505680faaeb7ada6102d8d075e Mon Sep 17 00:00:00 2001 From: viktorljung Date: Tue, 9 Feb 2016 22:34:09 +0100 Subject: [PATCH 147/355] changed assetbranch --- assets | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/assets b/assets index ab1e1129..c2847a65 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit ab1e11294f54a99993bb10004fac0501b6ac0b51 +Subproject commit c2847a658ef603cf5c0ee993c4133bdf9c879d1c From 001e2441dddd8d08d51daa511878669c6f858246 Mon Sep 17 00:00:00 2001 From: viktorljung Date: Tue, 9 Feb 2016 22:54:51 +0100 Subject: [PATCH 148/355] Mergefixes --- src/Engine/Rendering/DrawFinalPass.cpp | 40 +++++++++++++++----------- src/Engine/Rendering/PickingPass.cpp | 18 +++++++----- 2 files changed, 35 insertions(+), 23 deletions(-) diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index c97ab6b5..46a47e7e 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -204,10 +204,12 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& BindExplosionUniforms(explosionSkinnedHandle, explosionEffectJob, scene); //bind textures BindExplosionTextures(explosionSkinnedHandle, explosionEffectJob); - if (explosionEffectJob->Animation != nullptr) { - std::vector frameBones = explosionEffectJob->Skeleton->GetFrameBones(*explosionEffectJob->Animation, explosionEffectJob->AnimationTime); - glUniformMatrix4fv(glGetUniformLocation(forwardSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - } + std::vector frameBones; + if (explosionEffectJob->AnimationOffset.animation != nullptr) { + frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations, explosionEffectJob->AnimationOffset); + } else { + frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations); + } } else { m_ExplosionEffectProgram->Bind(); @@ -229,10 +231,12 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& //bind textures BindExplosionTextures(explosionSplatMapSkinnedHandle, explosionEffectJob); GLERROR("asdasd"); - if (explosionEffectJob->Animation != nullptr) { - std::vector frameBones = explosionEffectJob->Skeleton->GetFrameBones(*explosionEffectJob->Animation, explosionEffectJob->AnimationTime); - glUniformMatrix4fv(glGetUniformLocation(explosionSplatMapSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - } + std::vector frameBones; + if (explosionEffectJob->AnimationOffset.animation != nullptr) { + frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations, explosionEffectJob->AnimationOffset); + } else { + frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations); + } } else { m_ExplosionEffectSplatMapProgram->Bind(); @@ -271,10 +275,12 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& BindModelUniforms(forwardSkinnedHandle, modelJob, scene); //bind textures BindModelTextures(forwardSkinnedHandle, modelJob); - if (modelJob->Animation != nullptr) { - std::vector frameBones = modelJob->Skeleton->GetFrameBones(*modelJob->Animation, modelJob->AnimationTime); - glUniformMatrix4fv(glGetUniformLocation(forwardSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - } + std::vector frameBones; + if (modelJob->AnimationOffset.animation != nullptr) { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); + } else { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); + } } else { m_ForwardPlusProgram->Bind(); GLERROR("Bind ForwardPlusProgram"); @@ -295,10 +301,12 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& //bind textures BindModelTextures(forwardSplatMapSkinnedHandle, modelJob); GLERROR("asdasd"); - if (modelJob->Animation != nullptr) { - std::vector frameBones = modelJob->Skeleton->GetFrameBones(*modelJob->Animation, modelJob->AnimationTime); - glUniformMatrix4fv(glGetUniformLocation(forwardSplatMapSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - } + std::vector frameBones; + if (modelJob->AnimationOffset.animation != nullptr) { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); + } else { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); + } } else { m_ForwardPlusSplatMapProgram->Bind(); GLERROR("Bind SplatMap program"); diff --git a/src/Engine/Rendering/PickingPass.cpp b/src/Engine/Rendering/PickingPass.cpp index c445b8fd..9d911325 100644 --- a/src/Engine/Rendering/PickingPass.cpp +++ b/src/Engine/Rendering/PickingPass.cpp @@ -104,10 +104,12 @@ void PickingPass::Draw(RenderScene& scene) if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { - if (modelJob->Animation != nullptr) { - std::vector frameBones = modelJob->Skeleton->GetFrameBones(*modelJob->Animation, modelJob->AnimationTime); - glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - } + std::vector frameBones; + if (modelJob->AnimationOffset.animation != nullptr) { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); + } else { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); + } } } else { m_PickingProgram->Bind(); @@ -182,9 +184,11 @@ void PickingPass::Draw(RenderScene& scene) if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { - if (modelJob->Animation != nullptr) { - std::vector frameBones = modelJob->Skeleton->GetFrameBones(*modelJob->Animation, modelJob->AnimationTime); - glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + std::vector frameBones; + if (modelJob->AnimationOffset.animation != nullptr) { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); + } else { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); } } From daa96baab5ff799d329051a49b6acc7670e9d249 Mon Sep 17 00:00:00 2001 From: viktorljung Date: Tue, 9 Feb 2016 23:03:49 +0100 Subject: [PATCH 149/355] BoneAttachmentSystem fix for not having a skeleton --- src/Engine/Rendering/BoneAttachmentSystem.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/Engine/Rendering/BoneAttachmentSystem.cpp b/src/Engine/Rendering/BoneAttachmentSystem.cpp index c74ec9cd..bdc45fa6 100644 --- a/src/Engine/Rendering/BoneAttachmentSystem.cpp +++ b/src/Engine/Rendering/BoneAttachmentSystem.cpp @@ -21,6 +21,11 @@ void BoneAttachmentSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapp Skeleton* skeleton = model->m_RawModel->m_Skeleton; + + if(skeleton == nullptr) { + return; + } + const Skeleton::Animation* animation = skeleton->GetAnimation(parent["Animation"]["AnimationName1"]); if (!animation) { From 5cea3bed3a578c5fd6d56bc14cfae1527d966ec0 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Tue, 9 Feb 2016 23:27:04 +0100 Subject: [PATCH 150/355] Work in progress weapon system --- include/Game/Systems/WeaponSystem.h | 93 +++++++++++++++++-- resources/DefaultInput.ini | 2 + resources/Schema/Components.xsd | 1 + resources/Schema/Components/AssaultWeapon.xml | 8 ++ resources/Schema/Components/AssaultWeapon.xsd | 27 ++++++ resources/Schema/Types/Entity.xsd | 1 + src/Game/Systems/WeaponSystem.cpp | 40 +++++++- 7 files changed, 164 insertions(+), 8 deletions(-) create mode 100755 resources/Schema/Components/AssaultWeapon.xml create mode 100755 resources/Schema/Components/AssaultWeapon.xsd diff --git a/include/Game/Systems/WeaponSystem.h b/include/Game/Systems/WeaponSystem.h index d6525377..fccb1b0b 100644 --- a/include/Game/Systems/WeaponSystem.h +++ b/include/Game/Systems/WeaponSystem.h @@ -9,29 +9,108 @@ #include "Core/System.h" #include "Core/EPlayerDamage.h" #include "Core/EShoot.h" +#include "Core/EPlayerSpawned.h" #include "Input/EInputCommand.h" #include "Core/EntityFile.h" #include "Core/EntityFileParser.h" -#include -#include - - -class WeaponSystem : public ImpureSystem +class WeaponSystem : public PureSystem, ImpureSystem { public: WeaponSystem(SystemParams params, IRenderer* renderer); virtual void Update(double dt) override; + virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& cComponent, double dt) override; private: IRenderer* m_Renderer; + std::unordered_map> m_ActiveWeapons; + // Events + EventRelay m_EPlayerSpawned; + bool OnPlayerSpawned(Events::PlayerSpawned& e); EventRelay m_EShoot; - bool WeaponSystem::OnShoot(Events::Shoot& e); + bool OnShoot(Events::Shoot& e); EventRelay m_EInputCommand; - bool WeaponSystem::OnInputCommand(Events::InputCommand& e); + bool OnInputCommand(Events::InputCommand& e); + + void selectWeapon(EntityWrapper player, ComponentInfo::EnumType slot); +}; + +class WeaponBehaviour +{ +public: + WeaponBehaviour(EntityWrapper weaponEntity) + : m_Entity(weaponEntity) + { } + + virtual void Fire() = 0; + virtual void CeaseFire() { } + virtual void Reload() { } + virtual void Update(double dt) { } + +protected: + EntityWrapper m_Entity; +}; + +class AssaultWeaponBehaviour : public WeaponBehaviour +{ +public: + AssaultWeaponBehaviour(EntityWrapper weaponEntity) + : WeaponBehaviour(weaponEntity) + { } + + virtual void Fire() override + { + m_TimeSinceLastFire = 0.0; + m_Firing = true; + fireRound(); + } + + virtual void CeaseFire() override + { + m_Firing = false; + } + + virtual void Update(double dt) override + { + if (!m_Firing) { + return; + } + + m_TimeSinceLastFire += dt; + + ComponentWrapper& cAssaultWeapon = m_Entity["AssaultWeapon"]; + if (m_TimeSinceLastFire > (double)cAssaultWeapon["RPM"] / 60.0) { + fireRound(); + } + } + +private: + bool m_Firing = false; + double m_TimeSinceLastFire = 0.0; + ComponentWrapper m_Component; + + void fireRound() + { + ComponentWrapper& cAssaultWeapon = m_Entity["AssaultWeapon"]; + + int& magAmmo = cAssaultWeapon["MagazineAmmo"]; + int ammo = cAssaultWeapon["Ammo"]; + + // Reload if our magazine is empty and we have ammo to fill it with + if (magAmmo <= 0 && ammo > 0) { + CeaseFire(); + Reload(); + return; + } + + // Fire + magAmmo -= 1; + + m_TimeSinceLastFire = 0.0; + } }; #endif \ No newline at end of file diff --git a/resources/DefaultInput.ini b/resources/DefaultInput.ini index a3f7d166..167226de 100644 --- a/resources/DefaultInput.ini +++ b/resources/DefaultInput.ini @@ -14,6 +14,8 @@ R=Reload Space=Jump LeftControl=Crouch LeftShift=Sprint +1=SelectWeapon,1 +2=SelectWeapon,2 F1=ToggleEditor C=ConnectToServer N=SwitchToServer diff --git a/resources/Schema/Components.xsd b/resources/Schema/Components.xsd index 265a3cc5..1d5b05f6 100644 --- a/resources/Schema/Components.xsd +++ b/resources/Schema/Components.xsd @@ -31,4 +31,5 @@ + \ No newline at end of file diff --git a/resources/Schema/Components/AssaultWeapon.xml b/resources/Schema/Components/AssaultWeapon.xml new file mode 100755 index 00000000..8dc2a50a --- /dev/null +++ b/resources/Schema/Components/AssaultWeapon.xml @@ -0,0 +1,8 @@ + + + 32 + 32 + 360 + 360 + 40 + \ No newline at end of file diff --git a/resources/Schema/Components/AssaultWeapon.xsd b/resources/Schema/Components/AssaultWeapon.xsd new file mode 100755 index 00000000..167fee18 --- /dev/null +++ b/resources/Schema/Components/AssaultWeapon.xsd @@ -0,0 +1,27 @@ + + + + + + + + + + Ammo currently loaded into the magazine + + + Max number of rounds in a magazine + + + Current ammo carried + + + Maximum ammo able to be carried + + + Rate of fire in rounds per minute + + + + + diff --git a/resources/Schema/Types/Entity.xsd b/resources/Schema/Types/Entity.xsd index 028af9e6..3eed11f3 100644 --- a/resources/Schema/Types/Entity.xsd +++ b/resources/Schema/Types/Entity.xsd @@ -38,6 +38,7 @@ + diff --git a/src/Game/Systems/WeaponSystem.cpp b/src/Game/Systems/WeaponSystem.cpp index a650a6b7..fe0f066f 100644 --- a/src/Game/Systems/WeaponSystem.cpp +++ b/src/Game/Systems/WeaponSystem.cpp @@ -2,6 +2,7 @@ WeaponSystem::WeaponSystem(SystemParams params, IRenderer* renderer) : System(params) + , PureSystem("Player") , ImpureSystem() , m_Renderer(renderer) { @@ -14,8 +15,23 @@ void WeaponSystem::Update(double dt) } +void WeaponSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& cComponent, double dt) +{ + +} + bool WeaponSystem::OnInputCommand(Events::InputCommand& e) { + // Make sure player is alive + if (!e.Player.Valid()) { + return false; + } + + // Weapon selection + if (e.Command == "SelectWeapon") { + selectWeapon(e.Player, static_cast(e.Value)); + } + // Only shoot client-side! if (!IsClient) { return false; @@ -39,7 +55,29 @@ bool WeaponSystem::OnInputCommand(Events::InputCommand& e) return true; } -bool WeaponSystem::OnShoot(Events::Shoot& eShoot) +void WeaponSystem::selectWeapon(EntityWrapper player, ComponentInfo::EnumType slot) +{ + // Primary + if (slot == 1) { + // TODO: if class... + m_ActiveWeapons[player] = std::make_shared(); + } + + // Secondary + if (slot == 2) { + //m_ActiveWeapons[player] = std::make_shared(); + } +} + +bool WeaponSystem::OnPlayerSpawned(Events::PlayerSpawned& e) +{ + // Select primary weapon on player spawn + // TODO: Select the active one specified by player component + selectWeapon(e.Player, 1); + return true; +} + +bool WeaponSystem::OnShoot(Events::Shoot& eShoot) { if (!eShoot.Player.Valid()) { return false; From d65ce805a502f82b45e92e116148b794442ce6a8 Mon Sep 17 00:00:00 2001 From: William Moberg Date: Wed, 10 Feb 2016 10:53:25 +0100 Subject: [PATCH 151/355] FrustumOctree has its own system, won't cull away explosion effects. --- .../Collision/FillFrustumOctreeSystem.h | 25 +++++++++++++++++++ include/Engine/Collision/FillOctreeSystem.h | 4 +-- .../Collision/FillFrustumOctreeSystem.cpp | 21 ++++++++++++++++ src/Game/Game.cpp | 3 ++- 4 files changed, 50 insertions(+), 3 deletions(-) create mode 100644 include/Engine/Collision/FillFrustumOctreeSystem.h create mode 100644 src/Engine/Collision/FillFrustumOctreeSystem.cpp diff --git a/include/Engine/Collision/FillFrustumOctreeSystem.h b/include/Engine/Collision/FillFrustumOctreeSystem.h new file mode 100644 index 00000000..f7f1413c --- /dev/null +++ b/include/Engine/Collision/FillFrustumOctreeSystem.h @@ -0,0 +1,25 @@ +#ifndef FillFrustumOctreeSystem_h__ +#define FillFrustumOctreeSystem_h__ + +#include "../Core/System.h" +#include "../Core/Octree.h" +#include "Collision.h" +#include "EntityAABB.h" + +class FillFrustumOctreeSystem : public ImpureSystem, public PureSystem +{ +public: + FillFrustumOctreeSystem(World* world, EventBroker* eventBroker, Octree* octree) + : System(world, eventBroker) + , PureSystem("Model") + , m_Octree(octree) + { } + + virtual void Update(double dt) override; + virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) override; + +private: + Octree* m_Octree; +}; + +#endif \ No newline at end of file diff --git a/include/Engine/Collision/FillOctreeSystem.h b/include/Engine/Collision/FillOctreeSystem.h index 9fd87b94..3bacccac 100644 --- a/include/Engine/Collision/FillOctreeSystem.h +++ b/include/Engine/Collision/FillOctreeSystem.h @@ -1,5 +1,5 @@ -#ifndef CollidableOctreeSystem_h__ -#define CollidableOctreeSystem_h__ +#ifndef FillOctreeSystem_h__ +#define FillOctreeSystem_h__ #include "../Core/System.h" #include "../Core/Octree.h" diff --git a/src/Engine/Collision/FillFrustumOctreeSystem.cpp b/src/Engine/Collision/FillFrustumOctreeSystem.cpp new file mode 100644 index 00000000..f02a30f1 --- /dev/null +++ b/src/Engine/Collision/FillFrustumOctreeSystem.cpp @@ -0,0 +1,21 @@ +#include "Collision/FillFrustumOctreeSystem.h" + +void FillFrustumOctreeSystem::Update(double dt) +{ + m_Octree->ClearDynamicObjects(); +} + +void FillFrustumOctreeSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) +{ + if (entity.HasComponent("ExplosionEffect")) { + //TODO: Fix hack, get real box by using shader equation. + EntityAABB aabb = AABB(glm::vec3(-300), glm::vec3(300)); + aabb.Entity = entity; + m_Octree->AddDynamicObject(aabb); + } else { + boost::optional absoluteAABB = Collision::EntityAbsoluteAABB(entity); + if (absoluteAABB) { + m_Octree->AddDynamicObject(*absoluteAABB); + } + } +} \ No newline at end of file diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index d32eb2ba..0f836c6f 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -1,5 +1,6 @@ #include "Game.h" #include "Collision/FillOctreeSystem.h" +#include "Collision/FillFrustumOctreeSystem.h" #include "Collision/EntityAABB.h" #include "Collision/TriggerSystem.h" #include "Collision/CollisionSystem.h" @@ -101,7 +102,7 @@ Game::Game(int argc, char* argv[]) ++updateOrderLevel; m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeCollision, "Collidable"); m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeTrigger, "Player"); - m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeFrustrumCulling, "Model"); + m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeFrustrumCulling); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); From 09bb42b3f45aeb26133be0773f517b5019fc9f7e Mon Sep 17 00:00:00 2001 From: viktorljung Date: Wed, 10 Feb 2016 11:00:44 +0100 Subject: [PATCH 152/355] Importer animation fix --- assets | 2 +- resources/Schema/Entities/AnimationTests2.xml | 2 +- src/Engine/Rendering/DrawFinalPass.cpp | 7 +++++++ src/Engine/Rendering/PickingPass.cpp | 4 ++++ src/Engine/Rendering/RawModelCustom.cpp | 9 ++++----- 5 files changed, 17 insertions(+), 7 deletions(-) diff --git a/assets b/assets index c2847a65..6ae43521 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit c2847a658ef603cf5c0ee993c4133bdf9c879d1c +Subproject commit 6ae43521b000345bd52bf92c06c5353d14b726ae diff --git a/resources/Schema/Entities/AnimationTests2.xml b/resources/Schema/Entities/AnimationTests2.xml index adb38d8d..3c482c61 100644 --- a/resources/Schema/Entities/AnimationTests2.xml +++ b/resources/Schema/Entities/AnimationTests2.xml @@ -45,7 +45,7 @@ Aim - Models/AssaultAnims.mesh + Models/Characters/Assault/HelloCube.mesh true diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index 46a47e7e..abc00b89 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -210,6 +210,7 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& } else { frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations); } + glUniformMatrix4fv(glGetUniformLocation(explosionSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); } else { m_ExplosionEffectProgram->Bind(); @@ -237,6 +238,8 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& } else { frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations); } + glUniformMatrix4fv(glGetUniformLocation(explosionSplatMapSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + } else { m_ExplosionEffectSplatMapProgram->Bind(); @@ -281,6 +284,8 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& } else { frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); } + glUniformMatrix4fv(glGetUniformLocation(forwardSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + } else { m_ForwardPlusProgram->Bind(); GLERROR("Bind ForwardPlusProgram"); @@ -307,6 +312,8 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& } else { frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); } + glUniformMatrix4fv(glGetUniformLocation(forwardSplatMapSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + } else { m_ForwardPlusSplatMapProgram->Bind(); GLERROR("Bind SplatMap program"); diff --git a/src/Engine/Rendering/PickingPass.cpp b/src/Engine/Rendering/PickingPass.cpp index 9d911325..41850698 100644 --- a/src/Engine/Rendering/PickingPass.cpp +++ b/src/Engine/Rendering/PickingPass.cpp @@ -110,6 +110,8 @@ void PickingPass::Draw(RenderScene& scene) } else { frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); } + glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + } } else { m_PickingProgram->Bind(); @@ -190,6 +192,8 @@ void PickingPass::Draw(RenderScene& scene) } else { frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); } + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + } glBindVertexArray(modelJob->Model->VAO); diff --git a/src/Engine/Rendering/RawModelCustom.cpp b/src/Engine/Rendering/RawModelCustom.cpp index 7eb58fd4..4ebf80b6 100644 --- a/src/Engine/Rendering/RawModelCustom.cpp +++ b/src/Engine/Rendering/RawModelCustom.cpp @@ -288,12 +288,11 @@ void RawModelCustom::ReadAnimationFile(std::string filePath) std::ifstream in(filePath.c_str(), std::ios_base::binary | std::ios_base::ate); if (!in.is_open()) { - //throw Resource::FailedLoadingException("Open animation file failed"); + if (hasSkin) { + throw Resource::FailedLoadingException("Open animation file for a skinned mesh failed, unknown stuff will happen"); + } return; - } else if (hasSkin) { - throw Resource::FailedLoadingException("Open animation file for a skinned mesh failed, unknown stuff will happen"); - return; - } + } unsigned int fileByteSize = static_cast(in.tellg()); in.seekg(0, std::ios_base::beg); From 2c48c2680f06f37427a8b10b695ef43092d187b7 Mon Sep 17 00:00:00 2001 From: viktorljung Date: Wed, 10 Feb 2016 11:04:28 +0100 Subject: [PATCH 153/355] Cleanup --- include/Engine/Rendering/Skeleton.h | 2 +- resources/Schema/Entities/AnimationTests2.xml | 34 +++++-------------- src/Engine/Rendering/Skeleton.cpp | 2 ++ 3 files changed, 12 insertions(+), 26 deletions(-) diff --git a/include/Engine/Rendering/Skeleton.h b/include/Engine/Rendering/Skeleton.h index 21e38d6f..124d618b 100644 --- a/include/Engine/Rendering/Skeleton.h +++ b/include/Engine/Rendering/Skeleton.h @@ -104,7 +104,7 @@ public: std::vector GetFrameBones(std::vector animations, bool noRootMotion = false); std::vector GetFrameBones(std::vector animations, AnimationOffset animationOffset, bool noRootMotion = false); - void AccumulateBoneTransforms(bool noRootMotion, const Animation* animation, float time, std::map& boneMatrices, const Bone* bone, glm::mat4 parentMatrix); + //void AccumulateBoneTransforms(bool noRootMotion, const Animation* animation, float time, std::map& boneMatrices, const Bone* bone, glm::mat4 parentMatrix); void AccumulateBoneTransforms(bool noRootMotion, std::vector animations, std::map& boneMatrices, const Bone* bone, glm::mat4 parentMatrix); void AccumulateBoneTransforms(bool noRootMotion, std::vector animations, AnimationOffset animationOffset, std::map& boneMatrices, const Bone* bone, glm::mat4 parentMatrix); diff --git a/resources/Schema/Entities/AnimationTests2.xml b/resources/Schema/Entities/AnimationTests2.xml index 3c482c61..68f27045 100644 --- a/resources/Schema/Entities/AnimationTests2.xml +++ b/resources/Schema/Entities/AnimationTests2.xml @@ -17,7 +17,7 @@ - Models/DirectionalLightWidget.mesh + Models/Widgets/Lights/DirectionalLightWidget.mesh @@ -31,21 +31,21 @@ Run 0.5 - 0.052207647453917483 + 0.44037772975435119 1 1 - Strafe Right + StrafeRight 0.5 - 0.90342197388335332 - Reload Switch - 0.11766622175243757 + 0.62650761653875175 + ReloadSwitch + 0.88913372073808805 1 - Aim + AimRifle - Models/Characters/Assault/HelloCube.mesh + Models/Characters/Assault/AssaultAnimations.mesh true @@ -53,23 +53,7 @@ - - - - - R_Arm_Weapon_Joint - - - Models/WepTest.mesh - - - - - - - - - + diff --git a/src/Engine/Rendering/Skeleton.cpp b/src/Engine/Rendering/Skeleton.cpp index 7f2f752f..f272f14d 100644 --- a/src/Engine/Rendering/Skeleton.cpp +++ b/src/Engine/Rendering/Skeleton.cpp @@ -80,6 +80,7 @@ std::vector Skeleton::GetFrameBones(std::vector animat } return finalMatrices; } +/* void Skeleton::AccumulateBoneTransforms(bool noRootMotion, const Animation* animation, float time, std::map& boneMatrices, const Bone* bone, glm::mat4 parentMatrix) { @@ -153,6 +154,7 @@ void Skeleton::AccumulateBoneTransforms(bool noRootMotion, const Animation* anim AccumulateBoneTransforms(noRootMotion, animation, time, boneMatrices, child, boneMatrix); } } +*/ void Skeleton::AccumulateBoneTransforms(bool noRootMotion, std::vector animations, std::map& boneMatrices, const Bone* bone, glm::mat4 parentMatrix) { From 94ff12cf66e800af9c3f073e9c6031d2eedb3736 Mon Sep 17 00:00:00 2001 From: stiffly Date: Wed, 10 Feb 2016 11:04:18 +0100 Subject: [PATCH 154/355] When using a PlaySoundOnEntity Event, you no longer have to provide the child of an entity as parameter. --- include/Engine/Sound/SoundManager.h | 2 +- include/Game/Systems/SoundSystem.h | 3 --- src/Engine/Sound/SoundManager.cpp | 7 +++++-- src/Game/Systems/PlayerMovementSystem.cpp | 5 +---- src/Game/Systems/SoundSystem.cpp | 24 ++++++++--------------- 5 files changed, 15 insertions(+), 26 deletions(-) diff --git a/include/Engine/Sound/SoundManager.h b/include/Engine/Sound/SoundManager.h index 38ec62ff..5b027c62 100644 --- a/include/Engine/Sound/SoundManager.h +++ b/include/Engine/Sound/SoundManager.h @@ -94,7 +94,7 @@ private: float m_BGMVolumeChannel = 1.0f; float m_SFXVolumeChannel = 1.0f; EntityWrapper m_LocalPlayer = EntityWrapper(); - + // Events EventRelay m_EPlaySoundOnEntity; bool OnPlaySoundOnEntity(const Events::PlaySoundOnEntity &e); diff --git a/include/Game/Systems/SoundSystem.h b/include/Game/Systems/SoundSystem.h index 0f7f5102..ed30a3c4 100644 --- a/include/Game/Systems/SoundSystem.h +++ b/include/Game/Systems/SoundSystem.h @@ -36,11 +36,8 @@ private: World* m_World = nullptr; EventBroker* m_EventBroker = nullptr; std::string m_Announcer = ""; - // Logic for playing a sound when a player jumps void playerJumps(); - // Helper function - EntityID createChildEmitter(EntityWrapper parent); std::default_random_engine generator; diff --git a/src/Engine/Sound/SoundManager.cpp b/src/Engine/Sound/SoundManager.cpp index 8ba6a502..8e103d5c 100644 --- a/src/Engine/Sound/SoundManager.cpp +++ b/src/Engine/Sound/SoundManager.cpp @@ -192,7 +192,10 @@ bool SoundManager::OnPlaySoundOnEntity(const Events::PlaySoundOnEntity & e) { Source* source = createSource(e.FilePath); source->Type = SoundType::SFX; - m_Sources[e.EmitterID] = source; + EntityID child = m_World->CreateEntity(e.EmitterID); + m_World->AttachComponent(child, "Transform"); + m_World->AttachComponent(child, "SoundEmitter"); + m_Sources[child] = source; playSound(source); return false; } @@ -243,7 +246,7 @@ bool SoundManager::OnPlayBackgroundMusic(const Events::PlayBackgroundMusic & e) } auto emitterChild = m_World->CreateEntity((*it).EntityID); auto emitter = m_World->AttachComponent(emitterChild, "SoundEmitter"); - (bool&)emitter["Loop"] = false; + (bool&)emitter["Loop"] = true; (std::string&)emitter["FilePath"] = e.FilePath; m_World->AttachComponent(emitterChild, "Transform"); Source* source = createSource(e.FilePath); diff --git a/src/Game/Systems/PlayerMovementSystem.cpp b/src/Game/Systems/PlayerMovementSystem.cpp index fca52dfd..34d8c689 100644 --- a/src/Game/Systems/PlayerMovementSystem.cpp +++ b/src/Game/Systems/PlayerMovementSystem.cpp @@ -197,10 +197,7 @@ void PlayerMovementSystem::playerStep(double dt) // Player moved a step's distance // Create footstep sound Events::PlaySoundOnEntity e; - EntityID child = m_World->CreateEntity(m_LocalPlayer.ID); - m_World->AttachComponent(child, "Transform"); - m_World->AttachComponent(child, "SoundEmitter"); - e.EmitterID = child; + e.EmitterID = m_LocalPlayer.ID; e.FilePath = m_LeftFoot ? "Audio/footstep/footstep2.wav" : "Audio/footstep/footstep3.wav"; m_LeftFoot = !m_LeftFoot; m_EventBroker->Publish(e); diff --git a/src/Game/Systems/SoundSystem.cpp b/src/Game/Systems/SoundSystem.cpp index 06e7d67a..0f35d617 100644 --- a/src/Game/Systems/SoundSystem.cpp +++ b/src/Game/Systems/SoundSystem.cpp @@ -31,7 +31,7 @@ bool SoundSystem::OnPlayerSpawned(const Events::PlayerSpawned &e) m_World->AttachComponent(e.Player.ID, "Listener"); m_LocalPlayer = e.Player; Events::PlaySoundOnEntity go; - go.EmitterID = createChildEmitter(m_LocalPlayer); + go.EmitterID = m_LocalPlayer.ID; go.FilePath = "Audio/announcer/" + m_Announcer + "/go.wav"; m_EventBroker->Publish(go); // TEMP: starts bgm @@ -67,7 +67,7 @@ void SoundSystem::playerJumps() glm::vec3 vel = (glm::vec3)m_World->GetComponent(m_LocalPlayer.ID, "Physics")["Velocity"]; if (vel.y == 0) { Events::PlaySoundOnEntity e; - e.EmitterID = createChildEmitter(m_LocalPlayer); + e.EmitterID = m_LocalPlayer.ID; e.FilePath = "Audio/jump/jump1.wav"; m_EventBroker->Publish(e); } @@ -76,7 +76,7 @@ void SoundSystem::playerJumps() bool SoundSystem::OnShoot(const Events::Shoot & e) { Events::PlaySoundOnEntity ev; - ev.EmitterID = createChildEmitter(m_LocalPlayer); + ev.EmitterID = m_LocalPlayer.ID; ev.FilePath = "Audio/laser/laser1.wav"; m_EventBroker->Publish(ev); return true; @@ -92,7 +92,7 @@ bool SoundSystem::OnCaptured(const Events::Captured & e) } else { ev.FilePath = "Audio/announcer/" + m_Announcer + "/objective_failed.wav"; // have not been tested } - ev.EmitterID = createChildEmitter(m_LocalPlayer); + ev.EmitterID = m_LocalPlayer.ID; m_EventBroker->Publish(ev); return false; } @@ -122,7 +122,7 @@ bool SoundSystem::OnPlayerDeath(const Events::PlayerDeath & e) { //if (e.PlayerID == m_LocalPlayer.ID) { Events::PlaySoundOnEntity ev; - ev.EmitterID = createChildEmitter(m_LocalPlayer); + ev.EmitterID = m_LocalPlayer.ID; ev.FilePath = "Audio/die/die2.wav"; m_EventBroker->Publish(ev); //} @@ -133,7 +133,7 @@ bool SoundSystem::OnPlayerHealthPickup(const Events::PlayerHealthPickup & e) { //if (e.PlayerHealedID == m_LocalPlayer.ID) { Events::PlaySoundOnEntity ev; - ev.EmitterID = createChildEmitter(m_LocalPlayer); + ev.EmitterID = m_LocalPlayer.ID; ev.FilePath = "Audio/pickup/pickup2.wav"; m_EventBroker->Publish(ev); //} @@ -153,7 +153,7 @@ bool SoundSystem::OnTriggerTouch(const Events::TriggerTouch & e) bool SoundSystem::OnDoubleJump(const Events::DoubleJump & e) { Events::PlaySoundOnEntity ev; - ev.EmitterID = createChildEmitter(m_LocalPlayer); + ev.EmitterID = m_LocalPlayer.ID; ev.FilePath = "Audio/jump/jump2.wav"; m_EventBroker->Publish(ev); return false; @@ -162,16 +162,8 @@ bool SoundSystem::OnDoubleJump(const Events::DoubleJump & e) bool SoundSystem::OnDashAbility(const Events::DashAbility &e) { Events::PlaySoundOnEntity ev; - ev.EmitterID = createChildEmitter(m_LocalPlayer); + ev.EmitterID = m_LocalPlayer.ID; ev.FilePath = "Audio/jump/dash1.wav"; m_EventBroker->Publish(ev); return false; -} - -EntityID SoundSystem::createChildEmitter(EntityWrapper localPlayer) -{ - EntityID child = m_World->CreateEntity(localPlayer.ID); - m_World->AttachComponent(child, "Transform"); - m_World->AttachComponent(child, "SoundEmitter"); - return child; } \ No newline at end of file From 97be22c4a57327676722fe4f8090b3a5e794353a Mon Sep 17 00:00:00 2001 From: viktorljung Date: Wed, 10 Feb 2016 11:22:05 +0100 Subject: [PATCH 155/355] Skinned transparent model Picking fixed --- resources/Schema/Entities/AnimationTests2.xml | 7 +- src/Engine/Rendering/PickingPass.cpp | 101 ++++++++++++------ 2 files changed, 71 insertions(+), 37 deletions(-) diff --git a/resources/Schema/Entities/AnimationTests2.xml b/resources/Schema/Entities/AnimationTests2.xml index 68f27045..96a439a4 100644 --- a/resources/Schema/Entities/AnimationTests2.xml +++ b/resources/Schema/Entities/AnimationTests2.xml @@ -31,14 +31,14 @@ Run 0.5 - 0.44037772975435119 + 0.23980116887997371 1 1 StrafeRight 0.5 - 0.62650761653875175 + 0.42593105566437428 ReloadSwitch - 0.88913372073808805 + 0.68855715986371058 1 @@ -47,7 +47,6 @@ Models/Characters/Assault/AssaultAnimations.mesh - true diff --git a/src/Engine/Rendering/PickingPass.cpp b/src/Engine/Rendering/PickingPass.cpp index 41850698..9842f659 100644 --- a/src/Engine/Rendering/PickingPass.cpp +++ b/src/Engine/Rendering/PickingPass.cpp @@ -156,45 +156,80 @@ void PickingPass::Draw(RenderScene& scene) auto modelJob = std::dynamic_pointer_cast(job); if (modelJob) { - int pickColor[2] = { m_ColorCounter[0], m_ColorCounter[1] }; - PickingInfo pickInfo; - pickInfo.Entity = modelJob->Entity; - pickInfo.World = modelJob->World; - pickInfo.Camera = scene.Camera; + if (modelJob->Model->isSkined()) { + m_PickingSkinnedProgram->Bind(); + int pickColor[2] = { m_ColorCounter[0], m_ColorCounter[1] }; - auto color = m_EntityColors.find(std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)); - if (color != m_EntityColors.end()) { - pickColor[0] = color->second[0]; - pickColor[1] = color->second[1]; + PickingInfo pickInfo; + pickInfo.Entity = modelJob->Entity; + pickInfo.World = modelJob->World; + pickInfo.Camera = scene.Camera; + + auto color = m_EntityColors.find(std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)); + if (color != m_EntityColors.end()) { + pickColor[0] = color->second[0]; + pickColor[1] = color->second[1]; + } else { + m_EntityColors[std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)] = glm::ivec2(pickColor[0], pickColor[1]); + if (m_ColorCounter[0] > 255) { + m_ColorCounter[0] = 0; + m_ColorCounter[1] += 1; + } else { + m_ColorCounter[0] += 1; + } + } + + m_PickingColorsToEntity[glm::ivec2(pickColor[0], pickColor[1])] = pickInfo; + + glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); + glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "V"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix())); + glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix())); + glUniform2fv(glGetUniformLocation(shaderSkinnedHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1]))); + + if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { + + std::vector frameBones; + if (modelJob->AnimationOffset.animation != nullptr) { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); + } else { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); + } + glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + + } } else { - m_EntityColors[std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)] = glm::ivec2(pickColor[0], pickColor[1]); - if (m_ColorCounter[0] > 255) { - m_ColorCounter[0] = 0; - m_ColorCounter[1] += 1; + int pickColor[2] = { m_ColorCounter[0], m_ColorCounter[1] }; + + PickingInfo pickInfo; + pickInfo.Entity = modelJob->Entity; + pickInfo.World = modelJob->World; + pickInfo.Camera = scene.Camera; + + auto color = m_EntityColors.find(std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)); + if (color != m_EntityColors.end()) { + pickColor[0] = color->second[0]; + pickColor[1] = color->second[1]; } else { - m_ColorCounter[0] += 1; + m_EntityColors[std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)] = glm::ivec2(pickColor[0], pickColor[1]); + if (m_ColorCounter[0] > 255) { + m_ColorCounter[0] = 0; + m_ColorCounter[1] += 1; + } else { + m_ColorCounter[0] += 1; + } } + + m_PickingColorsToEntity[glm::ivec2(pickColor[0], pickColor[1])] = pickInfo; + + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); + 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())); + glUniform2fv(glGetUniformLocation(shaderHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1]))); } - m_PickingColorsToEntity[glm::ivec2(pickColor[0], pickColor[1])] = pickInfo; + - glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); - 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())); - glUniform2fv(glGetUniformLocation(shaderHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1]))); - - if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { - - std::vector frameBones; - if (modelJob->AnimationOffset.animation != nullptr) { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); - } else { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); - } - glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - - } glBindVertexArray(modelJob->Model->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer); @@ -214,8 +249,8 @@ void PickingPass::ClearPicking() { m_PickingColorsToEntity.clear(); m_EntityColors.clear(); - m_ColorCounter[0] = 1; - m_ColorCounter[1] = 0; + m_ColorCounter[0] = 0; + m_ColorCounter[1] = 1; m_PickingBuffer.Bind(); glClearColor(0.f, 0.f, 0.f, 0.f); From 2ec30fd2b20e35667954d1417d7748be9111a22a Mon Sep 17 00:00:00 2001 From: Jocke Date: Wed, 10 Feb 2016 11:28:03 +0100 Subject: [PATCH 156/355] Cleaned up code and fixed crash when closing client before server when using udp. --- include/Engine/Network/Client.h | 4 +- include/Engine/Network/NetworkServer.h | 11 -- include/Engine/Network/Server.h | 4 +- include/Engine/Network/TCPClient.h | 4 - include/Engine/Network/UDPClient.h | 4 - include/Engine/Network/UDPServer.h | 6 -- src/Engine/Network/Server.cpp | 133 +++++++++++++------------ src/Engine/Network/TCPClient.cpp | 1 - src/Engine/Network/TCPServer.cpp | 2 - src/Engine/Network/UDPServer.cpp | 12 ++- 10 files changed, 78 insertions(+), 103 deletions(-) diff --git a/include/Engine/Network/Client.h b/include/Engine/Network/Client.h index 0c9608ff..ffdf812f 100644 --- a/include/Engine/Network/Client.h +++ b/include/Engine/Network/Client.h @@ -103,9 +103,9 @@ protected: bool OnPlayerSpawned(const Events::PlayerSpawned& e); private: - //UDPClient m_UDPClient; + UDPClient m_UDPClient; //TCPClient m_TCPClient; - TCPClient m_UDPClient; + //TCPClient m_UDPClient; }; #endif diff --git a/include/Engine/Network/NetworkServer.h b/include/Engine/Network/NetworkServer.h index 36544292..d6406eab 100644 --- a/include/Engine/Network/NetworkServer.h +++ b/include/Engine/Network/NetworkServer.h @@ -16,17 +16,6 @@ public: virtual void Send(Packet & packet) = 0; protected: char m_ReadBuffer[BUFFERSIZE] = { 0 }; - //void handle_accept(boost::shared_ptr socket, const boost::system::error_code & error); - //void parseConnect(Packet & packet); - //void readFromClients(); - - //public: - // virtual void Connect(std::string playerName, std::string address, int port) = 0; - // virtual void Disconnect() = 0; - // virtual Packet Receive() = 0; - // virtual void Send(Packet & packet) = 0; - //protected: - // char m_ReadBuffer[BUFFERSIZE] = { 0 }; }; #endif \ No newline at end of file diff --git a/include/Engine/Network/Server.h b/include/Engine/Network/Server.h index 0a3c93c8..1b2e6956 100644 --- a/include/Engine/Network/Server.h +++ b/include/Engine/Network/Server.h @@ -92,8 +92,8 @@ protected: EventRelay m_EComponentDeleted; bool OnComponentDeleted(const Events::ComponentDeleted& e); private: - TCPServer m_TCPServer; - //UDPServer m_UDPServer; + //TCPServer m_TCPServer; + UDPServer m_UDPServer; }; #endif diff --git a/include/Engine/Network/TCPClient.h b/include/Engine/Network/TCPClient.h index ff10b63a..9f61cca5 100644 --- a/include/Engine/Network/TCPClient.h +++ b/include/Engine/Network/TCPClient.h @@ -16,10 +16,6 @@ public: void Send(Packet & packet); bool IsSocketAvailable(); private: - // Assio UDP logic - //boost::asio::io_service m_IOService; - //boost::asio::ip::udp::endpoint m_ReceiverEndpoint; - //boost::shared_ptr m_Socket; // Assio TCP logic boost::asio::ip::tcp::endpoint m_Endpoint; boost::asio::io_service m_IOService; diff --git a/include/Engine/Network/UDPClient.h b/include/Engine/Network/UDPClient.h index ca369f6b..3a458d3e 100644 --- a/include/Engine/Network/UDPClient.h +++ b/include/Engine/Network/UDPClient.h @@ -3,10 +3,6 @@ #include #include "Network/NetworkClient.h" -//virtual void Connect(std::string address, int port) = 0; -//virtual int Receive(char * data) = 0; -//virtual void Send(Packet & packet) = 0; -//virtual void Disconnect() = 0; class UDPClient : public NetworkClient { diff --git a/include/Engine/Network/UDPServer.h b/include/Engine/Network/UDPServer.h index 7c912a21..246fb333 100644 --- a/include/Engine/Network/UDPServer.h +++ b/include/Engine/Network/UDPServer.h @@ -3,11 +3,6 @@ #include "NetworkServer.h" #include -// -//virtual void AcceptNewConnections() = 0; -//virtual void Receive(Packet & packet, PlayerDefinition & playerDefinition) = 0; -//virtual void Send(Packet & packet, PlayerDefinition & playerDefinition) = 0; -//virtual void Send(Packet & packet) = 0; class UDPServer : public NetworkServer { @@ -16,7 +11,6 @@ public: ~UDPServer(); void AcceptNewConnections(int& nextPlayerID, std::map& connectedPlayers); void Receive(Packet & packet, PlayerDefinition & playerDefinition); - //void parseConnect(Packet & packet, PlayerDefinition & playerDefinition); void Send(Packet & packet, PlayerDefinition & playerDefinition); void Send(Packet & packet); bool IsSocketAvailable(); diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index de7b6e14..d3099e12 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -23,36 +23,37 @@ void Server::Start(World* world, EventBroker* eventBroker) void Server::Update() { - m_TCPServer.AcceptNewConnections(m_NextPlayerID, m_ConnectedPlayers); PlayerDefinition pd; - for (auto& kv : m_ConnectedPlayers) { - while (kv.second.TCPSocket->available()) { - // Packet will get real data in receive - Packet packet(MessageType::Invalid); - m_TCPServer.Receive(packet, kv.second); - m_Address = kv.second.TCPSocket->remote_endpoint().address(); - m_Port = kv.second.TCPSocket->remote_endpoint().port(); - if (packet.GetMessageType() == MessageType::Connect) { - parseTCPConnect(packet); - } else { - parseMessageType(packet); - } - } - } - - //while (m_UDPServer.IsSocketAvailable()) { - // // Packet will get real data in receive - // Packet packet(MessageType::Invalid); - // m_UDPServer.Receive(packet, pd); - // m_Address = pd.Endpoint.address(); - // m_Port = pd.Endpoint.port(); - // if (packet.GetMessageType() == MessageType::Connect) { - // parseConnect(packet, pd); - // } else { - // parseMessageType(packet); + + //m_TCPServer.AcceptNewConnections(m_NextPlayerID, m_ConnectedPlayers); + //for (auto& kv : m_ConnectedPlayers) { + // while (kv.second.TCPSocket->available()) { + // // Packet will get real data in receive + // Packet packet(MessageType::Invalid); + // m_TCPServer.Receive(packet, kv.second); + // m_Address = kv.second.TCPSocket->remote_endpoint().address(); + // m_Port = kv.second.TCPSocket->remote_endpoint().port(); + // if (packet.GetMessageType() == MessageType::Connect) { + // parseTCPConnect(packet); + // } else { + // parseMessageType(packet); + // } // } //} + while (m_UDPServer.IsSocketAvailable()) { + // Packet will get real data in receive + Packet packet(MessageType::Invalid); + m_UDPServer.Receive(packet, pd); + m_Address = pd.Endpoint.address(); + m_Port = pd.Endpoint.port(); + if (packet.GetMessageType() == MessageType::Connect) { + parseConnect(packet, pd); + } else { + parseMessageType(packet); + } + } + std::clock_t currentTime = std::clock(); // Send snapshot if (snapshotInterval < (1000 * (currentTime - previousSnapshotMessage) / (double)CLOCKS_PER_SEC)) { @@ -118,7 +119,7 @@ void Server::broadcast(Packet& packet) { for (auto& kv : m_ConnectedPlayers) { packet.ChangePacketID(kv.second.PacketID); - m_TCPServer.Send(packet, kv.second); + m_UDPServer.Send(packet, kv.second); } } @@ -213,54 +214,54 @@ void Server::checkForTimeOuts() } void Server::parseConnect(Packet & packet, PlayerDefinition & pd) -{ - //LOG_INFO("Parsing connections"); - //// Check if player is already connected - //if (GetPlayerIDFromEndpoint() != -1) { - // return; - //} - //// Create a new player - //pd.EntityID = 0; // Overlook this - //pd.Address = pd.Endpoint.address(); - //pd.Port = pd.Endpoint.port(); - //pd.Name = packet.ReadString(); - //pd.PacketID = 0; - //pd.StopTime = std::clock(); - //m_ConnectedPlayers[m_NextPlayerID++] = pd; - //LOG_INFO("Spectator \"%s\" connected on IP: %s", pd.Name.c_str(), pd.Endpoint.address().to_string().c_str()); - - //// Send a message to the player that connected - //Packet connnectPacket(MessageType::Connect, pd.PacketID); - //m_UDPServer.Send(connnectPacket); - - //// Send notification that a player has connected - //Packet notificationPacket(MessageType::PlayerConnected); - //broadcast(notificationPacket); -} - -void Server::parseTCPConnect(Packet & packet) { LOG_INFO("Parsing connections"); // Check if player is already connected - PlayerID playerID = GetPlayerIDFromEndpoint(); - if (playerID = -1) { + if (GetPlayerIDFromEndpoint() != -1) { return; } // Create a new player - m_ConnectedPlayers.at(playerID).EntityID = 0; // Overlook this - m_ConnectedPlayers.at(playerID).Name = packet.ReadString(); - m_ConnectedPlayers.at(playerID).PacketID = 0; - m_ConnectedPlayers.at(playerID).StopTime = std::clock(); - LOG_INFO("Spectator \"%s\" connected on IP: %s", m_ConnectedPlayers.at(playerID).Name.c_str(), m_ConnectedPlayers.at(playerID).Endpoint.address().to_string().c_str()); + pd.EntityID = 0; // Overlook this + pd.Address = pd.Endpoint.address(); + pd.Port = pd.Endpoint.port(); + pd.Name = packet.ReadString(); + pd.PacketID = 0; + pd.StopTime = std::clock(); + m_ConnectedPlayers[m_NextPlayerID++] = pd; + LOG_INFO("Spectator \"%s\" connected on IP: %s", pd.Name.c_str(), pd.Endpoint.address().to_string().c_str()); // Send a message to the player that connected - Packet connnectPacket(MessageType::Connect, m_ConnectedPlayers.at(playerID).PacketID); - m_TCPServer.Send(connnectPacket); + Packet connnectPacket(MessageType::Connect, pd.PacketID); + m_UDPServer.Send(connnectPacket); // Send notification that a player has connected Packet notificationPacket(MessageType::PlayerConnected); - //broadcast(notificationPacket); + broadcast(notificationPacket); } +// +//void Server::parseTCPConnect(Packet & packet) +//{ +// LOG_INFO("Parsing connections"); +// // Check if player is already connected +// PlayerID playerID = GetPlayerIDFromEndpoint(); +// if (playerID = -1) { +// return; +// } +// // Create a new player +// m_ConnectedPlayers.at(playerID).EntityID = 0; // Overlook this +// m_ConnectedPlayers.at(playerID).Name = packet.ReadString(); +// m_ConnectedPlayers.at(playerID).PacketID = 0; +// m_ConnectedPlayers.at(playerID).StopTime = std::clock(); +// LOG_INFO("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_TCPServer.Send(connnectPacket); +// +// // Send notification that a player has connected +// Packet notificationPacket(MessageType::PlayerConnected); +// //broadcast(notificationPacket); +//} void Server::parseDisconnect() { @@ -310,7 +311,7 @@ void Server::kick(PlayerID player) { disconnect(player); Packet packet = Packet(MessageType::Kick); - m_TCPServer.Send(packet); + m_UDPServer.Send(packet); } bool Server::OnInputCommand(const Events::InputCommand & e) @@ -339,7 +340,7 @@ bool Server::OnPlayerSpawned(const Events::PlayerSpawned & e) packet.WritePrimitive(e.Spawner.ID); // We don't send PlayerID here because it will always be set to -1 packet.WriteString(m_ConnectedPlayers[e.PlayerID].Name); - m_TCPServer.Send(packet, m_ConnectedPlayers[e.PlayerID]); + m_UDPServer.Send(packet, m_ConnectedPlayers[e.PlayerID]); return false; } @@ -375,7 +376,7 @@ void Server::parseClientPing() // Return ping Packet packet(MessageType::Ping, m_ConnectedPlayers[player].PacketID); packet.WriteString("Ping received"); - m_TCPServer.Send(packet); + m_UDPServer.Send(packet); } void Server::parsePing() diff --git a/src/Engine/Network/TCPClient.cpp b/src/Engine/Network/TCPClient.cpp index 69938c38..21bb653f 100644 --- a/src/Engine/Network/TCPClient.cpp +++ b/src/Engine/Network/TCPClient.cpp @@ -83,7 +83,6 @@ void TCPClient::Send(Packet & packet) m_Socket->send(boost::asio::buffer( packet.Data(), packet.Size()), 0, error); - //Network::logSentData(packet.Size()); } bool TCPClient::IsSocketAvailable() diff --git a/src/Engine/Network/TCPServer.cpp b/src/Engine/Network/TCPServer.cpp index 105aab9f..f8da15e2 100644 --- a/src/Engine/Network/TCPServer.cpp +++ b/src/Engine/Network/TCPServer.cpp @@ -12,8 +12,6 @@ TCPServer::~TCPServer() void TCPServer::AcceptNewConnections(int& nextPlayerID, std::map& connectedPlayers) { - //PlayerDefinition pd; - //connectedPlayers[nextPlayerID++] = pd; boost::shared_ptr newSocket = boost::shared_ptr(new tcp::socket(m_IOService)); m_IOService.poll(); acceptor->async_accept(*newSocket, diff --git a/src/Engine/Network/UDPServer.cpp b/src/Engine/Network/UDPServer.cpp index e0bdf3a2..6bf4e466 100644 --- a/src/Engine/Network/UDPServer.cpp +++ b/src/Engine/Network/UDPServer.cpp @@ -6,8 +6,7 @@ UDPServer::UDPServer() } UDPServer::~UDPServer() -{ -} +{ } void UDPServer::Send(Packet& packet, PlayerDefinition & playerDefinition) { @@ -49,13 +48,16 @@ bool UDPServer::IsSocketAvailable() int UDPServer::readBuffer(char* data) { + boost::system::error_code error = boost::asio::error::host_not_found; unsigned int length = m_Socket->receive_from( boost::asio::buffer((void*)data , BUFFERSIZE) - , m_ReceiverEndpoint, 0); + , m_ReceiverEndpoint, 0, error); + if (error) { + LOG_WARNING(error.message().c_str()); + } return length; } void UDPServer::AcceptNewConnections(int& nextPlayerID, std::map& connectedPlayers) -{ -} \ No newline at end of file +{ } \ No newline at end of file From 3d2f9fa79d4a9a4362b73206ea492e7bcc808023 Mon Sep 17 00:00:00 2001 From: stiffly Date: Wed, 10 Feb 2016 11:36:54 +0100 Subject: [PATCH 157/355] Drum sounds does not start every single time a TriggerTouch happens. Specific and temporary logic for play test. --- include/Game/Systems/SoundSystem.h | 5 ++++ src/Game/Systems/SoundSystem.cpp | 43 ++++++++++++++++++++++-------- 2 files changed, 37 insertions(+), 11 deletions(-) diff --git a/include/Game/Systems/SoundSystem.h b/include/Game/Systems/SoundSystem.h index ed30a3c4..09582826 100644 --- a/include/Game/Systems/SoundSystem.h +++ b/include/Game/Systems/SoundSystem.h @@ -39,6 +39,11 @@ private: // Logic for playing a sound when a player jumps void playerJumps(); + // Temporary solution for play test. + bool m_DrumsIsPlaying = false; + double m_DrumTimer = 0.0; + bool drumTimer(double dt); + std::default_random_engine generator; EventRelay m_EPlayerSpawned; diff --git a/src/Game/Systems/SoundSystem.cpp b/src/Game/Systems/SoundSystem.cpp index 0f35d617..df14cd86 100644 --- a/src/Game/Systems/SoundSystem.cpp +++ b/src/Game/Systems/SoundSystem.cpp @@ -23,7 +23,12 @@ void SoundSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& cComp { } void SoundSystem::Update(double dt) -{ } +{ + // Temp for play test. + if(m_DrumsIsPlaying) { + m_DrumsIsPlaying = !drumTimer(dt); + } +} bool SoundSystem::OnPlayerSpawned(const Events::PlayerSpawned &e) { @@ -73,6 +78,17 @@ void SoundSystem::playerJumps() } } +bool SoundSystem::drumTimer(double dt) +{ + m_DrumTimer += dt; + if (m_DrumTimer > 15) { + m_DrumTimer = 0.0; + return true; + } else { + return false; + } +} + bool SoundSystem::OnShoot(const Events::Shoot & e) { Events::PlaySoundOnEntity ev; @@ -94,6 +110,8 @@ bool SoundSystem::OnCaptured(const Events::Captured & e) } ev.EmitterID = m_LocalPlayer.ID; m_EventBroker->Publish(ev); + // Temp for play test. + m_DrumsIsPlaying = false; return false; } @@ -106,11 +124,11 @@ bool SoundSystem::OnPlayerDamage(const Events::PlayerDamage & e) std::vector paths; paths.push_back("Audio/hurt/hurt" + std::to_string(rand) + ".wav"); - // Breathe - int ammountOfbreaths = (static_cast(e.Damage) / 10) + 2; // TEMP: Idk something stupid like this shit - for (int i = 0; i < ammountOfbreaths; i++) { - paths.push_back("Audio/exhausted/breath.wav"); - } +// // Breathe +// int ammountOfbreaths = (static_cast(e.Damage) / 10) + 2; // TEMP: Idk something stupid like this shit +// for (int i = 0; i < ammountOfbreaths; i++) { +// paths.push_back("Audio/exhausted/breath.wav"); +// } Events::PlayQueueOnEntity ev; ev.Emitter = m_LocalPlayer; ev.FilePaths = paths; @@ -120,32 +138,35 @@ bool SoundSystem::OnPlayerDamage(const Events::PlayerDamage & e) bool SoundSystem::OnPlayerDeath(const Events::PlayerDeath & e) { - //if (e.PlayerID == m_LocalPlayer.ID) { Events::PlaySoundOnEntity ev; ev.EmitterID = m_LocalPlayer.ID; ev.FilePath = "Audio/die/die2.wav"; m_EventBroker->Publish(ev); - //} return false; } bool SoundSystem::OnPlayerHealthPickup(const Events::PlayerHealthPickup & e) { - //if (e.PlayerHealedID == m_LocalPlayer.ID) { Events::PlaySoundOnEntity ev; ev.EmitterID = m_LocalPlayer.ID; ev.FilePath = "Audio/pickup/pickup2.wav"; m_EventBroker->Publish(ev); - //} return false; } bool SoundSystem::OnTriggerTouch(const Events::TriggerTouch & e) { + // Temp for play test. + if (m_DrumsIsPlaying) { + return false; + } if (m_World->HasComponent(e.Trigger.ID, "CapturePoint")) { - Events::PlayBackgroundMusic ev; + Events::PlaySoundOnEntity ev; // should be BGM + ev.EmitterID = m_LocalPlayer.ID; ev.FilePath = "Audio/bgm/drumstest.wav"; m_EventBroker->Publish(ev); + // Temp for play test. + m_DrumsIsPlaying = true; } return false; } From b6b96c5f11f52b12954ac170b9496330668ced1e Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Wed, 10 Feb 2016 11:51:58 +0100 Subject: [PATCH 158/355] Added DoubleJumpHexagon entity. Spawned DoubleJumpHexagon as the player doublejumps. Fixed DoubleJumping bug where you couldnt doublejump on rocks (where velocity wasnt 0.0) --- include/Game/Systems/PlayerMovementSystem.h | 3 ++ resources/DefaultInput.ini | 3 ++ .../Schema/Entities/DoubleJumpHexagon.xml | 30 +++++++++++++++++++ src/Game/Systems/PlayerMovementSystem.cpp | 8 ++++- 4 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 resources/Schema/Entities/DoubleJumpHexagon.xml diff --git a/include/Game/Systems/PlayerMovementSystem.h b/include/Game/Systems/PlayerMovementSystem.h index 34862e90..a0194545 100644 --- a/include/Game/Systems/PlayerMovementSystem.h +++ b/include/Game/Systems/PlayerMovementSystem.h @@ -5,6 +5,9 @@ #include "Input/FirstPersonInputController.h" #include +#include "Core/EntityFile.h" +#include "Core/EntityFileParser.h" + class PlayerMovementSystem : public ImpureSystem, PureSystem { public: diff --git a/resources/DefaultInput.ini b/resources/DefaultInput.ini index 589dfb3f..eb5b7658 100644 --- a/resources/DefaultInput.ini +++ b/resources/DefaultInput.ini @@ -2,6 +2,9 @@ Sensitivity=0.5 InvertPitch=false +[KeyBoard] +DoubleTapToDash=true + [Bindings] MouseLeft=PrimaryFire MouseX=Yaw diff --git a/resources/Schema/Entities/DoubleJumpHexagon.xml b/resources/Schema/Entities/DoubleJumpHexagon.xml new file mode 100644 index 00000000..bbc41119 --- /dev/null +++ b/resources/Schema/Entities/DoubleJumpHexagon.xml @@ -0,0 +1,30 @@ + + + + + + Models/JumpEffectHexagon.mesh + + true + + + + + + + 1.5 + + + true + + + true + 3 + + true + + + + + + diff --git a/src/Game/Systems/PlayerMovementSystem.cpp b/src/Game/Systems/PlayerMovementSystem.cpp index 52890c3a..6b26db1c 100644 --- a/src/Game/Systems/PlayerMovementSystem.cpp +++ b/src/Game/Systems/PlayerMovementSystem.cpp @@ -90,9 +90,15 @@ void PlayerMovementSystem::Update(double dt) //you cant jump and dash at the same time - since there is no friction in the air and we would thus dash much further in the air if (!controller->PlayerIsDashing() && controller->Jumping() && !controller->Crouching() && (isOnGround || !controller->DoubleJumping())) { (bool)cPhysics["IsOnGround"] = false; - if (velocity.y == 0.f) { + if (isOnGround) { controller->SetDoubleJumping(false); } else { + //put a hexagon at the players feet + auto hexagonEffect = ResourceManager::Load("Schema/Entities/DoubleJumpHexagon.xml"); + EntityFileParser parser(hexagonEffect); + EntityID hexagonEffectID = parser.MergeEntities(m_World); + EntityWrapper hexagonEW = EntityWrapper(m_World, hexagonEffectID); + hexagonEW["Transform"]["Position"] = (glm::vec3)player["Transform"]["Position"]; controller->SetDoubleJumping(true); } velocity.y = 4.f; From 86f4ff0b3cc74a1ac8ecf874855a0b4bc5ff7463 Mon Sep 17 00:00:00 2001 From: William Moberg Date: Wed, 10 Feb 2016 12:38:36 +0100 Subject: [PATCH 159/355] Added an annotation for Trigger and Collideable components. --- resources/Schema/Components/Collidable.xsd | 3 +++ resources/Schema/Components/Trigger.xsd | 3 +++ 2 files changed, 6 insertions(+) diff --git a/resources/Schema/Components/Collidable.xsd b/resources/Schema/Components/Collidable.xsd index 84c66f11..93f7ac24 100644 --- a/resources/Schema/Components/Collidable.xsd +++ b/resources/Schema/Components/Collidable.xsd @@ -4,5 +4,8 @@ + + Needs a Model or AABB component to work, uses AABB if both are attached. + \ No newline at end of file diff --git a/resources/Schema/Components/Trigger.xsd b/resources/Schema/Components/Trigger.xsd index a8bc8865..8119b966 100644 --- a/resources/Schema/Components/Trigger.xsd +++ b/resources/Schema/Components/Trigger.xsd @@ -4,5 +4,8 @@ + + Needs a Model or AABB component to work, uses AABB if both are attached. + \ No newline at end of file From afebf879a02dcf2901048c2a1c5e6e0582b8f6bf Mon Sep 17 00:00:00 2001 From: viktorljung Date: Wed, 10 Feb 2016 13:44:47 +0100 Subject: [PATCH 160/355] Merge fixes --- include/Engine/Collision/Collision.h | 2 +- include/Engine/Rendering/DrawFinalPass.h | 2 + .../Shaders/FillDepthBufferSkinned.vert.glsl | 33 ++ .../Shaders/ForwardPlusSkinned.vert.glsl | 2 +- .../Shaders/ShieldStencilSkinned.vert.glsl | 33 ++ src/Engine/Collision/Collision.cpp | 25 +- src/Engine/Collision/CollisionSystem.cpp | 2 +- src/Engine/Rendering/DrawFinalPass.cpp | 445 ++++++++++-------- src/Engine/Rendering/PickingPass.cpp | 26 +- src/Engine/Rendering/RenderSystem.cpp | 19 +- 10 files changed, 348 insertions(+), 241 deletions(-) create mode 100644 resources/Shaders/FillDepthBufferSkinned.vert.glsl create mode 100644 resources/Shaders/ShieldStencilSkinned.vert.glsl diff --git a/include/Engine/Collision/Collision.h b/include/Engine/Collision/Collision.h index 6d16e090..624fbca0 100644 --- a/include/Engine/Collision/Collision.h +++ b/include/Engine/Collision/Collision.h @@ -64,7 +64,7 @@ bool RayVsModel(const Ray& ray, float& outVCoord); bool AABBvsTriangles(const AABB& box, - const std::vector& modelVertices, + const RawModel::Vertex* modelVertices, const std::vector& modelIndices, const glm::mat4& modelMatrix, glm::vec3& boxVelocity, diff --git a/include/Engine/Rendering/DrawFinalPass.h b/include/Engine/Rendering/DrawFinalPass.h index 72fd756b..7d5e2a7a 100644 --- a/include/Engine/Rendering/DrawFinalPass.h +++ b/include/Engine/Rendering/DrawFinalPass.h @@ -78,6 +78,8 @@ private: ShaderProgram* m_ExplosionEffectSkinnedProgram; ShaderProgram* m_ExplosionEffectSplatMapSkinnedProgram; ShaderProgram* m_ForwardPlusSplatMapSkinnedProgram; + ShaderProgram* m_ShieldToStencilSkinnedProgram; + ShaderProgram* m_FillDepthBufferSkinnedProgram; }; #endif \ No newline at end of file diff --git a/resources/Shaders/FillDepthBufferSkinned.vert.glsl b/resources/Shaders/FillDepthBufferSkinned.vert.glsl new file mode 100644 index 00000000..ce2a142d --- /dev/null +++ b/resources/Shaders/FillDepthBufferSkinned.vert.glsl @@ -0,0 +1,33 @@ +#version 430 + +uniform mat4 M; +uniform mat4 V; +uniform mat4 P; +uniform mat4 Bones[100]; + + +layout(location = 0) in vec3 Position; +layout(location = 5) in vec4 BoneIndices; +layout(location = 6) in vec4 BoneWeights; + + + +out VertexData{ + vec3 Position; +}Output; + +void main() +{ + mat4 boneTransform = mat4(1); + + if(BoneWeights[0] > 0.0f){ + boneTransform = BoneWeights[0] * Bones[int(BoneIndices[0])] + + BoneWeights[1] * Bones[int(BoneIndices[1])] + + BoneWeights[2] * Bones[int(BoneIndices[2])] + + BoneWeights[3] * Bones[int(BoneIndices[3])]; + } + + gl_Position = P*V*M*boneTransform * vec4(Position, 1.0); + + Output.Position = vec3(0.0); +} \ No newline at end of file diff --git a/resources/Shaders/ForwardPlusSkinned.vert.glsl b/resources/Shaders/ForwardPlusSkinned.vert.glsl index 5368b260..5fd55a8c 100644 --- a/resources/Shaders/ForwardPlusSkinned.vert.glsl +++ b/resources/Shaders/ForwardPlusSkinned.vert.glsl @@ -38,7 +38,7 @@ void main() Output.Position = (boneTransform * vec4(Position, 1.0)).xyz; Output.TextureCoordinate = TextureCoords; - Output.Normal = vec3(M * vec4(Normal, 0.0)); + Output.Normal = vec3(M * boneTransform * vec4(Normal, 0.0)); Output.Tangent = vec3(M * vec4(Tangent, 0.0)); Output.BiTangent = vec3(M * vec4(BiTangent, 0.0)); Output.ExplosionColor = vec4(1.0); diff --git a/resources/Shaders/ShieldStencilSkinned.vert.glsl b/resources/Shaders/ShieldStencilSkinned.vert.glsl new file mode 100644 index 00000000..ce2a142d --- /dev/null +++ b/resources/Shaders/ShieldStencilSkinned.vert.glsl @@ -0,0 +1,33 @@ +#version 430 + +uniform mat4 M; +uniform mat4 V; +uniform mat4 P; +uniform mat4 Bones[100]; + + +layout(location = 0) in vec3 Position; +layout(location = 5) in vec4 BoneIndices; +layout(location = 6) in vec4 BoneWeights; + + + +out VertexData{ + vec3 Position; +}Output; + +void main() +{ + mat4 boneTransform = mat4(1); + + if(BoneWeights[0] > 0.0f){ + boneTransform = BoneWeights[0] * Bones[int(BoneIndices[0])] + + BoneWeights[1] * Bones[int(BoneIndices[1])] + + BoneWeights[2] * Bones[int(BoneIndices[2])] + + BoneWeights[3] * Bones[int(BoneIndices[3])]; + } + + gl_Position = P*V*M*boneTransform * vec4(Position, 1.0); + + Output.Position = vec3(0.0); +} \ No newline at end of file diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index 839a8e77..34b7e553 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -183,7 +183,7 @@ bool RayVsTriangle(const Ray& ray, } outDistance = dist; outUCoord = glm::dot(m, DxE2) * DetInv; - outVCoord = glm::dot(ray.Direction(), MxE1) * DetInv; + outVCoord = glm::dot(ray.Direction(), MxE1) * DetInv; //u,v can be very close to 0 but still negative sometimes. added a deltafactor to compensate for that problem //If u and v are positive, u+v <= 1, dist is positive, and less than closest. @@ -330,7 +330,7 @@ bool rectangleVsTriangle(const glm::vec2& boxMin, float push = rightRes < -leftRes ? rightRes : leftRes; float absPushSq = abs(push); absPushSq *= absPushSq; - + if (absPushSq < resolutionDistanceSq) { resolutionDistanceSq = absPushSq; resolutionDirection = push * normal; @@ -355,8 +355,8 @@ constexpr bool FaceIsGround(float faceNormalY) //An array containing 3 int pairs { 0, 2 }, { 0, 1 }, { 1, 2 } constexpr std::array, 3> dimensionPairs({ std::pair(0, 2), std::pair(0, 1), std::pair(1, 2) }); -bool AABBvsTriangle(const AABB& box, - const std::array& triPos, +bool AABBvsTriangle(const AABB& box, + const std::array& triPos, const glm::vec3& originalBoxVelocity, float verticalStepHeight, bool& isOnGround, @@ -385,7 +385,7 @@ bool AABBvsTriangle(const AABB& box, Resolution() : DistanceSq(INFINITY) , Vector(0.f) - {} + { } BoxTriResolveCase Case; float DistanceSq; glm::vec3 Vector; @@ -525,9 +525,9 @@ bool AABBvsTriangle(const AABB& box, return true; } -bool AABBvsTriangles(const AABB& box, - const std::vector& modelVertices, - const std::vector& modelIndices, +bool AABBvsTriangles(const AABB& box, + const RawModel::Vertex* modelVertices, + const std::vector& modelIndices, const glm::mat4& modelMatrix, glm::vec3& boxVelocity, float verticalStepHeight, @@ -579,12 +579,11 @@ bool AttachAABBComponentFromModel(EntityWrapper entity) glm::vec3 mini(INFINITY); glm::vec3 maxi(-INFINITY); - for (const auto& v : model->m_Vertices) { + for (unsigned int i = 0; i < model->NumVertices(); i++) { + const auto& v = model->Vertices()[i]; mini = glm::min(mini, v.Position); - for (unsigned int i = 0; i < modelRes->NumberOfVertices(); i++) { - const auto& v = modelRes->Vertices()[i]; + maxi = glm::max(maxi, v.Position); } - entity.AttachComponent("AABB"); entity["AABB"]["Origin"] = 0.5f * (maxi + mini); entity["AABB"]["Size"] = maxi - mini; @@ -609,4 +608,4 @@ boost::optional EntityAbsoluteAABB(EntityWrapper& entity) return aabb; } -} +} \ No newline at end of file diff --git a/src/Engine/Collision/CollisionSystem.cpp b/src/Engine/Collision/CollisionSystem.cpp index 7d8905a8..afd09022 100644 --- a/src/Engine/Collision/CollisionSystem.cpp +++ b/src/Engine/Collision/CollisionSystem.cpp @@ -41,7 +41,7 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c glm::vec3 inOutVelocity = (glm::vec3)cPhysics["Velocity"]; bool isOnGround = (bool)cPhysics["IsOnGround"]; float verticalStepHeight = (float)(double)cPhysics["VerticalStepHeight"]; - if (Collision::AABBvsTriangles(boxA, model->m_Vertices, model->m_Indices, modelMatrix, inOutVelocity, verticalStepHeight, isOnGround, resolutionVector)) { + if (Collision::AABBvsTriangles(boxA, model->Vertices(), model->m_Indices, modelMatrix, inOutVelocity, verticalStepHeight, isOnGround, resolutionVector)) { (glm::vec3&)cTransform["Position"] += resolutionVector; cPhysics["Velocity"] = inOutVelocity; if (isOnGround) { diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index 66f222c5..760ecce5 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -142,12 +142,26 @@ void DrawFinalPass::InitializeShaderPrograms() m_ShieldToStencilProgram->Link(); GLERROR("Creating Shield program"); + m_ShieldToStencilSkinnedProgram = ResourceManager::Load("#ShieldToStencilProgramSkinned"); + m_ShieldToStencilSkinnedProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ShieldStencilSkinned.vert.glsl"))); + m_ShieldToStencilSkinnedProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ShieldStencil.frag.glsl"))); + m_ShieldToStencilSkinnedProgram->Compile(); + m_ShieldToStencilSkinnedProgram->Link(); + GLERROR("Creating Shield Skinned program"); + m_FillDepthBufferProgram = ResourceManager::Load("#FillDepthBufferProgram"); m_FillDepthBufferProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/FillDepthBuffer.vert.glsl"))); m_FillDepthBufferProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/FillDepthBuffer.frag.glsl"))); m_FillDepthBufferProgram->Compile(); m_FillDepthBufferProgram->Link(); GLERROR("Creating DepthFill program"); + + m_FillDepthBufferSkinnedProgram = ResourceManager::Load("#FillDepthBufferProgramSkinned"); + m_FillDepthBufferSkinnedProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/FillDepthBufferSkinned.vert.glsl"))); + m_FillDepthBufferSkinnedProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/FillDepthBuffer.frag.glsl"))); + m_FillDepthBufferSkinnedProgram->Compile(); + m_FillDepthBufferSkinnedProgram->Link(); + GLERROR("Creating DepthFill program"); } void DrawFinalPass::Draw(RenderScene& scene) @@ -181,11 +195,11 @@ void DrawFinalPass::Draw(RenderScene& scene) //Draw Opaque shielded objects state->StencilFunc(GL_NOTEQUAL, 1, 0xFF); state->StencilMask(0x00); - DrawShieldedModelRenderQueue(scene.Jobs.OpaqueShieldedObjects, scene); + DrawModelRenderQueues(scene.Jobs.OpaqueShieldedObjects, scene); //might need changing GLERROR("Shielded Opaque object"); //Draw Transparen Shielded objects - DrawShieldedModelRenderQueue(scene.Jobs.TransparentShieldedObjects, scene); + DrawModelRenderQueues(scene.Jobs.TransparentShieldedObjects, scene); //might need changing GLERROR("Shielded Transparent objects"); GLERROR("END"); @@ -298,100 +312,186 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, m_LightCullingPass->LightGridSSBO()); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, m_LightCullingPass->LightIndexSSBO()); - for(auto &job : jobs) - { - auto explosionEffectJob = std::dynamic_pointer_cast(job); - if(explosionEffectJob) { - //Bind program - if(GLERROR("Prebind")) { - continue; - } - m_ExplosionEffectProgram->Bind(); - if(GLERROR("BindProgram")) { - continue; - } + for (auto &job : jobs) { + auto explosionEffectJob = std::dynamic_pointer_cast(job); + if (explosionEffectJob) { + switch (explosionEffectJob->Type) { + case RawModel::MaterialType::Basic: + case RawModel::MaterialType::SingleTextures: + { + if (explosionEffectJob->Model->isSkined()) { + m_ExplosionEffectSkinnedProgram->Bind(); + GLERROR("Bind ExplosionEffectSkinned program"); + //bind uniforms + BindExplosionUniforms(explosionSkinnedHandle, explosionEffectJob, scene); + //bind textures + BindExplosionTextures(explosionSkinnedHandle, explosionEffectJob); + std::vector frameBones; + if (explosionEffectJob->AnimationOffset.animation != nullptr) { + frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations, explosionEffectJob->AnimationOffset); + } else { + frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations); + } + glUniformMatrix4fv(glGetUniformLocation(explosionSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + } else { + m_ExplosionEffectProgram->Bind(); + GLERROR("Bind ExplosionEffect program"); + //bind uniforms + BindExplosionUniforms(explosionHandle, explosionEffectJob, scene); + //bind textures + BindExplosionTextures(explosionHandle, explosionEffectJob); + } + break; + } + case RawModel::MaterialType::SplatMapping: + { + if (explosionEffectJob->Model->isSkined()) { + m_ExplosionEffectSplatMapSkinnedProgram->Bind(); + GLERROR("Bind ExplosionEffectSplatMapSkinned program"); + //bind uniforms + BindExplosionUniforms(explosionSplatMapSkinnedHandle, explosionEffectJob, scene); + //bind textures + BindExplosionTextures(explosionSplatMapSkinnedHandle, explosionEffectJob); + GLERROR("asdasd"); + std::vector frameBones; + if (explosionEffectJob->AnimationOffset.animation != nullptr) { + frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations, explosionEffectJob->AnimationOffset); + } else { + frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations); + } + glUniformMatrix4fv(glGetUniformLocation(explosionSplatMapSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + + } else { + m_ExplosionEffectSplatMapProgram->Bind(); + GLERROR("Bind ExplosionEffectSplatMap program"); + //bind uniforms + //bind uniforms + BindExplosionUniforms(explosionSplatMapHandle, explosionEffectJob, scene); + //bind textures + BindExplosionTextures(explosionSplatMapHandle, explosionEffectJob); + GLERROR("asdasd"); + } + break; + } + } glDisable(GL_CULL_FACE); - //Bind uniforms - BindExplosionUniforms(explosionHandle, explosionEffectJob, scene); - if(GLERROR("BindExplosionUniforms")) { - continue; - } - - if (explosionEffectJob->Model->m_RawModel->m_Skeleton != nullptr) { - - if (explosionEffectJob->Animation != nullptr) { - std::vector frameBones = explosionEffectJob->Skeleton->GetFrameBones(*explosionEffectJob->Animation, explosionEffectJob->AnimationTime); - glUniformMatrix4fv(glGetUniformLocation(explosionHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - } - } - if(GLERROR("Animation")) { - continue; - } - - //bind textures - BindExplosionTextures(explosionEffectJob); - if(GLERROR("BindExplosionTextures")) { - continue; - } //draw glBindVertexArray(explosionEffectJob->Model->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, explosionEffectJob->Model->ElementBuffer); glDrawElements(GL_TRIANGLES, explosionEffectJob->EndIndex - explosionEffectJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(explosionEffectJob->StartIndex*sizeof(unsigned int))); glEnable(GL_CULL_FACE); - if(GLERROR("explosion effect end")) { - continue; - } + GLERROR("explosion effect end"); + } else { + auto modelJob = std::dynamic_pointer_cast(job); + if (modelJob) { + //bind forward program + //TODO: JOHAN/TOBIAS: Bind shader based on ModelJob->ShaderID; + switch (modelJob->Type) { + case RawModel::MaterialType::Basic: + case RawModel::MaterialType::SingleTextures: + { + if (modelJob->Model->isSkined()) { + m_ForwardPlusSkinnedProgram->Bind(); + GLERROR("Bind ForwardPlusSkinnedProgram"); + //bind uniforms + BindModelUniforms(forwardSkinnedHandle, modelJob, scene); + //bind textures + BindModelTextures(forwardSkinnedHandle, modelJob); + std::vector frameBones; + if (modelJob->AnimationOffset.animation != nullptr) { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); + } else { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); + } + glUniformMatrix4fv(glGetUniformLocation(forwardSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - } else { - auto modelJob = std::dynamic_pointer_cast(job); - if (modelJob) { - //bind forward program - m_ForwardPlusProgram->Bind(); - glUniform2f(glGetUniformLocation(forwardHandle, "ScreenDimensions"), m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); - - //bind uniforms - BindModelUniforms(forwardHandle, modelJob, scene); - - //bind textures - BindModelTextures(modelJob); - - if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { - - if (modelJob->Animation != nullptr) { - std::vector frameBones = modelJob->Skeleton->GetFrameBones(*modelJob->Animation, modelJob->AnimationTime); - glUniformMatrix4fv(glGetUniformLocation(forwardHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + } else { + m_ForwardPlusProgram->Bind(); + GLERROR("Bind ForwardPlusProgram"); + //bind uniforms + BindModelUniforms(forwardHandle, modelJob, scene); + //bind textures + BindModelTextures(forwardHandle, modelJob); + } + break; } - } + case RawModel::MaterialType::SplatMapping: + { + if (modelJob->Model->isSkined()) { + m_ForwardPlusSplatMapSkinnedProgram->Bind(); + GLERROR("Bind SplatMap program"); + //bind uniforms + BindModelUniforms(forwardSplatMapSkinnedHandle, modelJob, scene); + //bind textures + BindModelTextures(forwardSplatMapSkinnedHandle, modelJob); + GLERROR("asdasd"); + std::vector frameBones; + if (modelJob->AnimationOffset.animation != nullptr) { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); + } else { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); + } + glUniformMatrix4fv(glGetUniformLocation(forwardSplatMapSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - //draw - glBindVertexArray(modelJob->Model->VAO); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer); - glDrawElements(GL_TRIANGLES, modelJob->EndIndex - modelJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(modelJob->StartIndex*sizeof(unsigned int))); - if(GLERROR("models end")) { - continue; + } else { + m_ForwardPlusSplatMapProgram->Bind(); + GLERROR("Bind SplatMap program"); + //bind uniforms + BindModelUniforms(forwardSplatHandle, modelJob, scene); + //bind textures + BindModelTextures(forwardSplatHandle, modelJob); + GLERROR("asdasd"); + } + break; + } + } + //draw + glBindVertexArray(modelJob->Model->VAO); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer); + glDrawElements(GL_TRIANGLES, modelJob->EndIndex - modelJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(modelJob->StartIndex*sizeof(unsigned int))); + if (GLERROR("models end")) { + continue; + } } } } - } - } void DrawFinalPass::DrawShieldToStencilBuffer(std::list>& jobs, RenderScene& scene) { - m_ShieldToStencilProgram->Bind(); - GLuint shaderHandle = m_ShieldToStencilProgram->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())); for (auto &job : jobs) { auto modelJob = std::dynamic_pointer_cast(job); if (modelJob) { - glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); + if(modelJob->Model->isSkined()) { + m_ShieldToStencilSkinnedProgram->Bind(); + GLuint shaderHandle = m_ShieldToStencilSkinnedProgram->GetHandle(); + + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); + 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())); + std::vector frameBones; + if (modelJob->AnimationOffset.animation != nullptr) { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); + } else { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); + } + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + + } else { + m_ShieldToStencilProgram->Bind(); + GLuint shaderHandle = m_ShieldToStencilProgram->GetHandle(); + + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); + 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())); + + } glBindVertexArray(modelJob->Model->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer); @@ -417,139 +517,70 @@ void DrawFinalPass::DrawShieldedModelRenderQueue(std::list(job); if (explosionEffectJob) { - switch (explosionEffectJob->Type) { - case RawModel::MaterialType::Basic: - case RawModel::MaterialType::SingleTextures: - { - if (explosionEffectJob->Model->isSkined()) { - m_ExplosionEffectSkinnedProgram->Bind(); - GLERROR("Bind ExplosionEffectSkinned program"); - //bind uniforms - BindExplosionUniforms(explosionSkinnedHandle, explosionEffectJob, scene); - //bind textures - BindExplosionTextures(explosionSkinnedHandle, explosionEffectJob); - std::vector frameBones; - if (explosionEffectJob->AnimationOffset.animation != nullptr) { - frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations, explosionEffectJob->AnimationOffset); - } else { - frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations); - } - glUniformMatrix4fv(glGetUniformLocation(explosionSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - } - else { - m_ExplosionEffectProgram->Bind(); - GLERROR("Bind ExplosionEffect program"); - //bind uniforms - BindExplosionUniforms(explosionHandle, explosionEffectJob, scene); - //bind textures - BindExplosionTextures(explosionHandle, explosionEffectJob); - } - break; - } - case RawModel::MaterialType::SplatMapping: - { - if (explosionEffectJob->Model->isSkined()) { - m_ExplosionEffectSplatMapSkinnedProgram->Bind(); - GLERROR("Bind ExplosionEffectSplatMapSkinned program"); - //bind uniforms - BindExplosionUniforms(explosionSplatMapSkinnedHandle, explosionEffectJob, scene); - //bind textures - BindExplosionTextures(explosionSplatMapSkinnedHandle, explosionEffectJob); - GLERROR("asdasd"); - std::vector frameBones; - if (explosionEffectJob->AnimationOffset.animation != nullptr) { - frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations, explosionEffectJob->AnimationOffset); - } else { - frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations); - } - glUniformMatrix4fv(glGetUniformLocation(explosionSplatMapSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + //Bind program + if (GLERROR("Prebind")) { + continue; + } + m_ExplosionEffectProgram->Bind(); + if (GLERROR("BindProgram")) { + continue; + } - } - else { - m_ExplosionEffectSplatMapProgram->Bind(); - GLERROR("Bind ExplosionEffectSplatMap program"); - //bind uniforms - //bind uniforms - BindExplosionUniforms(explosionSplatMapHandle, explosionEffectJob, scene); - //bind textures - BindExplosionTextures(explosionSplatMapHandle, explosionEffectJob); - GLERROR("asdasd"); - } - break; - } - } glDisable(GL_CULL_FACE); + //Bind uniforms + BindExplosionUniforms(explosionHandle, explosionEffectJob, scene); + if (GLERROR("BindExplosionUniforms")) { + continue; + } + + std::vector frameBones; + if (explosionEffectJob->AnimationOffset.animation != nullptr) { + frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations, explosionEffectJob->AnimationOffset); + } else { + frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations); + } + glUniformMatrix4fv(glGetUniformLocation(explosionHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + + if (GLERROR("Animation")) { + continue; + } + + //bind textures + BindExplosionTextures(explosionHandle, explosionEffectJob); + if (GLERROR("BindExplosionTextures")) { + continue; + } //draw glBindVertexArray(explosionEffectJob->Model->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, explosionEffectJob->Model->ElementBuffer); glDrawElements(GL_TRIANGLES, explosionEffectJob->EndIndex - explosionEffectJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(explosionEffectJob->StartIndex*sizeof(unsigned int))); glEnable(GL_CULL_FACE); - GLERROR("explosion effect end"); + if (GLERROR("explosion effect end")) { + continue; + } + } else { auto modelJob = std::dynamic_pointer_cast(job); if (modelJob) { //bind forward program - //TODO: JOHAN/TOBIAS: Bind shader based on ModelJob->ShaderID; - switch (modelJob->Type) { - case RawModel::MaterialType::Basic: - case RawModel::MaterialType::SingleTextures: - { - if (modelJob->Model->isSkined()) { - m_ForwardPlusSkinnedProgram->Bind(); - GLERROR("Bind ForwardPlusSkinnedProgram"); - //bind uniforms - BindModelUniforms(forwardSkinnedHandle, modelJob, scene); - //bind textures - BindModelTextures(forwardSkinnedHandle, modelJob); - std::vector frameBones; - if (modelJob->AnimationOffset.animation != nullptr) { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); - } else { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); - } - glUniformMatrix4fv(glGetUniformLocation(forwardSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + m_ForwardPlusProgram->Bind(); + glUniform2f(glGetUniformLocation(forwardHandle, "ScreenDimensions"), m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); - } else { - m_ForwardPlusProgram->Bind(); - GLERROR("Bind ForwardPlusProgram"); - //bind uniforms - BindModelUniforms(forwardHandle, modelJob, scene); - //bind textures - BindModelTextures(forwardHandle, modelJob); - } - break; - } - case RawModel::MaterialType::SplatMapping: - { - if (modelJob->Model->isSkined()) { - m_ForwardPlusSplatMapSkinnedProgram->Bind(); - GLERROR("Bind SplatMap program"); - //bind uniforms - BindModelUniforms(forwardSplatMapSkinnedHandle, modelJob, scene); - //bind textures - BindModelTextures(forwardSplatMapSkinnedHandle, modelJob); - GLERROR("asdasd"); - std::vector frameBones; - if (modelJob->AnimationOffset.animation != nullptr) { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); - } else { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); - } - glUniformMatrix4fv(glGetUniformLocation(forwardSplatMapSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + //bind uniforms + BindModelUniforms(forwardHandle, modelJob, scene); + + //bind textures + BindModelTextures(forwardHandle ,modelJob); + + std::vector frameBones; + if (modelJob->AnimationOffset.animation != nullptr) { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); + } else { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); + } + glUniformMatrix4fv(glGetUniformLocation(forwardHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - } else { - m_ForwardPlusSplatMapProgram->Bind(); - GLERROR("Bind SplatMap program"); - //bind uniforms - BindModelUniforms(forwardSplatHandle, modelJob, scene); - //bind textures - BindModelTextures(forwardSplatHandle, modelJob); - GLERROR("asdasd"); - } - break; - } - } //draw glBindVertexArray(modelJob->Model->VAO); @@ -566,25 +597,35 @@ void DrawFinalPass::DrawShieldedModelRenderQueue(std::list>& jobs, RenderScene& scene) { - m_FillDepthBufferProgram->Bind(); - GLuint shaderHandle = m_FillDepthBufferProgram->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())); - + + for (auto &job : jobs) { auto modelJob = std::dynamic_pointer_cast(job); - //bind uniforms - glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); + if(modelJob->Model->isSkined()) { + m_FillDepthBufferSkinnedProgram->Bind(); + GLuint shaderHandle = m_FillDepthBufferSkinnedProgram->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())); + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); - if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { - - if (modelJob->Animation != nullptr) { - std::vector frameBones = modelJob->Skeleton->GetFrameBones(*modelJob->Animation, modelJob->AnimationTime); - glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + std::vector frameBones; + if (modelJob->AnimationOffset.animation != nullptr) { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); + } else { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); } + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + + } else { + m_FillDepthBufferProgram->Bind(); + GLuint shaderHandle = m_FillDepthBufferProgram->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())); + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); } + //draw glBindVertexArray(modelJob->Model->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer); diff --git a/src/Engine/Rendering/PickingPass.cpp b/src/Engine/Rendering/PickingPass.cpp index 795d1097..80f0efb7 100644 --- a/src/Engine/Rendering/PickingPass.cpp +++ b/src/Engine/Rendering/PickingPass.cpp @@ -184,13 +184,14 @@ void PickingPass::Draw(RenderScene& scene) glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix())); glUniform2fv(glGetUniformLocation(shaderHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1]))); - if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { - - if (modelJob->Animation != nullptr) { - std::vector frameBones = modelJob->Skeleton->GetFrameBones(*modelJob->Animation, modelJob->AnimationTime); - glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - } + std::vector frameBones; + if (modelJob->AnimationOffset.animation != nullptr) { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); + } else { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); } + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + glBindVertexArray(modelJob->Model->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer); @@ -230,13 +231,14 @@ void PickingPass::Draw(RenderScene& scene) glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix())); glUniform2fv(glGetUniformLocation(shaderHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1]))); - if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { - - if (modelJob->Animation != nullptr) { - std::vector frameBones = modelJob->Skeleton->GetFrameBones(*modelJob->Animation, modelJob->AnimationTime); - glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - } + std::vector frameBones; + if (modelJob->AnimationOffset.animation != nullptr) { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); + } else { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); } + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + glBindVertexArray(modelJob->Model->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer); diff --git a/src/Engine/Rendering/RenderSystem.cpp b/src/Engine/Rendering/RenderSystem.cpp index 9b9b8654..67b0cff5 100644 --- a/src/Engine/Rendering/RenderSystem.cpp +++ b/src/Engine/Rendering/RenderSystem.cpp @@ -109,7 +109,7 @@ void RenderSystem::fillModels(RenderScene::Queues &Jobs) fillPercentage )); if (m_World->HasComponent(cModel.EntityID, "Shield")){ - TODO Calc hash + explosionEffectJob->CalculateHash(); Jobs.ShieldObjects.push_back(explosionEffectJob); } else if (m_World->HasComponent(cModel.EntityID, "Shielded") || m_World->HasComponent(cModel.EntityID, "Player")) { @@ -119,10 +119,9 @@ void RenderSystem::fillModels(RenderScene::Queues &Jobs) } if (cModel["Transparent"]) { - TODO: Calc hash Jobs.TransparentShieldedObjects.push_back(explosionEffectJob); } else { - explosionEffectJob->CalculateHash(); + explosionEffectJob->CalculateHash(); Jobs.OpaqueShieldedObjects.push_back(explosionEffectJob); } } else { @@ -131,10 +130,9 @@ void RenderSystem::fillModels(RenderScene::Queues &Jobs) } if (cModel["Transparent"]) { - TODO CALC HASH Jobs.TransparentObjects.push_back(explosionEffectJob); } else { - TODO CALC HASH + explosionEffectJob->CalculateHash(); Jobs.OpaqueObjects.push_back(explosionEffectJob); } } @@ -150,7 +148,7 @@ void RenderSystem::fillModels(RenderScene::Queues &Jobs) fillPercentage )); if (m_World->HasComponent(cModel.EntityID, "Shield")) { - TODO: CALC HASH + modelJob->CalculateHash(); Jobs.ShieldObjects.push_back(modelJob); } else if (m_World->HasComponent(cModel.EntityID, "Shielded") || m_World->HasComponent(cModel.EntityID, "Player")) { @@ -160,10 +158,9 @@ void RenderSystem::fillModels(RenderScene::Queues &Jobs) } if (cModel["Transparent"]) { - TODO CALC HASH Jobs.TransparentShieldedObjects.push_back(modelJob); } else { - modelJob->CalculateHash(); + modelJob->CalculateHash(); Jobs.OpaqueShieldedObjects.push_back(modelJob); } } else { @@ -172,10 +169,9 @@ void RenderSystem::fillModels(RenderScene::Queues &Jobs) } if (cModel["Transparent"]) { - CALC HASH Jobs.TransparentObjects.push_back(modelJob); } else { - CALC HASH + modelJob->CalculateHash(); Jobs.OpaqueObjects.push_back(modelJob); } } @@ -298,7 +294,8 @@ void RenderSystem::Update(double dt) fillModels(scene.Jobs); fillPointLights(scene.Jobs.PointLight, m_World); - scene.OpaqueObjects.sort(); + //TODO: Make sure all objects needed are also sorted. + scene.Jobs.OpaqueObjects.sort(); fillDirectionalLights(scene.Jobs.DirectionalLight, m_World); fillText(scene.Jobs.Text, m_World); m_RenderFrame->Add(scene); From c2128790af8445d55c9559b37d499357b01ad020 Mon Sep 17 00:00:00 2001 From: stiffly Date: Wed, 10 Feb 2016 14:07:11 +0100 Subject: [PATCH 161/355] Now using appropriate variable to see if a player is on ground. Does not check if playervel.y == 0 which will be false if a player is on a obstacle. --- src/Game/Systems/PlayerMovementSystem.cpp | 7 +++---- src/Game/Systems/SoundSystem.cpp | 4 ++-- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/src/Game/Systems/PlayerMovementSystem.cpp b/src/Game/Systems/PlayerMovementSystem.cpp index 1a0f7eb1..1cd067a6 100644 --- a/src/Game/Systems/PlayerMovementSystem.cpp +++ b/src/Game/Systems/PlayerMovementSystem.cpp @@ -187,13 +187,12 @@ void PlayerMovementSystem::playerStep(double dt) } // Position of the local player, used see how far a player has moved. glm::vec3 pos = (glm::vec3)m_World->GetComponent(m_LocalPlayer.ID, "Transform")["Position"]; - // Velocity of the local player, used to see if a player is airborne. - glm::vec3 vel = (glm::vec3)m_World->GetComponent(m_LocalPlayer.ID, "Physics")["Velocity"]; + // Used to see if a player is airborne. + bool grounded = (bool)m_World->GetComponent(m_LocalPlayer.ID, "Physics")["IsOnGround"]; m_DistanceMoved += glm::length(pos - m_LastPosition); // Set the last position for next iteration m_LastPosition = pos; - bool isAirborne = vel.y != 0; - if (m_DistanceMoved > m_PlayerStepLength && !isAirborne) { + if (m_DistanceMoved > m_PlayerStepLength && grounded) { // Player moved a step's distance // Create footstep sound Events::PlaySoundOnEntity e; diff --git a/src/Game/Systems/SoundSystem.cpp b/src/Game/Systems/SoundSystem.cpp index df14cd86..acb7501c 100644 --- a/src/Game/Systems/SoundSystem.cpp +++ b/src/Game/Systems/SoundSystem.cpp @@ -69,8 +69,8 @@ bool SoundSystem::OnInputCommand(const Events::InputCommand & e) void SoundSystem::playerJumps() { - glm::vec3 vel = (glm::vec3)m_World->GetComponent(m_LocalPlayer.ID, "Physics")["Velocity"]; - if (vel.y == 0) { + bool grounded = (bool)m_World->GetComponent(m_LocalPlayer.ID, "Physics")["IsOnGround"]; + if (grounded) { Events::PlaySoundOnEntity e; e.EmitterID = m_LocalPlayer.ID; e.FilePath = "Audio/jump/jump1.wav"; From 1e238b24071af7486b6620ce1c1bf18c141b9019 Mon Sep 17 00:00:00 2001 From: viktorljung Date: Wed, 10 Feb 2016 14:28:25 +0100 Subject: [PATCH 162/355] Changed asset branch --- assets | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/assets b/assets index 6ae43521..7531e441 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit 6ae43521b000345bd52bf92c06c5353d14b726ae +Subproject commit 7531e441fea639076d69c6cf05e3ae8ff7170cf9 From e9d36c48a641c5c166c9a1e6b218b979a1c05fc4 Mon Sep 17 00:00:00 2001 From: viktorljung Date: Wed, 10 Feb 2016 14:36:25 +0100 Subject: [PATCH 163/355] Changed isSkined to IsSkinned and removed duplicated code in PickingPass --- include/Engine/Rendering/Model.h | 2 +- include/Engine/Rendering/ModelJob.h | 6 +- include/Engine/Rendering/RawModelCustom.h | 2 +- src/Engine/Rendering/DrawFinalPass.cpp | 12 +- src/Engine/Rendering/Model.cpp | 6 +- src/Engine/Rendering/PickingPass.cpp | 156 ++++++++-------------- 6 files changed, 67 insertions(+), 117 deletions(-) diff --git a/include/Engine/Rendering/Model.h b/include/Engine/Rendering/Model.h index 30706cc5..4d21f724 100644 --- a/include/Engine/Rendering/Model.h +++ b/include/Engine/Rendering/Model.h @@ -20,7 +20,7 @@ public: const RawModel::Vertex* Vertices() const { return m_RawModel->Vertices(); } unsigned int NumberOfVertices() const { return m_RawModel->NumVertices(); } const AABB& Box() const { return m_Box; } - bool isSkined() const { return m_RawModel->isSkined(); } + bool IsSkinned() const { return m_RawModel->IsSkinned(); } GLuint VAO; GLuint ElementBuffer; RawModel* m_RawModel; diff --git a/include/Engine/Rendering/ModelJob.h b/include/Engine/Rendering/ModelJob.h index 633e5daa..bc2b8b6e 100644 --- a/include/Engine/Rendering/ModelJob.h +++ b/include/Engine/Rendering/ModelJob.h @@ -27,7 +27,7 @@ struct ModelJob : RenderJob ::RawModel::MaterialBasic* matGroup = matProp.material; switch(matProp.type){ case ::RawModel::MaterialType::Basic: - if (Model->isSkined()) { + if (Model->IsSkinned()) { ShaderID = ResourceManager::Load("#ForwardPlusSkinnedProgram")->ResourceID; } else { @@ -37,7 +37,7 @@ struct ModelJob : RenderJob break; case ::RawModel::MaterialType::SingleTextures: { - if (Model->isSkined()) { + if (Model->IsSkinned()) { ShaderID = ResourceManager::Load("#ForwardPlusSkinnedProgram")->ResourceID; } else { @@ -64,7 +64,7 @@ struct ModelJob : RenderJob break; case ::RawModel::MaterialType::SplatMapping: { - if (Model->isSkined()) { + if (Model->IsSkinned()) { ShaderID = ResourceManager::Load("#ForwardPlusSplatMapSkinnedProgram")->ResourceID; } else { diff --git a/include/Engine/Rendering/RawModelCustom.h b/include/Engine/Rendering/RawModelCustom.h index 476bf52e..cf21fb6d 100644 --- a/include/Engine/Rendering/RawModelCustom.h +++ b/include/Engine/Rendering/RawModelCustom.h @@ -114,7 +114,7 @@ public: } }; - bool isSkined() const { return hasSkin; }; + bool IsSkinned() const { return hasSkin; }; std::vector m_Materials; diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index 760ecce5..0d08b98f 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -320,7 +320,7 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& case RawModel::MaterialType::Basic: case RawModel::MaterialType::SingleTextures: { - if (explosionEffectJob->Model->isSkined()) { + if (explosionEffectJob->Model->IsSkinned()) { m_ExplosionEffectSkinnedProgram->Bind(); GLERROR("Bind ExplosionEffectSkinned program"); //bind uniforms @@ -346,7 +346,7 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& } case RawModel::MaterialType::SplatMapping: { - if (explosionEffectJob->Model->isSkined()) { + if (explosionEffectJob->Model->IsSkinned()) { m_ExplosionEffectSplatMapSkinnedProgram->Bind(); GLERROR("Bind ExplosionEffectSplatMapSkinned program"); //bind uniforms @@ -392,7 +392,7 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& case RawModel::MaterialType::Basic: case RawModel::MaterialType::SingleTextures: { - if (modelJob->Model->isSkined()) { + if (modelJob->Model->IsSkinned()) { m_ForwardPlusSkinnedProgram->Bind(); GLERROR("Bind ForwardPlusSkinnedProgram"); //bind uniforms @@ -419,7 +419,7 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& } case RawModel::MaterialType::SplatMapping: { - if (modelJob->Model->isSkined()) { + if (modelJob->Model->IsSkinned()) { m_ForwardPlusSplatMapSkinnedProgram->Bind(); GLERROR("Bind SplatMap program"); //bind uniforms @@ -468,7 +468,7 @@ void DrawFinalPass::DrawShieldToStencilBuffer(std::list(job); if (modelJob) { - if(modelJob->Model->isSkined()) { + if(modelJob->Model->IsSkinned()) { m_ShieldToStencilSkinnedProgram->Bind(); GLuint shaderHandle = m_ShieldToStencilSkinnedProgram->GetHandle(); @@ -602,7 +602,7 @@ void DrawFinalPass::DrawToDepthBuffer(std::list>& job for (auto &job : jobs) { auto modelJob = std::dynamic_pointer_cast(job); - if(modelJob->Model->isSkined()) { + if(modelJob->Model->IsSkinned()) { m_FillDepthBufferSkinnedProgram->Bind(); GLuint shaderHandle = m_FillDepthBufferSkinnedProgram->GetHandle(); glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "V"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix())); diff --git a/src/Engine/Rendering/Model.cpp b/src/Engine/Rendering/Model.cpp index 9ce99564..6457c980 100644 --- a/src/Engine/Rendering/Model.cpp +++ b/src/Engine/Rendering/Model.cpp @@ -87,7 +87,7 @@ Model::Model(std::string fileName) glBindBuffer(GL_ARRAY_BUFFER, buffer); std::vector structSizes; - if (m_RawModel->isSkined()) { + if (m_RawModel->IsSkinned()) { structSizes = { 3, 3, 3, 3, 2, 4, 4 }; } else { structSizes = { 3, 3, 3, 3, 2 }; @@ -106,7 +106,7 @@ Model::Model(std::string fileName) glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++; glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++; glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++; - if (m_RawModel->isSkined()) { + if (m_RawModel->IsSkinned()) { glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++; glVertexAttribPointer(element, structSizes[element], GL_FLOAT, GL_FALSE, stride, (GLvoid*)(sizeof(GLfloat) * (offset += structSizes[element - 1]))); element++; } @@ -118,7 +118,7 @@ Model::Model(std::string fileName) glEnableVertexAttribArray(2); glEnableVertexAttribArray(3); glEnableVertexAttribArray(4); - if (m_RawModel->isSkined()) { + if (m_RawModel->IsSkinned()) { glEnableVertexAttribArray(5); glEnableVertexAttribArray(6); } diff --git a/src/Engine/Rendering/PickingPass.cpp b/src/Engine/Rendering/PickingPass.cpp index bef0e117..fa1b3ca3 100644 --- a/src/Engine/Rendering/PickingPass.cpp +++ b/src/Engine/Rendering/PickingPass.cpp @@ -69,34 +69,32 @@ void PickingPass::Draw(RenderScene& scene) auto modelJob = std::dynamic_pointer_cast(job); if (modelJob) { - if (modelJob->Model->isSkined()) + int pickColor[2] = { m_ColorCounter[0], m_ColorCounter[1] }; + + PickingInfo pickInfo; + pickInfo.Entity = modelJob->Entity; + pickInfo.World = modelJob->World; + pickInfo.Camera = scene.Camera; + + auto color = m_EntityColors.find(std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)); + if (color != m_EntityColors.end()) { + pickColor[0] = color->second[0]; + pickColor[1] = color->second[1]; + } else { + m_EntityColors[std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)] = glm::ivec2(pickColor[0], pickColor[1]); + if (m_ColorCounter[0] > 255) { + m_ColorCounter[0] = 0; + m_ColorCounter[1] += 1; + } else { + m_ColorCounter[0] += 1; + } + } + + m_PickingColorsToEntity[glm::ivec2(pickColor[0], pickColor[1])] = pickInfo; + + if (modelJob->Model->IsSkinned()) { m_PickingSkinnedProgram->Bind(); - int pickColor[2] = { m_ColorCounter[0], m_ColorCounter[1] }; - - PickingInfo pickInfo; - pickInfo.Entity = modelJob->Entity; - pickInfo.World = modelJob->World; - pickInfo.Camera = scene.Camera; - - auto color = m_EntityColors.find(std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)); - if (color != m_EntityColors.end()) { - pickColor[0] = color->second[0]; - pickColor[1] = color->second[1]; - } - else { - m_EntityColors[std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)] = glm::ivec2(pickColor[0], pickColor[1]); - if (m_ColorCounter[0] > 255) { - m_ColorCounter[0] = 0; - m_ColorCounter[1] += 1; - } - else { - m_ColorCounter[0] += 1; - } - } - - m_PickingColorsToEntity[glm::ivec2(pickColor[0], pickColor[1])] = pickInfo; - glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "V"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix())); glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix())); @@ -114,32 +112,7 @@ void PickingPass::Draw(RenderScene& scene) } } else { - m_PickingProgram->Bind(); - int pickColor[2] = { m_ColorCounter[0], m_ColorCounter[1] }; - - PickingInfo pickInfo; - pickInfo.Entity = modelJob->Entity; - pickInfo.World = modelJob->World; - pickInfo.Camera = scene.Camera; - - auto color = m_EntityColors.find(std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)); - if (color != m_EntityColors.end()) { - pickColor[0] = color->second[0]; - pickColor[1] = color->second[1]; - } - else { - m_EntityColors[std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)] = glm::ivec2(pickColor[0], pickColor[1]); - if (m_ColorCounter[0] > 255) { - m_ColorCounter[0] = 0; - m_ColorCounter[1] += 1; - } - else { - m_ColorCounter[0] += 1; - } - } - - m_PickingColorsToEntity[glm::ivec2(pickColor[0], pickColor[1])] = pickInfo; - + m_PickingProgram->Bind(); glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); 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())); @@ -155,31 +128,32 @@ void PickingPass::Draw(RenderScene& scene) for (auto &job : scene.Jobs.TransparentObjects) { auto modelJob = std::dynamic_pointer_cast(job); + int pickColor[2] = { m_ColorCounter[0], m_ColorCounter[1] }; + + PickingInfo pickInfo; + pickInfo.Entity = modelJob->Entity; + pickInfo.World = modelJob->World; + pickInfo.Camera = scene.Camera; + + auto color = m_EntityColors.find(std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)); + if (color != m_EntityColors.end()) { + pickColor[0] = color->second[0]; + pickColor[1] = color->second[1]; + } else { + m_EntityColors[std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)] = glm::ivec2(pickColor[0], pickColor[1]); + if (m_ColorCounter[0] > 255) { + m_ColorCounter[0] = 0; + m_ColorCounter[1] += 1; + } else { + m_ColorCounter[0] += 1; + } + } + + m_PickingColorsToEntity[glm::ivec2(pickColor[0], pickColor[1])] = pickInfo; + if (modelJob) { - if (modelJob->Model->isSkined()) { - int pickColor[2] = { m_ColorCounter[0], m_ColorCounter[1] }; - - PickingInfo pickInfo; - pickInfo.Entity = modelJob->Entity; - pickInfo.World = modelJob->World; - pickInfo.Camera = scene.Camera; - - auto color = m_EntityColors.find(std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)); - if (color != m_EntityColors.end()) { - pickColor[0] = color->second[0]; - pickColor[1] = color->second[1]; - } else { - m_EntityColors[std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)] = glm::ivec2(pickColor[0], pickColor[1]); - if (m_ColorCounter[0] > 255) { - m_ColorCounter[0] = 0; - m_ColorCounter[1] += 1; - } else { - m_ColorCounter[0] += 1; - } - } - - m_PickingColorsToEntity[glm::ivec2(pickColor[0], pickColor[1])] = pickInfo; - + if (modelJob->Model->IsSkinned()) { + m_PickingSkinnedProgram->Bind(); glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "V"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix())); glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix())); @@ -193,36 +167,12 @@ void PickingPass::Draw(RenderScene& scene) } glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); } else { - int pickColor[2] = { m_ColorCounter[0], m_ColorCounter[1] }; - - PickingInfo pickInfo; - pickInfo.Entity = modelJob->Entity; - pickInfo.World = modelJob->World; - pickInfo.Camera = scene.Camera; - - auto color = m_EntityColors.find(std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)); - if (color != m_EntityColors.end()) { - pickColor[0] = color->second[0]; - pickColor[1] = color->second[1]; - } else { - m_EntityColors[std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)] = glm::ivec2(pickColor[0], pickColor[1]); - if (m_ColorCounter[0] > 255) { - m_ColorCounter[0] = 0; - m_ColorCounter[1] += 1; - } else { - m_ColorCounter[0] += 1; - } - } - - m_PickingColorsToEntity[glm::ivec2(pickColor[0], pickColor[1])] = pickInfo; - + m_PickingProgram->Bind(); glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); 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())); glUniform2fv(glGetUniformLocation(shaderHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1]))); } - - glBindVertexArray(modelJob->Model->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer); @@ -257,7 +207,7 @@ void PickingPass::Draw(RenderScene& scene) m_PickingColorsToEntity[glm::ivec2(pickColor[0], pickColor[1])] = pickInfo; - if(modelJob->Model->isSkined()) { + if(modelJob->Model->IsSkinned()) { m_PickingSkinnedProgram->Bind(); glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "V"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix())); @@ -314,7 +264,7 @@ void PickingPass::Draw(RenderScene& scene) m_PickingColorsToEntity[glm::ivec2(pickColor[0], pickColor[1])] = pickInfo; - if (modelJob->Model->isSkined()) { + if (modelJob->Model->IsSkinned()) { m_PickingSkinnedProgram->Bind(); From 61275274f7fd1b196b88f8ee3cd72dffd853baf0 Mon Sep 17 00:00:00 2001 From: viktorljung Date: Wed, 10 Feb 2016 14:39:45 +0100 Subject: [PATCH 164/355] Commited this --- src/Engine/Rendering/RenderSystem.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/Engine/Rendering/RenderSystem.cpp b/src/Engine/Rendering/RenderSystem.cpp index ab2b6dc2..ab9a3c27 100644 --- a/src/Engine/Rendering/RenderSystem.cpp +++ b/src/Engine/Rendering/RenderSystem.cpp @@ -62,14 +62,14 @@ void RenderSystem::fillModels(RenderScene::Queues &Jobs) } // Only render children of a camera if that camera is currently active -// if (isChildOfACamera(entity) && !isChildOfCurrentCamera(entity)) { -// continue; -// } DO NOT COMMIT THIS DO NOT COMMIT THIS DO NOT COMMIT THIS DO NOT COMMIT THIS DO NOT COMMIT THIS DO NOT COMMIT THIS DO NOT COMMIT THIS + if (isChildOfACamera(entity) && !isChildOfCurrentCamera(entity)) { + continue; + } // Hide things parented to local player if they have the HiddenFromLocalPlayer component -// if (entity.HasComponent("HiddenForLocalPlayer") && (entity == m_LocalPlayer || entity.IsChildOf(m_LocalPlayer))) { -// continue; -// } DO NOT COMMIT THIS DO NOT COMMIT THIS DO NOT COMMIT THIS DO NOT COMMIT THIS DO NOT COMMIT THIS DO NOT COMMIT THIS DO NOT COMMIT THIS + if (entity.HasComponent("HiddenForLocalPlayer") && (entity == m_LocalPlayer || entity.IsChildOf(m_LocalPlayer))) { + continue; + } Model* model; try { From d931660c56cc994df1b0cac66eecb53db59c9a55 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Wed, 10 Feb 2016 01:16:38 +0100 Subject: [PATCH 165/355] WIP --- include/Engine/Core/EntityWrapper.h | 2 +- include/Engine/Core/EventBroker.h | 3 +- include/Engine/Core/Octree.h | 4 +- include/Engine/Core/System.h | 2 +- include/Game/Systems/WeaponSystem.h | 129 ++++++++++++++++-- resources/Schema/Components/AssaultWeapon.xml | 3 +- resources/Schema/Components/AssaultWeapon.xsd | 1 + resources/Schema/Entities/Player.xml | 7 +- src/Engine/Core/EntityWrapper.cpp | 3 +- src/Engine/Core/EventBroker.cpp | 14 +- src/Game/Game.cpp | 2 +- src/Game/Systems/PlayerSpawnSystem.cpp | 3 + src/Game/Systems/WeaponSystem.cpp | 108 ++++++--------- 13 files changed, 181 insertions(+), 100 deletions(-) diff --git a/include/Engine/Core/EntityWrapper.h b/include/Engine/Core/EntityWrapper.h index bf34b9be..0ffb190e 100644 --- a/include/Engine/Core/EntityWrapper.h +++ b/include/Engine/Core/EntityWrapper.h @@ -29,7 +29,7 @@ struct EntityWrapper EntityWrapper FirstChildByName(const std::string& name); EntityWrapper FirstParentWithComponent(const std::string& componentType); bool IsChildOf(EntityWrapper potentialParent); - bool Valid(); + bool Valid() const; ComponentWrapper operator[](const char* componentName); bool operator==(const EntityWrapper& e) const; diff --git a/include/Engine/Core/EventBroker.h b/include/Engine/Core/EventBroker.h index dc1babc0..20d3b60c 100644 --- a/include/Engine/Core/EventBroker.h +++ b/include/Engine/Core/EventBroker.h @@ -5,6 +5,7 @@ #include #include #include +#include #include "../Common.h" #include "Event.h" @@ -107,7 +108,7 @@ private: typedef std::unordered_map ContextRelays_t; ContextRelays_t m_ContextRelays; std::vector m_RelaysToSubscribe; - std::vector> m_RelaysToUnsubscribe; + std::unordered_map> m_RelaysToUnsubscribe; typedef std::list>> EventQueue_t; std::shared_ptr m_EventQueueRead; diff --git a/include/Engine/Core/Octree.h b/include/Engine/Core/Octree.h index 8bac5503..8fce7744 100644 --- a/include/Engine/Core/Octree.h +++ b/include/Engine/Core/Octree.h @@ -5,9 +5,7 @@ #include "../Common.h" #include "AABB.h" - -//Fwd declarations. -class Ray; +#include "Ray.h" namespace OctSpace { diff --git a/include/Engine/Core/System.h b/include/Engine/Core/System.h index e21d8c7e..43438fd5 100644 --- a/include/Engine/Core/System.h +++ b/include/Engine/Core/System.h @@ -68,7 +68,7 @@ protected: const std::string m_ComponentType; - virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& cComponent, double dt) = 0; + virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& cPlayer, double dt) = 0; }; class ImpureSystem : public virtual System diff --git a/include/Game/Systems/WeaponSystem.h b/include/Game/Systems/WeaponSystem.h index fccb1b0b..489048b8 100644 --- a/include/Game/Systems/WeaponSystem.h +++ b/include/Game/Systems/WeaponSystem.h @@ -13,17 +13,23 @@ #include "Input/EInputCommand.h" #include "Core/EntityFile.h" #include "Core/EntityFileParser.h" +#include "Core/Octree.h" +#include "Collision/EntityAABB.h" + +class WeaponBehaviour; class WeaponSystem : public PureSystem, ImpureSystem { public: - WeaponSystem(SystemParams params, IRenderer* renderer); + WeaponSystem(SystemParams params, IRenderer* renderer, Octree* collisionOctree); virtual void Update(double dt) override; - virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& cComponent, double dt) override; + virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& cPlayer, double dt) override; private: + SystemParams m_SystemParams; IRenderer* m_Renderer; + Octree* m_CollisionOctree; std::unordered_map> m_ActiveWeapons; @@ -38,12 +44,18 @@ private: void selectWeapon(EntityWrapper player, ComponentInfo::EnumType slot); }; -class WeaponBehaviour +class WeaponBehaviour : protected System { public: - WeaponBehaviour(EntityWrapper weaponEntity) - : m_Entity(weaponEntity) + WeaponBehaviour(SystemParams systemParams, Octree* collisionOctree, EntityWrapper weaponEntity) + : System(systemParams) + , m_CollisionOctree(collisionOctree) + , m_Entity(weaponEntity) { } + virtual ~WeaponBehaviour() = default; + + WeaponBehaviour(const WeaponBehaviour&) = delete; + WeaponBehaviour& operator=(const WeaponBehaviour &) = delete; virtual void Fire() = 0; virtual void CeaseFire() { } @@ -51,15 +63,19 @@ public: virtual void Update(double dt) { } protected: + Octree* m_CollisionOctree; EntityWrapper m_Entity; }; class AssaultWeaponBehaviour : public WeaponBehaviour { public: - AssaultWeaponBehaviour(EntityWrapper weaponEntity) - : WeaponBehaviour(weaponEntity) - { } + AssaultWeaponBehaviour(SystemParams systemParams, Octree* collisionOctree, EntityWrapper weaponEntity) + : WeaponBehaviour(systemParams, collisionOctree, weaponEntity) + { + m_RayRed = ResourceManager::Load("Schema/Entities/RayRed.xml"); + m_RayBlue = ResourceManager::Load("Schema/Entities/RayBlue.xml"); + } virtual void Fire() override { @@ -73,6 +89,25 @@ public: m_Firing = false; } + virtual void Reload() override + { + ComponentWrapper& cAssaultWeapon = m_Entity["AssaultWeapon"]; + + int& magAmmo = cAssaultWeapon["MagazineAmmo"]; + int magSize = cAssaultWeapon["MagazineSize"]; + int& ammo = cAssaultWeapon["Ammo"]; + + // Don't reload if we're already fully loaded + if (magAmmo == magSize) { + return; + } + + // Throw away rounds in magazine to incentivise ammo sharing + int toLoad = glm::min(magSize, ammo); + magAmmo = toLoad; + ammo -= toLoad; + } + virtual void Update(double dt) override { if (!m_Firing) { @@ -82,7 +117,7 @@ public: m_TimeSinceLastFire += dt; ComponentWrapper& cAssaultWeapon = m_Entity["AssaultWeapon"]; - if (m_TimeSinceLastFire > (double)cAssaultWeapon["RPM"] / 60.0) { + if (m_TimeSinceLastFire >= 1.0 / ((double)cAssaultWeapon["RPM"] / 60.0)) { fireRound(); } } @@ -90,7 +125,8 @@ public: private: bool m_Firing = false; double m_TimeSinceLastFire = 0.0; - ComponentWrapper m_Component; + EntityFile* m_RayRed = nullptr; + EntityFile* m_RayBlue = nullptr; void fireRound() { @@ -99,18 +135,85 @@ private: int& magAmmo = cAssaultWeapon["MagazineAmmo"]; int ammo = cAssaultWeapon["Ammo"]; - // Reload if our magazine is empty and we have ammo to fill it with - if (magAmmo <= 0 && ammo > 0) { - CeaseFire(); + // Reload if our magazine is empty + if (magAmmo <= 0) { Reload(); return; } // Fire magAmmo -= 1; + spawnTracer(); m_TimeSinceLastFire = 0.0; } + + void spawnTracer() + { + ComponentWrapper cTeam = m_Entity["Team"]; + ComponentInfo::EnumType team = cTeam["Team"]; + + // Select the right color of effect + EntityFile* rayFile = nullptr; + if (team == cTeam["Team"].Enum("Red")) { + rayFile = m_RayRed; + } + if (team == cTeam["Team"].Enum("Blue")) { + rayFile = m_RayBlue; + } + if (rayFile == nullptr) { + return; + } + + // Create the entity + EntityFileParser parser(rayFile); + EntityID rayID = parser.MergeEntities(m_World); + EntityWrapper ray(m_World, rayID); + + // Figure out where to put it + EntityWrapper attachment; + if (m_Entity == LocalPlayer || true) { + // Spawn the effect from the weapon view model for the local player + attachment = m_Entity.FirstChildByName("WeaponMuzzle"); + } + // TODO: Spawn the effect from the weapon world model once it exists + + glm::mat4 transformation = Transform::AbsoluteTransformation(attachment); + glm::vec3 _scale; + glm::vec3 translation; + glm::quat _orientation; + glm::vec3 _skew; + glm::vec4 _perspective; + glm::decompose(transformation, _scale, _orientation, translation, _skew, _perspective); + + // Matrix to euler angles + glm::vec3 euler; + euler.y = glm::asin(-transformation[0][2]); + if (cos(euler.y) != 0) { + euler.x = atan2(transformation[1][2], transformation[2][2]); + euler.z = atan2(transformation[0][1], transformation[0][0]); + } else { + euler.x = atan2(-transformation[2][0], transformation[1][1]); + euler.z = 0; + } + + // TODO: Spread? + + (glm::vec3&)ray["Transform"]["Position"] = translation; + (glm::vec3&)ray["Transform"]["Orientation"] = euler; + glm::vec3& scale = ray["Transform"]["Scale"]; + scale.z = traceRayDistance(translation, glm::quat(euler) * glm::vec3(0.f, 0.f, -1.f)); + } + + float traceRayDistance(glm::vec3 origin, glm::vec3 direction) + { + OctSpace::Output result; + if (m_CollisionOctree->RayCollides(Ray(origin, direction), result)) { + return result.CollideDistance; + } else { + return 0.f; + } + } }; #endif \ No newline at end of file diff --git a/resources/Schema/Components/AssaultWeapon.xml b/resources/Schema/Components/AssaultWeapon.xml index 8dc2a50a..902795c1 100755 --- a/resources/Schema/Components/AssaultWeapon.xml +++ b/resources/Schema/Components/AssaultWeapon.xml @@ -4,5 +4,6 @@ 32 360 360 - 40 + 5 + 120 \ No newline at end of file diff --git a/resources/Schema/Components/AssaultWeapon.xsd b/resources/Schema/Components/AssaultWeapon.xsd index 167fee18..1b2704ea 100755 --- a/resources/Schema/Components/AssaultWeapon.xsd +++ b/resources/Schema/Components/AssaultWeapon.xsd @@ -18,6 +18,7 @@ Maximum ammo able to be carried + Rate of fire in rounds per minute diff --git a/resources/Schema/Entities/Player.xml b/resources/Schema/Entities/Player.xml index e9fa0be3..b13082e7 100644 --- a/resources/Schema/Entities/Player.xml +++ b/resources/Schema/Entities/Player.xml @@ -6,6 +6,9 @@ + + 600 + 2 @@ -118,7 +121,7 @@ - + @@ -145,7 +148,7 @@ Hold Pos - + 1 diff --git a/src/Engine/Core/EntityWrapper.cpp b/src/Engine/Core/EntityWrapper.cpp index 071329a3..be7b96a8 100644 --- a/src/Engine/Core/EntityWrapper.cpp +++ b/src/Engine/Core/EntityWrapper.cpp @@ -54,7 +54,7 @@ bool EntityWrapper::IsChildOf(EntityWrapper potentialParent) return false; } -bool EntityWrapper::Valid() +bool EntityWrapper::Valid() const { if (this->World == nullptr) { return false; @@ -65,7 +65,6 @@ bool EntityWrapper::Valid() } if (!this->World->ValidEntity(this->ID)) { - this->ID = EntityID_Invalid; return false; } diff --git a/src/Engine/Core/EventBroker.cpp b/src/Engine/Core/EventBroker.cpp index d847e1a2..ef4d138d 100644 --- a/src/Engine/Core/EventBroker.cpp +++ b/src/Engine/Core/EventBroker.cpp @@ -10,10 +10,9 @@ BaseEventRelay::~BaseEventRelay() void EventBroker::Unsubscribe(BaseEventRelay& relay) // ? { auto identifier = std::make_tuple(relay.m_EventID, relay.m_ContextTypeName, relay.m_EventTypeName); - relay.m_Broker = nullptr; if (m_IsProcessing) { - m_RelaysToUnsubscribe.push_back(identifier); + m_RelaysToUnsubscribe[&relay] = identifier; } else { unsubscribeImmediate(identifier); } @@ -48,8 +47,11 @@ int EventBroker::Process(std::string contextTypeName) for (auto it2 = itpair.first; it2 != itpair.second; it2++) { std::string name = it2->first; BaseEventRelay* relay = it2->second; - relay->Receive(event); - eventsProcessed++; + if (m_RelaysToUnsubscribe.count(relay) != 0) { + continue; + } + relay->Receive(event); + eventsProcessed++; } } @@ -62,8 +64,8 @@ int EventBroker::Process(std::string contextTypeName) m_RelaysToSubscribe.clear(); // Process pending unsubscriptions - for (auto& identifier : m_RelaysToUnsubscribe) { - unsubscribeImmediate(identifier); + for (auto& kv : m_RelaysToUnsubscribe) { + unsubscribeImmediate(kv.second); } m_RelaysToUnsubscribe.clear(); diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index ce782ece..47170764 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -103,7 +103,7 @@ Game::Game(int argc, char* argv[]) m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); - m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer); + m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer, m_OctreeCollision); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); // Populate Octree with collidables diff --git a/src/Game/Systems/PlayerSpawnSystem.cpp b/src/Game/Systems/PlayerSpawnSystem.cpp index fa713675..b7a3d91b 100644 --- a/src/Game/Systems/PlayerSpawnSystem.cpp +++ b/src/Game/Systems/PlayerSpawnSystem.cpp @@ -71,6 +71,9 @@ bool PlayerSpawnSystem::OnInputCommand(const Events::InputCommand& e) bool PlayerSpawnSystem::OnPlayerSpawned(Events::PlayerSpawned& e) { // When a player is actually spawned (since the actual spawning is handled on the server) + if (!IsClient) { + return false; + } // Check if a player already exists if (m_PlayerEntities.count(e.PlayerID) != 0) { diff --git a/src/Game/Systems/WeaponSystem.cpp b/src/Game/Systems/WeaponSystem.cpp index fe0f066f..dfb84581 100644 --- a/src/Game/Systems/WeaponSystem.cpp +++ b/src/Game/Systems/WeaponSystem.cpp @@ -1,13 +1,15 @@ #include "Systems/WeaponSystem.h" -WeaponSystem::WeaponSystem(SystemParams params, IRenderer* renderer) +WeaponSystem::WeaponSystem(SystemParams params, IRenderer* renderer, Octree* collisionOctree) : System(params) , PureSystem("Player") - , ImpureSystem() + , m_SystemParams(params) , m_Renderer(renderer) + , m_CollisionOctree(collisionOctree) { EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &WeaponSystem::OnInputCommand); EVENT_SUBSCRIBE_MEMBER(m_EShoot, &WeaponSystem::OnShoot); + EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &WeaponSystem::OnPlayerSpawned); } void WeaponSystem::Update(double dt) @@ -15,41 +17,48 @@ void WeaponSystem::Update(double dt) } -void WeaponSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& cComponent, double dt) +void WeaponSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& cPlayer, double dt) { - + // Update potential weapon behaviour for player + //auto it = m_ActiveWeapons.find(entity); + //if (it != m_ActiveWeapons.end()) { + // //if (it->first.Valid()) { + // it->second->Update(dt); + // //} else { + // // m_ActiveWeapons.erase(it); + // //} + //} } bool WeaponSystem::OnInputCommand(Events::InputCommand& e) { + EntityWrapper player = e.Player; + if (e.PlayerID == -1) { + player = LocalPlayer; + } + // Make sure player is alive - if (!e.Player.Valid()) { + if (!player.Valid()) { return false; } // Weapon selection if (e.Command == "SelectWeapon") { - selectWeapon(e.Player, static_cast(e.Value)); - } - - // Only shoot client-side! - if (!IsClient) { - return false; - } - - // Only shoot if the player is alive - if (!e.Player.Valid()) { - return false; - } - - if (e.Command == "PrimaryFire" && e.Value > 0) { - Events::Shoot eShoot; - if (e.PlayerID == -1) { - eShoot.Player = LocalPlayer; - } else { - eShoot.Player = e.Player; + if (e.Value != 0) { + selectWeapon(player, static_cast(e.Value)); + } + } + + // Fire + if (e.Command == "PrimaryFire") { + if (m_ActiveWeapons.find(player) != m_ActiveWeapons.end()) { + auto weapon = m_ActiveWeapons.at(player); + if (e.Value > 0) { + weapon->Fire(); + } else { + weapon->CeaseFire(); + } } - m_EventBroker->Publish(eShoot); } return true; @@ -60,7 +69,11 @@ void WeaponSystem::selectWeapon(EntityWrapper player, ComponentInfo::EnumType sl // Primary if (slot == 1) { // TODO: if class... - m_ActiveWeapons[player] = std::make_shared(); + if (m_ActiveWeapons.count(player) == 0) { + m_ActiveWeapons.insert(std::make_pair(player, std::make_shared(m_SystemParams, m_CollisionOctree, player))); + } else { + m_ActiveWeapons.erase(player); + } } // Secondary @@ -83,49 +96,6 @@ bool WeaponSystem::OnShoot(Events::Shoot& eShoot) return false; } - // TODO: Weapon firing effects here - - auto rayRed = ResourceManager::Load("Schema/Entities/RayRed.xml"); - auto rayBlue = ResourceManager::Load("Schema/Entities/RayBlue.xml"); - - EntityWrapper weapon = eShoot.Player.FirstChildByName("WeaponMuzzle"); - if (weapon.Valid()) { - EntityWrapper ray; - if ((ComponentInfo::EnumType)eShoot.Player["Team"]["Team"] == eShoot.Player["Team"]["Team"].Enum("Red")) { - EntityFileParser parser(rayRed); - EntityID rayID = parser.MergeEntities(m_World); - ray = EntityWrapper(m_World, rayID); - } else { - EntityFileParser parser(rayBlue); - EntityID rayID = parser.MergeEntities(m_World); - ray = EntityWrapper(m_World, rayID); - } - - glm::mat4 transformation = Transform::AbsoluteTransformation(weapon); - glm::vec3 scale; - glm::vec3 translation; - glm::quat orientation; - glm::vec3 skew; - glm::vec4 perspective; - glm::decompose(transformation, scale, orientation, translation, skew, perspective); - - // Matrix to euler angles - glm::vec3 euler; - euler.y = glm::asin(-transformation[0][2]); - if (cos(euler.y) != 0) { - euler.x = atan2(transformation[1][2], transformation[2][2]); - euler.z = atan2(transformation[0][1], transformation[0][0]); - } else { - euler.x = atan2(-transformation[2][0], transformation[1][1]); - euler.z = 0; - } - - //LOG_DEBUG("rotation: %f %f %f", euler.x, euler.y, euler.z); - (glm::vec3&)ray["Transform"]["Position"] = translation; - (glm::vec3&)ray["Transform"]["Orientation"] = euler; - //(glm::vec3&)ray["Transform"]["Orientation"] = Transform::AbsoluteOrientationEuler(weapon); - } - // Only run further picking code for the local player! if (eShoot.Player != LocalPlayer) { return false; From f3a76eb13e2e70d9774a77f95119c0d32df0b4fc Mon Sep 17 00:00:00 2001 From: William Moberg Date: Wed, 10 Feb 2016 15:00:13 +0100 Subject: [PATCH 166/355] Explosion effects should get a proper sized AABB. --- include/Engine/Collision/Collision.h | 1 + src/Engine/Collision/Collision.cpp | 26 +++++++++++++++++++ .../Collision/FillFrustumOctreeSystem.cpp | 16 +++++------- 3 files changed, 34 insertions(+), 9 deletions(-) diff --git a/include/Engine/Collision/Collision.h b/include/Engine/Collision/Collision.h index 6e4858b2..8137ceef 100644 --- a/include/Engine/Collision/Collision.h +++ b/include/Engine/Collision/Collision.h @@ -80,6 +80,7 @@ bool AABBVsAABB(const AABB& a, const AABB& b, glm::vec3& minimumTranslation); // Calculates an absolute AABB from an entity AABB component boost::optional EntityAbsoluteAABB(EntityWrapper& entity); +boost::optional AbsoluteAABBExplosionEffect(EntityWrapper& entity); } diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index c0c27190..d82ec3fb 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -612,4 +612,30 @@ boost::optional EntityAbsoluteAABB(EntityWrapper& entity) return aabb; } +boost::optional AbsoluteAABBExplosionEffect(EntityWrapper& entity) +{ + boost::optional modelBox = EntityAbsoluteAABB(entity); + if (!modelBox) { + return boost::none; + } + bool isRandom = (bool)entity["ExplosionEffect"]["Randomness"]; + float random = isRandom ? (float)(double)entity["ExplosionEffect"]["RandomnessScalar"] : 0; + glm::vec3 origin = (glm::vec3)entity["ExplosionEffect"]["ExplosionOrigin"]; + glm::vec3 randomVel = (glm::vec3)entity["ExplosionEffect"]["Velocity"]; + randomVel *= (random + 1); + float endVelocity = randomVel.y; + if ((bool)entity["ExplosionEffect"]["ExponentialAccelaration"]) { + endVelocity *= endVelocity / 2.f; + } + float maxRadius = (float)(double)entity["ExplosionEffect"]["ExplosionDuration"] * endVelocity; + glm::vec3 size; + AABB explosionBox(origin - (size / 2.f), origin + (size / 2.f)); + + glm::vec3 mini = glm::min(explosionBox.MinCorner(), (*modelBox).MinCorner()); + glm::vec3 maxi = glm::max(explosionBox.MaxCorner(), (*modelBox).MaxCorner()); + EntityAABB aabb = AABB(mini, maxi); + aabb.Entity = entity; + return aabb; +} + } diff --git a/src/Engine/Collision/FillFrustumOctreeSystem.cpp b/src/Engine/Collision/FillFrustumOctreeSystem.cpp index f02a30f1..a8835266 100644 --- a/src/Engine/Collision/FillFrustumOctreeSystem.cpp +++ b/src/Engine/Collision/FillFrustumOctreeSystem.cpp @@ -7,15 +7,13 @@ void FillFrustumOctreeSystem::Update(double dt) void FillFrustumOctreeSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) { + boost::optional absoluteAABB; if (entity.HasComponent("ExplosionEffect")) { - //TODO: Fix hack, get real box by using shader equation. - EntityAABB aabb = AABB(glm::vec3(-300), glm::vec3(300)); - aabb.Entity = entity; - m_Octree->AddDynamicObject(aabb); + absoluteAABB = Collision::AbsoluteAABBExplosionEffect(entity); } else { - boost::optional absoluteAABB = Collision::EntityAbsoluteAABB(entity); - if (absoluteAABB) { - m_Octree->AddDynamicObject(*absoluteAABB); - } + absoluteAABB = Collision::EntityAbsoluteAABB(entity); } -} \ No newline at end of file + if (absoluteAABB) { + m_Octree->AddDynamicObject(*absoluteAABB); + } +} From 646806b50e3ed8f3f54c35664f54a82ee0b15bcb Mon Sep 17 00:00:00 2001 From: antc13 Date: Wed, 10 Feb 2016 15:40:59 +0100 Subject: [PATCH 167/355] New Map with meshes WIP --- assets | 2 +- resources/Schema/Entities/NewMap.xml | 2396 ++++++++++++++++++++++++++ 2 files changed, 2397 insertions(+), 1 deletion(-) create mode 100644 resources/Schema/Entities/NewMap.xml diff --git a/assets b/assets index 7531e441..e0ad8b8d 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit 7531e441fea639076d69c6cf05e3ae8ff7170cf9 +Subproject commit e0ad8b8d45a79b8f17876f9541cc5e03758ae16c diff --git a/resources/Schema/Entities/NewMap.xml b/resources/Schema/Entities/NewMap.xml new file mode 100644 index 00000000..a79fee7b --- /dev/null +++ b/resources/Schema/Entities/NewMap.xml @@ -0,0 +1,2396 @@ + + + + + + + + + + + + + + + + + + Models/Props/Ground.mesh + + + + + + + + + Models/Props/Highground1.mesh + + + + + + + + + + Models/Props/Highground2.mesh + + + + + + + + + + Models/Props/Highground1.mesh + + + + + + + + + + + + Models/Props/Highground2.mesh + + + + + + + + + + + + Models/Props/Highground3.mesh + + + + + + + + + + Models/Props/Highground4.mesh + + + + + + + + + + Models/Props/Highground5.mesh + + + + + + + + + + Models/Props/Highground6.mesh + + + + + + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar1.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar1.mesh + + + + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar2.mesh + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar3.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar1.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar1.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar3.mesh + + + + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar2.mesh + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar2.mesh + + + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + + + + Models/Props/Walls/SmallWall3.mesh + + + + + + + + + + + + + Models/Props/Walls/SmallWall3.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall3.mesh + + + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + + Models/Props/Walls/SmallWall4.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall3.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + + Models/Props/Walls/MediumWall2.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall2.mesh + + + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall3.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall3.mesh + + + + + + + + + + + + + Models/Props/Walls/SmallWall4.mesh + + + + + + + + + + + + + + Models/Props/Walls/SmallWall4.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + + + + + + + + + + Models/Props/Bridges/WoodenBridge.mesh + + + + + + + + + + + + + + Models/Props/Bridges/WoodenBridge.mesh + + + + + + + + + + + + + + Models/Props/Bridges/WoodenBridge.mesh + + + + + + + + + + + + + Models/Props/Bridges/SciFiBridge.mesh + + + + + + + + + + + + + + Models/Props/Bridges/SciFiBridge.mesh + + + + + + + + + + + + + + Models/Props/Flora/TreeLog.mesh + + + + + + + + + + + + + + + + + + + + + Models/Props/Pillars/SciFiBridgePillar1.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiBridgePillar1.mesh + + + + + + + + + + + + + + Models/Props/Walls/MediumWall2.mesh + + + + + + + + + + + Models/Props/Walls/MediumWall2.mesh + + + + + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiBridgePillar1.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + + + Models/Props/Flora/TreeLog.mesh + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + + + + + + + + + + Models/Props/PickUps/PickUpHolder.mesh + + + + + + + + + + + + + + Models/Props/PickUps/PickUpHolder.mesh + + + + + + + + + + + + + + Models/Props/PickUps/PickUpHolder.mesh + + + + + + + + + + + + + + Models/Props/PickUps/PickUpHolder.mesh + + + + + + + + + + + + + Models/Props/PickUps/PickUpHolder.mesh + + + + + + + + + + + + + + Models/Props/PickUps/PickUpHolder.mesh + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Models/Props/CapturePoint.mesh + + + + + + + + + + + + + + + + + + + 1 + + + Models/Props/CapturePoint.mesh + + + + + + + + + + + + + + + 2 + + + Models/Props/CapturePoint.mesh + + + + + + + + + + + + + + 3 + + + Models/Props/CapturePoint.mesh + + + + + + + + + + + + + + + + + + 4 + + + Models/Props/CapturePoint.mesh + + + + + + + + + + + + + + + + + + + + + + + + + 1 + + + + + + + + + 10 + + + + + + + + + + 10 + + + + + + + + + + + + + 10 + + + + + + + + + + + 10 + + + + + + + + + + + 10 + + + + + + + + + + + 1 + + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + + + + + + + + + + From 27cdccac75b2564839609072ec8f02ed8ad9c576 Mon Sep 17 00:00:00 2001 From: William Moberg Date: Wed, 10 Feb 2016 16:10:41 +0100 Subject: [PATCH 168/355] Frustrum octree should only get AABBs derived from Model now. --- include/Engine/Collision/Collision.h | 2 +- src/Engine/Collision/Collision.cpp | 6 +++--- src/Engine/Collision/FillFrustumOctreeSystem.cpp | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/include/Engine/Collision/Collision.h b/include/Engine/Collision/Collision.h index 86f397f7..c3759393 100644 --- a/include/Engine/Collision/Collision.h +++ b/include/Engine/Collision/Collision.h @@ -79,7 +79,7 @@ bool AABBVsAABB(const AABB& a, const AABB& b); bool AABBVsAABB(const AABB& a, const AABB& b, glm::vec3& minimumTranslation); // Calculates an absolute AABB from an entity AABB component -boost::optional EntityAbsoluteAABB(EntityWrapper& entity); +boost::optional EntityAbsoluteAABB(EntityWrapper& entity, bool takeModelBox = false); boost::optional AbsoluteAABBExplosionEffect(EntityWrapper& entity); } diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index 07080caf..b7b21969 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -565,10 +565,10 @@ bool AABBvsTriangles(const AABB& box, return hit; } -boost::optional EntityAbsoluteAABB(EntityWrapper& entity) +boost::optional EntityAbsoluteAABB(EntityWrapper& entity, bool takeModelBox) { AABB modelSpaceBox; - if (entity.HasComponent("AABB")) { + if (entity.HasComponent("AABB") && !takeModelBox) { ComponentWrapper& cAABB = entity["AABB"]; modelSpaceBox = EntityAABB::FromOriginSize((glm::vec3)cAABB["Origin"], (glm::vec3)cAABB["Size"]); } else if (entity.HasComponent("Model")) { @@ -614,7 +614,7 @@ boost::optional EntityAbsoluteAABB(EntityWrapper& entity) boost::optional AbsoluteAABBExplosionEffect(EntityWrapper& entity) { - boost::optional modelBox = EntityAbsoluteAABB(entity); + boost::optional modelBox = EntityAbsoluteAABB(entity, true); if (!modelBox) { return boost::none; } diff --git a/src/Engine/Collision/FillFrustumOctreeSystem.cpp b/src/Engine/Collision/FillFrustumOctreeSystem.cpp index a8835266..2be8bee0 100644 --- a/src/Engine/Collision/FillFrustumOctreeSystem.cpp +++ b/src/Engine/Collision/FillFrustumOctreeSystem.cpp @@ -11,7 +11,7 @@ void FillFrustumOctreeSystem::UpdateComponent(EntityWrapper& entity, ComponentWr if (entity.HasComponent("ExplosionEffect")) { absoluteAABB = Collision::AbsoluteAABBExplosionEffect(entity); } else { - absoluteAABB = Collision::EntityAbsoluteAABB(entity); + absoluteAABB = Collision::EntityAbsoluteAABB(entity, true); } if (absoluteAABB) { m_Octree->AddDynamicObject(*absoluteAABB); From 4f2ad3ad00ab561cb241be49812f757d00416b2b Mon Sep 17 00:00:00 2001 From: Jocke Date: Wed, 10 Feb 2016 16:16:56 +0100 Subject: [PATCH 169/355] Reliable message should now be working, further testing is to be done. --- include/Engine/Network/Client.h | 8 +- include/Engine/Network/PlayerDefinition.h | 4 +- include/Engine/Network/Server.h | 13 +- src/Engine/Network/Client.cpp | 62 ++++++-- src/Engine/Network/Packet.cpp | 7 +- src/Engine/Network/Server.cpp | 165 ++++++++++++---------- src/Engine/Network/TCPServer.cpp | 9 +- src/Engine/Network/UDPClient.cpp | 4 - src/Engine/Network/UDPServer.cpp | 1 - 9 files changed, 160 insertions(+), 113 deletions(-) diff --git a/include/Engine/Network/Client.h b/include/Engine/Network/Client.h index ffdf812f..d1530b0e 100644 --- a/include/Engine/Network/Client.h +++ b/include/Engine/Network/Client.h @@ -70,7 +70,8 @@ protected: void disconnect(); void parseMessageType(Packet& packet); void updateFields(Packet& packet, const ComponentInfo& componentInfo, const EntityID& entityID, const std::string& componentType); - void parseConnect(Packet& packet); + void parseUDPConnect(Packet& packet); + void parseTCPConnect(Packet& packet); void parsePlayerConnected(Packet& packet); void parsePing(); void parseKick(); @@ -103,9 +104,8 @@ protected: bool OnPlayerSpawned(const Events::PlayerSpawned& e); private: - UDPClient m_UDPClient; - //TCPClient m_TCPClient; - //TCPClient m_UDPClient; + UDPClient m_Unreliable; + TCPClient m_Reliable; }; #endif diff --git a/include/Engine/Network/PlayerDefinition.h b/include/Engine/Network/PlayerDefinition.h index e4c3e5c5..afd5d889 100644 --- a/include/Engine/Network/PlayerDefinition.h +++ b/include/Engine/Network/PlayerDefinition.h @@ -10,8 +10,8 @@ struct PlayerDefinition { boost::asio::ip::udp::endpoint Endpoint; unsigned int PacketID; std::clock_t StopTime; - boost::asio::ip::address Address; - unsigned short Port; + boost::asio::ip::address TCPAddress; + unsigned short TCPPort; // use for tcp connections boost::shared_ptr TCPSocket; }; diff --git a/include/Engine/Network/Server.h b/include/Engine/Network/Server.h index 1b2e6956..7386e43d 100644 --- a/include/Engine/Network/Server.h +++ b/include/Engine/Network/Server.h @@ -59,7 +59,8 @@ protected: // Private member functions //int receive(char* data); - void broadcast(Packet& packet); + void reliableBroadcast(Packet& packet); + void unreliableBroadcast(Packet& packet); void sendSnapshot(); void addChildrenToPacket(Packet& packet, EntityID entityID); void sendPing(); @@ -74,13 +75,9 @@ protected: void parseOnInputCommand(Packet& packet); void parseClientPing(); void parsePing(); - void parseConnect(Packet & packet, PlayerDefinition & pd); + void parseUDPConnect(Packet & packet); void parseTCPConnect(Packet & packet); void parseDisconnect(); - //// Pure virtual functions - //virtual void readFromClients() = 0; - //virtual void send(Packet& packet, PlayerDefinition & playerDefinition) = 0; - //virtual void send(Packet& packet) = 0; // Debug event EventRelay m_EInputCommand; @@ -92,8 +89,8 @@ protected: EventRelay m_EComponentDeleted; bool OnComponentDeleted(const Events::ComponentDeleted& e); private: - //TCPServer m_TCPServer; - UDPServer m_UDPServer; + TCPServer m_Reliable; + UDPServer m_Unreliable; }; #endif diff --git a/src/Engine/Network/Client.cpp b/src/Engine/Network/Client.cpp index eaacac47..ba528f27 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -34,11 +34,27 @@ void Client::Start(World* world, EventBroker* eventBroker) void Client::Update() { m_EventBroker->Process(); - while (m_UDPClient.IsSocketAvailable()) { + while (m_Unreliable.IsSocketAvailable()) { // Packet will get real data in receive Packet packet(MessageType::Invalid); - m_UDPClient.Receive(packet); - parseMessageType(packet); + m_Unreliable.Receive(packet); + if (packet.GetMessageType() == MessageType::Connect) { + parseUDPConnect(packet); + } else { + parseMessageType(packet); + } + } + + while (m_Reliable.IsSocketAvailable()) { + // Packet will get real data in receive + Packet packet(MessageType::Invalid); + m_Reliable.Receive(packet); + if (packet.GetMessageType() == MessageType::Connect) { + parseTCPConnect(packet); + } else { + parseMessageType(packet); + } + } if (m_IsConnected) { @@ -67,9 +83,6 @@ void Client::parseMessageType(Packet& packet) //identifyPacketLoss(); switch (static_cast(messageType)) { - case MessageType::Connect: - parseConnect(packet); - break; case MessageType::Ping: parsePing(); break; @@ -100,12 +113,32 @@ void Client::parseMessageType(Packet& packet) } } -void Client::parseConnect(Packet& packet) +void Client::parseUDPConnect(Packet& packet) { // Map ServerEntityID and your PlayerID 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 messageType = packet.ReadPrimitive(); + // Read packet ID + m_PreviousPacketID = m_PacketID; // Set previous packet id + m_PacketID = packet.ReadPrimitive(); //Read new packet id + // parse player id and other stuff + m_PlayerID = packet.ReadPrimitive(); + m_PlayerID = packet.ReadPrimitive(); + LOG_INFO("A Player connected"); + Packet UnreliablePacket(MessageType::Connect, m_SendPacketID); + // Add player id and other stuff + packet.WritePrimitive(m_PlayerID); + m_Unreliable.Send(packet); + LOG_INFO("Sent UDP Connect Server"); +} + void Client::parsePlayerConnected(Packet & packet) { // Map ServerEntityID and other player's PlayerID @@ -123,7 +156,7 @@ void Client::parsePing() Packet packet(MessageType::Ping, m_SendPacketID); packet.WriteString("Ping recieved"); - m_UDPClient.Send(packet); + m_Reliable.Send(packet); } void Client::parseKick() @@ -255,14 +288,15 @@ void Client::disconnect() m_PreviousPacketID = 0; m_PacketID = 0; Packet packet(MessageType::Disconnect, m_SendPacketID); - m_UDPClient.Send(packet); + m_Reliable.Send(packet); } bool Client::OnInputCommand(const Events::InputCommand & e) { if (e.Command == "ConnectToServer") { // Connect for now if (e.Value > 0) { - m_UDPClient.Connect(m_PlayerName, address, port); + m_Reliable.Connect(m_PlayerName, address, port); + m_Unreliable.Connect(m_PlayerName, address, port); } //LOG_DEBUG("Client::OnInputCommand: Command is %s. Value is %f. PlayerID is %i.", e.Command.c_str(), e.Value, e.PlayerID); return true; @@ -299,7 +333,7 @@ bool Client::OnPlayerDamage(const Events::PlayerDamage & e) Packet packet(MessageType::OnPlayerDamage, m_SendPacketID); packet.WritePrimitive(e.Damage); packet.WritePrimitive(m_ClientIDToServerID.at(e.Player.ID)); - m_UDPClient.Send(packet); + m_Reliable.Send(packet); return false; } @@ -327,7 +361,7 @@ void Client::sendLocalPlayerTransform() packet.WritePrimitive(orientation.x); packet.WritePrimitive(orientation.y); packet.WritePrimitive(orientation.z); - m_UDPClient.Send(packet); + m_Unreliable.Send(packet); } void Client::identifyPacketLoss() @@ -370,7 +404,7 @@ void Client::sendInputCommands() packet.WriteString(m_InputCommandBuffer[i].Command); packet.WritePrimitive(m_InputCommandBuffer[i].Value); } - m_UDPClient.Send(packet); + m_Reliable.Send(packet); m_InputCommandBuffer.clear(); } } @@ -378,7 +412,7 @@ void Client::sendInputCommands() void Client::becomePlayer() { Packet packet = Packet(MessageType::BecomePlayer, m_SendPacketID); - m_UDPClient.Send(packet); + m_Reliable.Send(packet); } bool Client::clientServerMapsHasEntity(EntityID clientEntityID) diff --git a/src/Engine/Network/Packet.cpp b/src/Engine/Network/Packet.cpp index c9e8832a..c99390bb 100644 --- a/src/Engine/Network/Packet.cpp +++ b/src/Engine/Network/Packet.cpp @@ -35,11 +35,11 @@ void Packet::Init(MessageType type, unsigned int & packetID) m_Offset = 0; // Create message header // allocate memory for size of packet(only used in tcp) - Packet::WritePrimitive(0); + WritePrimitive(0); // Add message type int messageType = static_cast(type); - Packet::WritePrimitive(messageType); - Packet::WritePrimitive(packetID); + WritePrimitive(messageType); + WritePrimitive(packetID); packetID++; m_HeaderSize = m_Offset; } @@ -98,6 +98,7 @@ void Packet::ReconstructFromData(char * data, int sizeOfData) void Packet::UpdateSize() { + int whatisoffset = m_Offset; memcpy(m_Data, &m_Offset, sizeof(int)); } diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index d3099e12..406abfb7 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -24,31 +24,31 @@ void Server::Start(World* world, EventBroker* eventBroker) void Server::Update() { PlayerDefinition pd; - - //m_TCPServer.AcceptNewConnections(m_NextPlayerID, m_ConnectedPlayers); - //for (auto& kv : m_ConnectedPlayers) { - // while (kv.second.TCPSocket->available()) { - // // Packet will get real data in receive - // Packet packet(MessageType::Invalid); - // m_TCPServer.Receive(packet, kv.second); - // m_Address = kv.second.TCPSocket->remote_endpoint().address(); - // m_Port = kv.second.TCPSocket->remote_endpoint().port(); - // if (packet.GetMessageType() == MessageType::Connect) { - // parseTCPConnect(packet); - // } else { - // parseMessageType(packet); - // } - // } - //} - while (m_UDPServer.IsSocketAvailable()) { + m_Reliable.AcceptNewConnections(m_NextPlayerID, m_ConnectedPlayers); + for (auto& kv : m_ConnectedPlayers) { + while (kv.second.TCPSocket->available()) { + // Packet will get real data in receive + Packet packet(MessageType::Invalid); + m_Reliable.Receive(packet, kv.second); + m_Address = kv.second.TCPSocket->remote_endpoint().address(); + m_Port = kv.second.TCPSocket->remote_endpoint().port(); + if (packet.GetMessageType() == MessageType::Connect) { + parseTCPConnect(packet); + } else { + parseMessageType(packet); + } + } + } + + while (m_Unreliable.IsSocketAvailable()) { // Packet will get real data in receive Packet packet(MessageType::Invalid); - m_UDPServer.Receive(packet, pd); + m_Unreliable.Receive(packet, pd); m_Address = pd.Endpoint.address(); m_Port = pd.Endpoint.port(); if (packet.GetMessageType() == MessageType::Connect) { - parseConnect(packet, pd); + parseUDPConnect(packet); } else { parseMessageType(packet); } @@ -115,11 +115,19 @@ void Server::parseMessageType(Packet& packet) } } -void Server::broadcast(Packet& packet) +void Server::reliableBroadcast(Packet& packet) { for (auto& kv : m_ConnectedPlayers) { packet.ChangePacketID(kv.second.PacketID); - m_UDPServer.Send(packet, kv.second); + m_Reliable.Send(packet, kv.second); + } +} + +void Server::unreliableBroadcast(Packet& packet) +{ + for (auto& kv : m_ConnectedPlayers) { + packet.ChangePacketID(kv.second.PacketID); + m_Unreliable.Send(packet, kv.second); } } @@ -128,7 +136,7 @@ void Server::sendSnapshot() { Packet packet(MessageType::Snapshot); addChildrenToPacket(packet, EntityID_Invalid); - broadcast(packet); + unreliableBroadcast(packet); } void Server::addChildrenToPacket(Packet & packet, EntityID entityID) @@ -189,7 +197,7 @@ void Server::sendPing() // Time message m_StartPingTime = std::clock(); // Send message - broadcast(packet); + reliableBroadcast(packet); } void Server::checkForTimeOuts() @@ -199,7 +207,7 @@ void Server::checkForTimeOuts() std::vector playersToRemove; for (auto& kv : m_ConnectedPlayers) { - if (kv.second.Address != boost::asio::ip::address()) { + if (kv.second.TCPAddress != boost::asio::ip::address()) { int stopPing = 1000 * kv.second.StopTime / static_cast(CLOCKS_PER_SEC); if (startPing > stopPing + m_TimeoutMs) { @@ -213,63 +221,71 @@ void Server::checkForTimeOuts() } } -void Server::parseConnect(Packet & packet, PlayerDefinition & pd) +void Server::parseUDPConnect(Packet & packet) { + // Pop size of message int + packet.ReadPrimitive(); + int messageType = packet.ReadPrimitive(); + // Read packet ID + m_PreviousPacketID = m_PacketID; // Set previous packet id + m_PacketID = packet.ReadPrimitive(); //Read new packet id + // parse player id and other stuff + PlayerID playerID = packet.ReadPrimitive(); + // 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::parseTCPConnect(Packet & packet) +{ + // Pop size of message int + packet.ReadPrimitive(); + int messageType = packet.ReadPrimitive(); + // Read packet ID + m_PreviousPacketID = m_PacketID; // Set previous packet id + m_PacketID = packet.ReadPrimitive(); //Read new packet id + LOG_INFO("Parsing connections"); // Check if player is already connected - if (GetPlayerIDFromEndpoint() != -1) { + // Ska vara till lagd i TCPServer receive + PlayerID playerID = GetPlayerIDFromEndpoint(); + if (playerID == -1) { return; } // Create a new player - pd.EntityID = 0; // Overlook this - pd.Address = pd.Endpoint.address(); - pd.Port = pd.Endpoint.port(); - pd.Name = packet.ReadString(); - pd.PacketID = 0; - pd.StopTime = std::clock(); - m_ConnectedPlayers[m_NextPlayerID++] = pd; - LOG_INFO("Spectator \"%s\" connected on IP: %s", pd.Name.c_str(), pd.Endpoint.address().to_string().c_str()); + m_ConnectedPlayers.at(playerID).EntityID = 0; // Overlook this + m_ConnectedPlayers.at(playerID).Name = packet.ReadString(); + m_ConnectedPlayers.at(playerID).PacketID = 0; + m_ConnectedPlayers.at(playerID).StopTime = std::clock(); + m_ConnectedPlayers.at(playerID).TCPAddress = m_Address; + m_ConnectedPlayers.at(playerID).TCPPort = m_Port; + + LOG_INFO("parseTCPConnect: Spectator \"%s\" connected on IP: %s", m_ConnectedPlayers.at(playerID).Name.c_str(), + m_ConnectedPlayers.at(playerID).TCPAddress); // Send a message to the player that connected - Packet connnectPacket(MessageType::Connect, pd.PacketID); - m_UDPServer.Send(connnectPacket); + Packet connnectPacket(MessageType::Connect, m_ConnectedPlayers.at(playerID).PacketID); + // Write playerID to packet + connnectPacket.WritePrimitive(playerID); + m_Reliable.Send(connnectPacket); // Send notification that a player has connected - Packet notificationPacket(MessageType::PlayerConnected); - broadcast(notificationPacket); + //Packet notificationPacket(MessageType::PlayerConnected); + //broadcast(notificationPacket); } -// -//void Server::parseTCPConnect(Packet & packet) -//{ -// LOG_INFO("Parsing connections"); -// // Check if player is already connected -// PlayerID playerID = GetPlayerIDFromEndpoint(); -// if (playerID = -1) { -// return; -// } -// // Create a new player -// m_ConnectedPlayers.at(playerID).EntityID = 0; // Overlook this -// m_ConnectedPlayers.at(playerID).Name = packet.ReadString(); -// m_ConnectedPlayers.at(playerID).PacketID = 0; -// m_ConnectedPlayers.at(playerID).StopTime = std::clock(); -// LOG_INFO("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_TCPServer.Send(connnectPacket); -// -// // Send notification that a player has connected -// Packet notificationPacket(MessageType::PlayerConnected); -// //broadcast(notificationPacket); -//} void Server::parseDisconnect() { LOG_INFO("%i: Parsing disconnect", m_PacketID); for (auto& kv : m_ConnectedPlayers) { - if (kv.second.Address == m_Address && - kv.second.Port == m_Port) { + if (kv.second.TCPAddress == m_Address && + kv.second.TCPPort == m_Port) { disconnect(kv.first); break; } @@ -311,7 +327,7 @@ void Server::kick(PlayerID player) { disconnect(player); Packet packet = Packet(MessageType::Kick); - m_UDPServer.Send(packet); + m_Reliable.Send(packet); } bool Server::OnInputCommand(const Events::InputCommand & e) @@ -340,7 +356,7 @@ bool Server::OnPlayerSpawned(const Events::PlayerSpawned & e) packet.WritePrimitive(e.Spawner.ID); // We don't send PlayerID here because it will always be set to -1 packet.WriteString(m_ConnectedPlayers[e.PlayerID].Name); - m_UDPServer.Send(packet, m_ConnectedPlayers[e.PlayerID]); + m_Reliable.Send(packet, m_ConnectedPlayers[e.PlayerID]); return false; } @@ -349,7 +365,7 @@ bool Server::OnEntityDeleted(const Events::EntityDeleted & e) if (!e.Cascaded) { Packet packet = Packet(MessageType::EntityDeleted); packet.WritePrimitive(e.DeletedEntity); - broadcast(packet); + reliableBroadcast(packet); } return false; } @@ -360,7 +376,7 @@ bool Server::OnComponentDeleted(const Events::ComponentDeleted & e) Packet packet = Packet(MessageType::ComponentDeleted); packet.WritePrimitive(e.Entity); packet.WriteString(e.ComponentType); - broadcast(packet); + reliableBroadcast(packet); } return false; } @@ -376,14 +392,14 @@ void Server::parseClientPing() // Return ping Packet packet(MessageType::Ping, m_ConnectedPlayers[player].PacketID); packet.WriteString("Ping received"); - m_UDPServer.Send(packet); + m_Reliable.Send(packet); } void Server::parsePing() { for (auto& kv : m_ConnectedPlayers) { - if (kv.second.Address == m_Address && - kv.second.Port == m_Port) { + if (kv.second.TCPAddress == m_Address && + kv.second.TCPPort == m_Port) { kv.second.StopTime = std::clock(); break; } @@ -430,9 +446,12 @@ void Server::parsePlayerTransform(Packet& packet) PlayerID Server::GetPlayerIDFromEndpoint() { + // check both tcp and udp connection for (auto& kv : m_ConnectedPlayers) { - if (kv.second.Address == m_Address && - kv.second.Port == m_Port) { + if ((kv.second.TCPAddress == m_Address + && kv.second.TCPPort == m_Port) + || (kv.second.Endpoint.address() == m_Address + && kv.second.Endpoint.port() == m_Port)) { return kv.first; } } diff --git a/src/Engine/Network/TCPServer.cpp b/src/Engine/Network/TCPServer.cpp index f8da15e2..0b44013d 100644 --- a/src/Engine/Network/TCPServer.cpp +++ b/src/Engine/Network/TCPServer.cpp @@ -23,8 +23,8 @@ PlayerID GetPlayerIDFromEndpoint(const std::map& con boost::asio::ip::address address, unsigned short port) { for (auto& kv : connectedPlayers) { - if (kv.second.Address == address && - kv.second.Port == port) { + if (kv.second.TCPAddress == address && + kv.second.TCPPort == port) { return kv.first; } } @@ -43,8 +43,8 @@ void TCPServer::handle_accept(boost::shared_ptr socket, PlayerDefinition pd; pd.StopTime = std::clock(); pd.TCPSocket = socket; - pd.Address = socket.get()->remote_endpoint().address(); - pd.Port = socket.get()->remote_endpoint().port(); + pd.TCPAddress = socket.get()->remote_endpoint().address(); + pd.TCPPort = socket.get()->remote_endpoint().port(); connectedPlayers[nextPlayerID++] = pd; } } @@ -78,6 +78,7 @@ void TCPServer::Receive(Packet & packet, PlayerDefinition & playerDefinition) if (bytesRead > 0) { packet.ReconstructFromData(m_ReadBuffer, bytesRead); } + lastReceivedSocket = playerDefinition.TCPSocket; } int TCPServer::readBuffer(char* data, PlayerDefinition & playerDefinition) diff --git a/src/Engine/Network/UDPClient.cpp b/src/Engine/Network/UDPClient.cpp index e5eafc08..c76de084 100644 --- a/src/Engine/Network/UDPClient.cpp +++ b/src/Engine/Network/UDPClient.cpp @@ -18,10 +18,6 @@ void 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(new boost::asio::ip::udp::socket(m_IOService)); m_Socket->connect(m_ReceiverEndpoint); - - Packet packet(MessageType::Connect, m_SendPacketID); - packet.WriteString(playerName); - Send(packet); } void UDPClient::Disconnect() diff --git a/src/Engine/Network/UDPServer.cpp b/src/Engine/Network/UDPServer.cpp index 6bf4e466..4b0a08ba 100644 --- a/src/Engine/Network/UDPServer.cpp +++ b/src/Engine/Network/UDPServer.cpp @@ -31,7 +31,6 @@ void UDPServer::Send(Packet & packet) 0); } - void UDPServer::Receive(Packet & packet, PlayerDefinition & playerDefinition) { int bytesRead = readBuffer(m_ReadBuffer); From 2d5f71e442270b416a9ec08f758a4135bea91e97 Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Wed, 10 Feb 2016 16:25:47 +0100 Subject: [PATCH 170/355] Added 3 PickupSpawnSystem tests. --- src/Tests/PickupSpawnTest.cpp | 205 ++++++++++++++++++++++++++++++++++ src/Tests/PickupSpawnTest.h | 73 ++++++++++++ 2 files changed, 278 insertions(+) create mode 100644 src/Tests/PickupSpawnTest.cpp create mode 100644 src/Tests/PickupSpawnTest.h diff --git a/src/Tests/PickupSpawnTest.cpp b/src/Tests/PickupSpawnTest.cpp new file mode 100644 index 00000000..ebddb71f --- /dev/null +++ b/src/Tests/PickupSpawnTest.cpp @@ -0,0 +1,205 @@ +#include +using boost::unit_test_framework::test_suite; +using boost::unit_test_framework::test_case; + +#include "PickupSpawnTest.h" + + +BOOST_AUTO_TEST_SUITE(PickupSpawnTestSuite) + +//dont use the same name as the classname in test cases... +BOOST_AUTO_TEST_CASE(PickupSpawnTest_HealthPickupRespawns_PlayerHealthPickupEventTriggers) +{ + PickupSpawnTest game(1); + bool success = game.Game_Loop_OneHundredTimes(); + BOOST_TEST(success); +} +BOOST_AUTO_TEST_CASE(PickupSpawnTest_APlayerAtMaxHealth_CantTakeHealthPickup) +{ + PickupSpawnTest game(2); + bool success = game.Game_Loop_OneHundredTimes(); + BOOST_TEST(success); +} +BOOST_AUTO_TEST_CASE(PickupSpawnTest_APickupCanRespawnSlowly) +{ + PickupSpawnTest game(3); + bool success = game.Game_Loop_OneHundredTimes(); + BOOST_TEST(success); +} +BOOST_AUTO_TEST_SUITE_END() + +PickupSpawnTest::PickupSpawnTest(int runTestNumber) +{ + ResourceManager::RegisterType("ConfigFile"); + ResourceManager::RegisterType("EntityFile"); + + m_Config = ResourceManager::Load("Config.ini"); + LOG_LEVEL = static_cast<_LOG_LEVEL>(m_Config->Get("Debug.LogLevel", 1)); + + m_EventBroker = new EventBroker(); + m_World = new World(); + + // Create system pipeline + m_SystemPipeline = new SystemPipeline(m_World, m_EventBroker); + m_SystemPipeline->AddSystem(0); + m_SystemPipeline->AddSystem(1); + + //must register components (Components.xsd), else you cant create entities. Easiest done by loading a test xsd file + auto file = ResourceManager::Load("Schema/Entities/HealthPickup.xml"); + EntityFilePreprocessor fpp(file); + fpp.RegisterComponents(m_World); + EntityFileParser fp(file); + //connect the healthpickup to the world + m_HealthPickupID = fp.MergeEntities(m_World); + + //create a player + m_PlayerID = m_World->CreateEntity(); + auto& player = m_World->AttachComponent(m_PlayerID, "Player"); + + m_RunTestNumber = runTestNumber; + + //further testsetups + TestSetup(m_RunTestNumber); + + //init glfw so dt works + glfwInit(); + + //listen to the 2 events that are related to PickupSpawn + EVENT_SUBSCRIBE_MEMBER(m_HP, &PickupSpawnTest::OnHealthPickup); + EVENT_SUBSCRIBE_MEMBER(m_PS, &PickupSpawnTest::OnPickupSpawned); +} + +bool PickupSpawnTest::OnHealthPickup(Events::PlayerHealthPickup& e) { + //very that the event has the correct healthgain number and playerid + if (m_RunTestNumber == 1) { + if (e.HealthAmount == 22.0 && e.Player.ID == m_PlayerID) { + testStage1Success = true; + } + } + if (m_RunTestNumber == 2) { + testStage1Success = false; + } + if (m_RunTestNumber == 3) { + if (e.HealthAmount == 50.0 && e.Player.ID == m_PlayerID) { + testStage1Success = true; + } + } + return true; +} +bool PickupSpawnTest::OnPickupSpawned(Events::PickupSpawned& e) { + //verify that the newly spawned pickup has the same variable values as the original one + if (m_RunTestNumber == 1) { + if ((double)e.Pickup["HealthPickup"]["HealthGain"] == 22.0 && (double)e.Pickup["HealthPickup"]["RespawnTimer"] == 2.0) { + testStage2Success = true; + } + } + if (m_RunTestNumber == 2) { + testStage2Success = false; + } + if (m_RunTestNumber == 3) { + testStage2Success = false; + } + return true; +} + +void PickupSpawnTest::TestSetup(int testNumber) +{ + //cant use switch here, since each case might initialize different variables + if (m_RunTestNumber == 1) { + //PickupSpawnTest_HealthPickupRespawns_PlayerHealthPickupEventTriggers + auto& healthPickupEW = EntityWrapper(m_World, m_HealthPickupID); + healthPickupEW["HealthPickup"]["RespawnTimer"] = 2.0; + healthPickupEW["HealthPickup"]["HealthGain"] = 22.0; + + //create a player + auto& health = m_World->AttachComponent(m_PlayerID, "Health"); + health["Health"] = 20.0; + health["MaxHealth"] = 100.0; + + Events::TriggerTouch eTriggerTouch; + DoTouchEvent(m_PlayerID, m_HealthPickupID); + } + if (m_RunTestNumber == 2) { + //PickupSpawnTest_APlayerAtMaxHealth_CantTakeHealthPickup + auto& healthPickupEW = EntityWrapper(m_World, m_HealthPickupID); + healthPickupEW["HealthPickup"]["RespawnTimer"] = 1.0; + healthPickupEW["HealthPickup"]["HealthGain"] = 50.0; + + //create a player at max health + auto& health = m_World->AttachComponent(m_PlayerID, "Health"); + health["Health"] = 100.0; + health["MaxHealth"] = 100.0; + + Events::TriggerTouch eTriggerTouch; + DoTouchEvent(m_PlayerID, m_HealthPickupID); + } + if (m_RunTestNumber == 3) { + //PickupSpawnTest_APickupCanRespawnSlowly + auto& healthPickupEW = EntityWrapper(m_World, m_HealthPickupID); + healthPickupEW["HealthPickup"]["RespawnTimer"] = 100.0; + healthPickupEW["HealthPickup"]["HealthGain"] = 50.0; + + //create a player + auto& health = m_World->AttachComponent(m_PlayerID, "Health"); + health["Health"] = 1.0; + health["MaxHealth"] = 100.0; + + Events::TriggerTouch eTriggerTouch; + DoTouchEvent(m_PlayerID, m_HealthPickupID); + } +} + +//generic stuff +void PickupSpawnTest::Tick() +{ + glfwPollEvents(); + + //just set dt to 1.0 since we want fast testing + double dt = 1.0; + + // Iterate through systems and update world! + m_SystemPipeline->Update(dt); + + m_EventBroker->Swap(); + m_EventBroker->Clear(); + + //verify that healthgain event has been published and pickup has respawned + if (m_RunTestNumber == 1 && testStage1Success && testStage2Success) { + m_TestSucceeded = true; + } + //verify that no healthgain event has been published and that no pickup has respawned + if (m_NumLoops > 90 && m_RunTestNumber == 2 && !testStage1Success && !testStage2Success) { + m_TestSucceeded = true; + } + //3: verify that the pickup hasnt spawned + if (m_NumLoops > 90 && m_RunTestNumber == 3 && testStage1Success && !testStage2Success) { + m_TestSucceeded = true; + } +} +bool PickupSpawnTest::Game_Loop_OneHundredTimes() { + //100 loops will be more than enough to do the test + int loops = 100; + bool success = false; + while (loops > 0) { + Tick(); + m_NumLoops++; + if (m_TestSucceeded) { + success = true; + break; + } + loops--; + } + return success; +} +PickupSpawnTest::~PickupSpawnTest() +{ + delete m_SystemPipeline; + delete m_World; + //delete m_EventBroker; +} +void PickupSpawnTest::DoTouchEvent(EntityID whoDidSomething, EntityID onWhatObject) { + Events::TriggerTouch touchEvent; + touchEvent.Entity = EntityWrapper(m_World, whoDidSomething); + touchEvent.Trigger = EntityWrapper(m_World, onWhatObject); + m_EventBroker->Publish(touchEvent); +} diff --git a/src/Tests/PickupSpawnTest.h b/src/Tests/PickupSpawnTest.h new file mode 100644 index 00000000..2869c119 --- /dev/null +++ b/src/Tests/PickupSpawnTest.h @@ -0,0 +1,73 @@ +#ifndef PickupSpawnTest_h__ +#define PickupSpawnTest_h__ + +#include "Core/ResourceManager.h" +#include "Core/ConfigFile.h" +#include "Core/EventBroker.h" +#include "Core/World.h" +#include "Input/InputProxy.h" +#include "Input/KeyboardInputHandler.h" +#include "Input/MouseInputHandler.h" +#include "Core/EKeyDown.h" +#include "Core/EntityFile.h" +#include "Core/SystemPipeline.h" + +#include "Core/EntityFilePreprocessor.h" +#include "Core/EntityFileParser.h" +#include "Core/EntityFileWriter.h" + +#include "Engine/Collision/ETrigger.h" + +//#include "Core/System.h" +//#include "Core/Transform.h" +//#include "Core/ResourceManager.h" +//#include "Core/EntityFileParser.h" +//#include "Core/EPickupSpawned.h" +//#include "Core/EPlayerHealthPickup.h" +#include "Engine/Collision/ETrigger.h" +//#include "Common.h" +//#include +#include "Collision/TriggerSystem.h" +#include "Collision/CollisionSystem.h" +#include "Core/EntityFileWriter.h" +#include "Game/Systems/HealthSystem.h" +#include "Game/Systems/PickupSpawnSystem.h" + +#include "Core/ResourceManager.h" + +class PickupSpawnTest +{ +public: + PickupSpawnTest(int runTestNumber); + ~PickupSpawnTest(); + + void Tick(); + bool m_TestSucceeded = false; + int m_NumLoops = 0; + + bool Game_Loop_OneHundredTimes(); + + void TestSetup(int testNumber); + void DoTouchEvent(EntityID whoDidSomething, EntityID onWhatObject); + +private: + double m_LastTime; + ConfigFile* m_Config = nullptr; + EventBroker* m_EventBroker; + World* m_World; + SystemPipeline* m_SystemPipeline; + EntityID m_PlayerID, m_HealthPickupID; + int m_RunTestNumber; + + EventRelay m_HP; + bool OnHealthPickup(Events::PlayerHealthPickup& e); + EventRelay m_PS; + bool OnPickupSpawned(Events::PickupSpawned& e); + + bool testStage1Success = false; + bool testStage2Success = false; + + +}; + +#endif From f7756ff60fc850c44ab93d156a14dd9763fd57d3 Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Wed, 10 Feb 2016 16:51:00 +0100 Subject: [PATCH 171/355] Tiny refactoring of PickupSpawnTest. Updated and fixed HealthSystemTest. --- src/Tests/HealthSystemTest.cpp | 28 +++++++++------- src/Tests/HealthSystemTest.h | 4 ++- src/Tests/PickupSpawnTest.cpp | 59 ++++++++++++++++++---------------- src/Tests/PickupSpawnTest.h | 8 ++--- 4 files changed, 54 insertions(+), 45 deletions(-) diff --git a/src/Tests/HealthSystemTest.cpp b/src/Tests/HealthSystemTest.cpp index 36608f8f..7d06bba3 100644 --- a/src/Tests/HealthSystemTest.cpp +++ b/src/Tests/HealthSystemTest.cpp @@ -55,19 +55,14 @@ GameHealthSystemTest::GameHealthSystemTest() //create entity which has transform,player,model,health in it. i.e. is a player EntityID playerID = m_World->CreateEntity(); ComponentWrapper player = m_World->AttachComponent(playerID, "Player"); - ComponentWrapper health = m_World->AttachComponent(playerID, "Health"); - healthsID = playerID; + ComponentWrapper& health = m_World->AttachComponent(playerID, "Health"); + health["Health"] = 100.0; + m_PlayersID = playerID; EntityID playerID2 = m_World->CreateEntity(); ComponentWrapper player2 = m_World->AttachComponent(playerID2, "Player"); ComponentWrapper health2 = m_World->AttachComponent(playerID2, "Health"); - //heal player with 40 - Events::PlayerHealthPickup e3; - e3.HealthAmount = 40.0f; - e3.Player = EntityWrapper(m_World, player.EntityID); - m_EventBroker->Publish(e3); - //damage player with 50 Events::PlayerDamage e; e.Damage = 50.0f; @@ -103,9 +98,18 @@ void GameHealthSystemTest::Tick() m_EventBroker->Swap(); m_EventBroker->Clear(); - - //if health reaches 90 then we know the test has succeeded (start with 100hp, remove 50hp, add 40hp) - double currentHealth = (double)m_World->GetComponent(healthsID, "Health")["Health"]; - if (currentHealth == 90) + + double currentHealth = (double)m_World->GetComponent(m_PlayersID, "Health")["Health"]; + //if players health reach 50 means he got damaged by 50 + if (currentHealth == 50) { + m_TestStage1Success = true; + //heal player with 40 + Events::PlayerHealthPickup e3; + e3.HealthAmount = 40.0f; + e3.Player = EntityWrapper(m_World, m_PlayersID); + m_EventBroker->Publish(e3); + } + if (m_TestStage1Success && currentHealth == 90.0f) { TestSucceeded = true; + } } diff --git a/src/Tests/HealthSystemTest.h b/src/Tests/HealthSystemTest.h index 62c5f55b..685a06dd 100644 --- a/src/Tests/HealthSystemTest.h +++ b/src/Tests/HealthSystemTest.h @@ -31,7 +31,9 @@ private: EventBroker* m_EventBroker; World* m_World; SystemPipeline* m_SystemPipeline; - int healthsID; + int m_PlayersID; + bool m_TestStage1Success = false; + }; #endif diff --git a/src/Tests/PickupSpawnTest.cpp b/src/Tests/PickupSpawnTest.cpp index ebddb71f..2de9e459 100644 --- a/src/Tests/PickupSpawnTest.cpp +++ b/src/Tests/PickupSpawnTest.cpp @@ -4,7 +4,6 @@ using boost::unit_test_framework::test_case; #include "PickupSpawnTest.h" - BOOST_AUTO_TEST_SUITE(PickupSpawnTestSuite) //dont use the same name as the classname in test cases... @@ -73,15 +72,15 @@ bool PickupSpawnTest::OnHealthPickup(Events::PlayerHealthPickup& e) { //very that the event has the correct healthgain number and playerid if (m_RunTestNumber == 1) { if (e.HealthAmount == 22.0 && e.Player.ID == m_PlayerID) { - testStage1Success = true; + m_TestStage1Success = true; } } if (m_RunTestNumber == 2) { - testStage1Success = false; + m_TestStage1Success = false; } if (m_RunTestNumber == 3) { if (e.HealthAmount == 50.0 && e.Player.ID == m_PlayerID) { - testStage1Success = true; + m_TestStage1Success = true; } } return true; @@ -90,22 +89,24 @@ bool PickupSpawnTest::OnPickupSpawned(Events::PickupSpawned& e) { //verify that the newly spawned pickup has the same variable values as the original one if (m_RunTestNumber == 1) { if ((double)e.Pickup["HealthPickup"]["HealthGain"] == 22.0 && (double)e.Pickup["HealthPickup"]["RespawnTimer"] == 2.0) { - testStage2Success = true; + m_TestStage2Success = true; } } if (m_RunTestNumber == 2) { - testStage2Success = false; + m_TestStage2Success = false; } if (m_RunTestNumber == 3) { - testStage2Success = false; + m_TestStage2Success = false; } return true; } void PickupSpawnTest::TestSetup(int testNumber) { - //cant use switch here, since each case might initialize different variables - if (m_RunTestNumber == 1) { + switch (m_RunTestNumber) + { + case 1: + { //PickupSpawnTest_HealthPickupRespawns_PlayerHealthPickupEventTriggers auto& healthPickupEW = EntityWrapper(m_World, m_HealthPickupID); healthPickupEW["HealthPickup"]["RespawnTimer"] = 2.0; @@ -115,11 +116,10 @@ void PickupSpawnTest::TestSetup(int testNumber) auto& health = m_World->AttachComponent(m_PlayerID, "Health"); health["Health"] = 20.0; health["MaxHealth"] = 100.0; - - Events::TriggerTouch eTriggerTouch; - DoTouchEvent(m_PlayerID, m_HealthPickupID); } - if (m_RunTestNumber == 2) { + break; + case 2: + { //PickupSpawnTest_APlayerAtMaxHealth_CantTakeHealthPickup auto& healthPickupEW = EntityWrapper(m_World, m_HealthPickupID); healthPickupEW["HealthPickup"]["RespawnTimer"] = 1.0; @@ -129,11 +129,10 @@ void PickupSpawnTest::TestSetup(int testNumber) auto& health = m_World->AttachComponent(m_PlayerID, "Health"); health["Health"] = 100.0; health["MaxHealth"] = 100.0; - - Events::TriggerTouch eTriggerTouch; - DoTouchEvent(m_PlayerID, m_HealthPickupID); } - if (m_RunTestNumber == 3) { + break; + case 3: + { //PickupSpawnTest_APickupCanRespawnSlowly auto& healthPickupEW = EntityWrapper(m_World, m_HealthPickupID); healthPickupEW["HealthPickup"]["RespawnTimer"] = 100.0; @@ -143,10 +142,14 @@ void PickupSpawnTest::TestSetup(int testNumber) auto& health = m_World->AttachComponent(m_PlayerID, "Health"); health["Health"] = 1.0; health["MaxHealth"] = 100.0; - - Events::TriggerTouch eTriggerTouch; - DoTouchEvent(m_PlayerID, m_HealthPickupID); } + break; + default: + break; + } + //do the triggerTouch event to get the pickupSpawnTest started + Events::TriggerTouch eTriggerTouch; + DoTouchEvent(m_PlayerID, m_HealthPickupID); } //generic stuff @@ -164,16 +167,16 @@ void PickupSpawnTest::Tick() m_EventBroker->Clear(); //verify that healthgain event has been published and pickup has respawned - if (m_RunTestNumber == 1 && testStage1Success && testStage2Success) { - m_TestSucceeded = true; + if (m_RunTestNumber == 1 && m_TestStage1Success && m_TestStage2Success) { + TestSucceeded = true; } //verify that no healthgain event has been published and that no pickup has respawned - if (m_NumLoops > 90 && m_RunTestNumber == 2 && !testStage1Success && !testStage2Success) { - m_TestSucceeded = true; + if (NumLoops > 90 && m_RunTestNumber == 2 && !m_TestStage1Success && !m_TestStage2Success) { + TestSucceeded = true; } //3: verify that the pickup hasnt spawned - if (m_NumLoops > 90 && m_RunTestNumber == 3 && testStage1Success && !testStage2Success) { - m_TestSucceeded = true; + if (NumLoops > 90 && m_RunTestNumber == 3 && m_TestStage1Success && !m_TestStage2Success) { + TestSucceeded = true; } } bool PickupSpawnTest::Game_Loop_OneHundredTimes() { @@ -182,8 +185,8 @@ bool PickupSpawnTest::Game_Loop_OneHundredTimes() { bool success = false; while (loops > 0) { Tick(); - m_NumLoops++; - if (m_TestSucceeded) { + NumLoops++; + if (TestSucceeded) { success = true; break; } diff --git a/src/Tests/PickupSpawnTest.h b/src/Tests/PickupSpawnTest.h index 2869c119..fdb18b12 100644 --- a/src/Tests/PickupSpawnTest.h +++ b/src/Tests/PickupSpawnTest.h @@ -42,8 +42,8 @@ public: ~PickupSpawnTest(); void Tick(); - bool m_TestSucceeded = false; - int m_NumLoops = 0; + bool TestSucceeded = false; + int NumLoops = 0; bool Game_Loop_OneHundredTimes(); @@ -64,8 +64,8 @@ private: EventRelay m_PS; bool OnPickupSpawned(Events::PickupSpawned& e); - bool testStage1Success = false; - bool testStage2Success = false; + bool m_TestStage1Success = false; + bool m_TestStage2Success = false; }; From 02cd822cf198295c01835ef7a1a445c469272e00 Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Wed, 10 Feb 2016 17:04:05 +0100 Subject: [PATCH 172/355] Tiny test refactoring --- src/Tests/HealthSystemTest.cpp | 2 +- src/Tests/PickupSpawnTest.cpp | 46 +++++++++++++++++++--------------- src/Tests/PickupSpawnTest.h | 5 ++-- 3 files changed, 29 insertions(+), 24 deletions(-) diff --git a/src/Tests/HealthSystemTest.cpp b/src/Tests/HealthSystemTest.cpp index 7d06bba3..fa88d815 100644 --- a/src/Tests/HealthSystemTest.cpp +++ b/src/Tests/HealthSystemTest.cpp @@ -101,7 +101,7 @@ void GameHealthSystemTest::Tick() double currentHealth = (double)m_World->GetComponent(m_PlayersID, "Health")["Health"]; //if players health reach 50 means he got damaged by 50 - if (currentHealth == 50) { + if (currentHealth == 50.0) { m_TestStage1Success = true; //heal player with 40 Events::PlayerHealthPickup e3; diff --git a/src/Tests/PickupSpawnTest.cpp b/src/Tests/PickupSpawnTest.cpp index 2de9e459..7cbed85f 100644 --- a/src/Tests/PickupSpawnTest.cpp +++ b/src/Tests/PickupSpawnTest.cpp @@ -69,34 +69,41 @@ PickupSpawnTest::PickupSpawnTest(int runTestNumber) } bool PickupSpawnTest::OnHealthPickup(Events::PlayerHealthPickup& e) { - //very that the event has the correct healthgain number and playerid - if (m_RunTestNumber == 1) { + switch (m_RunTestNumber) + { + case 1: + //verify that the event has the correct healthgain number and playerid if (e.HealthAmount == 22.0 && e.Player.ID == m_PlayerID) { m_TestStage1Success = true; } - } - if (m_RunTestNumber == 2) { + break; + case 2: m_TestStage1Success = false; - } - if (m_RunTestNumber == 3) { + break; + case 3: + //verify that the event has the correct healthgain number and playerid if (e.HealthAmount == 50.0 && e.Player.ID == m_PlayerID) { m_TestStage1Success = true; } + break; } return true; } bool PickupSpawnTest::OnPickupSpawned(Events::PickupSpawned& e) { - //verify that the newly spawned pickup has the same variable values as the original one - if (m_RunTestNumber == 1) { + switch (m_RunTestNumber) + { + case 1: + //verify that the newly spawned pickup has the same variable values as the original one if ((double)e.Pickup["HealthPickup"]["HealthGain"] == 22.0 && (double)e.Pickup["HealthPickup"]["RespawnTimer"] == 2.0) { m_TestStage2Success = true; } - } - if (m_RunTestNumber == 2) { + break; + case 2: m_TestStage2Success = false; - } - if (m_RunTestNumber == 3) { + break; + case 3: m_TestStage2Success = false; + break; } return true; } @@ -168,15 +175,15 @@ void PickupSpawnTest::Tick() //verify that healthgain event has been published and pickup has respawned if (m_RunTestNumber == 1 && m_TestStage1Success && m_TestStage2Success) { - TestSucceeded = true; + m_TestSucceeded = true; } //verify that no healthgain event has been published and that no pickup has respawned - if (NumLoops > 90 && m_RunTestNumber == 2 && !m_TestStage1Success && !m_TestStage2Success) { - TestSucceeded = true; + if (m_NumLoops > 90 && m_RunTestNumber == 2 && !m_TestStage1Success && !m_TestStage2Success) { + m_TestSucceeded = true; } //3: verify that the pickup hasnt spawned - if (NumLoops > 90 && m_RunTestNumber == 3 && m_TestStage1Success && !m_TestStage2Success) { - TestSucceeded = true; + if (m_NumLoops > 90 && m_RunTestNumber == 3 && m_TestStage1Success && !m_TestStage2Success) { + m_TestSucceeded = true; } } bool PickupSpawnTest::Game_Loop_OneHundredTimes() { @@ -185,8 +192,8 @@ bool PickupSpawnTest::Game_Loop_OneHundredTimes() { bool success = false; while (loops > 0) { Tick(); - NumLoops++; - if (TestSucceeded) { + m_NumLoops++; + if (m_TestSucceeded) { success = true; break; } @@ -198,7 +205,6 @@ PickupSpawnTest::~PickupSpawnTest() { delete m_SystemPipeline; delete m_World; - //delete m_EventBroker; } void PickupSpawnTest::DoTouchEvent(EntityID whoDidSomething, EntityID onWhatObject) { Events::TriggerTouch touchEvent; diff --git a/src/Tests/PickupSpawnTest.h b/src/Tests/PickupSpawnTest.h index fdb18b12..b9d5483a 100644 --- a/src/Tests/PickupSpawnTest.h +++ b/src/Tests/PickupSpawnTest.h @@ -42,11 +42,8 @@ public: ~PickupSpawnTest(); void Tick(); - bool TestSucceeded = false; - int NumLoops = 0; bool Game_Loop_OneHundredTimes(); - void TestSetup(int testNumber); void DoTouchEvent(EntityID whoDidSomething, EntityID onWhatObject); @@ -67,6 +64,8 @@ private: bool m_TestStage1Success = false; bool m_TestStage2Success = false; + bool m_TestSucceeded = false; + int m_NumLoops = 0; }; From b0bdca5cdd779d4ec16780212e1b394b46ee0763 Mon Sep 17 00:00:00 2001 From: Teejoon Date: Wed, 10 Feb 2016 17:15:08 +0100 Subject: [PATCH 173/355] =?UTF-8?q?SplatMap=20r=C3=A4knas=20r=C3=A4tt=20ny?= =?UTF-8?q?=20och=20mitmaps=20i=20Texture.cpp?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- assets | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/assets b/assets index 2151ad93..b49fe601 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit 2151ad934d2ff3f779ae7e4b38c20bbb728cd02d +Subproject commit b49fe60133b1d00a8aa5ada2742484e375337754 From 97780395cfefa0b2913c3dfa294d0cced41dc2f3 Mon Sep 17 00:00:00 2001 From: Teejoon Date: Wed, 10 Feb 2016 17:15:54 +0100 Subject: [PATCH 174/355] ... Now mipmaps and Splatmaps i comming :) --- .../Schema/Entities/SplatMapTesWorld.xml | 8 +++++++- .../Shaders/ForwardPlusSplatMap.frag.glsl | 20 +++++++++---------- src/Engine/Rendering/Texture.cpp | 3 ++- 3 files changed, 19 insertions(+), 12 deletions(-) diff --git a/resources/Schema/Entities/SplatMapTesWorld.xml b/resources/Schema/Entities/SplatMapTesWorld.xml index 11660a63..fe5718eb 100644 --- a/resources/Schema/Entities/SplatMapTesWorld.xml +++ b/resources/Schema/Entities/SplatMapTesWorld.xml @@ -9,8 +9,14 @@ + + + + + + - Models/Test/SplatMapTest.mesh + Models/Ground.mesh diff --git a/resources/Shaders/ForwardPlusSplatMap.frag.glsl b/resources/Shaders/ForwardPlusSplatMap.frag.glsl index c4908534..239c51b5 100644 --- a/resources/Shaders/ForwardPlusSplatMap.frag.glsl +++ b/resources/Shaders/ForwardPlusSplatMap.frag.glsl @@ -151,8 +151,6 @@ vec4 CalcNormalMappedValue(vec3 normal, vec3 tangent, vec3 bitangent, vec2 textu return vec4(TBN * normalize(NormalMap), 0.0); } -#define TEXTURE_TILE 5.0 - vec4 CalcBlendedTexel(vec4 blendValue, sampler2D R, sampler2D G, sampler2D B, sampler2D A, sampler2D D, vec2 R_TileValues, vec2 G_TileValues, vec2 B_TileValues, vec2 A_TileValues, vec2 D_TileValues){ vec4 R_Channel = texture2D(R, Input.TextureCoordinate * R_TileValues); @@ -163,10 +161,11 @@ vec4 CalcBlendedTexel(vec4 blendValue, sampler2D R, sampler2D G, sampler2D B, sa float total = blendValue.r + blendValue.g + blendValue.b + blendValue.a; if(total > 1.0f){ - blendValue.r / total; - blendValue.g / total; - blendValue.b / total; - blendValue.a / total; + float totalDiv = 1.0f / total; + blendValue.r = blendValue.r * totalDiv; + blendValue.g = blendValue.g * totalDiv; + blendValue.b = blendValue.b * totalDiv; + blendValue.a = blendValue.a * totalDiv; } float D_percent = clamp( 1.0f - total, 0.0f, 1.0f); @@ -188,10 +187,11 @@ vec4 CalcBlendedNormal(vec4 blendValue, sampler2D R, sampler2D G, sampler2D B, s float total = blendValue.r + blendValue.g + blendValue.b + blendValue.a; if(total > 1.0f){ - blendValue.r / total; - blendValue.g / total; - blendValue.b / total; - blendValue.a / total; + float totalDiv = 1 / total; + blendValue.r = blendValue.r * totalDiv; + blendValue.g = blendValue.g * totalDiv; + blendValue.b = blendValue.b * totalDiv; + blendValue.a = blendValue.a * totalDiv; } float D_percent = clamp( 1.0f - total, 0.0f, 1.0f); diff --git a/src/Engine/Rendering/Texture.cpp b/src/Engine/Rendering/Texture.cpp index 57f3ca36..df197400 100644 --- a/src/Engine/Rendering/Texture.cpp +++ b/src/Engine/Rendering/Texture.cpp @@ -30,9 +30,10 @@ Texture::Texture(std::string path) glBindTexture(GL_TEXTURE_2D, m_Texture); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexImage2D(GL_TEXTURE_2D, 0, format, image.Width, image.Height, 0, format, GL_UNSIGNED_BYTE, image.Data); + glGenerateMipmap(GL_TEXTURE_2D); 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_LINEAR); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); GLERROR("Texture load"); } From 1ba9d97ab7b56a4628dfd7672d1738ddc3ad646d Mon Sep 17 00:00:00 2001 From: stiffly Date: Wed, 10 Feb 2016 17:17:41 +0100 Subject: [PATCH 175/355] Fixed crash when trying to jump, when no player is spawned. --- src/Game/Systems/SoundSystem.cpp | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/Game/Systems/SoundSystem.cpp b/src/Game/Systems/SoundSystem.cpp index acb7501c..e3aa49b2 100644 --- a/src/Game/Systems/SoundSystem.cpp +++ b/src/Game/Systems/SoundSystem.cpp @@ -25,7 +25,7 @@ void SoundSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& cComp void SoundSystem::Update(double dt) { // Temp for play test. - if(m_DrumsIsPlaying) { + if (m_DrumsIsPlaying) { m_DrumsIsPlaying = !drumTimer(dt); } } @@ -69,6 +69,9 @@ bool SoundSystem::OnInputCommand(const Events::InputCommand & e) void SoundSystem::playerJumps() { + if (!m_LocalPlayer.Valid()) { + return; + } bool grounded = (bool)m_World->GetComponent(m_LocalPlayer.ID, "Physics")["IsOnGround"]; if (grounded) { Events::PlaySoundOnEntity e; @@ -124,11 +127,11 @@ bool SoundSystem::OnPlayerDamage(const Events::PlayerDamage & e) std::vector paths; paths.push_back("Audio/hurt/hurt" + std::to_string(rand) + ".wav"); -// // Breathe -// int ammountOfbreaths = (static_cast(e.Damage) / 10) + 2; // TEMP: Idk something stupid like this shit -// for (int i = 0; i < ammountOfbreaths; i++) { -// paths.push_back("Audio/exhausted/breath.wav"); -// } + // // Breathe + // int ammountOfbreaths = (static_cast(e.Damage) / 10) + 2; // TEMP: Idk something stupid like this shit + // for (int i = 0; i < ammountOfbreaths; i++) { + // paths.push_back("Audio/exhausted/breath.wav"); + // } Events::PlayQueueOnEntity ev; ev.Emitter = m_LocalPlayer; ev.FilePaths = paths; @@ -140,7 +143,7 @@ bool SoundSystem::OnPlayerDeath(const Events::PlayerDeath & e) { Events::PlaySoundOnEntity ev; ev.EmitterID = m_LocalPlayer.ID; - ev.FilePath = "Audio/die/die2.wav"; + ev.FilePath = "Audio/die/die2.wav"; m_EventBroker->Publish(ev); return false; } From 7cbdc33f840fa53075af983a6e3157baaf3c10bd Mon Sep 17 00:00:00 2001 From: Jocke Date: Wed, 10 Feb 2016 17:39:23 +0100 Subject: [PATCH 176/355] Updated submodules --- assets | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/assets b/assets index 7531e441..1c510a53 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit 7531e441fea639076d69c6cf05e3ae8ff7170cf9 +Subproject commit 1c510a53d38b0f443ef141ddb3265a76c394ef7c From 53265bbc90c4c2e647be75ddbfe739e34eb9e5c2 Mon Sep 17 00:00:00 2001 From: Tleety Date: Wed, 10 Feb 2016 17:50:17 +0100 Subject: [PATCH 177/355] PNG is now a resource. You can now load textures threaded. PNG will now throw exceptions when errors happend SpriteComponent is now working without billboarding. --- include/Engine/GUI/TextureFrame.h | 5 +- include/Engine/Rendering/DrawFinalPass.h | 2 + include/Engine/Rendering/Model.h | 1 + include/Engine/Rendering/PNG.h | 3 +- include/Engine/Rendering/Renderer.h | 1 + include/Engine/Rendering/SpriteJob.h | 19 ++--- .../Engine/Rendering/Util/CommonFunctions.h | 11 +-- .../Schema/Entities/QualityAssurance.xml | 74 +++++++++++++++---- resources/Shaders/Sprite.vert.glsl | 3 +- src/Engine/Rendering/DrawBloomPass.cpp | 2 +- src/Engine/Rendering/DrawFinalPass.cpp | 17 +++-- src/Engine/Rendering/Model.cpp | 8 +- src/Engine/Rendering/PNG.cpp | 22 ++---- src/Engine/Rendering/Renderer.cpp | 17 +++-- src/Engine/Rendering/Texture.cpp | 29 ++++---- src/Engine/Rendering/Util/CommonFunctions.cpp | 17 +++++ src/Game/Game.cpp | 1 + 17 files changed, 149 insertions(+), 83 deletions(-) diff --git a/include/Engine/GUI/TextureFrame.h b/include/Engine/GUI/TextureFrame.h index 2c6d34dd..77967b4d 100644 --- a/include/Engine/GUI/TextureFrame.h +++ b/include/Engine/GUI/TextureFrame.h @@ -3,6 +3,7 @@ #include "Frame.h" #include "../Rendering/Texture.h" +#include "../Rendering/Util/CommonFunctions.h" namespace GUI { @@ -55,10 +56,10 @@ public: return; } - m_Texture = ResourceManager::Load(resourceName); + m_Texture = CommonFunctions::LoadTexture(resourceName, false); m_TextureName = resourceName; if (m_Texture == nullptr) { - m_Texture = ResourceManager::Load("Textures/Core/ErrorTexture.png"); + m_Texture = CommonFunctions::LoadTexture("Textures/Core/ErrorTexture.png", false); } SizeToTexture(); diff --git a/include/Engine/Rendering/DrawFinalPass.h b/include/Engine/Rendering/DrawFinalPass.h index 867ec844..98f986b4 100644 --- a/include/Engine/Rendering/DrawFinalPass.h +++ b/include/Engine/Rendering/DrawFinalPass.h @@ -7,6 +7,7 @@ #include "FrameBuffer.h" #include "ShaderProgram.h" #include "Util/UnorderedMapVec2.h" +#include "Util/CommonFunctions.h" #include "Texture.h" class DrawFinalPass @@ -43,6 +44,7 @@ private: Texture* m_BlackTexture; Texture* m_NeutralNormalTexture; Texture* m_GreyTexture; + Texture* m_ErrorTexture; FrameBuffer m_FinalPassFrameBuffer; GLuint m_BloomTexture; diff --git a/include/Engine/Rendering/Model.h b/include/Engine/Rendering/Model.h index f751a8cc..6812494c 100644 --- a/include/Engine/Rendering/Model.h +++ b/include/Engine/Rendering/Model.h @@ -2,6 +2,7 @@ #define Model_h__ #include "Rendering/RawModelCustom.h" +#include "Util/CommonFunctions.h" //#include "Rendering/RawModelAssimp.h" #include "../OpenGL.h" diff --git a/include/Engine/Rendering/PNG.h b/include/Engine/Rendering/PNG.h index f2cbf157..a45e9e7c 100644 --- a/include/Engine/Rendering/PNG.h +++ b/include/Engine/Rendering/PNG.h @@ -6,9 +6,10 @@ #include #include "../Common.h" +#include "../Core/ResourceManager.h" #include "Image.h" -class PNG : public Image +class PNG : public Image, public Resource { public: PNG(std::string path); diff --git a/include/Engine/Rendering/Renderer.h b/include/Engine/Rendering/Renderer.h index 33a61edf..04754514 100644 --- a/include/Engine/Rendering/Renderer.h +++ b/include/Engine/Rendering/Renderer.h @@ -22,6 +22,7 @@ #include "../Core/Transform.h" #include "imgui/imgui.h" #include "TextPass.h" +#include "Util/CommonFunctions.h" class Renderer : public IRenderer { diff --git a/include/Engine/Rendering/SpriteJob.h b/include/Engine/Rendering/SpriteJob.h index a20d0395..23bf6360 100644 --- a/include/Engine/Rendering/SpriteJob.h +++ b/include/Engine/Rendering/SpriteJob.h @@ -24,23 +24,17 @@ struct SpriteJob : RenderJob ::RawModel::MaterialGroup matGroup = Model->MaterialGroups().front(); TextureID = (matGroup.Texture) ? matGroup.Texture->ResourceID : 0; - if (cSprite["DiffuseTexture"]) { - DiffuseTexture = ResourceManager::Load(cSprite["DiffuseTexture"]); - } else { - DiffuseTexture = nullptr; - } - if (cSprite["GlowMap"]) { - IncandescenceTexture = ResourceManager::Load(cSprite["GlowMap"]); - } else { - IncandescenceTexture = nullptr; - } + DiffuseTexture = CommonFunctions::LoadTexture(cSprite["DiffuseTexture"], true); + + IncandescenceTexture = CommonFunctions::LoadTexture(cSprite["GlowMap"], true); + StartIndex = matGroup.StartIndex; EndIndex = matGroup.EndIndex; Matrix = matrix; Color = cSprite["Color"]; Entity = cSprite.EntityID; - glm::vec3 abspos = Transform::AbsolutePosition(world, cSprite.EntityID); - glm::vec3 viewpos = glm::vec3(camera->ViewMatrix() * glm::vec4(abspos, 1)); + Position = Transform::AbsolutePosition(world, cSprite.EntityID); + glm::vec3 viewpos = glm::vec3(camera->ViewMatrix() * glm::vec4(Position, 1)); Depth = viewpos.z; World = world; @@ -58,6 +52,7 @@ struct SpriteJob : RenderJob const Texture* IncandescenceTexture; float Shininess = 0.f; glm::vec4 Color; + glm::vec3 Position; const ::Model* Model = nullptr; unsigned int StartIndex = 0; unsigned int EndIndex = 0; diff --git a/include/Engine/Rendering/Util/CommonFunctions.h b/include/Engine/Rendering/Util/CommonFunctions.h index b262568c..e178f52d 100644 --- a/include/Engine/Rendering/Util/CommonFunctions.h +++ b/include/Engine/Rendering/Util/CommonFunctions.h @@ -4,14 +4,11 @@ #include "../../Common.h" #include "../../OpenGL.h" #include "../../GLM.h" +#include "../Texture.h" -class CommonFuntions -{ -public: - CommonFuntions() = delete; - -private: - +namespace CommonFunctions +{ +Texture* LoadTexture(std::string path, bool threaded); }; #endif \ No newline at end of file diff --git a/resources/Schema/Entities/QualityAssurance.xml b/resources/Schema/Entities/QualityAssurance.xml index e057cf38..23ebb4a5 100644 --- a/resources/Schema/Entities/QualityAssurance.xml +++ b/resources/Schema/Entities/QualityAssurance.xml @@ -40,7 +40,7 @@ - + @@ -188,7 +188,7 @@ - + @@ -683,7 +683,7 @@ - + @@ -730,7 +730,7 @@ - + @@ -790,7 +790,7 @@ - + @@ -837,7 +837,7 @@ - + @@ -883,7 +883,7 @@ - + @@ -930,7 +930,7 @@ - + @@ -977,7 +977,7 @@ - + @@ -1374,7 +1374,7 @@ - + @@ -1383,7 +1383,7 @@ true - 0.75008034908941568 + 0.75102457088592522 3.7999999523162842 true @@ -1430,7 +1430,7 @@ - + @@ -1439,7 +1439,7 @@ - 1.1999860997035228 + 1.2009303215000324 Models/Assault.mesh @@ -1482,7 +1482,7 @@ - + @@ -1497,7 +1497,7 @@ true - 0.68343188336345406 + 0.68437610515996361 true @@ -1553,6 +1553,50 @@ + + + + + + + + + + + + Textures/FoliageDiff.png + Textures/DefenderGunBlueIncd.png + + + + + + + + + Textures/FoliageDiff.png + Textures/AssaultWeaponBlueGlowMap.png + + + + + + + + + + + Textures/FoliageDiff.png + Textures/GlowTest.png + + + + + + + + + diff --git a/resources/Shaders/Sprite.vert.glsl b/resources/Shaders/Sprite.vert.glsl index e910a26a..c09d745b 100644 --- a/resources/Shaders/Sprite.vert.glsl +++ b/resources/Shaders/Sprite.vert.glsl @@ -16,7 +16,8 @@ out VertexData{ void main() { - gl_Position = P * M * vec4(Position, 1.0); + + gl_Position = P * V * M * vec4(Position, 1.0); Output.Position = Position; Output.TextureCoordinate = TextureCoords; diff --git a/src/Engine/Rendering/DrawBloomPass.cpp b/src/Engine/Rendering/DrawBloomPass.cpp index 5d8b2359..2c9e47b4 100644 --- a/src/Engine/Rendering/DrawBloomPass.cpp +++ b/src/Engine/Rendering/DrawBloomPass.cpp @@ -13,7 +13,7 @@ DrawBloomPass::DrawBloomPass(IRenderer* renderer) void DrawBloomPass::InitializeTextures() { - m_WhiteTexture = ResourceManager::Load("Textures/Core/White.png"); + m_WhiteTexture = CommonFunctions::LoadTexture("Textures/Core/White.png", false); } void DrawBloomPass::InitializeShaderPrograms() diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index e5919fbe..98f17835 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -11,10 +11,11 @@ DrawFinalPass::DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCulling void DrawFinalPass::InitializeTextures() { - m_WhiteTexture = ResourceManager::Load("Textures/Core/White.png"); - m_BlackTexture = ResourceManager::Load("Textures/Core/Black.png"); - m_NeutralNormalTexture = ResourceManager::Load("Textures/Core/NeutralNormalMap.png"); - m_GreyTexture = ResourceManager::Load("Textures/Core/Grey.png"); + m_WhiteTexture = CommonFunctions::LoadTexture("Textures/Core/White.png", false); + m_BlackTexture = CommonFunctions::LoadTexture("Textures/Core/Black.png", false); + m_NeutralNormalTexture = CommonFunctions::LoadTexture("Textures/Core/NeutralNormalMap.png", false); + m_GreyTexture = CommonFunctions::LoadTexture("Textures/Core/Grey.png", false); + m_ErrorTexture = CommonFunctions::LoadTexture("Textures/Core/ErrorTexture.png", false); } void DrawFinalPass::InitializeFrameBuffers() @@ -56,7 +57,7 @@ void DrawFinalPass::InitializeShaderPrograms() m_ExplosionEffectProgram->Link(); GLERROR("Creating explosion program"); - m_SpriteProgram = ResourceManager::Load("#m_SpriteProgram"); + m_SpriteProgram = ResourceManager::Load("#SpriteProgram"); m_SpriteProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/Sprite.vert.glsl"))); m_SpriteProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/Sprite.frag.glsl"))); m_SpriteProgram->Compile(); @@ -222,10 +223,12 @@ void DrawFinalPass::DrawSprites(std::list>&jobs, Rend for(auto& job : jobs) { auto spriteJob = std::dynamic_pointer_cast(job); - if(spriteJob) { + if (spriteJob) { + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(spriteJob->Matrix)); 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())); + glUniform3fv(glGetUniformLocation(shaderHandle, "CameraPos"), 1, glm::value_ptr(scene.Camera->Position())); 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); @@ -234,7 +237,7 @@ void DrawFinalPass::DrawSprites(std::list>&jobs, Rend if (spriteJob->DiffuseTexture != nullptr) { glBindTexture(GL_TEXTURE_2D, spriteJob->DiffuseTexture->m_Texture); } else { - glBindTexture(GL_TEXTURE_2D, m_WhiteTexture->m_Texture); + glBindTexture(GL_TEXTURE_2D, m_ErrorTexture->m_Texture); } glActiveTexture(GL_TEXTURE1); diff --git a/src/Engine/Rendering/Model.cpp b/src/Engine/Rendering/Model.cpp index cf4923a3..82dd71af 100644 --- a/src/Engine/Rendering/Model.cpp +++ b/src/Engine/Rendering/Model.cpp @@ -7,16 +7,16 @@ Model::Model(std::string fileName) for (auto& group : m_RawModel->MaterialGroups) { if (!group.TexturePath.empty()) { - group.Texture = std::shared_ptr(ResourceManager::Load(group.TexturePath)); + group.Texture = std::shared_ptr(CommonFunctions::LoadTexture(group.TexturePath, false)); } if (!group.NormalMapPath.empty()) { - group.NormalMap = std::shared_ptr(ResourceManager::Load(group.NormalMapPath)); + group.NormalMap = std::shared_ptr(CommonFunctions::LoadTexture(group.NormalMapPath, false)); } if (!group.SpecularMapPath.empty()) { - group.SpecularMap = std::shared_ptr(ResourceManager::Load(group.SpecularMapPath)); + group.SpecularMap = std::shared_ptr(CommonFunctions::LoadTexture(group.SpecularMapPath, false)); } if (!group.IncandescenceMapPath.empty()) { - group.IncandescenceMap = std::shared_ptr(ResourceManager::Load(group.IncandescenceMapPath)); + group.IncandescenceMap = std::shared_ptr(CommonFunctions::LoadTexture(group.IncandescenceMapPath, false)); } } diff --git a/src/Engine/Rendering/PNG.cpp b/src/Engine/Rendering/PNG.cpp index 7ffd5c20..409da9b1 100644 --- a/src/Engine/Rendering/PNG.cpp +++ b/src/Engine/Rendering/PNG.cpp @@ -4,40 +4,35 @@ PNG::PNG(std::string path) { FILE* file = fopen(path.c_str(), "rb"); if (!file) { - LOG_ERROR("Failed to open texture file \"%s\": %s", path.c_str(), const_cast(strerror(errno))); - return; + throw Resource::FailedLoadingException("Failed to open texture file."); } png_byte header[8]; fread(header, 1, 8, file); bool isPNG = !png_sig_cmp(header, 0, 8); if (!isPNG) { - LOG_ERROR("Failed to load texture file \"%s\": File isn't PNG", path.c_str()); fclose(file); - return; + throw Resource::FailedLoadingException("File is not PNG."); } // Initialize libpng png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, (png_error_ptr)&PNG::pngErrorFunction, (png_error_ptr)&PNG::pngErrorFunction); if (!png_ptr) { - LOG_ERROR("libpng: Failed to initialze png_struct"); png_destroy_read_struct(&png_ptr, nullptr, nullptr); fclose(file); - return; + throw Resource::FailedLoadingException("Failed to initialze png_struct."); } png_infop info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { - LOG_ERROR("libpng: Failed to initialze png_info"); png_destroy_read_struct(&png_ptr, nullptr, nullptr); fclose(file); - return; + throw Resource::FailedLoadingException("Failed to initialze png_info."); } png_infop info_end_ptr = png_create_info_struct(png_ptr); if (!info_end_ptr) { - LOG_ERROR("libpng: Failed to initialze second png_info"); png_destroy_read_struct(&png_ptr, &info_ptr, nullptr); fclose(file); - return; + throw Resource::FailedLoadingException("Failed to initialze second png_info."); } png_init_io(png_ptr, file); @@ -51,8 +46,8 @@ PNG::PNG(std::string path) unsigned int width, height; png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, NULL, NULL, NULL); if (bit_depth != 8) { - LOG_ERROR("libpng: Unsupported bit depth \"%i\" of image \"%s\", must be 8", bit_depth, path.c_str()); - return; + throw Resource::FailedLoadingException("Unsupported bit depth. Must be 8"); + } switch (color_type) { case PNG_COLOR_TYPE_RGB: @@ -60,8 +55,7 @@ PNG::PNG(std::string path) Format = Image::ImageFormat::RGBA; break; default: - LOG_ERROR("libpng: Unsupported color format \"%i\" of image \"%s\"", color_type, path.c_str()); - return; + throw Resource::FailedLoadingException("Unsupported color format."); } // Convert RGB to RGBA, since DirectX rather treat them all the same way diff --git a/src/Engine/Rendering/Renderer.cpp b/src/Engine/Rendering/Renderer.cpp index a63e02a0..c0e4d07c 100644 --- a/src/Engine/Rendering/Renderer.cpp +++ b/src/Engine/Rendering/Renderer.cpp @@ -106,16 +106,21 @@ void Renderer::Draw(RenderFrame& frame) for (auto scene : frame.RenderScenes){ SortRenderJobsByDepth(*scene); + GLERROR("SortByDepth"); m_PickingPass->Draw(*scene); + GLERROR("Drawing pickingpass"); m_LightCullingPass->GenerateNewFrustum(*scene); + GLERROR("Generate frustums"); m_LightCullingPass->FillLightList(*scene); + GLERROR("Filling light list"); m_LightCullingPass->CullLights(*scene); + GLERROR("LightCulling"); m_DrawFinalPass->Draw(*scene); + GLERROR("Draw Geometry+Light"); //m_DrawScenePass->Draw(*scene); - GLERROR("Renderer::Draw m_DrawScenePass->Draw"); - m_TextPass->Draw(*scene, *m_DrawFinalPass->FinalPassFrameBuffer()); + GLERROR("Draw Text"); } m_DrawBloomPass->Draw(m_DrawFinalPass->BloomTexture()); @@ -136,7 +141,8 @@ void Renderer::Draw(RenderFrame& frame) } m_ImGuiRenderPass->Draw(); - glfwSwapBuffers(m_Window); + GLERROR("Imgui draw"); + glfwSwapBuffers(m_Window); } PickData Renderer::Pick(glm::vec2 screenCoord) @@ -146,8 +152,8 @@ PickData Renderer::Pick(glm::vec2 screenCoord) void Renderer::InitializeTextures() { - m_ErrorTexture = ResourceManager::Load("Textures/Core/ErrorTexture.png"); - m_WhiteTexture = ResourceManager::Load("Textures/Core/White.png"); + m_ErrorTexture = CommonFunctions::LoadTexture("Textures/Core/ErrorTexture.png", false); + m_WhiteTexture = CommonFunctions::LoadTexture("Textures/Core/White.png", false); } @@ -155,6 +161,7 @@ void Renderer::SortRenderJobsByDepth(RenderScene &scene) { //Sort all forward jobs so transparency is good. scene.TransparentObjects.sort(Renderer::DepthSort); + scene.SpriteJobs.sort(Renderer::DepthSort); } void Renderer::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) diff --git a/src/Engine/Rendering/Texture.cpp b/src/Engine/Rendering/Texture.cpp index 492b35be..a4b2d4c9 100644 --- a/src/Engine/Rendering/Texture.cpp +++ b/src/Engine/Rendering/Texture.cpp @@ -2,24 +2,25 @@ Texture::Texture(std::string path) { + PNG* img = ResourceManager::Load(path); //TODO: Make this threaded. Catch exeptions in all other load places. - PNG image(path); + //PNG image(path); - if (image.Width == 0 && image.Height == 0 || image.Format == Image::ImageFormat::Unknown) { - //image = PNG("Textures/Core/ErrorTexture.png"); - return; // Temporary fix to remove crash - /* - if (image.Width == 0 && image.Height == 0 || image.Format == Image::ImageFormat::Unknown) { - LOG_ERROR("Couldn't even load the error texture. This is a dark day indeed."); - return; - }*/ - } + //if (img->Width == 0 && img->Height == 0 || img->Format == Image::ImageFormat::Unknown) { + // //image = PNG("Textures/Core/ErrorTexture.png"); + // //return; // Temporary fix to remove crash - this->Width = image.Width; - this->Height = image.Height; + // if (img->Width == 0 && img->Height == 0 || img->Format == Image::ImageFormat::Unknown) { + // LOG_ERROR("Couldn't even load the error texture. This is a dark day indeed."); + // return; + // } + //} + + this->Width = img->Width; + this->Height = img->Height; GLint format; - switch (image.Format) { + switch (img->Format) { case Image::ImageFormat::RGB: format = GL_RGB; break; @@ -32,7 +33,7 @@ Texture::Texture(std::string path) glGenTextures(1, &m_Texture); glBindTexture(GL_TEXTURE_2D, m_Texture); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - glTexImage2D(GL_TEXTURE_2D, 0, format, image.Width, image.Height, 0, format, GL_UNSIGNED_BYTE, image.Data); + glTexImage2D(GL_TEXTURE_2D, 0, format, img->Width, img->Height, 0, format, GL_UNSIGNED_BYTE, img->Data); 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_LINEAR); diff --git a/src/Engine/Rendering/Util/CommonFunctions.cpp b/src/Engine/Rendering/Util/CommonFunctions.cpp index 3c81de66..382cb790 100644 --- a/src/Engine/Rendering/Util/CommonFunctions.cpp +++ b/src/Engine/Rendering/Util/CommonFunctions.cpp @@ -1,2 +1,19 @@ #include "Rendering/Util/CommonFunctions.h" +Texture* CommonFunctions::LoadTexture(std::string path, bool threaded) +{ + Texture* img; + try { + if(threaded) { + img = ResourceManager::Load(path); + } else { + img = ResourceManager::Load(path); + } + } catch (const Resource::StillLoadingException&) { + img = ResourceManager::Load("Textures/Core/ErrorTexture.png"); + } catch (const std::exception&) { + img = nullptr; + } + + return img; +} diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index 0cc41a73..780842a6 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -25,6 +25,7 @@ Game::Game(int argc, char* argv[]) ResourceManager::RegisterType("Model"); ResourceManager::RegisterType("RawModel"); ResourceManager::RegisterType("Texture"); + ResourceManager::RegisterType("Png"); ResourceManager::RegisterType("ShaderProgram"); ResourceManager::RegisterType("EntityFile"); ResourceManager::RegisterType("FontFile"); From 67cf0081221fa90b6a259051b1de7156ab27244b Mon Sep 17 00:00:00 2001 From: William Moberg Date: Wed, 10 Feb 2016 18:03:58 +0100 Subject: [PATCH 178/355] Bug fixing. --- include/Engine/Core/Util/IfDebug.h | 2 +- src/Engine/Rendering/Model.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/include/Engine/Core/Util/IfDebug.h b/include/Engine/Core/Util/IfDebug.h index 79cb3a4c..85b64c8d 100644 --- a/include/Engine/Core/Util/IfDebug.h +++ b/include/Engine/Core/Util/IfDebug.h @@ -4,7 +4,7 @@ // } // NOTE: condition statement is not executed at all in release mode. #ifndef DEBUG_IF -#ifndef DEBUG +#ifdef DEBUG #define DEBUG_IF(c) if(c) #else #define DEBUG_IF(c) if(false) diff --git a/src/Engine/Rendering/Model.cpp b/src/Engine/Rendering/Model.cpp index 6457c980..0c3d7877 100644 --- a/src/Engine/Rendering/Model.cpp +++ b/src/Engine/Rendering/Model.cpp @@ -135,7 +135,7 @@ Model::Model(std::string fileName) maxi = glm::max(maxi, v.Position); } - m_Box = AABB(maxi, mini); + m_Box = AABB(mini, maxi); } Model::~Model() From 95fa1f4bbd4f1b757e05236d58aec9802a218973 Mon Sep 17 00:00:00 2001 From: Jocke Date: Wed, 10 Feb 2016 20:10:20 +0100 Subject: [PATCH 179/355] Connect Fix for TCP Client --- src/Engine/Network/TCPClient.cpp | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/src/Engine/Network/TCPClient.cpp b/src/Engine/Network/TCPClient.cpp index 21bb653f..703e4cbe 100644 --- a/src/Engine/Network/TCPClient.cpp +++ b/src/Engine/Network/TCPClient.cpp @@ -19,16 +19,25 @@ void TCPClient::Connect(std::string playerName, std::string address, int port) Send(packet); LOG_INFO("Connect message sent again!"); } - return; + else { + boost::system::error_code error = boost::asio::error::host_not_found; + m_Socket->connect(m_Endpoint, error); + if (!error) { + m_IsConnected = true; + Packet packet(MessageType::Connect, m_SendPacketID); + packet.WriteString(playerName); + Send(packet); + LOG_INFO("Connect message sent!"); + } + } } - if (!m_IsConnected) { + else if (!m_IsConnected) { 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(new tcp::socket(m_IOService, m_Endpoint)); + m_Socket = std::unique_ptr(new tcp::socket(m_IOService)); + m_Socket->connect(m_Endpoint, error); tcp::no_delay option(true); m_Socket->set_option(option); - m_Socket->close(); - m_Socket->connect(m_Endpoint, error); LOG_INFO(error.message().c_str()); if (!error) { m_IsConnected = true; From 224e95f34aee8c1f23bd8a6941b02b352989240e Mon Sep 17 00:00:00 2001 From: viktorljung Date: Wed, 10 Feb 2016 20:45:24 +0100 Subject: [PATCH 180/355] Fixed BoneAttachment component and optimized animation code a bit --- assets | 2 +- include/Engine/Rendering/AnimationSystem.h | 4 +- include/Engine/Rendering/ModelJob.h | 32 +- include/Engine/Rendering/Skeleton.h | 35 +- resources/Schema/Entities/AnimationTests2.xml | 508 +++++++++++++++++- resources/Schema/Entities/AnimationTests3.xml | 108 ++++ resources/Schema/Entities/FirstPersonArms | 57 ++ src/Engine/Core/ComponentPool.cpp | 2 +- src/Engine/Rendering/AnimationSystem.cpp | 29 +- src/Engine/Rendering/BoneAttachmentSystem.cpp | 9 +- src/Engine/Rendering/DrawFinalPass.cpp | 49 +- src/Engine/Rendering/PickingPass.cpp | 24 +- src/Engine/Rendering/RenderSystem.cpp | 12 +- src/Engine/Rendering/Skeleton.cpp | 405 ++++++-------- 14 files changed, 912 insertions(+), 364 deletions(-) create mode 100644 resources/Schema/Entities/AnimationTests3.xml create mode 100644 resources/Schema/Entities/FirstPersonArms diff --git a/assets b/assets index 7531e441..45cbc3ab 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit 7531e441fea639076d69c6cf05e3ae8ff7170cf9 +Subproject commit 45cbc3abaebe5f815e2c1b58bcf884d4953a4c52 diff --git a/include/Engine/Rendering/AnimationSystem.h b/include/Engine/Rendering/AnimationSystem.h index 15dbe39d..aa9d3a11 100644 --- a/include/Engine/Rendering/AnimationSystem.h +++ b/include/Engine/Rendering/AnimationSystem.h @@ -23,9 +23,7 @@ public: ~AnimationSystem() { } virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& animationComponent, double dt) override; private: - float angle = 0.f; - bool b_forward = false; - char bone[100]; + }; #endif \ No newline at end of file diff --git a/include/Engine/Rendering/ModelJob.h b/include/Engine/Rendering/ModelJob.h index bc2b8b6e..4bb1b51f 100644 --- a/include/Engine/Rendering/ModelJob.h +++ b/include/Engine/Rendering/ModelJob.h @@ -117,33 +117,11 @@ struct ModelJob : RenderJob FillColor = fillColor; FillPercentage = fillPercentage; - Skeleton = Model->m_RawModel->m_Skeleton; - if (Skeleton != nullptr) { - if (world->HasComponent(Entity, "Animation")) { - auto animationComponent = world->GetComponent(Entity, "Animation"); - - for (int i = 1; i <= 3; i++) { - ::Skeleton::AnimationData animationData; - animationData.animation = model->m_RawModel->m_Skeleton->GetAnimation(animationComponent["AnimationName" + std::to_string(i)]); - if (animationData.animation == nullptr) { - continue; - } - animationData.time = (double)animationComponent["Time" + std::to_string(i)]; - animationData.weight = (double)animationComponent["Weight" + std::to_string(i)]; - - Animations.push_back(animationData); - } - } - - if (world->HasComponent(Entity, "AnimationOffset")) { - auto animationOffsetComponent = world->GetComponent(Entity, "AnimationOffset"); - AnimationOffset.animation = model->m_RawModel->m_Skeleton->GetAnimation(animationOffsetComponent["AnimationName"]); - AnimationOffset.time = (double)animationOffsetComponent["Time"]; - } else { - AnimationOffset.animation = nullptr; - } + if (model->IsSkinned()) { + Skeleton = Model->m_RawModel->m_Skeleton; } + }; unsigned int TextureID; @@ -164,10 +142,8 @@ struct ModelJob : RenderJob ::Skeleton* Skeleton = nullptr; // const ::Skeleton::Animation* Animation = nullptr; - std::vector<::Skeleton::AnimationData> Animations; - ::Skeleton::AnimationOffset AnimationOffset; + - float AnimationTime = 0.f; glm::vec4 DiffuseColor; glm::vec4 SpecularColor; diff --git a/include/Engine/Rendering/Skeleton.h b/include/Engine/Rendering/Skeleton.h index 124d618b..a8dd982d 100644 --- a/include/Engine/Rendering/Skeleton.h +++ b/include/Engine/Rendering/Skeleton.h @@ -100,13 +100,13 @@ public: int GetBoneID(std::string name); - const Animation* GetAnimation(std::string name); - std::vector GetFrameBones(std::vector animations, bool noRootMotion = false); - std::vector GetFrameBones(std::vector animations, AnimationOffset animationOffset, bool noRootMotion = false); + void CalculateFrameBones(std::vector animations, AnimationOffset animationOffset, bool noRootMotion = false); + void CalculateFrameBones(std::vector animations, bool noRootMotion = false); - //void AccumulateBoneTransforms(bool noRootMotion, const Animation* animation, float time, std::map& boneMatrices, const Bone* bone, glm::mat4 parentMatrix); - void AccumulateBoneTransforms(bool noRootMotion, std::vector animations, std::map& boneMatrices, const Bone* bone, glm::mat4 parentMatrix); - void AccumulateBoneTransforms(bool noRootMotion, std::vector animations, AnimationOffset animationOffset, std::map& boneMatrices, const Bone* bone, glm::mat4 parentMatrix); + const Animation* GetAnimation(std::string name); + + void AccumulateBoneTransforms(bool noRootMotion, std::vector animations, const Bone* bone, glm::mat4 parentMatrix); + void AccumulateBoneTransforms(bool noRootMotion, std::vector animations, AnimationOffset animationOffset, const Bone* bone, glm::mat4 parentMatrix); void PrintSkeleton(); void PrintSkeleton(const Bone* parent, int depthCount); @@ -115,12 +115,35 @@ public: glm::mat4 GetBoneTransform(const Bone* bone, const Animation* animation, float time, glm::mat4 childMatrix); int GetKeyframe(const Animation& animation, double time); + + std::vector GetBones() + { + std::vector finalMatrices; + for (auto &kv : m_BoneLocalTransforms) { + finalMatrices.push_back(kv.second); + } + return finalMatrices;; + } + + glm::mat4 GetBoneTransformSuper(int boneID) + { + if(m_BoneTransforms.find(boneID) != m_BoneTransforms.end()) { + return m_BoneTransforms.at(boneID); + } else { + return glm::mat4(1); + } + } + private: glm::mat4 GetOffsetTransform(const Bone* bone, AnimationOffset animationOffset); std::map m_BonesByName; float aim = 0.f; + + + std::map m_BoneLocalTransforms; + std::map m_BoneTransforms; }; #endif diff --git a/resources/Schema/Entities/AnimationTests2.xml b/resources/Schema/Entities/AnimationTests2.xml index 96a439a4..09573ac7 100644 --- a/resources/Schema/Entities/AnimationTests2.xml +++ b/resources/Schema/Entities/AnimationTests2.xml @@ -31,28 +31,524 @@ Run 0.5 - 0.23980116887997371 + 0.78014858943309839 1 1 StrafeRight 0.5 - 0.42593105566437428 - ReloadSwitch - 0.68855715986371058 + 0.78620929522779459 + ShootFastRifle + 0.13809128482706701 1 AimRifle + Models/Characters/Assault/AssaultAnimations.mesh - + + true - + + + + + + + + + + R_Arm_Weapon_Joint + + + + Models/Weapons/Blue/AssaultWeapon.mesh + + true + + + + + + + + + + + + R_Hand + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Arm + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Shoulder + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Neck + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Spine_3 + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Spine_2 + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Spine_1 + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Hip + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + L_Leg_Top + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + L_Leg_Bottom + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + L_Foot + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + L_Toe + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + L_Shoulder + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + L_Arm + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + L_Hand + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + L_Shoulder_Armor_Joint + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Chin + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Head + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Perietal + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + L_Elbow + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Leg_Bottom + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Elbow + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Leg_Top + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Foot + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Toe + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + R_Shoulder_Armor_Joint + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/AnimationTests3.xml b/resources/Schema/Entities/AnimationTests3.xml new file mode 100644 index 00000000..bd985b2d --- /dev/null +++ b/resources/Schema/Entities/AnimationTests3.xml @@ -0,0 +1,108 @@ + + + + + + + + + + + + + + + + + + + + Models/Widgets/Lights/DirectionalLightWidget.mesh + + + + + + + + + + + + Run + 0.5 + 0.97312056690160276 + 1 + 1 + ReloadSwitch + 0.91310356788604263 + LeftRight + 0 + 0.040207288496060478 + 1 + + + DownUp + + + + Models/Characters/Assault/FirstPerson.mesh + + true + + + + + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeapon.mesh + + + + + + + + + + + + + + + + + + + + + 10 + + + + + + + + + + + Models/Core/UnitPlane.mesh + + + + + + + + + + + + diff --git a/resources/Schema/Entities/FirstPersonArms b/resources/Schema/Entities/FirstPersonArms new file mode 100644 index 00000000..bf749a4e --- /dev/null +++ b/resources/Schema/Entities/FirstPersonArms @@ -0,0 +1,57 @@ + + + + + + Run + 0.5 + 0.97312056690160276 + 1 + 1 + ReloadSwitch + 0.91310356788604263 + LeftRight + 0 + 0.040207288496060478 + 1 + + + DownUp + + + + Models/Characters/Assault/FirstPerson.mesh + + true + + + + + + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeapon.mesh + + + + + + + + + + + + + + + + + + diff --git a/src/Engine/Core/ComponentPool.cpp b/src/Engine/Core/ComponentPool.cpp index f4ca9f4a..7b465fbc 100644 --- a/src/Engine/Core/ComponentPool.cpp +++ b/src/Engine/Core/ComponentPool.cpp @@ -47,7 +47,7 @@ ComponentWrapper ComponentPool::Allocate(EntityID entity) ComponentWrapper ComponentPool::GetByEntity(EntityID ent) { - return ComponentWrapper(m_ComponentInfo, m_EntityToComponent.at(ent)); + return ComponentWrapper(m_ComponentInfo, m_EntityToComponent.at(ent)); } bool ComponentPool::KnowsEntity(EntityID ent) diff --git a/src/Engine/Rendering/AnimationSystem.cpp b/src/Engine/Rendering/AnimationSystem.cpp index 4566410f..25813a63 100644 --- a/src/Engine/Rendering/AnimationSystem.cpp +++ b/src/Engine/Rendering/AnimationSystem.cpp @@ -24,7 +24,7 @@ void AnimationSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& a const Skeleton::Animation* animation = skeleton->GetAnimation(animationComponent["AnimationName" + std::to_string(i)]); if (animation == nullptr) { - return; + continue;; } double animationSpeed = (double)animationComponent["Speed" + std::to_string(i)]; @@ -49,5 +49,32 @@ void AnimationSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& a } } } + + //Calculate bone transforms + if (skeleton != nullptr) { + std::vector animations; + if (entity.HasComponent("Animation")) { + for (int i = 1; i <= 3; i++) { + Skeleton::AnimationData animationData; + animationData.animation = model->m_RawModel->m_Skeleton->GetAnimation(entity["Animation"]["AnimationName" + std::to_string(i)]); + if (animationData.animation == nullptr) { + continue; + } + animationData.time = (double)entity["Animation"]["Time" + std::to_string(i)]; + animationData.weight = (double)entity["Animation"]["Weight" + std::to_string(i)]; + + animations.push_back(animationData); + } + } + + if (entity.HasComponent("AnimationOffset")) { + Skeleton::AnimationOffset animationOffset; + animationOffset.animation = skeleton->GetAnimation(entity["AnimationOffset"]["AnimationName"]); + animationOffset.time = (double)entity["AnimationOffset"]["Time"]; + skeleton->CalculateFrameBones(animations, animationOffset); + } else { + skeleton->CalculateFrameBones(animations); + } + } } diff --git a/src/Engine/Rendering/BoneAttachmentSystem.cpp b/src/Engine/Rendering/BoneAttachmentSystem.cpp index bdc45fa6..a9588a16 100644 --- a/src/Engine/Rendering/BoneAttachmentSystem.cpp +++ b/src/Engine/Rendering/BoneAttachmentSystem.cpp @@ -39,7 +39,8 @@ void BoneAttachmentSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapp } - glm::mat4 boneTransform = skeleton->GetBoneTransform(skeleton->Bones[id], animation, (double)parent["Animation"]["Time1"], glm::mat4(1)); + glm::mat4 boneTransform = skeleton->GetBoneTransformSuper(id); + //glm::mat4 boneTransform = skeleton->GetBoneTransform(skeleton->Bones[id], animation, (double)parent["Animation"]["Time1"], glm::mat4(1)); glm::vec3 scale; glm::quat rotation; @@ -48,7 +49,9 @@ void BoneAttachmentSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapp glm::vec4 perspective; glm::decompose(boneTransform, scale, rotation, translation, skew, perspective); - glm::vec3 angles; + glm::vec3 angles = glm::vec3(-glm::pitch(rotation), -glm::yaw(rotation), -glm::roll(rotation)); +/* + angles.y = asin(-boneTransform[0][2]); if (cos(angles.y) != 0) { angles.x = atan2(boneTransform[1][2], boneTransform[2][2]); @@ -56,7 +59,7 @@ void BoneAttachmentSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapp } else { angles.x = atan2(-boneTransform[2][0], boneTransform[1][1]); angles.z = 0; - } + }*/ if ((bool)entity["BoneAttachment"]["InheritPosition"]) { (glm::vec3&)entity["Transform"]["Position"] = translation + (glm::vec3)entity["BoneAttachment"]["PositionOffset"]; diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index 0d08b98f..00b85528 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -328,11 +328,7 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& //bind textures BindExplosionTextures(explosionSkinnedHandle, explosionEffectJob); std::vector frameBones; - if (explosionEffectJob->AnimationOffset.animation != nullptr) { - frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations, explosionEffectJob->AnimationOffset); - } else { - frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations); - } + frameBones = explosionEffectJob->Skeleton->GetBones(); glUniformMatrix4fv(glGetUniformLocation(explosionSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); } else { m_ExplosionEffectProgram->Bind(); @@ -355,11 +351,7 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& BindExplosionTextures(explosionSplatMapSkinnedHandle, explosionEffectJob); GLERROR("asdasd"); std::vector frameBones; - if (explosionEffectJob->AnimationOffset.animation != nullptr) { - frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations, explosionEffectJob->AnimationOffset); - } else { - frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations); - } + frameBones = explosionEffectJob->Skeleton->GetBones(); glUniformMatrix4fv(glGetUniformLocation(explosionSplatMapSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); } else { @@ -400,11 +392,7 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& //bind textures BindModelTextures(forwardSkinnedHandle, modelJob); std::vector frameBones; - if (modelJob->AnimationOffset.animation != nullptr) { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); - } else { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); - } + frameBones = modelJob->Skeleton->GetBones(); glUniformMatrix4fv(glGetUniformLocation(forwardSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); } else { @@ -428,11 +416,7 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& BindModelTextures(forwardSplatMapSkinnedHandle, modelJob); GLERROR("asdasd"); std::vector frameBones; - if (modelJob->AnimationOffset.animation != nullptr) { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); - } else { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); - } + frameBones = modelJob->Skeleton->GetBones(); glUniformMatrix4fv(glGetUniformLocation(forwardSplatMapSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); } else { @@ -476,13 +460,8 @@ void DrawFinalPass::DrawShieldToStencilBuffer(std::listViewMatrix())); glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix())); std::vector frameBones; - if (modelJob->AnimationOffset.animation != nullptr) { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); - } else { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); - } + frameBones = modelJob->Skeleton->GetBones(); glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - } else { m_ShieldToStencilProgram->Bind(); GLuint shaderHandle = m_ShieldToStencilProgram->GetHandle(); @@ -535,11 +514,7 @@ void DrawFinalPass::DrawShieldedModelRenderQueue(std::list frameBones; - if (explosionEffectJob->AnimationOffset.animation != nullptr) { - frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations, explosionEffectJob->AnimationOffset); - } else { - frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations); - } + frameBones = explosionEffectJob->Skeleton->GetBones(); glUniformMatrix4fv(glGetUniformLocation(explosionHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); if (GLERROR("Animation")) { @@ -574,11 +549,7 @@ void DrawFinalPass::DrawShieldedModelRenderQueue(std::list frameBones; - if (modelJob->AnimationOffset.animation != nullptr) { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); - } else { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); - } + frameBones = modelJob->Skeleton->GetBones(); glUniformMatrix4fv(glGetUniformLocation(forwardHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); @@ -610,11 +581,7 @@ void DrawFinalPass::DrawToDepthBuffer(std::list>& job glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); std::vector frameBones; - if (modelJob->AnimationOffset.animation != nullptr) { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); - } else { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); - } + frameBones = modelJob->Skeleton->GetBones(); glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); } else { diff --git a/src/Engine/Rendering/PickingPass.cpp b/src/Engine/Rendering/PickingPass.cpp index fa1b3ca3..cc9837ff 100644 --- a/src/Engine/Rendering/PickingPass.cpp +++ b/src/Engine/Rendering/PickingPass.cpp @@ -103,11 +103,7 @@ void PickingPass::Draw(RenderScene& scene) if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { std::vector frameBones; - if (modelJob->AnimationOffset.animation != nullptr) { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); - } else { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); - } + frameBones = modelJob->Skeleton->GetBones(); glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); } @@ -160,11 +156,7 @@ void PickingPass::Draw(RenderScene& scene) glUniform2fv(glGetUniformLocation(shaderSkinnedHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1]))); std::vector frameBones; - if (modelJob->AnimationOffset.animation != nullptr) { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); - } else { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); - } + frameBones = modelJob->Skeleton->GetBones(); glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); } else { m_PickingProgram->Bind(); @@ -215,11 +207,7 @@ void PickingPass::Draw(RenderScene& scene) glUniform2fv(glGetUniformLocation(shaderSkinnedHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1]))); std::vector frameBones; - if (modelJob->AnimationOffset.animation != nullptr) { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); - } else { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); - } + frameBones = modelJob->Skeleton->GetBones(); glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); } else { @@ -276,11 +264,7 @@ void PickingPass::Draw(RenderScene& scene) if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { std::vector frameBones; - if (modelJob->AnimationOffset.animation != nullptr) { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); - } else { - frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); - } + frameBones = modelJob->Skeleton->GetBones(); glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); } diff --git a/src/Engine/Rendering/RenderSystem.cpp b/src/Engine/Rendering/RenderSystem.cpp index ab9a3c27..d2c71f5e 100644 --- a/src/Engine/Rendering/RenderSystem.cpp +++ b/src/Engine/Rendering/RenderSystem.cpp @@ -62,14 +62,14 @@ void RenderSystem::fillModels(RenderScene::Queues &Jobs) } // Only render children of a camera if that camera is currently active - if (isChildOfACamera(entity) && !isChildOfCurrentCamera(entity)) { - continue; - } + if (isChildOfACamera(entity) && !isChildOfCurrentCamera(entity)) { + continue; + } // Hide things parented to local player if they have the HiddenFromLocalPlayer component - if (entity.HasComponent("HiddenForLocalPlayer") && (entity == m_LocalPlayer || entity.IsChildOf(m_LocalPlayer))) { - continue; - } + if (entity.HasComponent("HiddenForLocalPlayer") && (entity == m_LocalPlayer || entity.IsChildOf(m_LocalPlayer))) { + continue; + } Model* model; try { diff --git a/src/Engine/Rendering/Skeleton.cpp b/src/Engine/Rendering/Skeleton.cpp index f272f14d..1aabd84c 100644 --- a/src/Engine/Rendering/Skeleton.cpp +++ b/src/Engine/Rendering/Skeleton.cpp @@ -29,6 +29,32 @@ Skeleton::~Skeleton() } } + +void Skeleton::CalculateFrameBones(std::vector animations, AnimationOffset animationOffset, bool noRootMotion /*= false*/) +{ + if (animations.size() <= 0 || animationOffset.animation == nullptr) { + for (auto& b : Bones) { + m_BoneLocalTransforms[b.first] = glm::mat4(1); + m_BoneTransforms[b.first] = glm::mat4(1); + } + } else { + AccumulateBoneTransforms(noRootMotion, animations, animationOffset, RootBone, glm::mat4(1)); + } +} + + +void Skeleton::CalculateFrameBones(std::vector animations, bool noRootMotion /*= false*/) +{ + if (animations.size() <= 0) { + for (auto& b : Bones) { + m_BoneLocalTransforms[b.first] = glm::mat4(1); + m_BoneTransforms[b.first] = glm::mat4(1); + } + } else { + AccumulateBoneTransforms(noRootMotion, animations, RootBone, glm::mat4(1)); + } +} + const Skeleton::Animation* Skeleton::GetAnimation(std::string name) { auto it = Animations.find(name); @@ -39,252 +65,10 @@ const Skeleton::Animation* Skeleton::GetAnimation(std::string name) } } -std::vector Skeleton::GetFrameBones(std::vector animations, bool noRootMotion /*= false*/) -{ - if (animations.size() <= 0) { - std::vector finalMatrices; - for (auto& b : Bones) { - finalMatrices.push_back(glm::mat4(1));//b.second->OffsetMatrix); - } - return finalMatrices; - } - - std::map frameBones; - AccumulateBoneTransforms(true, animations, frameBones, RootBone, glm::mat4(1)); - - std::vector finalMatrices; - for (auto &kv : frameBones) { - finalMatrices.push_back(kv.second); - } - return finalMatrices; -} - - -std::vector Skeleton::GetFrameBones(std::vector animations, AnimationOffset animationOffset, bool noRootMotion /*= false*/) -{ - if (animations.size() <= 0 || animationOffset.animation == nullptr) { - std::vector finalMatrices; - for (auto& b : Bones) { - finalMatrices.push_back(glm::mat4(1));//b.second->OffsetMatrix); - } - return finalMatrices; - } - - - std::map frameBones; - AccumulateBoneTransforms(true, animations, animationOffset, frameBones, RootBone, glm::mat4(1)); - - std::vector finalMatrices; - for (auto &kv : frameBones) { - finalMatrices.push_back(kv.second); - } - return finalMatrices; -} -/* - -void Skeleton::AccumulateBoneTransforms(bool noRootMotion, const Animation* animation, float time, std::map& boneMatrices, const Bone* bone, glm::mat4 parentMatrix) +void Skeleton::AccumulateBoneTransforms(bool noRootMotion, std::vector animations, AnimationOffset animationOffset, const Bone* bone, glm::mat4 parentMatrix) { glm::mat4 boneMatrix; - Animation::Keyframe currentFrame; - Animation::Keyframe nextFrame; - - if(animation->JointAnimations.find(bone->ID) != animation->JointAnimations.end()) { - std::vector boneKeyFrames = animation->JointAnimations.at(bone->ID); - - if(boneKeyFrames.size() > 1) { // 2+ keyframes for the current bone - for (int index = boneKeyFrames.size()-1; index >= 0; index--) { // find the bone keyframes that surrounds the current frame - if (time >= boneKeyFrames.at(index).Time) { - currentFrame = boneKeyFrames.at(index); - nextFrame = boneKeyFrames.at((index + 1) % boneKeyFrames.size()); - break; - } - } - - float progress; - - if(nextFrame.Index == 0) { - progress = (time - currentFrame.Time) / (animation->Duration - currentFrame.Time); - } else { - progress = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); - - } - - - if (progress > 1.0f || progress < 0.0f) { - LOG_INFO("Progress: %f", progress); - progress = glm::clamp(progress, 0.0f, 1.0f); - } - Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties; - Animation::Keyframe::BoneProperty nextBoneProperty = nextFrame.BoneProperties; - - glm::vec3 positionInterp = currentBoneProperty.Position * (1.f - progress) + nextBoneProperty.Position * progress; - glm::quat rotationInterp = glm::slerp(currentBoneProperty.Rotation, nextBoneProperty.Rotation, progress); - glm::vec3 scaleInterp = currentBoneProperty.Scale * (1.f - progress) + nextBoneProperty.Scale * progress; - - // Flag for no root motion - if (bone == RootBone && noRootMotion) { - positionInterp.x = 0; - positionInterp.z = 0; - } - - boneMatrix = parentMatrix *(glm::translate(positionInterp) * glm::toMat4(rotationInterp) * glm::scale(scaleInterp)); - boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix; - - } else { // 1 keyframes for the current bone - currentFrame = boneKeyFrames.at(0); - boneMatrix = parentMatrix *(glm::translate(currentFrame.BoneProperties.Position) * glm::toMat4(currentFrame.BoneProperties.Rotation) * glm::scale(currentFrame.BoneProperties.Scale)); - - boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix; - } - } else { // 0 keyframes for the current bone - - // LOG_INFO("%s Has no keyframe", bone->Name.c_str()); - if (bone->Parent) { - boneMatrix = parentMatrix * glm::inverse(bone->OffsetMatrix) * bone->Parent->OffsetMatrix; - boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix; - } else { - boneMatrix = glm::inverse(bone->OffsetMatrix); - boneMatrices[bone->ID] = parentMatrix; - } - - } - - for (auto &child : bone->Children) { - AccumulateBoneTransforms(noRootMotion, animation, time, boneMatrices, child, boneMatrix); - } -} -*/ - -void Skeleton::AccumulateBoneTransforms(bool noRootMotion, std::vector animations, std::map& boneMatrices, const Bone* bone, glm::mat4 parentMatrix) -{ - glm::mat4 boneMatrix; - - - - std::vector JointTransforms; - - for (const AnimationData animationData : animations) { - const Animation* animation = animationData.animation; - const float time = animationData.time; - - JointFrameTransform jointTransform; - jointTransform.Weight = animationData.weight;; - - if (animation->JointAnimations.find(bone->ID) != animation->JointAnimations.end()) { - std::vector boneKeyFrames = animation->JointAnimations.at(bone->ID); - - Animation::Keyframe currentFrame; - Animation::Keyframe nextFrame; - - if (boneKeyFrames.size() > 1) { // 2+ keyframes for the current bone - for (int index = boneKeyFrames.size()-1; index >= 0; index--) { // find the bone keyframes that surrounds the current frame - if (time >= boneKeyFrames.at(index).Time) { - currentFrame = boneKeyFrames.at(index); - nextFrame = boneKeyFrames.at((index + 1) % boneKeyFrames.size()); - break; - } - } - - float progress; - - if (nextFrame.Index == 0) { - progress = (time - currentFrame.Time) / (animation->Duration - currentFrame.Time); - } else { - progress = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); - - } - - - if (progress > 1.0f || progress < 0.0f) { - LOG_INFO("Progress: %f", progress); - progress = glm::clamp(progress, 0.0f, 1.0f); - } - Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties; - Animation::Keyframe::BoneProperty nextBoneProperty = nextFrame.BoneProperties; - - jointTransform.PositionInterp = currentBoneProperty.Position * (1.f - progress) + nextBoneProperty.Position * progress; - jointTransform.RotationInterp = glm::slerp(currentBoneProperty.Rotation, nextBoneProperty.Rotation, progress); - jointTransform.ScaleInterp = currentBoneProperty.Scale * (1.f - progress) + nextBoneProperty.Scale * progress; - - // Flag for no root motion - if (bone == RootBone && noRootMotion) { - jointTransform.PositionInterp.x = 0; - jointTransform.PositionInterp.z = 0; - } - - JointTransforms.push_back(jointTransform); - - } else { // 1 keyframes for the current bone - currentFrame = boneKeyFrames.at(0); - jointTransform.PositionInterp = currentFrame.BoneProperties.Position; - jointTransform.RotationInterp = currentFrame.BoneProperties.Rotation; - jointTransform.ScaleInterp = currentFrame.BoneProperties.Scale; - JointTransforms.push_back(jointTransform); - - } - } else { // 0 keyframes for the current bone - - } - - } - - if(JointTransforms.size() <= 0) { - if (bone->Parent) { - boneMatrix = parentMatrix * glm::inverse(bone->OffsetMatrix) * bone->Parent->OffsetMatrix; - boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix; - } else { - boneMatrix = glm::inverse(bone->OffsetMatrix); - boneMatrices[bone->ID] = parentMatrix; - } - } else if (JointTransforms.size() == 1) { - boneMatrix = parentMatrix *(glm::translate(JointTransforms.at(0).PositionInterp) * glm::toMat4(JointTransforms.at(0).RotationInterp) * glm::scale(JointTransforms.at(0).ScaleInterp)); - boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix; - } else { - - glm::vec3 finalPosInterp; - glm::quat finalRotInterp; - glm::vec3 finalScaleInterp; - float totalWeight = 0; - - for (JointFrameTransform jointTransform : JointTransforms) { - totalWeight += jointTransform.Weight; - } - - - for (JointFrameTransform jointTransform : JointTransforms) - { - if(jointTransform.Weight == 1.0f) { - finalPosInterp = jointTransform.PositionInterp; - finalRotInterp = jointTransform.RotationInterp; - finalScaleInterp = jointTransform.ScaleInterp; - break; - } else { - finalPosInterp += jointTransform.PositionInterp * (jointTransform.Weight/totalWeight); - finalRotInterp *= glm::slerp(glm::quat(), jointTransform.RotationInterp, (jointTransform.Weight/totalWeight)); - finalScaleInterp += jointTransform.ScaleInterp * (jointTransform.Weight/totalWeight); - } - - } - - boneMatrix = parentMatrix *(glm::translate(finalPosInterp) * glm::toMat4(finalRotInterp) * glm::scale(finalScaleInterp)); - boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix; - } - - - - for (auto &child : bone->Children) { - AccumulateBoneTransforms(noRootMotion, animations, boneMatrices, child, boneMatrix); - } -} - - -void Skeleton::AccumulateBoneTransforms(bool noRootMotion, std::vector animations, AnimationOffset animationOffset, std::map& boneMatrices, const Bone* bone, glm::mat4 parentMatrix) -{ - glm::mat4 boneMatrix; - - - std::vector JointTransforms; for (const AnimationData animationData : animations) { @@ -363,10 +147,12 @@ void Skeleton::AccumulateBoneTransforms(bool noRootMotion, std::vectorOffsetMatrix) * bone->Parent->OffsetMatrix)); } - boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix; + m_BoneLocalTransforms[bone->ID] = boneMatrix * bone->OffsetMatrix; + m_BoneTransforms[bone->ID] = boneMatrix; } else { boneMatrix = offset * glm::inverse(bone->OffsetMatrix); - boneMatrices[bone->ID] = parentMatrix; + m_BoneLocalTransforms[bone->ID] = parentMatrix; + m_BoneTransforms[bone->ID] = boneMatrix; } } else { @@ -401,15 +187,138 @@ void Skeleton::AccumulateBoneTransforms(bool noRootMotion, std::vectorID] = boneMatrix * bone->OffsetMatrix; + + m_BoneLocalTransforms[bone->ID] = boneMatrix * bone->OffsetMatrix; + m_BoneTransforms[bone->ID] = boneMatrix; } for (auto &child : bone->Children) { - AccumulateBoneTransforms(noRootMotion, animations, animationOffset, boneMatrices, child, boneMatrix); + AccumulateBoneTransforms(noRootMotion, animations, animationOffset, child, boneMatrix); } } +void Skeleton::AccumulateBoneTransforms(bool noRootMotion, std::vector animations, const Bone* bone, glm::mat4 parentMatrix) +{ + glm::mat4 boneMatrix; + std::vector JointTransforms; + + for (const AnimationData animationData : animations) { + const Animation* animation = animationData.animation; + const float time = animationData.time; + + JointFrameTransform jointTransform; + jointTransform.Weight = animationData.weight;; + + if (animation->JointAnimations.find(bone->ID) != animation->JointAnimations.end()) { + std::vector boneKeyFrames = animation->JointAnimations.at(bone->ID); + + Animation::Keyframe currentFrame; + Animation::Keyframe nextFrame; + + if (boneKeyFrames.size() > 1) { // 2+ keyframes for the current bone + for (int index = boneKeyFrames.size()-1; index >= 0; index--) { // find the bone keyframes that surrounds the current frame + if (time >= boneKeyFrames.at(index).Time) { + currentFrame = boneKeyFrames.at(index); + nextFrame = boneKeyFrames.at((index + 1) % boneKeyFrames.size()); + break; + } + } + + float progress; + + if (nextFrame.Index == 0) { + progress = (time - currentFrame.Time) / (animation->Duration - currentFrame.Time); + } else { + progress = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); + + } + + + if (progress > 1.0f || progress < 0.0f) { + LOG_INFO("Progress: %f", progress); + progress = glm::clamp(progress, 0.0f, 1.0f); + } + Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties; + Animation::Keyframe::BoneProperty nextBoneProperty = nextFrame.BoneProperties; + + jointTransform.PositionInterp = currentBoneProperty.Position * (1.f - progress) + nextBoneProperty.Position * progress; + jointTransform.RotationInterp = glm::slerp(currentBoneProperty.Rotation, nextBoneProperty.Rotation, progress); + jointTransform.ScaleInterp = currentBoneProperty.Scale * (1.f - progress) + nextBoneProperty.Scale * progress; + + // Flag for no root motion + if (bone == RootBone && noRootMotion) { + jointTransform.PositionInterp.x = 0; + jointTransform.PositionInterp.z = 0; + } + + JointTransforms.push_back(jointTransform); + + } else { // 1 keyframes for the current bone + currentFrame = boneKeyFrames.at(0); + jointTransform.PositionInterp = currentFrame.BoneProperties.Position; + jointTransform.RotationInterp = currentFrame.BoneProperties.Rotation; + jointTransform.ScaleInterp = currentFrame.BoneProperties.Scale; + JointTransforms.push_back(jointTransform); + + } + } else { // 0 keyframes for the current bone + + } + + } + + if (JointTransforms.size() <= 0) { + if (bone->Parent) { + boneMatrix = parentMatrix * glm::inverse(bone->OffsetMatrix) * bone->Parent->OffsetMatrix; + m_BoneLocalTransforms[bone->ID] = boneMatrix * bone->OffsetMatrix; + m_BoneTransforms[bone->ID] = boneMatrix; + } else { + boneMatrix = glm::inverse(bone->OffsetMatrix); + m_BoneLocalTransforms[bone->ID] = parentMatrix; + m_BoneTransforms[bone->ID] = boneMatrix; + } + } else if (JointTransforms.size() == 1) { + boneMatrix = parentMatrix *(glm::translate(JointTransforms.at(0).PositionInterp) * glm::toMat4(JointTransforms.at(0).RotationInterp) * glm::scale(JointTransforms.at(0).ScaleInterp)); + m_BoneLocalTransforms[bone->ID] = boneMatrix * bone->OffsetMatrix; + m_BoneTransforms[bone->ID] = boneMatrix; + } else { + + glm::vec3 finalPosInterp; + glm::quat finalRotInterp; + glm::vec3 finalScaleInterp; + float totalWeight = 0; + + for (JointFrameTransform jointTransform : JointTransforms) { + totalWeight += jointTransform.Weight; + } + + + for (JointFrameTransform jointTransform : JointTransforms) { + if (jointTransform.Weight == 1.0f) { + finalPosInterp = jointTransform.PositionInterp; + finalRotInterp = jointTransform.RotationInterp; + finalScaleInterp = jointTransform.ScaleInterp; + break; + } else { + finalPosInterp += jointTransform.PositionInterp * (jointTransform.Weight/totalWeight); + finalRotInterp *= glm::slerp(glm::quat(), jointTransform.RotationInterp, (jointTransform.Weight/totalWeight)); + finalScaleInterp += jointTransform.ScaleInterp * (jointTransform.Weight/totalWeight); + } + + } + + boneMatrix = parentMatrix *(glm::translate(finalPosInterp) * glm::toMat4(finalRotInterp) * glm::scale(finalScaleInterp)); + + m_BoneLocalTransforms[bone->ID] = boneMatrix * bone->OffsetMatrix; + m_BoneTransforms[bone->ID] = boneMatrix; + } + + + + for (auto &child : bone->Children) { + AccumulateBoneTransforms(noRootMotion, animations, child, boneMatrix); + } +} glm::mat4 Skeleton::GetOffsetTransform(const Bone* bone, AnimationOffset animationOffset) { From a53ab7f74574e2bdd018563ded7a62d2a7357314 Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Wed, 10 Feb 2016 20:46:16 +0100 Subject: [PATCH 181/355] A few fixes for DashAbility. Default DoubleTapToDash is now set to false. --- .../Engine/Input/FirstPersonInputController.h | 25 +++++++++++-------- resources/DefaultInput.ini | 4 +-- 2 files changed, 17 insertions(+), 12 deletions(-) diff --git a/include/Engine/Input/FirstPersonInputController.h b/include/Engine/Input/FirstPersonInputController.h index 2bbd768d..20402cd0 100644 --- a/include/Engine/Input/FirstPersonInputController.h +++ b/include/Engine/Input/FirstPersonInputController.h @@ -54,6 +54,7 @@ protected: //specialabilitys bool m_MovementKeyDown = false; bool m_SpecialAbilityKeyDown = false; + int m_NumberOfMovementKeysDown = 0; EventRelay m_ELockMouse; bool OnLockMouse(const Events::LockMouse& e); @@ -131,6 +132,7 @@ bool FirstPersonInputController::OnCommand(const Events::InputComm } //if value = 0 then you have just released this key if (e.Value != 0) { + m_NumberOfMovementKeysDown++; m_MovementKeyDown = true; //if you pressed the same key within m_AssaultDashDoubleTapSensitivityTimer then you have doubletapped it if (m_AssaultDashDoubleTapDeltaTime < m_AssaultDashDoubleTapSensitivityTimer && m_AssaultDashTapDirection == m_CurrentDirectionVector) { @@ -138,10 +140,14 @@ bool FirstPersonInputController::OnCommand(const Events::InputComm } } else { //== 0 - m_MovementKeyDown = false; - //you have just released the key, store what key it was and reset the doubletap-sensitivity-timer - m_AssaultDashTapDirection = m_CurrentDirectionVector; - m_AssaultDashDoubleTapDeltaTime = 0.f; + m_NumberOfMovementKeysDown--; + if (m_NumberOfMovementKeysDown == 0) { + m_MovementKeyDown = false; + } + //you have just released the key, store what key it was and reset the doubletap-sensitivity-timer + m_AssaultDashTapDirection = m_CurrentDirectionVector; + m_AssaultDashDoubleTapDeltaTime = 0.f; + } } @@ -201,12 +207,6 @@ void FirstPersonInputController::AssaultDashCheck(double dt, bool m_AssaultDashCoolDownTimer = assaultDashCoolDownMaxTimer; m_AssaultDashDoubleTapped = true; m_AssaultDashDoubleTapDeltaTime = 0.f; - //moving to the side has priority - return; - } - - //dashing with doubletap - check if doubletap to dash enabled - if (ResourceManager::Load("Input.ini")->Get("Keyboard.DoubleTapToDash", false)) { return; } @@ -215,6 +215,11 @@ void FirstPersonInputController::AssaultDashCheck(double dt, bool m_AssaultDashDoubleTapped = false; } + //dashing with doubletap - check if doubletap to dash enabled + if (!ResourceManager::Load("Input.ini")->Get("Keyboard.DoubleTapToDash", false)) { + return; + } + //check if we have received a valid doubletap if (!m_ValidDoubleTap) { return; diff --git a/resources/DefaultInput.ini b/resources/DefaultInput.ini index eb5b7658..35aceeb1 100644 --- a/resources/DefaultInput.ini +++ b/resources/DefaultInput.ini @@ -2,8 +2,8 @@ Sensitivity=0.5 InvertPitch=false -[KeyBoard] -DoubleTapToDash=true +[Keyboard] +DoubleTapToDash=false [Bindings] MouseLeft=PrimaryFire From f5de267f2552d3bc6ae8211fd2c77b6fe3862867 Mon Sep 17 00:00:00 2001 From: Tleety Date: Wed, 10 Feb 2016 20:58:10 +0100 Subject: [PATCH 182/355] Merge fixes and CapturePointHUD component skeleton added. --- include/Engine/Rendering/RawModelCustom.h | 2 +- include/Engine/Rendering/RenderQueue.h | 5 +- include/Engine/Rendering/SpriteJob.h | 8 +- resources/Schema/Components.xsd | 1 + .../Schema/Components/CapturePointHUD.xml | 2 + .../Schema/Components/CapturePointHUD.xsd | 6 + .../Schema/Entities/QualityAssurance.xml | 104 ++++++++++-------- resources/Schema/Types/Entity.xsd | 1 + src/Engine/Rendering/DrawFinalPass.cpp | 2 +- src/Engine/Rendering/Model.cpp | 47 ++------ src/Engine/Rendering/RenderSystem.cpp | 2 +- src/Engine/Rendering/Renderer.cpp | 2 +- 12 files changed, 87 insertions(+), 95 deletions(-) create mode 100644 resources/Schema/Components/CapturePointHUD.xml create mode 100644 resources/Schema/Components/CapturePointHUD.xsd diff --git a/include/Engine/Rendering/RawModelCustom.h b/include/Engine/Rendering/RawModelCustom.h index cf21fb6d..ebf8da2b 100644 --- a/include/Engine/Rendering/RawModelCustom.h +++ b/include/Engine/Rendering/RawModelCustom.h @@ -50,7 +50,7 @@ public: struct TextureProperties { std::string TexturePath; glm::vec2 UVRepeat; - std::shared_ptr<::Texture> Texture; + Texture* Texture; }; struct MaterialBasic diff --git a/include/Engine/Rendering/RenderQueue.h b/include/Engine/Rendering/RenderQueue.h index 21802e05..647adab8 100644 --- a/include/Engine/Rendering/RenderQueue.h +++ b/include/Engine/Rendering/RenderQueue.h @@ -26,8 +26,7 @@ struct RenderScene std::list> OpaqueShieldedObjects; std::list> TransparentShieldedObjects; std::list> ShieldObjects; - std::list> SpriteJobs; - + std::list> SpriteJob; std::list> PointLight; std::list> Text; std::list> DirectionalLight; @@ -44,7 +43,7 @@ struct RenderScene Jobs.OpaqueShieldedObjects.clear(); Jobs.TransparentShieldedObjects.clear(); Jobs.ShieldObjects.clear(); - SpriteJobs.clear(); + Jobs.SpriteJob.clear(); Jobs.DirectionalLight.clear(); } }; diff --git a/include/Engine/Rendering/SpriteJob.h b/include/Engine/Rendering/SpriteJob.h index 23bf6360..2708ab0e 100644 --- a/include/Engine/Rendering/SpriteJob.h +++ b/include/Engine/Rendering/SpriteJob.h @@ -21,15 +21,15 @@ struct SpriteJob : RenderJob : RenderJob() { Model = ResourceManager::Load<::Model>("Models/Core/UnitQuad.mesh"); - ::RawModel::MaterialGroup matGroup = Model->MaterialGroups().front(); - TextureID = (matGroup.Texture) ? matGroup.Texture->ResourceID : 0; + ::RawModel::MaterialProperties matProp = Model->MaterialGroups().front(); + TextureID = 0; DiffuseTexture = CommonFunctions::LoadTexture(cSprite["DiffuseTexture"], true); IncandescenceTexture = CommonFunctions::LoadTexture(cSprite["GlowMap"], true); - StartIndex = matGroup.StartIndex; - EndIndex = matGroup.EndIndex; + StartIndex = matProp.material->StartIndex; + EndIndex = matProp.material->EndIndex; Matrix = matrix; Color = cSprite["Color"]; Entity = cSprite.EntityID; diff --git a/resources/Schema/Components.xsd b/resources/Schema/Components.xsd index 9487a7ad..bcc3fbdf 100644 --- a/resources/Schema/Components.xsd +++ b/resources/Schema/Components.xsd @@ -37,4 +37,5 @@ + \ No newline at end of file diff --git a/resources/Schema/Components/CapturePointHUD.xml b/resources/Schema/Components/CapturePointHUD.xml new file mode 100644 index 00000000..c024411c --- /dev/null +++ b/resources/Schema/Components/CapturePointHUD.xml @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/resources/Schema/Components/CapturePointHUD.xsd b/resources/Schema/Components/CapturePointHUD.xsd new file mode 100644 index 00000000..dfdef822 --- /dev/null +++ b/resources/Schema/Components/CapturePointHUD.xsd @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/resources/Schema/Entities/QualityAssurance.xml b/resources/Schema/Entities/QualityAssurance.xml index 7a69ed32..c234f93a 100644 --- a/resources/Schema/Entities/QualityAssurance.xml +++ b/resources/Schema/Entities/QualityAssurance.xml @@ -40,7 +40,7 @@ - + @@ -120,11 +120,7 @@ - - Run - - 1 - + Models/Characters/Assault/AssaultAnimated.mesh @@ -136,11 +132,7 @@ - - Walk - - 1 - + Models/Characters/Assault/AssaultAnimated.mesh @@ -188,17 +180,13 @@ - + - - Run - - 1 - + Models/Characters/Assault/AssaultAnimated.mesh @@ -683,7 +671,7 @@ - + @@ -730,7 +718,7 @@ - + @@ -790,7 +778,7 @@ - + @@ -837,7 +825,7 @@ - + @@ -883,7 +871,7 @@ - + @@ -930,7 +918,7 @@ - + @@ -977,7 +965,7 @@ - + @@ -1390,7 +1378,7 @@ - + @@ -1399,7 +1387,7 @@ true - 0.75102457088592522 + 0.75134174339666815 3.7999999523162842 true @@ -1446,7 +1434,7 @@ - + @@ -1455,7 +1443,7 @@ - 1.2009303215000324 + 1.2012474940107754 Models/Characters/Assault/AssaultTPose.mesh @@ -1498,22 +1486,18 @@ - + - - Walk - - 1 - + true - 0.68437610515996361 + 0.68469327767070653 true @@ -1558,7 +1542,7 @@ - + @@ -1568,7 +1552,7 @@ true - 0.95047462600732735 + 0.95079179851807027 10 3 @@ -1616,7 +1600,7 @@ - + @@ -1626,7 +1610,7 @@ true - 1.350502887383392 + 1.3508200598941349 true 5 true @@ -1807,7 +1791,7 @@ true - 1.3671759474185377 + 1.3674931199292806 3.7999999523162842 true @@ -1850,11 +1834,7 @@ - - Hold Pos - - 1 - + Models/AssaultAnimated.mesh @@ -1916,7 +1896,8 @@ - Models/BushAlive.mesh + Models/Props/Flora/AliveBush.mesh + true @@ -1943,6 +1924,37 @@ + + + + + + + + + + + + Textures/Props/FoliageDiff.png + + + + + + + + + + Textures/Props/FoliageDiff.png + + + + + + + + + diff --git a/resources/Schema/Types/Entity.xsd b/resources/Schema/Types/Entity.xsd index 16366a67..8c9f6bcc 100644 --- a/resources/Schema/Types/Entity.xsd +++ b/resources/Schema/Types/Entity.xsd @@ -41,6 +41,7 @@ + diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index 2e1e717e..e5e046dc 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -193,7 +193,7 @@ void DrawFinalPass::Draw(RenderScene& scene) GLERROR("OpaqueObjects"); DrawModelRenderQueues(scene.Jobs.TransparentObjects, scene); GLERROR("TransparentObjects"); - DrawSprites(scene.SpriteJobs, scene); + DrawSprites(scene.Jobs.SpriteJob, scene); GLERROR("SpriteJobs"); //DrawStencilState* stencilState = new DrawStencilState(m_FinalPassFrameBuffer.GetHandle()); diff --git a/src/Engine/Rendering/Model.cpp b/src/Engine/Rendering/Model.cpp index 009e4abe..ce6eab8c 100644 --- a/src/Engine/Rendering/Model.cpp +++ b/src/Engine/Rendering/Model.cpp @@ -10,60 +10,31 @@ Model::Model(std::string fileName) case RawModel::MaterialType::SingleTextures: { RawModel::MaterialSingleTextures* materialSingleTexture = static_cast(materialProperty.material); - if (!materialSingleTexture->ColorMap.TexturePath.empty()) { - materialSingleTexture->ColorMap.Texture = std::shared_ptr(ResourceManager::LoadfixTexture>(materialSingleTexture->ColorMap.TexturePath)); - } - if (!materialSingleTexture->NormalMap.TexturePath.empty()) { - materialSingleTexture->NormalMap.Texture = std::shared_ptr(ResourceManager::LoadfixTexture>(materialSingleTexture->NormalMap.TexturePath)); - } - if (!materialSingleTexture->SpecularMap.TexturePath.empty()) { - materialSingleTexture->SpecularMap.Texture = std::shared_ptr(ResourceManager::LoadfixTexture>(materialSingleTexture->SpecularMap.TexturePath)); - } - if (!materialSingleTexture->IncandescenceMap.TexturePath.empty()) { - materialSingleTexture->IncandescenceMap.Texture = std::shared_ptr(ResourceManager::LoadfixTexture>(materialSingleTexture->IncandescenceMap.TexturePath)); - } + materialSingleTexture->ColorMap.Texture = CommonFunctions::LoadTexture(materialSingleTexture->ColorMap.TexturePath, false); + materialSingleTexture->NormalMap.Texture = CommonFunctions::LoadTexture(materialSingleTexture->NormalMap.TexturePath, false); + materialSingleTexture->SpecularMap.Texture = CommonFunctions::LoadTexture(materialSingleTexture->SpecularMap.TexturePath, false); + materialSingleTexture->IncandescenceMap.Texture = CommonFunctions::LoadTexture(materialSingleTexture->IncandescenceMap.TexturePath, false); } break; case RawModel::MaterialType::SplatMapping: { RawModel::MaterialSplatMapping* materialSplatMapping = static_cast(materialProperty.material); - if (!materialSplatMapping->SplatMap.TexturePath.empty()) { - materialSplatMapping->SplatMap.Texture = std::shared_ptr(ResourceManager::Load(materialSplatMapping->SplatMap.TexturePath)); - } + materialSplatMapping->SplatMap.Texture = CommonFunctions::LoadTexture(materialSplatMapping->SplatMap.TexturePath, false); for (auto& texture : materialSplatMapping->ColorMaps) { - if (!texture.TexturePath.empty()) { - texture.Texture = std::shared_ptr(ResourceManager::Load(texture.TexturePath)); - } - else { - texture.Texture = nullptr; - } + texture.Texture = CommonFunctions::LoadTexture(texture.TexturePath, false); } for (auto& texture : materialSplatMapping->NormalMaps) { - if (!texture.TexturePath.empty()) { - texture.Texture = std::shared_ptr(ResourceManager::Load(texture.TexturePath)); - } else { - texture.Texture = nullptr; - } + texture.Texture = CommonFunctions::LoadTexture(texture.TexturePath, false); } for (auto& texture : materialSplatMapping->SpecularMaps) { - if (!texture.TexturePath.empty()) { - texture.Texture = std::shared_ptr(ResourceManager::Load(texture.TexturePath)); - } - else { - texture.Texture = nullptr; - } + texture.Texture = CommonFunctions::LoadTexture(texture.TexturePath, false); } for (auto& texture : materialSplatMapping->IncandescenceMaps) { - if (!texture.TexturePath.empty()) { - texture.Texture = std::shared_ptr(ResourceManager::Load(texture.TexturePath)); - } - else { - texture.Texture = nullptr; - } + texture.Texture = CommonFunctions::LoadTexture(texture.TexturePath, false); } } break; diff --git a/src/Engine/Rendering/RenderSystem.cpp b/src/Engine/Rendering/RenderSystem.cpp index eb81818e..173afc95 100644 --- a/src/Engine/Rendering/RenderSystem.cpp +++ b/src/Engine/Rendering/RenderSystem.cpp @@ -346,7 +346,7 @@ void RenderSystem::Update(double dt) fillPointLights(scene.Jobs.PointLight, m_World); //TODO: Make sure all objects needed are also sorted. scene.Jobs.OpaqueObjects.sort(); - fillSprites(scene.SpriteJobs, m_World); + fillSprites(scene.Jobs.SpriteJob, m_World); fillDirectionalLights(scene.Jobs.DirectionalLight, m_World); fillText(scene.Jobs.Text, m_World); m_RenderFrame->Add(scene); diff --git a/src/Engine/Rendering/Renderer.cpp b/src/Engine/Rendering/Renderer.cpp index f02ca4d5..6f53eeda 100644 --- a/src/Engine/Rendering/Renderer.cpp +++ b/src/Engine/Rendering/Renderer.cpp @@ -167,7 +167,7 @@ void Renderer::SortRenderJobsByDepth(RenderScene &scene) { //Sort all forward jobs so transparency is good. scene.Jobs.TransparentObjects.sort(Renderer::DepthSort); - scene.SpriteJobs.sort(Renderer::DepthSort); + scene.Jobs.SpriteJob.sort(Renderer::DepthSort); } void Renderer::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) From ec54b1298d0b7d383ae837337ded5eb190705f44 Mon Sep 17 00:00:00 2001 From: Jocke Date: Wed, 10 Feb 2016 21:02:46 +0100 Subject: [PATCH 183/355] Reconnect is now possible. --- include/Engine/Network/TCPServer.h | 1 + src/Engine/Network/Client.cpp | 5 +++-- src/Engine/Network/Server.cpp | 2 ++ src/Engine/Network/TCPClient.cpp | 9 ++++++++- src/Engine/Network/TCPServer.cpp | 5 +++++ 5 files changed, 19 insertions(+), 3 deletions(-) diff --git a/include/Engine/Network/TCPServer.h b/include/Engine/Network/TCPServer.h index b1aa7ce0..9cc7646a 100644 --- a/include/Engine/Network/TCPServer.h +++ b/include/Engine/Network/TCPServer.h @@ -15,6 +15,7 @@ public: void Receive(Packet & packet, PlayerDefinition & playerDefinition); void Send(Packet & packet, PlayerDefinition & playerDefinition); void Send(Packet & packet); + void Disconnect(); private: // TCP logic boost::asio::io_service m_IOService; diff --git a/src/Engine/Network/Client.cpp b/src/Engine/Network/Client.cpp index 4eaefde2..f7fc956c 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -58,13 +58,14 @@ void Client::Update() } if (m_IsConnected) { - hasServerTimedOut(); // Don't send 1 input in 1 packet, bunch em up. if (m_SendInputIntervalMs < (1000 * (std::clock() - m_TimeSinceSentInputs) / (double)CLOCKS_PER_SEC)) { sendInputCommands(); m_TimeSinceSentInputs = std::clock(); } sendLocalPlayerTransform(); + + m_IsConnected = !hasServerTimedOut(); } //Network::Update(); } @@ -380,7 +381,7 @@ bool Client::hasServerTimedOut() if (timeSincePing > m_TimeoutMs) { // Clear everything and go to menu. LOG_INFO("Server has timed out, returning to menu, Beep Boop."); - m_IsConnected = false; + m_Reliable.Disconnect(); return true; } return false; diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index bc2099bd..0c9af69c 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -302,6 +302,8 @@ void Server::disconnect(PlayerID playerID) e.PlayerID = playerID; m_EventBroker->Publish(e); + m_ConnectedPlayers[playerID].TCPSocket->shutdown(boost::asio::ip::tcp::socket::shutdown_both); + m_ConnectedPlayers[playerID].TCPSocket->close(); m_ConnectedPlayers.erase(playerID); } diff --git a/src/Engine/Network/TCPClient.cpp b/src/Engine/Network/TCPClient.cpp index 703e4cbe..5c8ccee7 100644 --- a/src/Engine/Network/TCPClient.cpp +++ b/src/Engine/Network/TCPClient.cpp @@ -51,7 +51,10 @@ void TCPClient::Connect(std::string playerName, std::string address, int port) void TCPClient::Disconnect() { - + m_Socket->shutdown(boost::asio::ip::tcp::socket::shutdown_both); + m_Socket->close(); + m_Socket = nullptr; + m_IsConnected = false; } void TCPClient::Receive(Packet& packet) @@ -87,6 +90,10 @@ int TCPClient::readBuffer(char* data) void TCPClient::Send(Packet & packet) { + if (!m_Socket) { + LOG_WARNING("TCPClient::Send: Socket is null"); + return; + } packet.UpdateSize(); boost::system::error_code error; m_Socket->send(boost::asio::buffer( diff --git a/src/Engine/Network/TCPServer.cpp b/src/Engine/Network/TCPServer.cpp index 0b44013d..2bfcde74 100644 --- a/src/Engine/Network/TCPServer.cpp +++ b/src/Engine/Network/TCPServer.cpp @@ -72,6 +72,11 @@ void TCPServer::Send(Packet & packet) 0); } +void TCPServer::Disconnect() +{ + +} + void TCPServer::Receive(Packet & packet, PlayerDefinition & playerDefinition) { int bytesRead = readBuffer(m_ReadBuffer, playerDefinition); From f05d0a1b0ce197b6935bcb68bf5c3b5513ab9ec6 Mon Sep 17 00:00:00 2001 From: Teejoon Date: Wed, 10 Feb 2016 22:18:27 +0100 Subject: [PATCH 184/355] assets --- assets | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/assets b/assets index e0ad8b8d..77bab8c0 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit e0ad8b8d45a79b8f17876f9541cc5e03758ae16c +Subproject commit 77bab8c0f57ef2a5b97a4676c2249979d098f66f From 64a2354b24ee1e0304d00831e967ca12b4ad944c Mon Sep 17 00:00:00 2001 From: Tleety Date: Wed, 10 Feb 2016 22:22:09 +0100 Subject: [PATCH 185/355] WIP with CapturePointHUDSystem --- include/Game/Systems/CapturePointHUDSystem.h | 55 ++++ resources/Schema/Components.xsd | 2 +- .../Schema/Components/CapturePointHUD.xml | 5 +- .../Schema/Components/CapturePointHUD.xsd | 18 ++ .../Entities/CapturePointHUDHexagon.xml | 34 +++ .../Schema/Entities/QualityAssurance.xml | 208 +++++++++++++-- src/Game/Systems/CapturePointHUDSystem.cpp | 243 ++++++++++++++++++ 7 files changed, 542 insertions(+), 23 deletions(-) create mode 100644 include/Game/Systems/CapturePointHUDSystem.h create mode 100644 resources/Schema/Entities/CapturePointHUDHexagon.xml create mode 100644 src/Game/Systems/CapturePointHUDSystem.cpp diff --git a/include/Game/Systems/CapturePointHUDSystem.h b/include/Game/Systems/CapturePointHUDSystem.h new file mode 100644 index 00000000..18c32c76 --- /dev/null +++ b/include/Game/Systems/CapturePointHUDSystem.h @@ -0,0 +1,55 @@ +#ifndef CapturePointSystem_h__ +#define CapturePointSystem_h__ + +#include +#include + +#include "Common.h" +#include "Core/System.h" +#include "Engine/Collision/ETrigger.h" +#include "Core/ECaptured.h" +#include "Core/EWin.h" + +#include +#include + +class CapturePointSystem : public PureSystem +{ +public: + //WARNING: on new map, destroy all info in the vectors, as well as reset all variables (just make new?) + CapturePointSystem(World* world, EventBroker* eventBroker); + + //updatecomponent + virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& capturePoint, double dt) override; + +private: + //methods which will take care of specific events + EventRelay m_ETriggerTouch; + bool CapturePointSystem::OnTriggerTouch(const Events::TriggerTouch& e); + EventRelay m_ETriggerLeave; + bool CapturePointSystem::OnTriggerLeave(const Events::TriggerLeave& e); + EventRelay m_ECaptured; + bool CapturePointSystem::OnCaptured(const Events::Captured& e); + + bool m_WinnerWasFound = false; + //need to track these variables for the captureSystem to work as per design! + const int m_NotACapturePoint = 999; + int m_RedTeamNextPossibleCapturePoint = m_NotACapturePoint; + int m_BlueTeamNextPossibleCapturePoint = m_NotACapturePoint; + int m_RedTeamHomeCapturePoint = m_NotACapturePoint; + int m_BlueTeamHomeCapturePoint = m_NotACapturePoint; + + int m_NumberOfCapturePoints = 0; + std::map m_CapturePointNumberToEntityMap; + + //std::vector + + const double m_CaptureTimeToTakeOver = 15.0; + bool m_ResetTimers = false; + + //vectors which will keep track of enter/leave changes + std::vector> m_ETriggerTouchVector; + std::vector> m_ETriggerLeaveVector; +}; + +#endif \ No newline at end of file diff --git a/resources/Schema/Components.xsd b/resources/Schema/Components.xsd index bcc3fbdf..bf452eba 100644 --- a/resources/Schema/Components.xsd +++ b/resources/Schema/Components.xsd @@ -37,5 +37,5 @@ - + \ No newline at end of file diff --git a/resources/Schema/Components/CapturePointHUD.xml b/resources/Schema/Components/CapturePointHUD.xml index c024411c..2943d57b 100644 --- a/resources/Schema/Components/CapturePointHUD.xml +++ b/resources/Schema/Components/CapturePointHUD.xml @@ -1,2 +1,5 @@ - \ No newline at end of file + + 0 + + \ No newline at end of file diff --git a/resources/Schema/Components/CapturePointHUD.xsd b/resources/Schema/Components/CapturePointHUD.xsd index dfdef822..7984fc50 100644 --- a/resources/Schema/Components/CapturePointHUD.xsd +++ b/resources/Schema/Components/CapturePointHUD.xsd @@ -1,6 +1,24 @@ + + + Hud element for tracking capture points. + + + + + + Corresponds to the number on the capture point it should track. + + + + + Specify the team that own this capturePoint. + + + + \ No newline at end of file diff --git a/resources/Schema/Entities/CapturePointHUDHexagon.xml b/resources/Schema/Entities/CapturePointHUDHexagon.xml new file mode 100644 index 00000000..68cf42a7 --- /dev/null +++ b/resources/Schema/Entities/CapturePointHUDHexagon.xml @@ -0,0 +1,34 @@ + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + + 0.5 + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + diff --git a/resources/Schema/Entities/QualityAssurance.xml b/resources/Schema/Entities/QualityAssurance.xml index c234f93a..ce6a650e 100644 --- a/resources/Schema/Entities/QualityAssurance.xml +++ b/resources/Schema/Entities/QualityAssurance.xml @@ -40,7 +40,7 @@ - + @@ -180,7 +180,7 @@ - + @@ -671,7 +671,7 @@ - + @@ -718,7 +718,7 @@ - + @@ -778,7 +778,7 @@ - + @@ -825,7 +825,7 @@ - + @@ -871,7 +871,7 @@ - + @@ -918,7 +918,7 @@ - + @@ -965,7 +965,7 @@ - + @@ -1378,7 +1378,7 @@ - + @@ -1387,7 +1387,7 @@ true - 0.75134174339666815 + 0.75158864645285173 3.7999999523162842 true @@ -1434,7 +1434,7 @@ - + @@ -1443,7 +1443,7 @@ - 1.2012474940107754 + 1.2014943970669589 Models/Characters/Assault/AssaultTPose.mesh @@ -1486,7 +1486,7 @@ - + @@ -1497,7 +1497,7 @@ true - 0.68469327767070653 + 0.68494018072689011 true @@ -1542,7 +1542,7 @@ - + @@ -1552,7 +1552,7 @@ true - 0.95079179851807027 + 0.95103870157425385 10 3 @@ -1600,7 +1600,7 @@ - + @@ -1610,7 +1610,7 @@ true - 1.3508200598941349 + 1.3510669629503185 true 5 true @@ -1791,7 +1791,7 @@ true - 1.3674931199292806 + 1.3677400229854642 3.7999999523162842 true @@ -1936,7 +1936,6 @@ Textures/Props/FoliageDiff.png - @@ -1955,6 +1954,173 @@ + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + 2 + + + 0.5 + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + 3 + + + 0.5 + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + 4 + + + 0.5 + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + 1 + + + 0.5 + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + 0.5 + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + diff --git a/src/Game/Systems/CapturePointHUDSystem.cpp b/src/Game/Systems/CapturePointHUDSystem.cpp new file mode 100644 index 00000000..a943e234 --- /dev/null +++ b/src/Game/Systems/CapturePointHUDSystem.cpp @@ -0,0 +1,243 @@ +#include "Systems/CapturePointSystem.h" +#include + +CapturePointSystem::CapturePointSystem(World* world, EventBroker* eventBroker) + : System(world, eventBroker) + , PureSystem("CapturePoint") +{ + //subscribe/listenTo playerdamage,healthpickup events (using the eventBroker) + EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &CapturePointSystem::OnTriggerTouch); + EVENT_SUBSCRIBE_MEMBER(m_ETriggerLeave, &CapturePointSystem::OnTriggerLeave); + EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &CapturePointSystem::OnCaptured); +} + +//here all capturepoints will update their component +//NOTE: needs to run each frame, since we're possibly modifying the captureTimer for the capturePoints by dt +void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, ComponentWrapper& cCapturePoint, double dt) +{ + if (m_WinnerWasFound) { + return; + } + const int capturePointNumber = cCapturePoint["CapturePointNumber"]; + const bool hasTeamComponent = capturePointEntity.HasComponent("Team"); + + //if point doesnt have a teamComponent yet, add one. since: + //what if capture point has no team -> we cant get/use the team enum from it... + if (!hasTeamComponent) { + m_World->AttachComponent(cCapturePoint.EntityID, "Team"); + ComponentWrapper& teamComponent = capturePointEntity["Team"]; + teamComponent["Team"] = (int)teamComponent["Team"].Enum("Spectator"); + } + ComponentWrapper& teamComponent = capturePointEntity["Team"]; + const int redTeam = (int)teamComponent["Team"].Enum("Red"); + const int blueTeam = (int)teamComponent["Team"].Enum("Blue"); + const int spectatorTeam = (int)teamComponent["Team"].Enum("Spectator"); + + int homePointForTeam = (int)cCapturePoint["HomePointForTeam"]; + if (m_NumberOfCapturePoints == 0 && capturePointNumber != 0 && (homePointForTeam == redTeam || homePointForTeam == blueTeam)) { + m_NumberOfCapturePoints = capturePointNumber + 1;//ex 2 -> 0,1,2 = 3 + if (homePointForTeam == redTeam) { + m_RedTeamHomeCapturePoint = capturePointNumber; + m_BlueTeamHomeCapturePoint = 0; + } else { + m_BlueTeamHomeCapturePoint = capturePointNumber; + m_RedTeamHomeCapturePoint = 0; + } + } + + //if we havent received all capturepoints yet, just return + if (m_NumberOfCapturePoints == 0 || m_NumberOfCapturePoints != m_CapturePointNumberToEntityMap.size()) { + m_CapturePointNumberToEntityMap.insert(std::make_pair(capturePointNumber, capturePointEntity)); + return; + } + + //we have all capturepoints now - process stuff + int ownedBy = teamComponent["Team"]; + int redTeamPlayersStandingInside = 0; + int blueTeamPlayersStandingInside = 0; + if (capturePointEntity.HasComponent("Model")) { + //Now sets team color to the capturepoint, or white if it is uncaptured. + capturePointEntity["Model"]["Color"] = ownedBy == blueTeam ? glm::vec4(0, 0.2f, 1, 0.3) : ownedBy == redTeam ? glm::vec4(1, 0.2f, 0, 0.3) : glm::vec4(1, 1, 1, 0.3); + } + + //calculate next possible capturePoint for both teams + std::map nextPossibleCapturePoint; + nextPossibleCapturePoint["Red"] = -1; + nextPossibleCapturePoint["Blue"] = -1; + for (int i = 0; i < m_NumberOfCapturePoints; i++) + { + if (!m_CapturePointNumberToEntityMap[i].HasComponent("Team")) { + continue; + } + ComponentWrapper& capturePointOwnedBy = m_CapturePointNumberToEntityMap[i]["Team"]; + if ((int)capturePointOwnedBy["Team"] == redTeam && m_RedTeamHomeCapturePoint == 0) { + nextPossibleCapturePoint["Red"] = i + 1; + } + if ((int)capturePointOwnedBy["Team"] == blueTeam && m_BlueTeamHomeCapturePoint == 0) { + nextPossibleCapturePoint["Blue"] = i + 1; + } + } + for (int i = m_NumberOfCapturePoints - 1; i >= 0; i--) + { + if (!m_CapturePointNumberToEntityMap[i].HasComponent("Team")) { + continue; + } + ComponentWrapper& capturePointOwnedBy = m_CapturePointNumberToEntityMap[i]["Team"]; + if ((int)capturePointOwnedBy["Team"] == redTeam && m_RedTeamHomeCapturePoint != 0) { + nextPossibleCapturePoint["Red"] = i - 1; + } + if ((int)capturePointOwnedBy["Team"] == blueTeam && m_BlueTeamHomeCapturePoint != 0) { + nextPossibleCapturePoint["Blue"] = i - 1; + } + } + + //reset timers and reset the bool that triggers this + if (m_ResetTimers) { + for (int i = 0; i < m_NumberOfCapturePoints; i++) + { + ComponentWrapper& capturePoint = m_CapturePointNumberToEntityMap[i]["CapturePoint"]; + if ((int)capturePoint["CapturePointNumber"] != nextPossibleCapturePoint["Red"] && + (int)capturePoint["CapturePointNumber"] != nextPossibleCapturePoint["Blue"]) { + capturePoint["CaptureTimer"] = 0.0; + } + } + m_ResetTimers = false; + } + + //colorize next possible capturepoint + if (nextPossibleCapturePoint["Red"] == capturePointNumber) { + capturePointEntity["Model"]["Color"] = glm::vec4(1, 1, 0, 0.3); + } + if (nextPossibleCapturePoint["Blue"] == capturePointNumber) { + capturePointEntity["Model"]["Color"] = glm::vec4(0, 1, 1, 0.3); + } + + //check how many players are standing inside and are healthy + for (size_t i = m_ETriggerTouchVector.size(); i > 0; i--) + { + auto triggerTouched = m_ETriggerTouchVector[i - 1]; + if (std::get<1>(triggerTouched) == capturePointEntity) { + //some player has touched this - lets figure out: what team, health + EntityWrapper player = std::get<0>(triggerTouched); + //check if its really a player that has triggered the touch + if (!player.HasComponent("Player")) { + //if a non-player has entered the capturePoint, just erase that event and continue + m_ETriggerTouchVector.erase(m_ETriggerTouchVector.begin() + i - 1); + continue; + } + bool hasHealthComponent = player.HasComponent("Health"); + if (hasHealthComponent) { + double currentHealth = player["Health"]["Health"]; + //check if player is dead + if ((int)currentHealth == 0) { + continue; + } + } + //check team - spectatorNumber = "no team" + int teamNumber = player["Team"]["Team"]; + if (teamNumber == redTeam) { + redTeamPlayersStandingInside++; + } else if (teamNumber == blueTeam) { + blueTeamPlayersStandingInside++; + } + continue; + } + } + + //create data to be used in option B + //check so this is the next possible capture point for the take-over team and see if only one team is standing inside it + double timerDeltaChange = 0.0; + int currentTeam = 0; + bool canCapture = false; + if (redTeamPlayersStandingInside > 0 && blueTeamPlayersStandingInside == 0) { + timerDeltaChange = redTeamPlayersStandingInside*dt; + currentTeam = redTeam; + canCapture = nextPossibleCapturePoint["Red"] == capturePointNumber; + } + if (redTeamPlayersStandingInside == 0 && blueTeamPlayersStandingInside > 0) { + timerDeltaChange = -blueTeamPlayersStandingInside*dt; + currentTeam = blueTeam; + canCapture = nextPossibleCapturePoint["Blue"] == capturePointNumber; + } + + if (redTeamPlayersStandingInside == 0 && blueTeamPlayersStandingInside == 0) { + //A.nobodys standing inside + //do nothing (?) + } else if (redTeamPlayersStandingInside > 0 && blueTeamPlayersStandingInside > 0) { + //C.both teams have players inside + //do nothing (?) + } else { + //B. at most one of the teams have players inside + //if capturePoint is not owned by the take-over team, just modify the CaptureTimer accordingly + if (ownedBy != currentTeam && canCapture) { + if (abs((double)cCapturePoint["CaptureTimer"]) < 0.001f) { + LOG_DEBUG("Point is being captured by team %i", currentTeam); //Remove when we tested sufficiently. + } + cCapturePoint["CaptureTimer"] = (double)cCapturePoint["CaptureTimer"] + timerDeltaChange; + } + //if capturePoint is owned by the team, and the other team has been trying to take it, then increase/decrease the timer towards 0.0 + if ((ownedBy == currentTeam && currentTeam == redTeam && (double)cCapturePoint["CaptureTimer"] < 0.0) || + (ownedBy == currentTeam && currentTeam == blueTeam && (double)cCapturePoint["CaptureTimer"] > 0.0)) { + cCapturePoint["CaptureTimer"] = (double)cCapturePoint["CaptureTimer"] + timerDeltaChange; + } + //check if captureTimer > m_CaptureTimeToTakeOver and if so change owner and publish the eCaptured event + if (abs((double)cCapturePoint["CaptureTimer"]) > abs(m_CaptureTimeToTakeOver) && canCapture) { + teamComponent["Team"] = currentTeam; + cCapturePoint["CaptureTimer"] = 0.0; + //publish Captured event + LOG_DEBUG("Point is captured by team %i!", currentTeam); //Remove when we tested sufficiently. + Events::Captured e; + e.CapturePointID = cCapturePoint.EntityID; + e.TeamNumberThatCapturedCapturePoint = currentTeam; + m_EventBroker->Publish(e); + //NextPossibleCapturePoint will be calculated in the next update... + } + } + + //check for possible winCondition = check if the homebase is owned by the other team + bool checkForWinner = false; + if (capturePointNumber == m_RedTeamHomeCapturePoint && ownedBy != redTeam) + { + checkForWinner = true; + } + if (capturePointNumber == m_BlueTeamHomeCapturePoint && ownedBy != blueTeam) + { + checkForWinner = true; + } + + if (checkForWinner && !m_WinnerWasFound) + { + //publish Win event + Events::Win e; + e.TeamThatWon = ownedBy; + m_EventBroker->Publish(e); + m_WinnerWasFound = true; + } + +} + +bool CapturePointSystem::OnTriggerTouch(const Events::TriggerTouch& e) +{ + //personEntered = e.Entity, thingEntered = e.Trigger + m_ETriggerTouchVector.push_back(std::make_tuple(e.Entity, e.Trigger)); + return true; +} + +bool CapturePointSystem::OnTriggerLeave(const Events::TriggerLeave& e) +{ + for (size_t i = 0; i < m_ETriggerTouchVector.size(); i++) + { + auto triggerTouched = m_ETriggerTouchVector[i]; + if (std::get<0>(triggerTouched) == e.Entity && std::get<1>(triggerTouched) == e.Trigger) { + m_ETriggerTouchVector.erase(m_ETriggerTouchVector.begin() + i); + break; + } + } + return true; +} +bool CapturePointSystem::OnCaptured(const Events::Captured& e) +{ + //reset the timers in the next update since a capture has changed the "nextCapturePoint" for 1-2 teams + m_ResetTimers = true; + return true; +} From dded296cde37d3815688eea7a3ccd9942048c9fb Mon Sep 17 00:00:00 2001 From: viktorljung Date: Wed, 10 Feb 2016 23:19:44 +0100 Subject: [PATCH 186/355] Animation looping fix --- assets | 2 +- resources/Schema/Entities/AnimationTests2.xml | 505 +----------------- src/Engine/Rendering/AnimationSystem.cpp | 2 - src/Engine/Rendering/Skeleton.cpp | 4 + 4 files changed, 20 insertions(+), 493 deletions(-) diff --git a/assets b/assets index 45cbc3ab..172b3ad5 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit 45cbc3abaebe5f815e2c1b58bcf884d4953a4c52 +Subproject commit 172b3ad527fc14aa6175fa72580a66a00f04e0ba diff --git a/resources/Schema/Entities/AnimationTests2.xml b/resources/Schema/Entities/AnimationTests2.xml index 09573ac7..6536a839 100644 --- a/resources/Schema/Entities/AnimationTests2.xml +++ b/resources/Schema/Entities/AnimationTests2.xml @@ -55,498 +55,23 @@ - + - + + R_Arm_Weapon_Joint + + + + Models/Weapons/Blue/AssaultWeapon.mesh + + true + + + + + - - - - - R_Arm_Weapon_Joint - - - - Models/Weapons/Blue/AssaultWeapon.mesh - - true - - - - - - - - - - - - R_Hand - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - - R_Arm - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - - R_Shoulder - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - - Neck - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - - Spine_3 - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - - Spine_2 - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - - Spine_1 - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - - Hip - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - - L_Leg_Top - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - - L_Leg_Bottom - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - - L_Foot - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - - L_Toe - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - - L_Shoulder - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - - L_Arm - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - - L_Hand - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - - L_Shoulder_Armor_Joint - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - - Chin - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - - Head - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - - Perietal - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - - L_Elbow - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - - R_Leg_Bottom - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - - R_Elbow - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - - R_Leg_Top - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - - R_Foot - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - - R_Toe - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - - R_Shoulder_Armor_Joint - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - + diff --git a/src/Engine/Rendering/AnimationSystem.cpp b/src/Engine/Rendering/AnimationSystem.cpp index 25813a63..3df502c4 100644 --- a/src/Engine/Rendering/AnimationSystem.cpp +++ b/src/Engine/Rendering/AnimationSystem.cpp @@ -13,9 +13,7 @@ void AnimationSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& a return; } - Skeleton* skeleton = model->m_RawModel->m_Skeleton; - if(skeleton == nullptr) { return; } diff --git a/src/Engine/Rendering/Skeleton.cpp b/src/Engine/Rendering/Skeleton.cpp index 1aabd84c..5da95558 100644 --- a/src/Engine/Rendering/Skeleton.cpp +++ b/src/Engine/Rendering/Skeleton.cpp @@ -96,6 +96,7 @@ void Skeleton::AccumulateBoneTransforms(bool noRootMotion, std::vectorDuration - currentFrame.Time); } else { progress = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); @@ -227,6 +228,7 @@ void Skeleton::AccumulateBoneTransforms(bool noRootMotion, std::vectorDuration - currentFrame.Time); } else { progress = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); @@ -347,6 +349,7 @@ glm::mat4 Skeleton::GetOffsetTransform(const Bone* bone, AnimationOffset animati float progress; if (nextFrame.Index == 0) { + nextFrame = currentFrame; progress = (time - currentFrame.Time) / (animation->Duration - currentFrame.Time); } else { progress = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); @@ -400,6 +403,7 @@ glm::mat4 Skeleton::GetBoneTransform(const Bone* bone, const Animation* animatio float progress; if (nextFrame.Index == 0) { + nextFrame = currentFrame; progress = (time - currentFrame.Time) / (animation->Duration - currentFrame.Time); } else { progress = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); From eb244f87c4e773fd2939d24e2141cbeae10b2705 Mon Sep 17 00:00:00 2001 From: Jocke Date: Wed, 10 Feb 2016 23:27:46 +0100 Subject: [PATCH 187/355] Added disconnect functionality and removed some warnings. --- include/Engine/Network/Client.h | 2 +- include/Engine/Network/Packet.h | 2 +- include/Engine/Network/Server.h | 9 +++++---- include/Engine/Network/TCPClient.h | 2 +- src/Engine/Network/Client.cpp | 11 +++++------ src/Engine/Network/Packet.cpp | 2 +- src/Engine/Network/Server.cpp | 13 ++++++++++--- src/Engine/Network/TCPClient.cpp | 9 ++++++--- src/Engine/Network/TCPServer.cpp | 2 +- 9 files changed, 31 insertions(+), 21 deletions(-) diff --git a/include/Engine/Network/Client.h b/include/Engine/Network/Client.h index 4ff2ecf8..76bb0470 100644 --- a/include/Engine/Network/Client.h +++ b/include/Engine/Network/Client.h @@ -82,7 +82,7 @@ protected: void InterpolateFields(Packet & packet, const ComponentInfo & componentInfo, const EntityID & entityID, const std::string & componentType); void parseSnapshot(Packet& packet); void identifyPacketLoss(); - bool hasServerTimedOut(); + void hasServerTimedOut(); EntityID createPlayer(); void sendInputCommands(); void sendLocalPlayerTransform(); diff --git a/include/Engine/Network/Packet.h b/include/Engine/Network/Packet.h index 694fd703..b688b8c6 100644 --- a/include/Engine/Network/Packet.h +++ b/include/Engine/Network/Packet.h @@ -50,7 +50,7 @@ public: // Pops the first element as if it was a string. std::string ReadString(); // Construct a packet - void ReconstructFromData(char* data, int SizeOfData); + void ReconstructFromData(char* data, size_t SizeOfData); // Update size of packet variable in header void UpdateSize(); char* ReadData(int SizeOfData); diff --git a/include/Engine/Network/Server.h b/include/Engine/Network/Server.h index 308a74ed..ee40b707 100644 --- a/include/Engine/Network/Server.h +++ b/include/Engine/Network/Server.h @@ -27,12 +27,16 @@ public: ~Server(); void Start(World* m_world, EventBroker *eventBroker) override; void Update() override; -protected: +private: + // Network channels + TCPServer m_Reliable; + UDPServer m_Unreliable; // dont forget to set these in the childrens receive logic boost::asio::ip::address m_Address; unsigned short m_Port; // Sending messages to client logic std::map m_ConnectedPlayers; + std::vector m_PlayersToDisconnect; // HACK: Fix INPUTSIZE char readBuffer[BUFFERSIZE] = { 0 }; size_t bytesRead = 0; @@ -88,9 +92,6 @@ protected: bool OnEntityDeleted(const Events::EntityDeleted& e); EventRelay m_EComponentDeleted; bool OnComponentDeleted(const Events::ComponentDeleted& e); -private: - TCPServer m_Reliable; - UDPServer m_Unreliable; }; #endif diff --git a/include/Engine/Network/TCPClient.h b/include/Engine/Network/TCPClient.h index 9f61cca5..a666cbbe 100644 --- a/include/Engine/Network/TCPClient.h +++ b/include/Engine/Network/TCPClient.h @@ -20,7 +20,7 @@ private: boost::asio::ip::tcp::endpoint m_Endpoint; boost::asio::io_service m_IOService; std::unique_ptr m_Socket; - int readBuffer(char* data); + size_t readBuffer(char* data); PacketID m_SendPacketID = 0; bool m_IsConnected = false; }; diff --git a/src/Engine/Network/Client.cpp b/src/Engine/Network/Client.cpp index f7fc956c..c5c7596e 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -64,8 +64,8 @@ void Client::Update() m_TimeSinceSentInputs = std::clock(); } sendLocalPlayerTransform(); - - m_IsConnected = !hasServerTimedOut(); + + hasServerTimedOut(); } //Network::Update(); } @@ -290,6 +290,7 @@ void Client::disconnect() m_PacketID = 0; Packet packet(MessageType::Disconnect, m_SendPacketID); m_Reliable.Send(packet); + m_Reliable.Disconnect(); } bool Client::OnInputCommand(const Events::InputCommand & e) @@ -374,17 +375,15 @@ void Client::identifyPacketLoss() } } -bool Client::hasServerTimedOut() +void Client::hasServerTimedOut() { // Time in ms double timeSincePing = 1000 * (std::clock() - m_StartPingTime) / static_cast(CLOCKS_PER_SEC); if (timeSincePing > m_TimeoutMs) { // Clear everything and go to menu. LOG_INFO("Server has timed out, returning to menu, Beep Boop."); - m_Reliable.Disconnect(); - return true; + disconnect(); } - return false; } EntityID Client::createPlayer() diff --git a/src/Engine/Network/Packet.cpp b/src/Engine/Network/Packet.cpp index af8f91c2..475ca673 100644 --- a/src/Engine/Network/Packet.cpp +++ b/src/Engine/Network/Packet.cpp @@ -81,7 +81,7 @@ std::string Packet::ReadString() return returnValue; } -void Packet::ReconstructFromData(char * data, int sizeOfData) +void Packet::ReconstructFromData(char * data, size_t sizeOfData) { if (sizeOfData > m_MaxPacketSize) { // Delete our data diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index 0c9af69c..8a0ecd36 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -53,6 +53,11 @@ void Server::Update() parseMessageType(packet); } } + // Check if players have disconnected + for (int i = 0; i < m_PlayersToDisconnect.size(); i++) { + disconnect(m_PlayersToDisconnect.at(i)); + } + m_PlayersToDisconnect.clear(); std::clock_t currentTime = std::clock(); // Send snapshot @@ -74,6 +79,7 @@ void Server::Update() if (isReadingData) { Network::Update(); } + } void Server::parseMessageType(Packet& packet) @@ -249,7 +255,7 @@ void Server::parseTCPConnect(Packet & packet) // Read packet ID m_PreviousPacketID = m_PacketID; // Set previous packet id m_PacketID = packet.ReadPrimitive(); //Read new packet id - + LOG_INFO("Parsing connections"); // Check if player is already connected // Ska vara till lagd i TCPServer receive @@ -286,7 +292,7 @@ void Server::parseDisconnect() for (auto& kv : m_ConnectedPlayers) { if (kv.second.TCPAddress == m_Address && kv.second.TCPPort == m_Port) { - disconnect(kv.first); + m_PlayersToDisconnect.push_back(kv.first); break; } } @@ -301,10 +307,11 @@ void Server::disconnect(PlayerID playerID) e.Entity = m_ConnectedPlayers.at(playerID).EntityID; e.PlayerID = playerID; m_EventBroker->Publish(e); - + //m_World->DeleteEntity(m_ConnectedPlayers[playerID].EntityID); m_ConnectedPlayers[playerID].TCPSocket->shutdown(boost::asio::ip::tcp::socket::shutdown_both); m_ConnectedPlayers[playerID].TCPSocket->close(); m_ConnectedPlayers.erase(playerID); + // Send disconnect to the other players. } void Server::parseOnPlayerDamage(Packet & packet) diff --git a/src/Engine/Network/TCPClient.cpp b/src/Engine/Network/TCPClient.cpp index 5c8ccee7..38bac621 100644 --- a/src/Engine/Network/TCPClient.cpp +++ b/src/Engine/Network/TCPClient.cpp @@ -51,6 +51,9 @@ void 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; @@ -59,20 +62,20 @@ void TCPClient::Disconnect() void TCPClient::Receive(Packet& packet) { - int bytesRead = readBuffer(m_ReadBuffer); + size_t bytesRead = readBuffer(m_ReadBuffer); if (bytesRead > 0) { packet.ReconstructFromData(m_ReadBuffer, bytesRead); } } -int TCPClient::readBuffer(char* data) +size_t TCPClient::readBuffer(char* data) { if (!m_Socket) { return 0; } boost::system::error_code error; // Read size of packet - int bytesReceived = m_Socket->read_some(boost + size_t bytesReceived = m_Socket->read_some(boost ::asio::buffer((void*)data, sizeof(int)), error); int sizeOfPacket = 0; diff --git a/src/Engine/Network/TCPServer.cpp b/src/Engine/Network/TCPServer.cpp index 2bfcde74..a449e684 100644 --- a/src/Engine/Network/TCPServer.cpp +++ b/src/Engine/Network/TCPServer.cpp @@ -93,7 +93,7 @@ int TCPServer::readBuffer(char* data, PlayerDefinition & playerDefinition) } boost::system::error_code error; // Read size of packet - int bytesReceived = playerDefinition.TCPSocket->read_some(boost + size_t bytesReceived = playerDefinition.TCPSocket->read_some(boost ::asio::buffer((void*)data, sizeof(int)), error); int sizeOfPacket = 0; From 9c08c351b80197fd485e438b175a8293e681686d Mon Sep 17 00:00:00 2001 From: viktorljung Date: Wed, 10 Feb 2016 23:33:23 +0100 Subject: [PATCH 188/355] fixed reverse Animation looping --- src/Engine/Rendering/AnimationSystem.cpp | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/src/Engine/Rendering/AnimationSystem.cpp b/src/Engine/Rendering/AnimationSystem.cpp index 3df502c4..48681e6e 100644 --- a/src/Engine/Rendering/AnimationSystem.cpp +++ b/src/Engine/Rendering/AnimationSystem.cpp @@ -31,20 +31,27 @@ void AnimationSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& a double nextTime = (double)animationComponent["Time" + std::to_string(i)] + animationSpeed * dt; - if (!(bool)animationComponent["Loop" + std::to_string(i)] && glm::abs(nextTime) > animation->Duration) { - (double&)animationComponent["Time" + std::to_string(i)] = glm::sign(nextTime) * animation->Duration; + if (!(bool)animationComponent["Loop" + std::to_string(i)]) { + if (nextTime > animation->Duration) { + nextTime = animation->Duration; + } else if (nextTime < 0) { + nextTime = 0; + } + (double&)animationComponent["Speed" + std::to_string(i)] = 0.0; Events::AnimationComplete e; e.Entity = entity; e.Name = (std::string)animationComponent["AnimationName" + std::to_string(i)]; m_EventBroker->Publish(e); } else { - if (glm::abs(nextTime) > animation->Duration) { - (double&)animationComponent["Time" + std::to_string(i)] = glm::abs(nextTime) - animation->Duration; - } else { - (double&)animationComponent["Time" + std::to_string(i)] = nextTime; + if (nextTime > animation->Duration) { + nextTime -= animation->Duration; + } else if (nextTime < 0) { + nextTime += animation->Duration; } } + + (double&)animationComponent["Time" + std::to_string(i)] = nextTime; } } From 447f41dbff935c9521a2e74c594d85b1490b6cd9 Mon Sep 17 00:00:00 2001 From: Tleety Date: Wed, 10 Feb 2016 23:59:13 +0100 Subject: [PATCH 189/355] HUD for capture points now update with Capture point data. --- include/Game/Systems/CapturePointHUDSystem.h | 52 +- resources/Shaders/Sprite.frag.glsl | 5 +- src/Game/Game.cpp | 2 + src/Game/Systems/CapturePointHUDSystem.cpp | 482 ++++++++++--------- 4 files changed, 287 insertions(+), 254 deletions(-) diff --git a/include/Game/Systems/CapturePointHUDSystem.h b/include/Game/Systems/CapturePointHUDSystem.h index 18c32c76..102c52ce 100644 --- a/include/Game/Systems/CapturePointHUDSystem.h +++ b/include/Game/Systems/CapturePointHUDSystem.h @@ -1,55 +1,49 @@ -#ifndef CapturePointSystem_h__ -#define CapturePointSystem_h__ +#ifndef CapturePointHUDSystem_h__ +#define CapturePointHUDSystem_h__ #include #include +#include #include "Common.h" #include "Core/System.h" #include "Engine/Collision/ETrigger.h" -#include "Core/ECaptured.h" -#include "Core/EWin.h" -#include -#include - -class CapturePointSystem : public PureSystem +class CapturePointHUDSystem : public ImpureSystem { public: - //WARNING: on new map, destroy all info in the vectors, as well as reset all variables (just make new?) - CapturePointSystem(World* world, EventBroker* eventBroker); + CapturePointHUDSystem(World* world, EventBroker* eventBroker); - //updatecomponent - virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& capturePoint, double dt) override; + virtual void Update(double dt) override; private: //methods which will take care of specific events - EventRelay m_ETriggerTouch; + /* EventRelay m_ETriggerTouch; bool CapturePointSystem::OnTriggerTouch(const Events::TriggerTouch& e); EventRelay m_ETriggerLeave; bool CapturePointSystem::OnTriggerLeave(const Events::TriggerLeave& e); EventRelay m_ECaptured; - bool CapturePointSystem::OnCaptured(const Events::Captured& e); + bool CapturePointSystem::OnCaptured(const Events::Captured& e);*/ - bool m_WinnerWasFound = false; - //need to track these variables for the captureSystem to work as per design! - const int m_NotACapturePoint = 999; - int m_RedTeamNextPossibleCapturePoint = m_NotACapturePoint; - int m_BlueTeamNextPossibleCapturePoint = m_NotACapturePoint; - int m_RedTeamHomeCapturePoint = m_NotACapturePoint; - int m_BlueTeamHomeCapturePoint = m_NotACapturePoint; + //bool m_WinnerWasFound = false; + ////need to track these variables for the captureSystem to work as per design! + //const int m_NotACapturePoint = 999; + //int m_RedTeamNextPossibleCapturePoint = m_NotACapturePoint; + //int m_BlueTeamNextPossibleCapturePoint = m_NotACapturePoint; + //int m_RedTeamHomeCapturePoint = m_NotACapturePoint; + //int m_BlueTeamHomeCapturePoint = m_NotACapturePoint; - int m_NumberOfCapturePoints = 0; - std::map m_CapturePointNumberToEntityMap; + //int m_NumberOfCapturePoints = 0; + //std::map m_CapturePointNumberToEntityMap; - //std::vector + ////std::vector - const double m_CaptureTimeToTakeOver = 15.0; - bool m_ResetTimers = false; + //const double m_CaptureTimeToTakeOver = 15.0; + //bool m_ResetTimers = false; - //vectors which will keep track of enter/leave changes - std::vector> m_ETriggerTouchVector; - std::vector> m_ETriggerLeaveVector; + ////vectors which will keep track of enter/leave changes + //std::vector> m_ETriggerTouchVector; + //std::vector> m_ETriggerLeaveVector; }; #endif \ No newline at end of file diff --git a/resources/Shaders/Sprite.frag.glsl b/resources/Shaders/Sprite.frag.glsl index c391322d..a1ff3025 100644 --- a/resources/Shaders/Sprite.frag.glsl +++ b/resources/Shaders/Sprite.frag.glsl @@ -30,12 +30,11 @@ void main() float pos = ((P * vec4(Input.Position, 1)).y + 1.0)/2.0; if(pos <= FillPercentage) { - color_result += FillColor; + color_result = FillColor*diffuseTexel.a; } sceneColor = vec4(color_result.xyz, clamp(color_result.a, 0, 1)); - color_result += glowTexel*3; - bloomColor = vec4(clamp(color_result.xyz - 1.0, 0, 100), 1.0); + bloomColor = vec4(clamp((glowTexel.xyz*3) - 1.0, 0, 100), 1.0); } diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index 002efe26..b13cbda2 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -12,6 +12,7 @@ #include "Systems/PlayerDeathSystem.h" #include "Core/EntityFileWriter.h" #include "Game/Systems/CapturePointSystem.h" +#include "Game/Systems/CapturePointHUDSystem.h" #include "Game/Systems/PickupSpawnSystem.h" #include "Game/Systems/WeaponSystem.h" #include "Rendering/AnimationSystem.h" @@ -103,6 +104,7 @@ Game::Game(int argc, char* argv[]) m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); + m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); // Populate Octree with collidables ++updateOrderLevel; diff --git a/src/Game/Systems/CapturePointHUDSystem.cpp b/src/Game/Systems/CapturePointHUDSystem.cpp index a943e234..5c4c2b60 100644 --- a/src/Game/Systems/CapturePointHUDSystem.cpp +++ b/src/Game/Systems/CapturePointHUDSystem.cpp @@ -1,243 +1,281 @@ -#include "Systems/CapturePointSystem.h" -#include +#include "Systems/CapturePointHUDSystem.h" -CapturePointSystem::CapturePointSystem(World* world, EventBroker* eventBroker) +CapturePointHUDSystem::CapturePointHUDSystem(World* world, EventBroker* eventBroker) : System(world, eventBroker) - , PureSystem("CapturePoint") + , ImpureSystem() { //subscribe/listenTo playerdamage,healthpickup events (using the eventBroker) - EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &CapturePointSystem::OnTriggerTouch); - EVENT_SUBSCRIBE_MEMBER(m_ETriggerLeave, &CapturePointSystem::OnTriggerLeave); - EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &CapturePointSystem::OnCaptured); + //EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &CapturePointSystem::OnTriggerTouch); + //EVENT_SUBSCRIBE_MEMBER(m_ETriggerLeave, &CapturePointSystem::OnTriggerLeave); + //EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &CapturePointSystem::OnCaptured); } -//here all capturepoints will update their component -//NOTE: needs to run each frame, since we're possibly modifying the captureTimer for the capturePoints by dt -void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, ComponentWrapper& cCapturePoint, double dt) + +void CapturePointHUDSystem::Update(double dt) { - if (m_WinnerWasFound) { - return; - } - const int capturePointNumber = cCapturePoint["CapturePointNumber"]; - const bool hasTeamComponent = capturePointEntity.HasComponent("Team"); + bool LoadCheck = false; + int redTeam; + int blueTeam; + int spectatorTeam; - //if point doesnt have a teamComponent yet, add one. since: - //what if capture point has no team -> we cant get/use the team enum from it... - if (!hasTeamComponent) { - m_World->AttachComponent(cCapturePoint.EntityID, "Team"); - ComponentWrapper& teamComponent = capturePointEntity["Team"]; - teamComponent["Team"] = (int)teamComponent["Team"].Enum("Spectator"); - } - ComponentWrapper& teamComponent = capturePointEntity["Team"]; - const int redTeam = (int)teamComponent["Team"].Enum("Red"); - const int blueTeam = (int)teamComponent["Team"].Enum("Blue"); - const int spectatorTeam = (int)teamComponent["Team"].Enum("Spectator"); + auto CapturePointHUDElements = m_World->GetComponents("CapturePointHUD"); + auto CapturePoints = m_World->GetComponents("CapturePoint"); - int homePointForTeam = (int)cCapturePoint["HomePointForTeam"]; - if (m_NumberOfCapturePoints == 0 && capturePointNumber != 0 && (homePointForTeam == redTeam || homePointForTeam == blueTeam)) { - m_NumberOfCapturePoints = capturePointNumber + 1;//ex 2 -> 0,1,2 = 3 - if (homePointForTeam == redTeam) { - m_RedTeamHomeCapturePoint = capturePointNumber; - m_BlueTeamHomeCapturePoint = 0; - } else { - m_BlueTeamHomeCapturePoint = capturePointNumber; - m_RedTeamHomeCapturePoint = 0; - } - } + for(auto& cCapturePointHUD : *CapturePointHUDElements) { + int HUD_ID = cCapturePointHUD["CapturePointNumber"]; + EntityWrapper entityHUD = EntityWrapper(m_World, cCapturePointHUD.EntityID); + EntityWrapper entityHUDparent = entityHUD.Parent(); - //if we havent received all capturepoints yet, just return - if (m_NumberOfCapturePoints == 0 || m_NumberOfCapturePoints != m_CapturePointNumberToEntityMap.size()) { - m_CapturePointNumberToEntityMap.insert(std::make_pair(capturePointNumber, capturePointEntity)); - return; - } + for(auto& cCapturePoint : *CapturePoints) { + EntityWrapper entityCP = EntityWrapper(m_World, cCapturePoint.EntityID); - //we have all capturepoints now - process stuff - int ownedBy = teamComponent["Team"]; - int redTeamPlayersStandingInside = 0; - int blueTeamPlayersStandingInside = 0; - if (capturePointEntity.HasComponent("Model")) { - //Now sets team color to the capturepoint, or white if it is uncaptured. - capturePointEntity["Model"]["Color"] = ownedBy == blueTeam ? glm::vec4(0, 0.2f, 1, 0.3) : ownedBy == redTeam ? glm::vec4(1, 0.2f, 0, 0.3) : glm::vec4(1, 1, 1, 0.3); - } - - //calculate next possible capturePoint for both teams - std::map nextPossibleCapturePoint; - nextPossibleCapturePoint["Red"] = -1; - nextPossibleCapturePoint["Blue"] = -1; - for (int i = 0; i < m_NumberOfCapturePoints; i++) - { - if (!m_CapturePointNumberToEntityMap[i].HasComponent("Team")) { - continue; - } - ComponentWrapper& capturePointOwnedBy = m_CapturePointNumberToEntityMap[i]["Team"]; - if ((int)capturePointOwnedBy["Team"] == redTeam && m_RedTeamHomeCapturePoint == 0) { - nextPossibleCapturePoint["Red"] = i + 1; - } - if ((int)capturePointOwnedBy["Team"] == blueTeam && m_BlueTeamHomeCapturePoint == 0) { - nextPossibleCapturePoint["Blue"] = i + 1; - } - } - for (int i = m_NumberOfCapturePoints - 1; i >= 0; i--) - { - if (!m_CapturePointNumberToEntityMap[i].HasComponent("Team")) { - continue; - } - ComponentWrapper& capturePointOwnedBy = m_CapturePointNumberToEntityMap[i]["Team"]; - if ((int)capturePointOwnedBy["Team"] == redTeam && m_RedTeamHomeCapturePoint != 0) { - nextPossibleCapturePoint["Red"] = i - 1; - } - if ((int)capturePointOwnedBy["Team"] == blueTeam && m_BlueTeamHomeCapturePoint != 0) { - nextPossibleCapturePoint["Blue"] = i - 1; - } - } - - //reset timers and reset the bool that triggers this - if (m_ResetTimers) { - for (int i = 0; i < m_NumberOfCapturePoints; i++) - { - ComponentWrapper& capturePoint = m_CapturePointNumberToEntityMap[i]["CapturePoint"]; - if ((int)capturePoint["CapturePointNumber"] != nextPossibleCapturePoint["Red"] && - (int)capturePoint["CapturePointNumber"] != nextPossibleCapturePoint["Blue"]) { - capturePoint["CaptureTimer"] = 0.0; - } - } - m_ResetTimers = false; - } - - //colorize next possible capturepoint - if (nextPossibleCapturePoint["Red"] == capturePointNumber) { - capturePointEntity["Model"]["Color"] = glm::vec4(1, 1, 0, 0.3); - } - if (nextPossibleCapturePoint["Blue"] == capturePointNumber) { - capturePointEntity["Model"]["Color"] = glm::vec4(0, 1, 1, 0.3); - } - - //check how many players are standing inside and are healthy - for (size_t i = m_ETriggerTouchVector.size(); i > 0; i--) - { - auto triggerTouched = m_ETriggerTouchVector[i - 1]; - if (std::get<1>(triggerTouched) == capturePointEntity) { - //some player has touched this - lets figure out: what team, health - EntityWrapper player = std::get<0>(triggerTouched); - //check if its really a player that has triggered the touch - if (!player.HasComponent("Player")) { - //if a non-player has entered the capturePoint, just erase that event and continue - m_ETriggerTouchVector.erase(m_ETriggerTouchVector.begin() + i - 1); - continue; - } - bool hasHealthComponent = player.HasComponent("Health"); - if (hasHealthComponent) { - double currentHealth = player["Health"]["Health"]; - //check if player is dead - if ((int)currentHealth == 0) { - continue; + //Check if the HUD corresponds to the Capture Point Number + if (HUD_ID == (int)entityCP["CapturePoint"]["CapturePointNumber"]) { + ComponentWrapper& teamComponent = entityCP["Team"]; + if (!LoadCheck) { + redTeam = (int)teamComponent["Team"].Enum("Red"); + blueTeam = (int)teamComponent["Team"].Enum("Blue"); + spectatorTeam = (int)teamComponent["Team"].Enum("Spectator"); } + //Color hud with team color + auto capturePointTeam = (int)teamComponent["Team"]; + entityHUDparent["Sprite"]["Color"] = capturePointTeam == blueTeam ? glm::vec4(0, 0.2f, 1, 0.7) : capturePointTeam == redTeam ? glm::vec4(1, 0.2f, 0, 0.7) : glm::vec4(1, 1, 1, 0.3); + + //Progress is scaled with time + double currentCaptureTime = (double)entityCP["CapturePoint"]["CaptureTimer"]; + double progress = glm::abs(currentCaptureTime)/15.0; + int currentCapturingTeam = currentCaptureTime > 0 ? redTeam : currentCaptureTime < 0 ? blueTeam : spectatorTeam; + ((glm::vec3&)entityHUD["Transform"]["Orientation"]).z = currentCapturingTeam == redTeam ? glm::half_pi()+glm::pi() : glm::half_pi(); + glm::vec4 fillColor = currentCapturingTeam == redTeam ? glm::vec4(1, 0.2f, 0, 0.7) : glm::vec4(0, 0.2f, 1, 0.7); + entityHUD["Fill"]["Color"] = fillColor; + entityHUD["Fill"]["Percentage"] = progress; } - //check team - spectatorNumber = "no team" - int teamNumber = player["Team"]["Team"]; - if (teamNumber == redTeam) { - redTeamPlayersStandingInside++; - } else if (teamNumber == blueTeam) { - blueTeamPlayersStandingInside++; - } - continue; } } - //create data to be used in option B - //check so this is the next possible capture point for the take-over team and see if only one team is standing inside it - double timerDeltaChange = 0.0; - int currentTeam = 0; - bool canCapture = false; - if (redTeamPlayersStandingInside > 0 && blueTeamPlayersStandingInside == 0) { - timerDeltaChange = redTeamPlayersStandingInside*dt; - currentTeam = redTeam; - canCapture = nextPossibleCapturePoint["Red"] == capturePointNumber; - } - if (redTeamPlayersStandingInside == 0 && blueTeamPlayersStandingInside > 0) { - timerDeltaChange = -blueTeamPlayersStandingInside*dt; - currentTeam = blueTeam; - canCapture = nextPossibleCapturePoint["Blue"] == capturePointNumber; - } + //if (m_WinnerWasFound) { + // return; + //} + //const int capturePointNumber = cCapturePoint["CapturePointNumber"]; + //const bool hasTeamComponent = capturePointEntity.HasComponent("Team"); - if (redTeamPlayersStandingInside == 0 && blueTeamPlayersStandingInside == 0) { - //A.nobodys standing inside - //do nothing (?) - } else if (redTeamPlayersStandingInside > 0 && blueTeamPlayersStandingInside > 0) { - //C.both teams have players inside - //do nothing (?) - } else { - //B. at most one of the teams have players inside - //if capturePoint is not owned by the take-over team, just modify the CaptureTimer accordingly - if (ownedBy != currentTeam && canCapture) { - if (abs((double)cCapturePoint["CaptureTimer"]) < 0.001f) { - LOG_DEBUG("Point is being captured by team %i", currentTeam); //Remove when we tested sufficiently. - } - cCapturePoint["CaptureTimer"] = (double)cCapturePoint["CaptureTimer"] + timerDeltaChange; - } - //if capturePoint is owned by the team, and the other team has been trying to take it, then increase/decrease the timer towards 0.0 - if ((ownedBy == currentTeam && currentTeam == redTeam && (double)cCapturePoint["CaptureTimer"] < 0.0) || - (ownedBy == currentTeam && currentTeam == blueTeam && (double)cCapturePoint["CaptureTimer"] > 0.0)) { - cCapturePoint["CaptureTimer"] = (double)cCapturePoint["CaptureTimer"] + timerDeltaChange; - } - //check if captureTimer > m_CaptureTimeToTakeOver and if so change owner and publish the eCaptured event - if (abs((double)cCapturePoint["CaptureTimer"]) > abs(m_CaptureTimeToTakeOver) && canCapture) { - teamComponent["Team"] = currentTeam; - cCapturePoint["CaptureTimer"] = 0.0; - //publish Captured event - LOG_DEBUG("Point is captured by team %i!", currentTeam); //Remove when we tested sufficiently. - Events::Captured e; - e.CapturePointID = cCapturePoint.EntityID; - e.TeamNumberThatCapturedCapturePoint = currentTeam; - m_EventBroker->Publish(e); - //NextPossibleCapturePoint will be calculated in the next update... - } - } + ////if point doesnt have a teamComponent yet, add one. since: + ////what if capture point has no team -> we cant get/use the team enum from it... + //if (!hasTeamComponent) { + // m_World->AttachComponent(cCapturePoint.EntityID, "Team"); + // ComponentWrapper& teamComponent = capturePointEntity["Team"]; + // teamComponent["Team"] = (int)teamComponent["Team"].Enum("Spectator"); + //} + //ComponentWrapper& teamComponent = capturePointEntity["Team"]; + //const int redTeam = (int)teamComponent["Team"].Enum("Red"); + //const int blueTeam = (int)teamComponent["Team"].Enum("Blue"); + //const int spectatorTeam = (int)teamComponent["Team"].Enum("Spectator"); - //check for possible winCondition = check if the homebase is owned by the other team - bool checkForWinner = false; - if (capturePointNumber == m_RedTeamHomeCapturePoint && ownedBy != redTeam) - { - checkForWinner = true; - } - if (capturePointNumber == m_BlueTeamHomeCapturePoint && ownedBy != blueTeam) - { - checkForWinner = true; - } + //int homePointForTeam = (int)cCapturePoint["HomePointForTeam"]; + //if (m_NumberOfCapturePoints == 0 && capturePointNumber != 0 && (homePointForTeam == redTeam || homePointForTeam == blueTeam)) { + // m_NumberOfCapturePoints = capturePointNumber + 1;//ex 2 -> 0,1,2 = 3 + // if (homePointForTeam == redTeam) { + // m_RedTeamHomeCapturePoint = capturePointNumber; + // m_BlueTeamHomeCapturePoint = 0; + // } else { + // m_BlueTeamHomeCapturePoint = capturePointNumber; + // m_RedTeamHomeCapturePoint = 0; + // } + //} - if (checkForWinner && !m_WinnerWasFound) - { - //publish Win event - Events::Win e; - e.TeamThatWon = ownedBy; - m_EventBroker->Publish(e); - m_WinnerWasFound = true; - } + ////if we havent received all capturepoints yet, just return + //if (m_NumberOfCapturePoints == 0 || m_NumberOfCapturePoints != m_CapturePointNumberToEntityMap.size()) { + // m_CapturePointNumberToEntityMap.insert(std::make_pair(capturePointNumber, capturePointEntity)); + // return; + //} + + ////we have all capturepoints now - process stuff + //int ownedBy = teamComponent["Team"]; + //int redTeamPlayersStandingInside = 0; + //int blueTeamPlayersStandingInside = 0; + //if (capturePointEntity.HasComponent("Model")) { + // //Now sets team color to the capturepoint, or white if it is uncaptured. + // capturePointEntity["Model"]["Color"] = ownedBy == blueTeam ? glm::vec4(0, 0.2f, 1, 0.3) : ownedBy == redTeam ? glm::vec4(1, 0.2f, 0, 0.3) : glm::vec4(1, 1, 1, 0.3); + //} + + ////calculate next possible capturePoint for both teams + //std::map nextPossibleCapturePoint; + //nextPossibleCapturePoint["Red"] = -1; + //nextPossibleCapturePoint["Blue"] = -1; + //for (int i = 0; i < m_NumberOfCapturePoints; i++) + //{ + // if (!m_CapturePointNumberToEntityMap[i].HasComponent("Team")) { + // continue; + // } + // ComponentWrapper& capturePointOwnedBy = m_CapturePointNumberToEntityMap[i]["Team"]; + // if ((int)capturePointOwnedBy["Team"] == redTeam && m_RedTeamHomeCapturePoint == 0) { + // nextPossibleCapturePoint["Red"] = i + 1; + // } + // if ((int)capturePointOwnedBy["Team"] == blueTeam && m_BlueTeamHomeCapturePoint == 0) { + // nextPossibleCapturePoint["Blue"] = i + 1; + // } + //} + //for (int i = m_NumberOfCapturePoints - 1; i >= 0; i--) + //{ + // if (!m_CapturePointNumberToEntityMap[i].HasComponent("Team")) { + // continue; + // } + // ComponentWrapper& capturePointOwnedBy = m_CapturePointNumberToEntityMap[i]["Team"]; + // if ((int)capturePointOwnedBy["Team"] == redTeam && m_RedTeamHomeCapturePoint != 0) { + // nextPossibleCapturePoint["Red"] = i - 1; + // } + // if ((int)capturePointOwnedBy["Team"] == blueTeam && m_BlueTeamHomeCapturePoint != 0) { + // nextPossibleCapturePoint["Blue"] = i - 1; + // } + //} + + ////reset timers and reset the bool that triggers this + //if (m_ResetTimers) { + // for (int i = 0; i < m_NumberOfCapturePoints; i++) + // { + // ComponentWrapper& capturePoint = m_CapturePointNumberToEntityMap[i]["CapturePoint"]; + // if ((int)capturePoint["CapturePointNumber"] != nextPossibleCapturePoint["Red"] && + // (int)capturePoint["CapturePointNumber"] != nextPossibleCapturePoint["Blue"]) { + // capturePoint["CaptureTimer"] = 0.0; + // } + // } + // m_ResetTimers = false; + //} + + ////colorize next possible capturepoint + //if (nextPossibleCapturePoint["Red"] == capturePointNumber) { + // capturePointEntity["Model"]["Color"] = glm::vec4(1, 1, 0, 0.3); + //} + //if (nextPossibleCapturePoint["Blue"] == capturePointNumber) { + // capturePointEntity["Model"]["Color"] = glm::vec4(0, 1, 1, 0.3); + //} + + ////check how many players are standing inside and are healthy + //for (size_t i = m_ETriggerTouchVector.size(); i > 0; i--) + //{ + // auto triggerTouched = m_ETriggerTouchVector[i - 1]; + // if (std::get<1>(triggerTouched) == capturePointEntity) { + // //some player has touched this - lets figure out: what team, health + // EntityWrapper player = std::get<0>(triggerTouched); + // //check if its really a player that has triggered the touch + // if (!player.HasComponent("Player")) { + // //if a non-player has entered the capturePoint, just erase that event and continue + // m_ETriggerTouchVector.erase(m_ETriggerTouchVector.begin() + i - 1); + // continue; + // } + // bool hasHealthComponent = player.HasComponent("Health"); + // if (hasHealthComponent) { + // double currentHealth = player["Health"]["Health"]; + // //check if player is dead + // if ((int)currentHealth == 0) { + // continue; + // } + // } + // //check team - spectatorNumber = "no team" + // int teamNumber = player["Team"]["Team"]; + // if (teamNumber == redTeam) { + // redTeamPlayersStandingInside++; + // } else if (teamNumber == blueTeam) { + // blueTeamPlayersStandingInside++; + // } + // continue; + // } + //} + + ////create data to be used in option B + ////check so this is the next possible capture point for the take-over team and see if only one team is standing inside it + //double timerDeltaChange = 0.0; + //int currentTeam = 0; + //bool canCapture = false; + //if (redTeamPlayersStandingInside > 0 && blueTeamPlayersStandingInside == 0) { + // timerDeltaChange = redTeamPlayersStandingInside*dt; + // currentTeam = redTeam; + // canCapture = nextPossibleCapturePoint["Red"] == capturePointNumber; + //} + //if (redTeamPlayersStandingInside == 0 && blueTeamPlayersStandingInside > 0) { + // timerDeltaChange = -blueTeamPlayersStandingInside*dt; + // currentTeam = blueTeam; + // canCapture = nextPossibleCapturePoint["Blue"] == capturePointNumber; + //} + + //if (redTeamPlayersStandingInside == 0 && blueTeamPlayersStandingInside == 0) { + // //A.nobodys standing inside + // //do nothing (?) + //} else if (redTeamPlayersStandingInside > 0 && blueTeamPlayersStandingInside > 0) { + // //C.both teams have players inside + // //do nothing (?) + //} else { + // //B. at most one of the teams have players inside + // //if capturePoint is not owned by the take-over team, just modify the CaptureTimer accordingly + // if (ownedBy != currentTeam && canCapture) { + // if (abs((double)cCapturePoint["CaptureTimer"]) < 0.001f) { + // LOG_DEBUG("Point is being captured by team %i", currentTeam); //Remove when we tested sufficiently. + // } + // cCapturePoint["CaptureTimer"] = (double)cCapturePoint["CaptureTimer"] + timerDeltaChange; + // } + // //if capturePoint is owned by the team, and the other team has been trying to take it, then increase/decrease the timer towards 0.0 + // if ((ownedBy == currentTeam && currentTeam == redTeam && (double)cCapturePoint["CaptureTimer"] < 0.0) || + // (ownedBy == currentTeam && currentTeam == blueTeam && (double)cCapturePoint["CaptureTimer"] > 0.0)) { + // cCapturePoint["CaptureTimer"] = (double)cCapturePoint["CaptureTimer"] + timerDeltaChange; + // } + // //check if captureTimer > m_CaptureTimeToTakeOver and if so change owner and publish the eCaptured event + // if (abs((double)cCapturePoint["CaptureTimer"]) > abs(m_CaptureTimeToTakeOver) && canCapture) { + // teamComponent["Team"] = currentTeam; + // cCapturePoint["CaptureTimer"] = 0.0; + // //publish Captured event + // LOG_DEBUG("Point is captured by team %i!", currentTeam); //Remove when we tested sufficiently. + // Events::Captured e; + // e.CapturePointID = cCapturePoint.EntityID; + // e.TeamNumberThatCapturedCapturePoint = currentTeam; + // m_EventBroker->Publish(e); + // //NextPossibleCapturePoint will be calculated in the next update... + // } + //} + + ////check for possible winCondition = check if the homebase is owned by the other team + //bool checkForWinner = false; + //if (capturePointNumber == m_RedTeamHomeCapturePoint && ownedBy != redTeam) + //{ + // checkForWinner = true; + //} + //if (capturePointNumber == m_BlueTeamHomeCapturePoint && ownedBy != blueTeam) + //{ + // checkForWinner = true; + //} + + //if (checkForWinner && !m_WinnerWasFound) + //{ + // //publish Win event + // Events::Win e; + // e.TeamThatWon = ownedBy; + // m_EventBroker->Publish(e); + // m_WinnerWasFound = true; + //} } - -bool CapturePointSystem::OnTriggerTouch(const Events::TriggerTouch& e) -{ - //personEntered = e.Entity, thingEntered = e.Trigger - m_ETriggerTouchVector.push_back(std::make_tuple(e.Entity, e.Trigger)); - return true; -} - -bool CapturePointSystem::OnTriggerLeave(const Events::TriggerLeave& e) -{ - for (size_t i = 0; i < m_ETriggerTouchVector.size(); i++) - { - auto triggerTouched = m_ETriggerTouchVector[i]; - if (std::get<0>(triggerTouched) == e.Entity && std::get<1>(triggerTouched) == e.Trigger) { - m_ETriggerTouchVector.erase(m_ETriggerTouchVector.begin() + i); - break; - } - } - return true; -} -bool CapturePointSystem::OnCaptured(const Events::Captured& e) -{ - //reset the timers in the next update since a capture has changed the "nextCapturePoint" for 1-2 teams - m_ResetTimers = true; - return true; -} +// +//bool CapturePointSystem::OnTriggerTouch(const Events::TriggerTouch& e) +//{ +// //personEntered = e.Entity, thingEntered = e.Trigger +// m_ETriggerTouchVector.push_back(std::make_tuple(e.Entity, e.Trigger)); +// return true; +//} +// +//bool CapturePointSystem::OnTriggerLeave(const Events::TriggerLeave& e) +//{ +// for (size_t i = 0; i < m_ETriggerTouchVector.size(); i++) +// { +// auto triggerTouched = m_ETriggerTouchVector[i]; +// if (std::get<0>(triggerTouched) == e.Entity && std::get<1>(triggerTouched) == e.Trigger) { +// m_ETriggerTouchVector.erase(m_ETriggerTouchVector.begin() + i); +// break; +// } +// } +// return true; +//} +//bool CapturePointSystem::OnCaptured(const Events::Captured& e) +//{ +// //reset the timers in the next update since a capture has changed the "nextCapturePoint" for 1-2 teams +// m_ResetTimers = true; +// return true; +//} From 4b8f4981a36f819512c1faf535bd29f5d6dd2c4f Mon Sep 17 00:00:00 2001 From: antc13 Date: Thu, 11 Feb 2016 00:05:27 +0100 Subject: [PATCH 190/355] New Map with Meshes, WIP. --- assets | 2 +- resources/Schema/Entities/NewMap.xml | 1287 +++++++- resources/Schema/Entities/NewMapBackup.xml | 3222 ++++++++++++++++++++ resources/Schema/Entities/StoneWall.xml | 147 + 4 files changed, 4591 insertions(+), 67 deletions(-) create mode 100644 resources/Schema/Entities/NewMapBackup.xml create mode 100644 resources/Schema/Entities/StoneWall.xml diff --git a/assets b/assets index e0ad8b8d..c56f6380 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit e0ad8b8d45a79b8f17876f9541cc5e03758ae16c +Subproject commit c56f6380ab05c23419beafe14190013d1432e32c diff --git a/resources/Schema/Entities/NewMap.xml b/resources/Schema/Entities/NewMap.xml index a79fee7b..8a5227aa 100644 --- a/resources/Schema/Entities/NewMap.xml +++ b/resources/Schema/Entities/NewMap.xml @@ -134,7 +134,7 @@ - + @@ -199,7 +199,7 @@ Models/Props/Pillars/SciFiPillar1.mesh - + @@ -213,7 +213,7 @@ Models/Props/Pillars/SciFiPillar1.mesh - + @@ -292,7 +292,7 @@ Models/Props/Pillars/SciFiPillar2.mesh - + @@ -338,7 +338,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -363,7 +363,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -388,7 +388,8 @@ Models/Props/Walls/BigWall.mesh - + + @@ -413,7 +414,8 @@ Models/Props/Walls/BigWall.mesh - + + @@ -438,7 +440,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -713,8 +715,8 @@ Models/Props/Walls/MediumWall3.mesh - - + + @@ -725,7 +727,7 @@ Models/Props/Walls/MediumWall3.mesh - + @@ -737,7 +739,7 @@ Models/Props/Walls/MediumWall3.mesh - + @@ -801,7 +803,8 @@ Models/Props/Walls/BigWall.mesh - + + @@ -813,7 +816,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -966,7 +969,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -1136,6 +1139,247 @@ + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + Models/Props/Walls/SmallWall3.mesh + + + + + + + + + + + + Models/Props/Walls/SpecialWall1.mesh + + + + + + + + + + + + + Models/Props/Flora/SpecialRoot.mesh + + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + @@ -1150,8 +1394,8 @@ Models/Props/Bridges/WoodenBridge.mesh - - + + @@ -1178,8 +1422,8 @@ Models/Props/Bridges/WoodenBridge.mesh - - + + @@ -1205,12 +1449,118 @@ Models/Props/Bridges/SciFiBridge.mesh - + - + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + + + + @@ -1254,7 +1604,7 @@ Models/Props/Pillars/SciFiBridgePillar1.mesh - + @@ -1506,7 +1856,7 @@ true - + @@ -1517,7 +1867,7 @@ true - + @@ -1529,7 +1879,7 @@ true - + @@ -1541,7 +1891,7 @@ true - + @@ -1553,7 +1903,7 @@ true - + @@ -1565,7 +1915,7 @@ true - + @@ -1612,6 +1962,227 @@ + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + + Models/Props/Flora/SpecialRoot.mesh + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + @@ -1679,7 +2250,8 @@ Models/Props/Stones/MediumStone1.mesh - + + @@ -1717,8 +2289,8 @@ Models/Props/Stones/MediumStone1.mesh - - + + @@ -1730,8 +2302,8 @@ Models/Props/Stones/MediumStone1.mesh - - + + @@ -1756,7 +2328,7 @@ Models/Props/Stones/MediumStone1.mesh - + @@ -1768,21 +2340,8 @@ Models/Props/Stones/MediumStone1.mesh - - - - - - - - - - - Models/Props/Stones/BigStone.mesh - - - - + + @@ -1794,7 +2353,7 @@ Models/Props/Stones/MediumStone1.mesh - + @@ -1819,7 +2378,7 @@ Models/Props/Stones/MediumStone1.mesh - + @@ -2093,6 +2652,226 @@ + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystal.mesh + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystal.mesh + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystal.mesh + + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + @@ -2107,7 +2886,7 @@ Models/Props/PickUps/PickUpHolder.mesh - + @@ -2184,6 +2963,168 @@ + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + + + + + + + + + + + + + + + Models/Props/SciFiHolder1.mesh + + + + + + + + + + + + + Models/Props/SciFiHolder1.mesh + + + + + + + + + + + + + Models/Props/SciFiHolder1.mesh + + + + + + + + + + @@ -2193,9 +3134,6 @@ - - - @@ -2203,7 +3141,8 @@ Models/Props/CapturePoint.mesh - + + true @@ -2219,13 +3158,13 @@ - 1 Models/Props/CapturePoint.mesh - + + true @@ -2237,12 +3176,13 @@ - 2 Models/Props/CapturePoint.mesh + + true @@ -2254,13 +3194,13 @@ - 3 Models/Props/CapturePoint.mesh - + + true @@ -2272,7 +3212,6 @@ - @@ -2281,7 +3220,8 @@ Models/Props/CapturePoint.mesh - + + true @@ -2373,7 +3313,7 @@ 1 - + @@ -2386,11 +3326,226 @@ Models/Characters/Assault/AssaultTPose.mesh - + + + + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/NewMapBackup.xml b/resources/Schema/Entities/NewMapBackup.xml new file mode 100644 index 00000000..15ec64cf --- /dev/null +++ b/resources/Schema/Entities/NewMapBackup.xml @@ -0,0 +1,3222 @@ + + + + + + + + + + + + + + + + + + Models/Props/Ground.mesh + + + + + + + + + Models/Props/Highground1.mesh + + + + + + + + + + Models/Props/Highground2.mesh + + + + + + + + + + Models/Props/Highground1.mesh + + + + + + + + + + + + Models/Props/Highground2.mesh + + + + + + + + + + + + Models/Props/Highground3.mesh + + + + + + + + + + Models/Props/Highground4.mesh + + + + + + + + + + Models/Props/Highground5.mesh + + + + + + + + + + Models/Props/Highground6.mesh + + + + + + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar1.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar1.mesh + + + + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar2.mesh + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar3.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar1.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar1.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar3.mesh + + + + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar2.mesh + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar2.mesh + + + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + + + + Models/Props/Walls/SmallWall3.mesh + + + + + + + + + + + + + Models/Props/Walls/SmallWall3.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall3.mesh + + + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + + Models/Props/Walls/SmallWall4.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall3.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + + Models/Props/Walls/MediumWall2.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall2.mesh + + + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall3.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall3.mesh + + + + + + + + + + + + + Models/Props/Walls/SmallWall4.mesh + + + + + + + + + + + + + + Models/Props/Walls/SmallWall4.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + Models/Props/Walls/SmallWall3.mesh + + + + + + + + + + + + Models/Props/Walls/SpecialWall1.mesh + + + + + + + + + + + + + Models/Props/Flora/SpecialRoot.mesh + + + + + + + + + + + + + + + + + + + + Models/Props/Bridges/WoodenBridge.mesh + + + + + + + + + + + + + + Models/Props/Bridges/WoodenBridge.mesh + + + + + + + + + + + + + + Models/Props/Bridges/WoodenBridge.mesh + + + + + + + + + + + + + Models/Props/Bridges/SciFiBridge.mesh + + + + + + + + + + + + + + Models/Props/Bridges/SciFiBridge.mesh + + + + + + + + + + + + + + Models/Props/Flora/TreeLog.mesh + + + + + + + + + + + + + + + + + + + + + Models/Props/Pillars/SciFiBridgePillar1.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiBridgePillar1.mesh + + + + + + + + + + + + + + Models/Props/Walls/MediumWall2.mesh + + + + + + + + + + + Models/Props/Walls/MediumWall2.mesh + + + + + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiBridgePillar1.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + + + Models/Props/Flora/TreeLog.mesh + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + + Models/Props/Flora/SpecialRoot.mesh + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystal.mesh + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystal.mesh + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystal.mesh + + + + + + + + + + + + + + + + + + + + Models/Props/PickUps/PickUpHolder.mesh + + + + + + + + + + + + + + Models/Props/PickUps/PickUpHolder.mesh + + + + + + + + + + + + + + Models/Props/PickUps/PickUpHolder.mesh + + + + + + + + + + + + + + Models/Props/PickUps/PickUpHolder.mesh + + + + + + + + + + + + + Models/Props/PickUps/PickUpHolder.mesh + + + + + + + + + + + + + + Models/Props/PickUps/PickUpHolder.mesh + + + + + + + + + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Models/Props/CapturePoint.mesh + + true + + + + + + + + + + + + + + + + + + 1 + + + Models/Props/CapturePoint.mesh + + true + + + + + + + + + + + + + + 2 + + + Models/Props/CapturePoint.mesh + + true + + + + + + + + + + + + + + 3 + + + Models/Props/CapturePoint.mesh + + true + + + + + + + + + + + + + + + + + 4 + + + Models/Props/CapturePoint.mesh + + true + + + + + + + + + + + + + + + + + + + + + + + + 1 + + + + + + + + + 10 + + + + + + + + + + 10 + + + + + + + + + + + + + 10 + + + + + + + + + + + 10 + + + + + + + + + + + 10 + + + + + + + + + + + 1 + + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + + + + + + + + + + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/StoneWall.xml b/resources/Schema/Entities/StoneWall.xml new file mode 100644 index 00000000..e578d339 --- /dev/null +++ b/resources/Schema/Entities/StoneWall.xml @@ -0,0 +1,147 @@ + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + From 9d9c6bdf1ebf04b65da97f4a0c4909d49d957bae Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Thu, 11 Feb 2016 00:08:50 +0100 Subject: [PATCH 191/355] Third person animations and shoot effects base work --- assets | 2 +- include/Game/Game.h | 2 +- include/Game/Systems/WeaponSystem.h | 114 ++++++++++-------- resources/Schema/Entities/MovementTest.xml | 4 +- resources/Schema/Entities/Player.xml | 105 +++++++++++----- resources/Schema/Entities/RayBlue.xml | 6 +- src/Engine/Rendering/RenderSystem.cpp | 4 +- src/Engine/Rendering/Skeleton.cpp | 6 - src/Game/Game.cpp | 5 +- .../Network/MultiplayerSnapshotFilter.cpp | 4 +- src/Game/Systems/PlayerMovementSystem.cpp | 76 ++++++++++-- src/Game/Systems/PlayerSpawnSystem.cpp | 2 +- src/Game/Systems/WeaponSystem.cpp | 16 +-- 13 files changed, 228 insertions(+), 118 deletions(-) diff --git a/assets b/assets index 45cbc3ab..172b3ad5 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit 45cbc3abaebe5f815e2c1b58bcf884d4953a4c52 +Subproject commit 172b3ad527fc14aa6175fa72580a66a00f04e0ba diff --git a/include/Game/Game.h b/include/Game/Game.h index 42ef4d96..baf15656 100644 --- a/include/Game/Game.h +++ b/include/Game/Game.h @@ -46,7 +46,7 @@ public: private: std::string m_NetworkAddress; - int m_NetworkPort; + int m_NetworkPort = 0; ConfigFile* m_Config = nullptr; EventBroker* m_EventBroker; diff --git a/include/Game/Systems/WeaponSystem.h b/include/Game/Systems/WeaponSystem.h index 489048b8..c3daeceb 100644 --- a/include/Game/Systems/WeaponSystem.h +++ b/include/Game/Systems/WeaponSystem.h @@ -15,6 +15,7 @@ #include "Core/EntityFileParser.h" #include "Core/Octree.h" #include "Collision/EntityAABB.h" +#include "Systems/SpawnerSystem.h" class WeaponBehaviour; @@ -150,69 +151,80 @@ private: void spawnTracer() { - ComponentWrapper cTeam = m_Entity["Team"]; - ComponentInfo::EnumType team = cTeam["Team"]; + EntityWrapper spawner; + if (m_Entity == LocalPlayer) { + spawner = m_Entity.FirstChildByName("WeaponMuzzle"); + } else { + spawner = m_Entity.FirstChildByName("ThirdPersonWeaponMuzzle"); + } - // Select the right color of effect - EntityFile* rayFile = nullptr; - if (team == cTeam["Team"].Enum("Red")) { - rayFile = m_RayRed; - } - if (team == cTeam["Team"].Enum("Blue")) { - rayFile = m_RayBlue; - } - if (rayFile == nullptr) { + if (!spawner.Valid()) { return; } - // Create the entity - EntityFileParser parser(rayFile); - EntityID rayID = parser.MergeEntities(m_World); - EntityWrapper ray(m_World, rayID); + Events::SpawnerSpawn e; + e.Spawner = spawner; + m_EventBroker->Publish(e); - // Figure out where to put it - EntityWrapper attachment; - if (m_Entity == LocalPlayer || true) { - // Spawn the effect from the weapon view model for the local player - attachment = m_Entity.FirstChildByName("WeaponMuzzle"); - } - // TODO: Spawn the effect from the weapon world model once it exists + //ComponentWrapper cTeam = m_Entity["Team"]; + //ComponentInfo::EnumType team = cTeam["Team"]; - glm::mat4 transformation = Transform::AbsoluteTransformation(attachment); - glm::vec3 _scale; - glm::vec3 translation; - glm::quat _orientation; - glm::vec3 _skew; - glm::vec4 _perspective; - glm::decompose(transformation, _scale, _orientation, translation, _skew, _perspective); - - // Matrix to euler angles - glm::vec3 euler; - euler.y = glm::asin(-transformation[0][2]); - if (cos(euler.y) != 0) { - euler.x = atan2(transformation[1][2], transformation[2][2]); - euler.z = atan2(transformation[0][1], transformation[0][0]); - } else { - euler.x = atan2(-transformation[2][0], transformation[1][1]); - euler.z = 0; - } + //// Select the right color of effect + //EntityFile* rayFile = nullptr; + //if (team == cTeam["Team"].Enum("Red")) { + // rayFile = m_RayRed; + //} + //if (team == cTeam["Team"].Enum("Blue")) { + // rayFile = m_RayBlue; + //} + //if (rayFile == nullptr) { + // return; + //} - // TODO: Spread? + //// Create the entity + //EntityFileParser parser(rayFile); + //EntityID rayID = parser.MergeEntities(m_World); + //EntityWrapper ray(m_World, rayID); - (glm::vec3&)ray["Transform"]["Position"] = translation; - (glm::vec3&)ray["Transform"]["Orientation"] = euler; - glm::vec3& scale = ray["Transform"]["Scale"]; - scale.z = traceRayDistance(translation, glm::quat(euler) * glm::vec3(0.f, 0.f, -1.f)); + //// Figure out where to put it + //EntityWrapper attachment; + //if (m_Entity == LocalPlayer || true) { + // // Spawn the effect from the weapon view model for the local player + // attachment = m_Entity.FirstChildByName("WeaponMuzzle"); + //} + //// TODO: Spawn the effect from the weapon world model once it exists + + //glm::mat4 transformation = Transform::AbsoluteTransformation(attachment); + //glm::vec3 _scale; + //glm::vec3 translation; + //glm::quat _orientation; + //glm::vec3 _skew; + //glm::vec4 _perspective; + //glm::decompose(transformation, _scale, _orientation, translation, _skew, _perspective); + // + //// Matrix to euler angles + //glm::vec3 euler; + //euler.y = glm::asin(-transformation[0][2]); + //if (cos(euler.y) != 0) { + // euler.x = atan2(transformation[1][2], transformation[2][2]); + // euler.z = atan2(transformation[0][1], transformation[0][0]); + //} else { + // euler.x = atan2(-transformation[2][0], transformation[1][1]); + // euler.z = 0; + //} + + //// TODO: Spread? + + //(glm::vec3&)ray["Transform"]["Position"] = translation; + //(glm::vec3&)ray["Transform"]["Orientation"] = euler; + //glm::vec3& scale = ray["Transform"]["Scale"]; + //scale.z = traceRayDistance(translation, glm::quat(euler) * glm::vec3(0.f, 0.f, -1.f)); } float traceRayDistance(glm::vec3 origin, glm::vec3 direction) { - OctSpace::Output result; - if (m_CollisionOctree->RayCollides(Ray(origin, direction), result)) { - return result.CollideDistance; - } else { - return 0.f; - } + // TODO: Cast a ray and size tracer appropriately + return 100.f; } }; diff --git a/resources/Schema/Entities/MovementTest.xml b/resources/Schema/Entities/MovementTest.xml index b8b68ef1..16a28684 100644 --- a/resources/Schema/Entities/MovementTest.xml +++ b/resources/Schema/Entities/MovementTest.xml @@ -52,6 +52,7 @@ + sModels/Widgets/Lights/DirectionalLightWidget.mesh @@ -65,9 +66,6 @@ - - - Models/Test/ObstacleCourse.mesh diff --git a/resources/Schema/Entities/Player.xml b/resources/Schema/Entities/Player.xml index e0cafc23..423e729e 100644 --- a/resources/Schema/Entities/Player.xml +++ b/resources/Schema/Entities/Player.xml @@ -10,9 +10,7 @@ 600 - - 2 - + @@ -22,12 +20,10 @@ - + - - - + @@ -35,7 +31,7 @@ - + @@ -105,26 +101,48 @@ - + + + + + + Idle + 0.24743387388836702 + 1 + + + Models/Characters/Assault/FirstPerson.mesh + true + + + + + + + R_Arm_Weapon_Joint + - Models/Weapons/Red/AssaultWeaponRed.mesh - true + Models/Weapons/Blue/AssaultWeaponBlue.mesh - - + + - - - - - - - - - + + + + + Schema/Entities/RayBlue.xml + + + + + + + + @@ -147,18 +165,49 @@ - Hold Pos - - 1 + Idle + 1 + + AimRifle + + - Models/Characters/Assault/AssaultAnimated.mesh - + Models/Characters/Assault/AssaultAnimations.mesh + - + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + diff --git a/resources/Schema/Entities/RayBlue.xml b/resources/Schema/Entities/RayBlue.xml index 8d8e6e1e..022d7769 100644 --- a/resources/Schema/Entities/RayBlue.xml +++ b/resources/Schema/Entities/RayBlue.xml @@ -6,12 +6,12 @@ 0.25 - Models/Weapons/CylinderBullet.mesh - + Models/Effects/CylinderShot.mesh + true - + diff --git a/src/Engine/Rendering/RenderSystem.cpp b/src/Engine/Rendering/RenderSystem.cpp index 8dc24e14..36baea0d 100644 --- a/src/Engine/Rendering/RenderSystem.cpp +++ b/src/Engine/Rendering/RenderSystem.cpp @@ -66,8 +66,8 @@ void RenderSystem::fillModels(RenderScene::Queues &Jobs) } // Hide things parented to local player if they have the HiddenFromLocalPlayer component - if (entity.HasComponent("HiddenForLocalPlayer") && (entity == m_LocalPlayer || entity.IsChildOf(m_LocalPlayer))) { - continue; + if ((entity.HasComponent("HiddenForLocalPlayer") || entity.FirstParentWithComponent("HiddenForLocalPlayer").Valid()) && (entity == m_LocalPlayer || entity.IsChildOf(m_LocalPlayer))) { + //continue; } Model* model; diff --git a/src/Engine/Rendering/Skeleton.cpp b/src/Engine/Rendering/Skeleton.cpp index 1aabd84c..71f351e6 100644 --- a/src/Engine/Rendering/Skeleton.cpp +++ b/src/Engine/Rendering/Skeleton.cpp @@ -104,7 +104,6 @@ void Skeleton::AccumulateBoneTransforms(bool noRootMotion, std::vector 1.0f || progress < 0.0f) { - LOG_INFO("Progress: %f", progress); progress = glm::clamp(progress, 0.0f, 1.0f); } Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties; @@ -181,7 +180,6 @@ void Skeleton::AccumulateBoneTransforms(bool noRootMotion, std::vector 1.0f || progress < 0.0f) { - LOG_INFO("Progress: %f", progress); progress = glm::clamp(progress, 0.0f, 1.0f); } Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties; @@ -353,9 +349,7 @@ glm::mat4 Skeleton::GetOffsetTransform(const Bone* bone, AnimationOffset animati } - if (progress > 1.0f || progress < 0.0f) { - LOG_INFO("Progress: %f", progress); progress = glm::clamp(progress, 0.0f, 1.0f); } Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties; diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index a6f12f03..6057d463 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -227,11 +227,8 @@ int Game::parseArgs(int argc, char* argv[]) exit(1); } - if (vm.count("connect")) { - m_IsClient = true; - } - // HACK: Right now, client and server are mutually exclusive + m_IsClient = true; if (m_IsServer) { m_IsClient = false; } diff --git a/src/Game/Network/MultiplayerSnapshotFilter.cpp b/src/Game/Network/MultiplayerSnapshotFilter.cpp index 709ce6b1..65d40189 100644 --- a/src/Game/Network/MultiplayerSnapshotFilter.cpp +++ b/src/Game/Network/MultiplayerSnapshotFilter.cpp @@ -26,6 +26,8 @@ bool MultiplayerSnapshotFilter::FilterComponent(EntityWrapper entity, SharedComp bool MultiplayerSnapshotFilter::OnPlayerSpawned(Events::PlayerSpawned ePlayerSpawned) { - m_LocalPlayer = ePlayerSpawned.Player; + if (ePlayerSpawned.PlayerID == -1) { + m_LocalPlayer = ePlayerSpawned.Player; + } return true; } \ No newline at end of file diff --git a/src/Game/Systems/PlayerMovementSystem.cpp b/src/Game/Systems/PlayerMovementSystem.cpp index ec834715..7c69f0ce 100644 --- a/src/Game/Systems/PlayerMovementSystem.cpp +++ b/src/Game/Systems/PlayerMovementSystem.cpp @@ -29,12 +29,20 @@ void PlayerMovementSystem::updateMovementControllers(double dt) continue; } + // Aim pitch EntityWrapper cameraEntity = player.FirstChildByName("Camera"); if (cameraEntity.Valid()) { glm::vec3& cameraOrientation = cameraEntity["Transform"]["Orientation"]; cameraOrientation.x += controller->Rotation().x; // Limit camera pitch so we don't break our necks cameraOrientation.x = glm::clamp(cameraOrientation.x, -glm::half_pi(), glm::half_pi()); + // Set third person model aim pitch + EntityWrapper playerModel = player.FirstChildByName("PlayerModel"); + if (playerModel.Valid()) { + ComponentWrapper cAnimationOffset = playerModel["AnimationOffset"]; + double time = (cameraOrientation.x + glm::half_pi()) / glm::pi(); + cAnimationOffset["Time"] = time; + } } ComponentWrapper& cTransform = player["Transform"]; @@ -124,24 +132,74 @@ void PlayerMovementSystem::updateMovementControllers(double dt) EntityWrapper playerModel = player.FirstChildByName("PlayerModel"); if (playerModel.Valid()) { ComponentWrapper cAnimation = playerModel["Animation"]; + std::string& animationName1 = cAnimation["AnimationName1"]; + std::string& animationName2 = cAnimation["AnimationName2"]; + double& animationTime1 = cAnimation["Time1"]; + double& animationTime2 = cAnimation["Time2"]; + double& animationSpeed1 = cAnimation["Speed1"]; + double& animationSpeed2 = cAnimation["Speed2"]; + double& animationWeight1 = cAnimation["Weight1"]; + double& animationWeight2 = cAnimation["Weight2"]; float movementLength = glm::length(groundVelocity); //TODO: add assault dash animation here if (glm::length(controller->Movement()) > 0.f) { - if (controller->Crouching()) { - cAnimation["AnimationName1"] = "Crouch Walk"; - (double&)cAnimation["Speed1"] = 1.f * -glm::sign(controller->Movement().z); + double forwardMovement = controller->Movement().z; + double strafeMovement = controller->Movement().x; + + if (controller->Crouching() && animationName1 != "CrouchWalk") { + animationName1 = "CrouchWalk"; + animationSpeed1 = 1.0 * -glm::sign(controller->Movement().z); } else { - cAnimation["AnimationName1"] = "Run"; - (double&)cAnimation["Speed1"] = 2.f * -glm::sign(controller->Movement().z); + if (glm::abs(forwardMovement) > 0) { + if (animationName1 != "Run") { + animationName1 = "Run"; + if (animationName2 == "StrafeLeft" || animationName2 == "StrafeRight") { + animationTime1 = animationTime2; + } else { + animationTime1 = 0.0; + } + } + animationSpeed1 = 2.f * -glm::sign(forwardMovement); + } + + if (glm::abs(strafeMovement) > 0) { + if (animationName2 != "StrafeLeft" && animationName2 != "StrafeRight") { + if (strafeMovement < 0) { + animationName2 = "StrafeLeft"; + } + if (strafeMovement > 0) { + animationName2 = "StrafeRight"; + } + if (animationName1 == "Run") { + animationTime2 = animationTime1; + } else { + animationTime2 = 0.0; + } + } + animationSpeed2 = 2.f * glm::abs(strafeMovement); + } + + double strafeWeight = glm::abs(strafeMovement) / (glm::abs(forwardMovement) + glm::abs(strafeMovement)); + animationWeight2 = strafeWeight; + animationWeight1 = 1.0 - strafeWeight; } } else { if (controller->Crouching()) { - cAnimation["AnimationName1"] = "Crouch"; - (double&)cAnimation["Speed"] = 1.f; + animationName1 = "Crouch"; + animationName2 = ""; + animationSpeed1 = 1.0; + animationSpeed2 = 0.0; + animationWeight1 = 1.0; + animationWeight2 = 0.0; } else { - cAnimation["AnimationName1"] = "Hold Pos"; - (double&)cAnimation["Speed1"] = 1.f; + animationName1 = "Idle"; + animationName2 = ""; + animationSpeed1 = 1.f; + animationSpeed2 = 0.0; + animationWeight1 = 1.0; + animationWeight2 = 0.0; + //cAnimation["AnimationName2"] = "Idle"; } } } diff --git a/src/Game/Systems/PlayerSpawnSystem.cpp b/src/Game/Systems/PlayerSpawnSystem.cpp index 507ed0f5..2afb0de1 100644 --- a/src/Game/Systems/PlayerSpawnSystem.cpp +++ b/src/Game/Systems/PlayerSpawnSystem.cpp @@ -91,7 +91,7 @@ bool PlayerSpawnSystem::OnPlayerSpawned(Events::PlayerSpawned& e) if (cameraEntity.Valid()) { Events::SetCamera e; e.CameraEntity = cameraEntity; - m_EventBroker->Publish(e); + //m_EventBroker->Publish(e); } // HACK: Set the player model color to team color diff --git a/src/Game/Systems/WeaponSystem.cpp b/src/Game/Systems/WeaponSystem.cpp index dfb84581..117176c1 100644 --- a/src/Game/Systems/WeaponSystem.cpp +++ b/src/Game/Systems/WeaponSystem.cpp @@ -20,14 +20,14 @@ void WeaponSystem::Update(double dt) void WeaponSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& cPlayer, double dt) { // Update potential weapon behaviour for player - //auto it = m_ActiveWeapons.find(entity); - //if (it != m_ActiveWeapons.end()) { - // //if (it->first.Valid()) { - // it->second->Update(dt); - // //} else { - // // m_ActiveWeapons.erase(it); - // //} - //} + auto it = m_ActiveWeapons.find(entity); + if (it != m_ActiveWeapons.end()) { + if (it->first.Valid()) { + it->second->Update(dt); + } else { + m_ActiveWeapons.erase(it); + } + } } bool WeaponSystem::OnInputCommand(Events::InputCommand& e) From 73f59b89ccce4709376beb9cc5273f68afc71178 Mon Sep 17 00:00:00 2001 From: William Moberg Date: Thu, 11 Feb 2016 00:11:37 +0100 Subject: [PATCH 192/355] Added method EntityFirstHitByRay, takes an Octree or a vector of sorted entities and outputs the frist entity hit by a ray. --- include/Engine/Collision/Collision.h | 23 +++++++-- include/Engine/Core/Octree.h | 75 ++++++++++++++++++++++++++++ src/Engine/Collision/Collision.cpp | 66 ++++++++++++++++++------ src/Engine/Core/Octree.cpp | 25 +++------- 4 files changed, 151 insertions(+), 38 deletions(-) diff --git a/include/Engine/Collision/Collision.h b/include/Engine/Collision/Collision.h index c3759393..5b4150d8 100644 --- a/include/Engine/Collision/Collision.h +++ b/include/Engine/Collision/Collision.h @@ -20,6 +20,9 @@ class World; struct ComponentWrapper; +template +class Octree; + namespace Collision { //Return true if the ray hits the box. @@ -44,21 +47,24 @@ bool RayVsTriangle(const Ray& ray, float& outVCoord, bool trueOnNegativeDistance = false); //Return true if the ray hits any of the triangles in the model. Stops checking when a hit is detected. -bool RayVsModel(const Ray& ray, - const std::vector& modelVertices, - const std::vector& modelIndices); +bool RayVsModel(const Ray& ray, + const RawModel::Vertex* modelVertices, + const std::vector& modelIndices, + const glm::mat4& modelMatrix); //Return true if the ray hits any of the triangles in the model. //Also returns the position of the intersection point. Will loop through all the whole model indices. bool RayVsModel(const Ray& ray, - const std::vector& modelVertices, + const RawModel::Vertex* modelVertices, const std::vector& modelIndices, + const glm::mat4& modelMatrix, glm::vec3& outHitPosition); //Return true if the ray hits any of the triangles in the model. //Also returns the distance from the ray origin to the closest //intersection point, and the barycentric u,v-coordinates. Will loop through all the whole model indices. bool RayVsModel(const Ray& ray, - const std::vector& modelVertices, + const RawModel::Vertex* modelVertices, const std::vector& modelIndices, + const glm::mat4& modelMatrix, float& outDistance, float& outUCoord, float& outVCoord); @@ -81,6 +87,13 @@ bool AABBVsAABB(const AABB& a, const AABB& b, glm::vec3& minimumTranslation); // Calculates an absolute AABB from an entity AABB component boost::optional EntityAbsoluteAABB(EntityWrapper& entity, bool takeModelBox = false); boost::optional AbsoluteAABBExplosionEffect(EntityWrapper& entity); +//Returns the first entity hit by the input ray. entitiesPotentiallyHitSorted needs to be sorted +//by their distance to the ray, e.g. result from Octree::ObjectsPossiblyHitByRay. +//Returns boost::none if none was hit. outDistance will be the distance to the intersection point if the ray intersects. +boost::optional EntityFirstHitByRay(const Ray& ray, std::vector entitiesPotentiallyHitSorted, float outDistance, glm::vec3& outIntersectPos); +//Returns the first entity hit by the input ray that exists in the octree. +//outDistance will be the distance to the intersection point if the ray intersects. +boost::optional EntityFirstHitByRay(const Ray& ray, Octree* octree, float outDistance, glm::vec3& outIntersectPos); } diff --git a/include/Engine/Core/Octree.h b/include/Engine/Core/Octree.h index 6bdea4d3..be0cac95 100644 --- a/include/Engine/Core/Octree.h +++ b/include/Engine/Core/Octree.h @@ -43,6 +43,8 @@ public: void ObjectsInSameRegion(const Box& box, std::vector& outObjects); //Get the objects that are inside the frustum, the objects are put in outObjects. void ObjectsInFrustum(const Frustum& frustum, std::vector& outObjects); + //Get objects, which AABB the input ray intersects, the objects are put in outObjects. + void ObjectsPossiblyHitByRay(const Ray& ray, std::vector& outObjects); //Empty the tree of all objects, static and dynamic. void ClearObjects(); //Empty the tree of all dynamic objects. Static objects remain in the tree. @@ -102,6 +104,8 @@ struct Child void ObjectsInSameRegion(const Box& box, std::vector& outObjects) const; template void ObjectsInFrustum(const Frustum& frustum, std::vector& outObjects, bool takeAllDontTest) const; + template + void ObjectsPossiblyHitByRay(const Ray& ray, std::vector& outObjects) const; void ClearObjects(); void ClearDynamicObjects(); bool RayCollides(const Ray& ray, Output& data) const; @@ -121,6 +125,15 @@ struct Child std::vector childIndicesContainingBox(const AABB& box) const; }; +//To be able to sort child nodes and contained objects based on distance to ray origin. +struct RaySorterInfo +{ + int Index; + float Distance; +}; + +bool isFirstLower(const RaySorterInfo& first, const RaySorterInfo& second); + } template @@ -166,6 +179,13 @@ void Octree::ObjectsInFrustum(const Frustum& frustum, std::vector& outObje m_Root->ObjectsInFrustum(frustum, outObjects, false); } +template +void Octree::ObjectsPossiblyHitByRay(const Ray& ray, std::vector& outObjects) +{ + falsifyObjectChecks(); + m_Root->ObjectsPossiblyHitByRay(ray, outObjects); +} + template void Octree::ClearObjects() { @@ -284,4 +304,59 @@ void OctSpace::Child::ObjectsInFrustum(const Frustum& frustum, std::vector& o } } +template +void OctSpace::Child::ObjectsPossiblyHitByRay(const Ray& ray, std::vector& outObjects) const +{ + //If the node AABB is missed, everything it contains is missed. + if (Collision::RayAABBIntr(ray, m_Box)) { + //If the ray shoots the tree, and it is a parent. + if (hasChildren()) { + //Sort children according to their distance from the ray origin. + std::vector childInfos; + childInfos.resize(8); + for (int i = 0; i < 8; ++i) { + childInfos[i] = { i, glm::distance(ray.Origin(), m_Children[i]->m_Box.Origin()) }; + } + std::sort(childInfos.begin(), childInfos.end(), isFirstLower); + //Loop through the children, starting with the one closest to the ray origin. I.e the first to be hit. + for (const RaySorterInfo& info : childInfos) { + m_Children[info.Index]->ObjectsPossiblyHitByRay(ray, outObjects); + } + } else { + //Check against boxes in the node. + bool intersected = false; + float dist; + //Sort all contained objects according to the distance from the ray origin to + //the intersection, if they are intersecting. + std::vector objectHitInfos; + objectHitInfos.reserve(m_StaticObjIndices.size() + m_DynamicObjIndices.size()); + for (int i : m_StaticObjIndices) { + //If we haven't tested against this object before, and the ray hits. + if (!m_StaticObjectsRef[i].Checked && + Collision::RayVsAABB(ray, *m_StaticObjectsRef[i].Box, dist)) { + objectHitInfos.push_back({ i, dist }); + } + m_StaticObjectsRef[i].Checked = true; + } + for (int i : m_DynamicObjIndices) { + //If we haven't tested against this object before, and the ray hits. + if (!m_DynamicObjectsRef[i].Checked && + Collision::RayVsAABB(ray, *m_DynamicObjectsRef[i].Box, dist)) { + objectHitInfos.push_back({ i + (int)m_StaticObjIndices.size(), dist }); + } + m_DynamicObjectsRef[i].Checked = true; + } + std::sort(objectHitInfos.begin(), objectHitInfos.end(), isFirstLower); + int startSize = (int)outObjects.size(); + outObjects.resize(startSize + objectHitInfos.size()); + for (int i = 0; i < objectHitInfos.size(); ++i) { + outObjects[startSize + i] = (objectHitInfos[i].Index < m_StaticObjIndices.size()) ? + *static_cast(m_StaticObjectsRef[objectHitInfos[i].Index].Box.get()) : + *static_cast(m_DynamicObjectsRef[objectHitInfos[i].Index - m_StaticObjIndices.size()].Box.get()); + } + } + } +} + + #endif \ No newline at end of file diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index b7b21969..7b182de1 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -6,6 +6,7 @@ #include "Core/World.h" #include "Rendering/Model.h" #include "imgui/imgui.h" +#include "Core/Octree.h" namespace Collision { @@ -145,13 +146,14 @@ bool RayVsTriangle(const Ray& ray, } bool RayVsModel(const Ray& ray, - const std::vector& modelVertices, - const std::vector& modelIndices) + const RawModel::Vertex* modelVertices, + const std::vector& modelIndices, + const glm::mat4& modelMatrix) { - for (int i = 0; i < modelIndices.size(); ++i) { - glm::vec3 v0 = modelVertices[modelIndices[i]].Position; - glm::vec3 v1 = modelVertices[modelIndices[++i]].Position; - glm::vec3 v2 = modelVertices[modelIndices[++i]].Position; + for (int i = 0; i < modelIndices.size();) { + glm::vec3 v0 = Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix); + glm::vec3 v1 = Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix); + glm::vec3 v2 = Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix); if (RayVsTriangle(ray, v0, v1, v2)) { return true; } @@ -192,19 +194,20 @@ bool RayVsTriangle(const Ray& ray, } bool RayVsModel(const Ray& ray, - const std::vector& modelVertices, + const RawModel::Vertex* modelVertices, const std::vector& modelIndices, + const glm::mat4& modelMatrix, float& outDistance, float& outUCoord, float& outVCoord) { outDistance = INFINITY; bool hit = false; - for (int i = 0; i < modelIndices.size(); ++i) { - glm::vec3 v0 = modelVertices[modelIndices[i]].Position; - glm::vec3 v1 = modelVertices[modelIndices[++i]].Position; - glm::vec3 v2 = modelVertices[modelIndices[++i]].Position; - float dist; + for (int i = 0; i < modelIndices.size();) { + glm::vec3 v0 = Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix); + glm::vec3 v1 = Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix); + glm::vec3 v2 = Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix); + float dist = INFINITY; float u; float v; if (RayVsTriangle(ray, v0, v1, v2, dist, u, v)) { @@ -218,14 +221,15 @@ bool RayVsModel(const Ray& ray, } bool RayVsModel(const Ray& ray, - const std::vector& modelVertices, + const RawModel::Vertex* modelVertices, const std::vector& modelIndices, + const glm::mat4& modelMatrix, glm::vec3& outHitPosition) { float u; float v; float dist; - bool hit = RayVsModel(ray, modelVertices, modelIndices, dist, u, v); + bool hit = RayVsModel(ray, modelVertices, modelIndices, modelMatrix, dist, u, v); outHitPosition = ray.Origin() + dist * ray.Direction(); return hit; } @@ -572,11 +576,11 @@ boost::optional EntityAbsoluteAABB(EntityWrapper& entity, bool takeM ComponentWrapper& cAABB = entity["AABB"]; modelSpaceBox = EntityAABB::FromOriginSize((glm::vec3)cAABB["Origin"], (glm::vec3)cAABB["Size"]); } else if (entity.HasComponent("Model")) { - Model* model; std::string res = entity["Model"]["Resource"]; if (res.empty()) { return boost::none; } + Model* model; try { model = ResourceManager::Load<::Model, true>(res); } catch (const Resource::StillLoadingException&) { @@ -638,4 +642,36 @@ boost::optional AbsoluteAABBExplosionEffect(EntityWrapper& entity) return aabb; } +boost::optional EntityFirstHitByRay(const Ray& ray, std::vector entitiesPotentiallyHitSorted, float outDistance, glm::vec3& outIntersectPos) +{ + for (EntityAABB& entityBox : entitiesPotentiallyHitSorted) { + if (!entityBox.Entity.HasComponent("Model")) { + continue; + } + std::string res = entityBox.Entity["Model"]["Resource"]; + if (res.empty()) { + continue; + } + Model* model; + try { + model = ResourceManager::Load<::Model, true>(res); + } catch (const std::exception&) { + continue; + } + float u, v; + if (RayVsModel(ray, model->Vertices(), model->m_RawModel->m_Indices, Transform::ModelMatrix(entityBox.Entity), outDistance, u, v)) { + outIntersectPos = ray.Origin() + outDistance * ray.Direction(); + return entityBox; + } + } + return boost::none; +} + +boost::optional EntityFirstHitByRay(const Ray& ray, Octree* octree, float outDistance, glm::vec3& outIntersectPos) +{ + std::vector outObjects; + octree->ObjectsPossiblyHitByRay(ray, outObjects); + return Collision::EntityFirstHitByRay(ray, outObjects, outDistance, outIntersectPos); +} + } \ No newline at end of file diff --git a/src/Engine/Core/Octree.cpp b/src/Engine/Core/Octree.cpp index 7eee1f81..dca06c6f 100644 --- a/src/Engine/Core/Octree.cpp +++ b/src/Engine/Core/Octree.cpp @@ -5,22 +5,6 @@ #include "Core/Octree.h" #include "Collision/Collision.h" -namespace -{ -//To be able to sort nodes based on distance to ray origin. -struct ChildInfo -{ - int Index; - float Distance; -}; - -bool isFirstLower(const ChildInfo& first, const ChildInfo& second) -{ - return first.Distance < second.Distance; -} - -} - namespace OctSpace { @@ -123,14 +107,14 @@ bool Child::RayCollides(const Ray& ray, OctSpace::Output& data) const //If the ray shoots the tree, and it is a parent to 8 children :o if (hasChildren()) { //Sort children according to their distance from the ray origin. - std::vector childInfos; + std::vector childInfos; childInfos.reserve(8); for (int i = 0; i < 8; ++i) { childInfos.push_back({ i, glm::distance(ray.Origin(), m_Children[i]->m_Box.Origin()) }); } std::sort(childInfos.begin(), childInfos.end(), isFirstLower); //Loop through the children, starting with the one closest to the ray origin. I.e the first to be hit. - for (const ChildInfo& info : childInfos) { + for (const RaySorterInfo& info : childInfos) { if (m_Children[info.Index]->RayCollides(ray, data)) { return true; } @@ -275,4 +259,9 @@ std::vector Child::childIndicesContainingBox(const AABB& box) const } } +bool isFirstLower(const RaySorterInfo& first, const RaySorterInfo& second) +{ + return first.Distance < second.Distance; +} + } \ No newline at end of file From 35e4935497910a37711fc744646d05efced90e3e Mon Sep 17 00:00:00 2001 From: Tleety Date: Thu, 11 Feb 2016 10:01:11 +0100 Subject: [PATCH 193/355] Some assets and HUD stuff --- assets | 2 +- .../Schema/Entities/CapturePointHUDGroup | 172 ++++++++++++++++++ .../Schema/Entities/QualityAssurance.xml | 75 ++++---- src/Game/Systems/CapturePointHUDSystem.cpp | 5 +- 4 files changed, 215 insertions(+), 39 deletions(-) create mode 100644 resources/Schema/Entities/CapturePointHUDGroup diff --git a/assets b/assets index 7531e441..0580eeae 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit 7531e441fea639076d69c6cf05e3ae8ff7170cf9 +Subproject commit 0580eeae80919127622e16f2ec4f4083668d36cd diff --git a/resources/Schema/Entities/CapturePointHUDGroup b/resources/Schema/Entities/CapturePointHUDGroup new file mode 100644 index 00000000..9dce0ffb --- /dev/null +++ b/resources/Schema/Entities/CapturePointHUDGroup @@ -0,0 +1,172 @@ + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + 2 + + + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + 3 + + + 0.80222018197612788 + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + 4 + + + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + 1 + + + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/QualityAssurance.xml b/resources/Schema/Entities/QualityAssurance.xml index ce6a650e..2c77bc30 100644 --- a/resources/Schema/Entities/QualityAssurance.xml +++ b/resources/Schema/Entities/QualityAssurance.xml @@ -40,7 +40,7 @@ - + @@ -180,7 +180,7 @@ - + @@ -671,7 +671,7 @@ - + @@ -718,7 +718,7 @@ - + @@ -778,7 +778,7 @@ - + @@ -825,7 +825,7 @@ - + @@ -871,7 +871,7 @@ - + @@ -918,7 +918,7 @@ - + @@ -965,7 +965,7 @@ - + @@ -1023,6 +1023,7 @@ + 15 Models/Core/UnitCube.mesh @@ -1162,7 +1163,6 @@ - -12.033302729641917 3 @@ -1212,6 +1212,7 @@ + -15 4 @@ -1378,7 +1379,7 @@ - + @@ -1387,7 +1388,7 @@ true - 0.75158864645285173 + 0.75184169309215043 3.7999999523162842 true @@ -1434,7 +1435,7 @@ - + @@ -1443,7 +1444,7 @@ - 1.2014943970669589 + 1.2017474437062576 Models/Characters/Assault/AssaultTPose.mesh @@ -1486,7 +1487,7 @@ - + @@ -1497,7 +1498,7 @@ true - 0.68494018072689011 + 0.68519322736618882 true @@ -1542,7 +1543,7 @@ - + @@ -1552,7 +1553,7 @@ true - 0.95103870157425385 + 0.95129174821355256 10 3 @@ -1600,7 +1601,7 @@ - + @@ -1610,7 +1611,7 @@ true - 1.3510669629503185 + 1.3513200095896172 true 5 true @@ -1791,7 +1792,7 @@ true - 1.3677400229854642 + 1.3679930696247629 3.7999999523162842 true @@ -1965,7 +1966,7 @@ Textures/Core/UnitHexagon.png - + @@ -1978,7 +1979,7 @@ 2 - 0.5 + Textures/Core/UnitHexagon_Rotated.png @@ -1986,7 +1987,7 @@ - + @@ -1997,7 +1998,7 @@ Textures/Core/UnitHexagon.png - + @@ -2010,7 +2011,7 @@ 3 - 0.5 + Textures/Core/UnitHexagon_Rotated.png @@ -2018,7 +2019,7 @@ - + @@ -2029,7 +2030,7 @@ Textures/Core/UnitHexagon.png - + @@ -2042,7 +2043,8 @@ 4 - 0.5 + 1 + Textures/Core/UnitHexagon_Rotated.png @@ -2050,7 +2052,7 @@ - + @@ -2061,7 +2063,7 @@ Textures/Core/UnitHexagon.png - + @@ -2074,7 +2076,7 @@ 1 - 0.5 + Textures/Core/UnitHexagon_Rotated.png @@ -2082,7 +2084,7 @@ - + @@ -2093,7 +2095,7 @@ Textures/Core/UnitHexagon.png - + @@ -2104,7 +2106,8 @@ - 0.5 + 1 + Textures/Core/UnitHexagon_Rotated.png @@ -2112,7 +2115,7 @@ - + diff --git a/src/Game/Systems/CapturePointHUDSystem.cpp b/src/Game/Systems/CapturePointHUDSystem.cpp index 5c4c2b60..ad8cc63a 100644 --- a/src/Game/Systems/CapturePointHUDSystem.cpp +++ b/src/Game/Systems/CapturePointHUDSystem.cpp @@ -13,7 +13,7 @@ CapturePointHUDSystem::CapturePointHUDSystem(World* world, EventBroker* eventBro void CapturePointHUDSystem::Update(double dt) { - bool LoadCheck = false; + bool LoadCheck = true; int redTeam; int blueTeam; int spectatorTeam; @@ -32,10 +32,11 @@ void CapturePointHUDSystem::Update(double dt) //Check if the HUD corresponds to the Capture Point Number if (HUD_ID == (int)entityCP["CapturePoint"]["CapturePointNumber"]) { ComponentWrapper& teamComponent = entityCP["Team"]; - if (!LoadCheck) { + if (LoadCheck) { redTeam = (int)teamComponent["Team"].Enum("Red"); blueTeam = (int)teamComponent["Team"].Enum("Blue"); spectatorTeam = (int)teamComponent["Team"].Enum("Spectator"); + LoadCheck = false; } //Color hud with team color auto capturePointTeam = (int)teamComponent["Team"]; From 607150189c7a4717b0be98b167bab6ccf1ffaab1 Mon Sep 17 00:00:00 2001 From: viktorljung Date: Thu, 11 Feb 2016 10:51:11 +0100 Subject: [PATCH 194/355] Different animations can now be played on multiple meshes, AnimationOffset seems to make the lighting buggy --- include/Engine/Rendering/ModelJob.h | 30 +- include/Engine/Rendering/Skeleton.h | 33 +- resources/Schema/Entities/AnimationTests2.xml | 87 ++++- resources/Schema/Entities/AnimationTests3.xml | 75 ++-- src/Engine/Rendering/AnimationSystem.cpp | 27 -- src/Engine/Rendering/BoneAttachmentSystem.cpp | 5 +- src/Engine/Rendering/DrawFinalPass.cpp | 48 ++- src/Engine/Rendering/PickingPass.cpp | 24 +- src/Engine/Rendering/Skeleton.cpp | 328 +++++++++--------- 9 files changed, 380 insertions(+), 277 deletions(-) diff --git a/include/Engine/Rendering/ModelJob.h b/include/Engine/Rendering/ModelJob.h index 4bb1b51f..ba801f60 100644 --- a/include/Engine/Rendering/ModelJob.h +++ b/include/Engine/Rendering/ModelJob.h @@ -120,6 +120,32 @@ struct ModelJob : RenderJob if (model->IsSkinned()) { Skeleton = Model->m_RawModel->m_Skeleton; + + if (Skeleton != nullptr) { + if (world->HasComponent(Entity, "Animation")) { + auto animationComponent = world->GetComponent(Entity, "Animation"); + + for (int i = 1; i <= 3; i++) { + ::Skeleton::AnimationData animationData; + animationData.animation = model->m_RawModel->m_Skeleton->GetAnimation(animationComponent["AnimationName" + std::to_string(i)]); + if (animationData.animation == nullptr) { + continue; + } + animationData.time = (double)animationComponent["Time" + std::to_string(i)]; + animationData.weight = (double)animationComponent["Weight" + std::to_string(i)]; + + Animations.push_back(animationData); + } + } + + if (world->HasComponent(Entity, "AnimationOffset")) { + auto animationOffsetComponent = world->GetComponent(Entity, "AnimationOffset"); + AnimationOffset.animation = model->m_RawModel->m_Skeleton->GetAnimation(animationOffsetComponent["AnimationName"]); + AnimationOffset.time = (double)animationOffsetComponent["Time"]; + } else { + AnimationOffset.animation = nullptr; + } + } } }; @@ -140,8 +166,8 @@ struct ModelJob : RenderJob glm::vec4 Color; const ::Model* Model = nullptr; ::Skeleton* Skeleton = nullptr; - // const ::Skeleton::Animation* Animation = nullptr; - + std::vector<::Skeleton::AnimationData> Animations; + ::Skeleton::AnimationOffset AnimationOffset; diff --git a/include/Engine/Rendering/Skeleton.h b/include/Engine/Rendering/Skeleton.h index a8dd982d..ccf3e2b4 100644 --- a/include/Engine/Rendering/Skeleton.h +++ b/include/Engine/Rendering/Skeleton.h @@ -100,13 +100,13 @@ public: int GetBoneID(std::string name); - void CalculateFrameBones(std::vector animations, AnimationOffset animationOffset, bool noRootMotion = false); - void CalculateFrameBones(std::vector animations, bool noRootMotion = false); + std::vector GetFrameBones(std::vector animations, AnimationOffset animationOffset, bool noRootMotion = false); + std::vector GetFrameBones(std::vector animations, bool noRootMotion = false); const Animation* GetAnimation(std::string name); - void AccumulateBoneTransforms(bool noRootMotion, std::vector animations, const Bone* bone, glm::mat4 parentMatrix); - void AccumulateBoneTransforms(bool noRootMotion, std::vector animations, AnimationOffset animationOffset, const Bone* bone, glm::mat4 parentMatrix); + void AccumulateBoneTransforms(bool noRootMotion, std::vector animations, std::map& frameBones, const Bone* bone, glm::mat4 parentMatrix); + void AccumulateBoneTransforms(bool noRootMotion, std::vector animations, AnimationOffset animationOffset, std::map& frameBones, const Bone* bone, glm::mat4 parentMatrix); void PrintSkeleton(); void PrintSkeleton(const Bone* parent, int depthCount); @@ -115,35 +115,12 @@ public: glm::mat4 GetBoneTransform(const Bone* bone, const Animation* animation, float time, glm::mat4 childMatrix); int GetKeyframe(const Animation& animation, double time); - - std::vector GetBones() - { - std::vector finalMatrices; - for (auto &kv : m_BoneLocalTransforms) { - finalMatrices.push_back(kv.second); - } - return finalMatrices;; - } - - glm::mat4 GetBoneTransformSuper(int boneID) - { - if(m_BoneTransforms.find(boneID) != m_BoneTransforms.end()) { - return m_BoneTransforms.at(boneID); - } else { - return glm::mat4(1); - } - } - private: glm::mat4 GetOffsetTransform(const Bone* bone, AnimationOffset animationOffset); std::map m_BonesByName; - float aim = 0.f; - - - std::map m_BoneLocalTransforms; - std::map m_BoneTransforms; + }; #endif diff --git a/resources/Schema/Entities/AnimationTests2.xml b/resources/Schema/Entities/AnimationTests2.xml index 6536a839..f027dd1d 100644 --- a/resources/Schema/Entities/AnimationTests2.xml +++ b/resources/Schema/Entities/AnimationTests2.xml @@ -15,7 +15,9 @@ - + + + Models/Widgets/Lights/DirectionalLightWidget.mesh @@ -26,29 +28,24 @@ - + Run 0.5 - 0.78014858943309839 - 1 + 0.99150007800799234 + -1 1 - StrafeRight 0.5 - 0.78620929522779459 - ShootFastRifle - 0.13809128482706701 + 0.96957233017255007 + 0.093923612201312068 1 AimRifle - Models/Characters/Assault/AssaultAnimations.mesh - - true @@ -62,13 +59,11 @@ - Models/Weapons/Blue/AssaultWeapon.mesh - - true + Models/Weapons/Red/AssaultWeaponRed.mesh - - + + @@ -78,13 +73,27 @@ + 10 - + - + + + + + + 10 + + + + + + + + @@ -97,6 +106,48 @@ + + + + ShootFastRifle + 0.068159934509623099 + 1 + 1 + Run + 0.5 + 0.19240865965109588 + StrafeRight + 0.5 + 0.12533627444542628 + 1 + + + AimRifle + + + + Models/Characters/Assault/AssaultAnimations.mesh + + + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Red/AssaultWeaponRed.mesh + + + + + + + + + + diff --git a/resources/Schema/Entities/AnimationTests3.xml b/resources/Schema/Entities/AnimationTests3.xml index bd985b2d..39043231 100644 --- a/resources/Schema/Entities/AnimationTests3.xml +++ b/resources/Schema/Entities/AnimationTests3.xml @@ -26,57 +26,48 @@ - + Run 0.5 - 0.97312056690160276 - 1 + 0.14873348341666759 + -1 1 - ReloadSwitch - 0.91310356788604263 - LeftRight - 0 - 0.040207288496060478 + + 0.5 + 0.96957233017255007 + + 0.093923612201312068 1 - DownUp - + AimRifle - Models/Characters/Assault/FirstPerson.mesh - - true + Models/Characters/Assault/AssaultAnimations.mesh - + - + R_Arm_Weapon_Joint + - Models/Weapons/Blue/AssaultWeapon.mesh + Models/Weapons/Red/AssaultWeaponRed.mesh - - + + - - - - - - - @@ -101,6 +92,40 @@ + + + + ShootFastRifle + 0.11093210511546658 + 1 + + + AimRifle + + + + Models/Characters/Assault/AssaultAnimations.mesh + + + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Red/AssaultWeaponRed.mesh + + + + + + + + + + diff --git a/src/Engine/Rendering/AnimationSystem.cpp b/src/Engine/Rendering/AnimationSystem.cpp index 48681e6e..55edffe2 100644 --- a/src/Engine/Rendering/AnimationSystem.cpp +++ b/src/Engine/Rendering/AnimationSystem.cpp @@ -54,32 +54,5 @@ void AnimationSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& a (double&)animationComponent["Time" + std::to_string(i)] = nextTime; } } - - //Calculate bone transforms - if (skeleton != nullptr) { - std::vector animations; - if (entity.HasComponent("Animation")) { - for (int i = 1; i <= 3; i++) { - Skeleton::AnimationData animationData; - animationData.animation = model->m_RawModel->m_Skeleton->GetAnimation(entity["Animation"]["AnimationName" + std::to_string(i)]); - if (animationData.animation == nullptr) { - continue; - } - animationData.time = (double)entity["Animation"]["Time" + std::to_string(i)]; - animationData.weight = (double)entity["Animation"]["Weight" + std::to_string(i)]; - - animations.push_back(animationData); - } - } - - if (entity.HasComponent("AnimationOffset")) { - Skeleton::AnimationOffset animationOffset; - animationOffset.animation = skeleton->GetAnimation(entity["AnimationOffset"]["AnimationName"]); - animationOffset.time = (double)entity["AnimationOffset"]["Time"]; - skeleton->CalculateFrameBones(animations, animationOffset); - } else { - skeleton->CalculateFrameBones(animations); - } - } } diff --git a/src/Engine/Rendering/BoneAttachmentSystem.cpp b/src/Engine/Rendering/BoneAttachmentSystem.cpp index a9588a16..c0c2b8de 100644 --- a/src/Engine/Rendering/BoneAttachmentSystem.cpp +++ b/src/Engine/Rendering/BoneAttachmentSystem.cpp @@ -38,10 +38,7 @@ void BoneAttachmentSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapp return; } - - glm::mat4 boneTransform = skeleton->GetBoneTransformSuper(id); - //glm::mat4 boneTransform = skeleton->GetBoneTransform(skeleton->Bones[id], animation, (double)parent["Animation"]["Time1"], glm::mat4(1)); - + glm::mat4 boneTransform = skeleton->GetBoneTransform(skeleton->Bones[id], animation, (double)parent["Animation"]["Time1"], glm::mat4(1)); glm::vec3 scale; glm::quat rotation; glm::vec3 translation; diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index 00b85528..c3381632 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -328,7 +328,11 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& //bind textures BindExplosionTextures(explosionSkinnedHandle, explosionEffectJob); std::vector frameBones; - frameBones = explosionEffectJob->Skeleton->GetBones(); + if (explosionEffectJob->AnimationOffset.animation != nullptr) { + frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations, explosionEffectJob->AnimationOffset); + } else { + frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations); + } glUniformMatrix4fv(glGetUniformLocation(explosionSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); } else { m_ExplosionEffectProgram->Bind(); @@ -351,7 +355,11 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& BindExplosionTextures(explosionSplatMapSkinnedHandle, explosionEffectJob); GLERROR("asdasd"); std::vector frameBones; - frameBones = explosionEffectJob->Skeleton->GetBones(); + if (explosionEffectJob->AnimationOffset.animation != nullptr) { + frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations, explosionEffectJob->AnimationOffset); + } else { + frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations); + } glUniformMatrix4fv(glGetUniformLocation(explosionSplatMapSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); } else { @@ -392,7 +400,11 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& //bind textures BindModelTextures(forwardSkinnedHandle, modelJob); std::vector frameBones; - frameBones = modelJob->Skeleton->GetBones(); + if (modelJob->AnimationOffset.animation != nullptr) { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); + } else { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); + } glUniformMatrix4fv(glGetUniformLocation(forwardSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); } else { @@ -416,7 +428,11 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& BindModelTextures(forwardSplatMapSkinnedHandle, modelJob); GLERROR("asdasd"); std::vector frameBones; - frameBones = modelJob->Skeleton->GetBones(); + if (modelJob->AnimationOffset.animation != nullptr) { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); + } else { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); + } glUniformMatrix4fv(glGetUniformLocation(forwardSplatMapSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); } else { @@ -460,7 +476,11 @@ void DrawFinalPass::DrawShieldToStencilBuffer(std::listViewMatrix())); glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix())); std::vector frameBones; - frameBones = modelJob->Skeleton->GetBones(); + if (modelJob->AnimationOffset.animation != nullptr) { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); + } else { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); + } glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); } else { m_ShieldToStencilProgram->Bind(); @@ -514,7 +534,11 @@ void DrawFinalPass::DrawShieldedModelRenderQueue(std::list frameBones; - frameBones = explosionEffectJob->Skeleton->GetBones(); + if (explosionEffectJob->AnimationOffset.animation != nullptr) { + frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations, explosionEffectJob->AnimationOffset); + } else { + frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations); + } glUniformMatrix4fv(glGetUniformLocation(explosionHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); if (GLERROR("Animation")) { @@ -549,7 +573,11 @@ void DrawFinalPass::DrawShieldedModelRenderQueue(std::list frameBones; - frameBones = modelJob->Skeleton->GetBones(); + if (modelJob->AnimationOffset.animation != nullptr) { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); + } else { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); + } glUniformMatrix4fv(glGetUniformLocation(forwardHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); @@ -581,7 +609,11 @@ void DrawFinalPass::DrawToDepthBuffer(std::list>& job glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); std::vector frameBones; - frameBones = modelJob->Skeleton->GetBones(); + if (modelJob->AnimationOffset.animation != nullptr) { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); + } else { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); + } glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); } else { diff --git a/src/Engine/Rendering/PickingPass.cpp b/src/Engine/Rendering/PickingPass.cpp index cc9837ff..fa1b3ca3 100644 --- a/src/Engine/Rendering/PickingPass.cpp +++ b/src/Engine/Rendering/PickingPass.cpp @@ -103,7 +103,11 @@ void PickingPass::Draw(RenderScene& scene) if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { std::vector frameBones; - frameBones = modelJob->Skeleton->GetBones(); + if (modelJob->AnimationOffset.animation != nullptr) { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); + } else { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); + } glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); } @@ -156,7 +160,11 @@ void PickingPass::Draw(RenderScene& scene) glUniform2fv(glGetUniformLocation(shaderSkinnedHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1]))); std::vector frameBones; - frameBones = modelJob->Skeleton->GetBones(); + if (modelJob->AnimationOffset.animation != nullptr) { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); + } else { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); + } glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); } else { m_PickingProgram->Bind(); @@ -207,7 +215,11 @@ void PickingPass::Draw(RenderScene& scene) glUniform2fv(glGetUniformLocation(shaderSkinnedHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1]))); std::vector frameBones; - frameBones = modelJob->Skeleton->GetBones(); + if (modelJob->AnimationOffset.animation != nullptr) { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); + } else { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); + } glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); } else { @@ -264,7 +276,11 @@ void PickingPass::Draw(RenderScene& scene) if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { std::vector frameBones; - frameBones = modelJob->Skeleton->GetBones(); + if (modelJob->AnimationOffset.animation != nullptr) { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); + } else { + frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations); + } glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); } diff --git a/src/Engine/Rendering/Skeleton.cpp b/src/Engine/Rendering/Skeleton.cpp index 5da95558..f85efd17 100644 --- a/src/Engine/Rendering/Skeleton.cpp +++ b/src/Engine/Rendering/Skeleton.cpp @@ -30,30 +30,6 @@ Skeleton::~Skeleton() } -void Skeleton::CalculateFrameBones(std::vector animations, AnimationOffset animationOffset, bool noRootMotion /*= false*/) -{ - if (animations.size() <= 0 || animationOffset.animation == nullptr) { - for (auto& b : Bones) { - m_BoneLocalTransforms[b.first] = glm::mat4(1); - m_BoneTransforms[b.first] = glm::mat4(1); - } - } else { - AccumulateBoneTransforms(noRootMotion, animations, animationOffset, RootBone, glm::mat4(1)); - } -} - - -void Skeleton::CalculateFrameBones(std::vector animations, bool noRootMotion /*= false*/) -{ - if (animations.size() <= 0) { - for (auto& b : Bones) { - m_BoneLocalTransforms[b.first] = glm::mat4(1); - m_BoneTransforms[b.first] = glm::mat4(1); - } - } else { - AccumulateBoneTransforms(noRootMotion, animations, RootBone, glm::mat4(1)); - } -} const Skeleton::Animation* Skeleton::GetAnimation(std::string name) { @@ -65,7 +41,167 @@ const Skeleton::Animation* Skeleton::GetAnimation(std::string name) } } -void Skeleton::AccumulateBoneTransforms(bool noRootMotion, std::vector animations, AnimationOffset animationOffset, const Bone* bone, glm::mat4 parentMatrix) +std::vector Skeleton::GetFrameBones(std::vector animations, bool noRootMotion /*= false*/) +{ + if (animations.size() <= 0) { + std::vector finalMatrices; + for (auto& b : Bones) { + finalMatrices.push_back(glm::mat4(1));//b.second->OffsetMatrix); + } + return finalMatrices; + } + + std::map frameBones; + AccumulateBoneTransforms(true, animations, frameBones, RootBone, glm::mat4(1)); + + std::vector finalMatrices; + for (auto &kv : frameBones) { + finalMatrices.push_back(kv.second); + } + return finalMatrices; +} + +std::vector Skeleton::GetFrameBones(std::vector animations, AnimationOffset animationOffset, bool noRootMotion /*= false*/) +{ + if (animations.size() <= 0 || animationOffset.animation == nullptr) { + std::vector finalMatrices; + for (auto& b : Bones) { + finalMatrices.push_back(glm::mat4(1));//b.second->OffsetMatrix); + } + return finalMatrices; + } + + + std::map frameBones; + AccumulateBoneTransforms(true, animations, animationOffset, frameBones, RootBone, glm::mat4(1)); + + std::vector finalMatrices; + for (auto &kv : frameBones) { + finalMatrices.push_back(kv.second); + } + return finalMatrices; +} + +void Skeleton::AccumulateBoneTransforms(bool noRootMotion, std::vector animations, std::map& boneMatrices, const Bone* bone, glm::mat4 parentMatrix) +{ + glm::mat4 boneMatrix; + std::vector JointTransforms; + + for (const AnimationData animationData : animations) { + const Animation* animation = animationData.animation; + const float time = animationData.time; + + JointFrameTransform jointTransform; + jointTransform.Weight = animationData.weight;; + + if (animation->JointAnimations.find(bone->ID) != animation->JointAnimations.end()) { + std::vector boneKeyFrames = animation->JointAnimations.at(bone->ID); + + Animation::Keyframe currentFrame; + Animation::Keyframe nextFrame; + + if (boneKeyFrames.size() > 1) { // 2+ keyframes for the current bone + for (int index = boneKeyFrames.size()-1; index >= 0; index--) { // find the bone keyframes that surrounds the current frame + if (time >= boneKeyFrames.at(index).Time) { + currentFrame = boneKeyFrames.at(index); + nextFrame = boneKeyFrames.at((index + 1) % boneKeyFrames.size()); + break; + } + } + + float progress; + + if (nextFrame.Index == 0) { + nextFrame = currentFrame; + progress = (time - currentFrame.Time) / (animation->Duration - currentFrame.Time); + } else { + progress = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); + + } + + + if (progress > 1.0f || progress < 0.0f) { + LOG_INFO("Progress: %f", progress); + progress = glm::clamp(progress, 0.0f, 1.0f); + } + Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties; + Animation::Keyframe::BoneProperty nextBoneProperty = nextFrame.BoneProperties; + + jointTransform.PositionInterp = currentBoneProperty.Position * (1.f - progress) + nextBoneProperty.Position * progress; + jointTransform.RotationInterp = glm::slerp(currentBoneProperty.Rotation, nextBoneProperty.Rotation, progress); + jointTransform.ScaleInterp = currentBoneProperty.Scale * (1.f - progress) + nextBoneProperty.Scale * progress; + + // Flag for no root motion + if (bone == RootBone && noRootMotion) { + jointTransform.PositionInterp.x = 0; + jointTransform.PositionInterp.z = 0; + } + + JointTransforms.push_back(jointTransform); + + } else { // 1 keyframes for the current bone + currentFrame = boneKeyFrames.at(0); + jointTransform.PositionInterp = currentFrame.BoneProperties.Position; + jointTransform.RotationInterp = currentFrame.BoneProperties.Rotation; + jointTransform.ScaleInterp = currentFrame.BoneProperties.Scale; + JointTransforms.push_back(jointTransform); + + } + } else { // 0 keyframes for the current bone + + } + + } + + if (JointTransforms.size() <= 0) { + if (bone->Parent) { + boneMatrix = parentMatrix * glm::inverse(bone->OffsetMatrix) * bone->Parent->OffsetMatrix; + boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix; + } else { + boneMatrix = glm::inverse(bone->OffsetMatrix); + boneMatrices[bone->ID] = parentMatrix; + } + } else if (JointTransforms.size() == 1) { + boneMatrix = parentMatrix *(glm::translate(JointTransforms.at(0).PositionInterp) * glm::toMat4(JointTransforms.at(0).RotationInterp) * glm::scale(JointTransforms.at(0).ScaleInterp)); + boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix; + } else { + + glm::vec3 finalPosInterp; + glm::quat finalRotInterp; + glm::vec3 finalScaleInterp; + float totalWeight = 0; + + for (JointFrameTransform jointTransform : JointTransforms) { + totalWeight += jointTransform.Weight; + } + + + for (JointFrameTransform jointTransform : JointTransforms) { + if (jointTransform.Weight == 1.0f) { + finalPosInterp = jointTransform.PositionInterp; + finalRotInterp = jointTransform.RotationInterp; + finalScaleInterp = jointTransform.ScaleInterp; + break; + } else { + finalPosInterp += jointTransform.PositionInterp * (jointTransform.Weight/totalWeight); + finalRotInterp *= glm::slerp(glm::quat(), jointTransform.RotationInterp, (jointTransform.Weight/totalWeight)); + finalScaleInterp += jointTransform.ScaleInterp * (jointTransform.Weight/totalWeight); + } + + } + + boneMatrix = parentMatrix *(glm::translate(finalPosInterp) * glm::toMat4(finalRotInterp) * glm::scale(finalScaleInterp)); + boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix; + } + + + + for (auto &child : bone->Children) { + AccumulateBoneTransforms(noRootMotion, animations, boneMatrices, child, boneMatrix); + } +} + +void Skeleton::AccumulateBoneTransforms(bool noRootMotion, std::vector animations, AnimationOffset animationOffset, std::map& boneMatrices, const Bone* bone, glm::mat4 parentMatrix) { glm::mat4 boneMatrix; @@ -148,12 +284,10 @@ void Skeleton::AccumulateBoneTransforms(bool noRootMotion, std::vectorOffsetMatrix) * bone->Parent->OffsetMatrix)); } - m_BoneLocalTransforms[bone->ID] = boneMatrix * bone->OffsetMatrix; - m_BoneTransforms[bone->ID] = boneMatrix; + boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix; } else { boneMatrix = offset * glm::inverse(bone->OffsetMatrix); - m_BoneLocalTransforms[bone->ID] = parentMatrix; - m_BoneTransforms[bone->ID] = boneMatrix; + boneMatrices[bone->ID] = parentMatrix; } } else { @@ -189,136 +323,11 @@ void Skeleton::AccumulateBoneTransforms(bool noRootMotion, std::vectorID] = boneMatrix * bone->OffsetMatrix; - m_BoneTransforms[bone->ID] = boneMatrix; + boneMatrices[bone->ID] = boneMatrix * bone->OffsetMatrix; } for (auto &child : bone->Children) { - AccumulateBoneTransforms(noRootMotion, animations, animationOffset, child, boneMatrix); - } -} - -void Skeleton::AccumulateBoneTransforms(bool noRootMotion, std::vector animations, const Bone* bone, glm::mat4 parentMatrix) -{ - glm::mat4 boneMatrix; - std::vector JointTransforms; - - for (const AnimationData animationData : animations) { - const Animation* animation = animationData.animation; - const float time = animationData.time; - - JointFrameTransform jointTransform; - jointTransform.Weight = animationData.weight;; - - if (animation->JointAnimations.find(bone->ID) != animation->JointAnimations.end()) { - std::vector boneKeyFrames = animation->JointAnimations.at(bone->ID); - - Animation::Keyframe currentFrame; - Animation::Keyframe nextFrame; - - if (boneKeyFrames.size() > 1) { // 2+ keyframes for the current bone - for (int index = boneKeyFrames.size()-1; index >= 0; index--) { // find the bone keyframes that surrounds the current frame - if (time >= boneKeyFrames.at(index).Time) { - currentFrame = boneKeyFrames.at(index); - nextFrame = boneKeyFrames.at((index + 1) % boneKeyFrames.size()); - break; - } - } - - float progress; - - if (nextFrame.Index == 0) { - nextFrame = currentFrame; - progress = (time - currentFrame.Time) / (animation->Duration - currentFrame.Time); - } else { - progress = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); - - } - - - if (progress > 1.0f || progress < 0.0f) { - LOG_INFO("Progress: %f", progress); - progress = glm::clamp(progress, 0.0f, 1.0f); - } - Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties; - Animation::Keyframe::BoneProperty nextBoneProperty = nextFrame.BoneProperties; - - jointTransform.PositionInterp = currentBoneProperty.Position * (1.f - progress) + nextBoneProperty.Position * progress; - jointTransform.RotationInterp = glm::slerp(currentBoneProperty.Rotation, nextBoneProperty.Rotation, progress); - jointTransform.ScaleInterp = currentBoneProperty.Scale * (1.f - progress) + nextBoneProperty.Scale * progress; - - // Flag for no root motion - if (bone == RootBone && noRootMotion) { - jointTransform.PositionInterp.x = 0; - jointTransform.PositionInterp.z = 0; - } - - JointTransforms.push_back(jointTransform); - - } else { // 1 keyframes for the current bone - currentFrame = boneKeyFrames.at(0); - jointTransform.PositionInterp = currentFrame.BoneProperties.Position; - jointTransform.RotationInterp = currentFrame.BoneProperties.Rotation; - jointTransform.ScaleInterp = currentFrame.BoneProperties.Scale; - JointTransforms.push_back(jointTransform); - - } - } else { // 0 keyframes for the current bone - - } - - } - - if (JointTransforms.size() <= 0) { - if (bone->Parent) { - boneMatrix = parentMatrix * glm::inverse(bone->OffsetMatrix) * bone->Parent->OffsetMatrix; - m_BoneLocalTransforms[bone->ID] = boneMatrix * bone->OffsetMatrix; - m_BoneTransforms[bone->ID] = boneMatrix; - } else { - boneMatrix = glm::inverse(bone->OffsetMatrix); - m_BoneLocalTransforms[bone->ID] = parentMatrix; - m_BoneTransforms[bone->ID] = boneMatrix; - } - } else if (JointTransforms.size() == 1) { - boneMatrix = parentMatrix *(glm::translate(JointTransforms.at(0).PositionInterp) * glm::toMat4(JointTransforms.at(0).RotationInterp) * glm::scale(JointTransforms.at(0).ScaleInterp)); - m_BoneLocalTransforms[bone->ID] = boneMatrix * bone->OffsetMatrix; - m_BoneTransforms[bone->ID] = boneMatrix; - } else { - - glm::vec3 finalPosInterp; - glm::quat finalRotInterp; - glm::vec3 finalScaleInterp; - float totalWeight = 0; - - for (JointFrameTransform jointTransform : JointTransforms) { - totalWeight += jointTransform.Weight; - } - - - for (JointFrameTransform jointTransform : JointTransforms) { - if (jointTransform.Weight == 1.0f) { - finalPosInterp = jointTransform.PositionInterp; - finalRotInterp = jointTransform.RotationInterp; - finalScaleInterp = jointTransform.ScaleInterp; - break; - } else { - finalPosInterp += jointTransform.PositionInterp * (jointTransform.Weight/totalWeight); - finalRotInterp *= glm::slerp(glm::quat(), jointTransform.RotationInterp, (jointTransform.Weight/totalWeight)); - finalScaleInterp += jointTransform.ScaleInterp * (jointTransform.Weight/totalWeight); - } - - } - - boneMatrix = parentMatrix *(glm::translate(finalPosInterp) * glm::toMat4(finalRotInterp) * glm::scale(finalScaleInterp)); - - m_BoneLocalTransforms[bone->ID] = boneMatrix * bone->OffsetMatrix; - m_BoneTransforms[bone->ID] = boneMatrix; - } - - - - for (auto &child : bone->Children) { - AccumulateBoneTransforms(noRootMotion, animations, child, boneMatrix); + AccumulateBoneTransforms(noRootMotion, animations, animationOffset, boneMatrices, child, boneMatrix); } } @@ -356,11 +365,8 @@ glm::mat4 Skeleton::GetOffsetTransform(const Bone* bone, AnimationOffset animati } - - if (progress > 1.0f || progress < 0.0f) { - LOG_INFO("Progress: %f", progress); - progress = glm::clamp(progress, 0.0f, 1.0f); - } + progress = glm::clamp(progress, 0.0f, 1.0f); + Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties; Animation::Keyframe::BoneProperty nextBoneProperty = nextFrame.BoneProperties; From 350effd8ebc045f1614e3a1422f99d3d62fe8758 Mon Sep 17 00:00:00 2001 From: Tleety Date: Thu, 11 Feb 2016 11:32:51 +0100 Subject: [PATCH 195/355] New assets and some QA map stuff --- assets | 2 +- .../Schema/Entities/QualityAssurance.xml | 59 +++++++++++++------ 2 files changed, 41 insertions(+), 20 deletions(-) diff --git a/assets b/assets index 0580eeae..8ffd0a99 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit 0580eeae80919127622e16f2ec4f4083668d36cd +Subproject commit 8ffd0a99b9a2e5c140307d382a25c4a470cc8f33 diff --git a/resources/Schema/Entities/QualityAssurance.xml b/resources/Schema/Entities/QualityAssurance.xml index 2c77bc30..40951468 100644 --- a/resources/Schema/Entities/QualityAssurance.xml +++ b/resources/Schema/Entities/QualityAssurance.xml @@ -180,7 +180,7 @@ - + @@ -671,7 +671,7 @@ - + @@ -718,7 +718,7 @@ - + @@ -778,7 +778,7 @@ - + @@ -825,7 +825,7 @@ - + @@ -871,7 +871,7 @@ - + @@ -918,7 +918,7 @@ - + @@ -965,7 +965,7 @@ - + @@ -1379,7 +1379,7 @@ - + @@ -1388,7 +1388,7 @@ true - 0.75184169309215043 + 0.75205058136495551 3.7999999523162842 true @@ -1435,7 +1435,7 @@ - + @@ -1444,7 +1444,7 @@ - 1.2017474437062576 + 1.2019563319790627 Models/Characters/Assault/AssaultTPose.mesh @@ -1487,7 +1487,7 @@ - + @@ -1498,7 +1498,7 @@ true - 0.68519322736618882 + 0.68540211563899389 true @@ -1543,7 +1543,7 @@ - + @@ -1553,7 +1553,7 @@ true - 0.95129174821355256 + 0.95150063648635763 10 3 @@ -1601,7 +1601,7 @@ - + @@ -1611,7 +1611,7 @@ true - 1.3513200095896172 + 1.3515288978624223 true 5 true @@ -1792,7 +1792,7 @@ true - 1.3679930696247629 + 1.3682019578975679 3.7999999523162842 true @@ -2124,6 +2124,27 @@ + + + + + + + + + + + + Models/Widgets/Camera.mesh + + + + + + + + + From e350074cb579a84b47445035088cd821a52a2b2f Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Thu, 11 Feb 2016 11:36:15 +0100 Subject: [PATCH 196/355] Spawner now spawns with orientation --- src/Game/Systems/SpawnerSystem.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Game/Systems/SpawnerSystem.cpp b/src/Game/Systems/SpawnerSystem.cpp index ba0775a3..99f5df93 100644 --- a/src/Game/Systems/SpawnerSystem.cpp +++ b/src/Game/Systems/SpawnerSystem.cpp @@ -51,7 +51,7 @@ EntityWrapper SpawnerSystem::Spawn(EntityWrapper spawner, EntityWrapper parent / // Set its position and orientation to that of the SpawnPoint spawnedEntity["Transform"]["Position"] = Transform::AbsolutePosition(spawnPoint.World, spawnPoint.ID); // TODO: Quaternions, bitch - //spawnedEntity["Transform"]["Orientation"] = glm::eulerAngles(Transform::AbsoluteOrientation(spawnPoint.World, spawnPoint.ID)); + spawnedEntity["Transform"]["Orientation"] = glm::eulerAngles(Transform::AbsoluteOrientation(spawnPoint)); return spawnedEntity; } From 81943516a96ca1ef7cb0a769771a77e24acf0fc2 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Thu, 11 Feb 2016 11:36:39 +0100 Subject: [PATCH 197/355] Protected inheritance, not even once. --- include/Engine/Core/System.h | 4 +- include/Game/Systems/SoundSystem.h | 2 - include/Game/Systems/WeaponSystem.h | 79 +++++++------------------- resources/Schema/Entities/Player.xml | 13 +++-- src/Engine/Rendering/RenderSystem.cpp | 2 +- src/Game/Systems/PlayerSpawnSystem.cpp | 2 +- src/Game/Systems/SoundSystem.cpp | 11 ---- src/Game/Systems/WeaponSystem.cpp | 17 +++--- 8 files changed, 38 insertions(+), 92 deletions(-) diff --git a/include/Engine/Core/System.h b/include/Engine/Core/System.h index 43438fd5..1a387855 100644 --- a/include/Engine/Core/System.h +++ b/include/Engine/Core/System.h @@ -34,7 +34,7 @@ protected: , IsServer(params.IsServer) { if (IsClient) { - EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &System::OnPlayerSpawned); + EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &System::setLocalPlayer); } } virtual ~System() = default; @@ -47,7 +47,7 @@ protected: private: EventRelay m_EPlayerSpawned; - bool OnPlayerSpawned(Events::PlayerSpawned& e) + virtual bool setLocalPlayer(Events::PlayerSpawned& e) { if (e.PlayerID == -1) { LocalPlayer = e.Player; diff --git a/include/Game/Systems/SoundSystem.h b/include/Game/Systems/SoundSystem.h index 410ba2f1..962eb085 100644 --- a/include/Game/Systems/SoundSystem.h +++ b/include/Game/Systems/SoundSystem.h @@ -52,8 +52,6 @@ private: bool OnDashAbility(const Events::DashAbility &e); EventRelay m_ETriggerTouch; bool OnTriggerTouch(const Events::TriggerTouch &e); - EventRelay m_EShoot; - bool OnShoot(const Events::Shoot &e); EventRelay m_ECaptured; bool OnCaptured(const Events::Captured &e); EventRelay m_EPlayerDamage; diff --git a/include/Game/Systems/WeaponSystem.h b/include/Game/Systems/WeaponSystem.h index c3daeceb..b118b8cd 100644 --- a/include/Game/Systems/WeaponSystem.h +++ b/include/Game/Systems/WeaponSystem.h @@ -16,6 +16,7 @@ #include "Core/Octree.h" #include "Collision/EntityAABB.h" #include "Systems/SpawnerSystem.h" +#include "Sound/EPlaySoundOnEntity.h" class WeaponBehaviour; @@ -45,7 +46,7 @@ private: void selectWeapon(EntityWrapper player, ComponentInfo::EnumType slot); }; -class WeaponBehaviour : protected System +class WeaponBehaviour : public System { public: WeaponBehaviour(SystemParams systemParams, Octree* collisionOctree, EntityWrapper weaponEntity) @@ -73,10 +74,7 @@ class AssaultWeaponBehaviour : public WeaponBehaviour public: AssaultWeaponBehaviour(SystemParams systemParams, Octree* collisionOctree, EntityWrapper weaponEntity) : WeaponBehaviour(systemParams, collisionOctree, weaponEntity) - { - m_RayRed = ResourceManager::Load("Schema/Entities/RayRed.xml"); - m_RayBlue = ResourceManager::Load("Schema/Entities/RayBlue.xml"); - } + { } virtual void Fire() override { @@ -145,12 +143,17 @@ private: // Fire magAmmo -= 1; spawnTracer(); + playSound(); m_TimeSinceLastFire = 0.0; } void spawnTracer() { + if (!IsClient) { + return; + } + EntityWrapper spawner; if (m_Entity == LocalPlayer) { spawner = m_Entity.FirstChildByName("WeaponMuzzle"); @@ -165,60 +168,6 @@ private: Events::SpawnerSpawn e; e.Spawner = spawner; m_EventBroker->Publish(e); - - //ComponentWrapper cTeam = m_Entity["Team"]; - //ComponentInfo::EnumType team = cTeam["Team"]; - - //// Select the right color of effect - //EntityFile* rayFile = nullptr; - //if (team == cTeam["Team"].Enum("Red")) { - // rayFile = m_RayRed; - //} - //if (team == cTeam["Team"].Enum("Blue")) { - // rayFile = m_RayBlue; - //} - //if (rayFile == nullptr) { - // return; - //} - - //// Create the entity - //EntityFileParser parser(rayFile); - //EntityID rayID = parser.MergeEntities(m_World); - //EntityWrapper ray(m_World, rayID); - - //// Figure out where to put it - //EntityWrapper attachment; - //if (m_Entity == LocalPlayer || true) { - // // Spawn the effect from the weapon view model for the local player - // attachment = m_Entity.FirstChildByName("WeaponMuzzle"); - //} - //// TODO: Spawn the effect from the weapon world model once it exists - - //glm::mat4 transformation = Transform::AbsoluteTransformation(attachment); - //glm::vec3 _scale; - //glm::vec3 translation; - //glm::quat _orientation; - //glm::vec3 _skew; - //glm::vec4 _perspective; - //glm::decompose(transformation, _scale, _orientation, translation, _skew, _perspective); - // - //// Matrix to euler angles - //glm::vec3 euler; - //euler.y = glm::asin(-transformation[0][2]); - //if (cos(euler.y) != 0) { - // euler.x = atan2(transformation[1][2], transformation[2][2]); - // euler.z = atan2(transformation[0][1], transformation[0][0]); - //} else { - // euler.x = atan2(-transformation[2][0], transformation[1][1]); - // euler.z = 0; - //} - - //// TODO: Spread? - - //(glm::vec3&)ray["Transform"]["Position"] = translation; - //(glm::vec3&)ray["Transform"]["Orientation"] = euler; - //glm::vec3& scale = ray["Transform"]["Scale"]; - //scale.z = traceRayDistance(translation, glm::quat(euler) * glm::vec3(0.f, 0.f, -1.f)); } float traceRayDistance(glm::vec3 origin, glm::vec3 direction) @@ -226,6 +175,18 @@ private: // TODO: Cast a ray and size tracer appropriately return 100.f; } + + void playSound() + { + if (!IsClient) { + return; + } + + Events::PlaySoundOnEntity e; + e.EmitterID = m_Entity.ID; + e.FilePath = "Audio/laser/laser1.wav"; + m_EventBroker->Publish(e); + } }; #endif \ No newline at end of file diff --git a/resources/Schema/Entities/Player.xml b/resources/Schema/Entities/Player.xml index 423e729e..4ba23a0d 100644 --- a/resources/Schema/Entities/Player.xml +++ b/resources/Schema/Entities/Player.xml @@ -107,7 +107,7 @@ Idle - 0.24743387388836702 + 0.52743271827223559 1 @@ -126,8 +126,8 @@ Models/Weapons/Blue/AssaultWeaponBlue.mesh - - + + @@ -137,7 +137,7 @@ Schema/Entities/RayBlue.xml - + @@ -166,6 +166,7 @@ Idle + 0.69666320633760392 1 @@ -189,8 +190,8 @@ Models/Weapons/Blue/AssaultWeaponBlue.mesh - - + + diff --git a/src/Engine/Rendering/RenderSystem.cpp b/src/Engine/Rendering/RenderSystem.cpp index 36baea0d..18eab0fa 100644 --- a/src/Engine/Rendering/RenderSystem.cpp +++ b/src/Engine/Rendering/RenderSystem.cpp @@ -67,7 +67,7 @@ void RenderSystem::fillModels(RenderScene::Queues &Jobs) // Hide things parented to local player if they have the HiddenFromLocalPlayer component if ((entity.HasComponent("HiddenForLocalPlayer") || entity.FirstParentWithComponent("HiddenForLocalPlayer").Valid()) && (entity == m_LocalPlayer || entity.IsChildOf(m_LocalPlayer))) { - //continue; + continue; } Model* model; diff --git a/src/Game/Systems/PlayerSpawnSystem.cpp b/src/Game/Systems/PlayerSpawnSystem.cpp index 2afb0de1..507ed0f5 100644 --- a/src/Game/Systems/PlayerSpawnSystem.cpp +++ b/src/Game/Systems/PlayerSpawnSystem.cpp @@ -91,7 +91,7 @@ bool PlayerSpawnSystem::OnPlayerSpawned(Events::PlayerSpawned& e) if (cameraEntity.Valid()) { Events::SetCamera e; e.CameraEntity = cameraEntity; - //m_EventBroker->Publish(e); + m_EventBroker->Publish(e); } // HACK: Set the player model color to team color diff --git a/src/Game/Systems/SoundSystem.cpp b/src/Game/Systems/SoundSystem.cpp index a16e39a0..10dc61f7 100644 --- a/src/Game/Systems/SoundSystem.cpp +++ b/src/Game/Systems/SoundSystem.cpp @@ -3,7 +3,6 @@ SoundSystem::SoundSystem(SystemParams params) : System(params) , PureSystem("SoundEmitter") - //, ImpureSystem() { ConfigFile* config = ResourceManager::Load("Config.ini"); m_Announcer = ResourceManager::Load("Config.ini")->Get("Sound.Announcer", "female"); @@ -11,7 +10,6 @@ SoundSystem::SoundSystem(SystemParams params) EVENT_SUBSCRIBE_MEMBER(m_InputCommand, &SoundSystem::OnInputCommand); EVENT_SUBSCRIBE_MEMBER(m_EDoubleJump, &SoundSystem::OnDoubleJump); EVENT_SUBSCRIBE_MEMBER(m_EDashAbility, &SoundSystem::OnDashAbility); - EVENT_SUBSCRIBE_MEMBER(m_EShoot, &SoundSystem::OnShoot); EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &SoundSystem::OnPlayerDamage); EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &SoundSystem::OnCaptured); EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &SoundSystem::OnTriggerTouch); @@ -90,15 +88,6 @@ bool SoundSystem::drumTimer(double dt) } } -bool SoundSystem::OnShoot(const Events::Shoot & e) -{ - Events::PlaySoundOnEntity ev; - ev.EmitterID = LocalPlayer.ID; - ev.FilePath = "Audio/laser/laser1.wav"; - m_EventBroker->Publish(ev); - return true; -} - bool SoundSystem::OnCaptured(const Events::Captured & e) { int homeTeam = (int)m_World->GetComponent(e.CapturePointID, "Team")["Team"]; diff --git a/src/Game/Systems/WeaponSystem.cpp b/src/Game/Systems/WeaponSystem.cpp index 117176c1..eeb7dd00 100644 --- a/src/Game/Systems/WeaponSystem.cpp +++ b/src/Game/Systems/WeaponSystem.cpp @@ -21,13 +21,11 @@ void WeaponSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& cPla { // Update potential weapon behaviour for player auto it = m_ActiveWeapons.find(entity); - if (it != m_ActiveWeapons.end()) { - if (it->first.Valid()) { - it->second->Update(dt); - } else { - m_ActiveWeapons.erase(it); - } + if (it == m_ActiveWeapons.end()) { + selectWeapon(entity, 1); } + + m_ActiveWeapons.at(entity)->Update(dt); } bool WeaponSystem::OnInputCommand(Events::InputCommand& e) @@ -45,7 +43,7 @@ bool WeaponSystem::OnInputCommand(Events::InputCommand& e) // Weapon selection if (e.Command == "SelectWeapon") { if (e.Value != 0) { - selectWeapon(player, static_cast(e.Value)); + //selectWeapon(player, static_cast(e.Value)); } } @@ -72,7 +70,7 @@ void WeaponSystem::selectWeapon(EntityWrapper player, ComponentInfo::EnumType sl if (m_ActiveWeapons.count(player) == 0) { m_ActiveWeapons.insert(std::make_pair(player, std::make_shared(m_SystemParams, m_CollisionOctree, player))); } else { - m_ActiveWeapons.erase(player); + //m_ActiveWeapons.erase(player); } } @@ -86,7 +84,6 @@ bool WeaponSystem::OnPlayerSpawned(Events::PlayerSpawned& e) { // Select primary weapon on player spawn // TODO: Select the active one specified by player component - selectWeapon(e.Player, 1); return true; } @@ -137,4 +134,4 @@ bool WeaponSystem::OnShoot(Events::Shoot& eShoot) m_EventBroker->Publish(ePlayerDamage); return true; -} +} \ No newline at end of file From f11bd24d539cd9847b3307250bea8202272f02f3 Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Thu, 11 Feb 2016 11:46:34 +0100 Subject: [PATCH 198/355] Added CapturePointMaxTimer in CapturePointComponent. Removed next-capturepoint Color. Modified captureTimer to +-captureTimeToTakeOver after a capture. --- include/Game/Systems/CapturePointSystem.h | 1 - resources/Schema/Components/CapturePoint.xml | 1 + resources/Schema/Components/CapturePoint.xsd | 6 +- .../Schema/Entities/CaptureTestState5.xml | 323 ++++++++++++++---- src/Game/Systems/CapturePointSystem.cpp | 29 +- 5 files changed, 273 insertions(+), 87 deletions(-) diff --git a/include/Game/Systems/CapturePointSystem.h b/include/Game/Systems/CapturePointSystem.h index 18c32c76..33ba40c8 100644 --- a/include/Game/Systems/CapturePointSystem.h +++ b/include/Game/Systems/CapturePointSystem.h @@ -44,7 +44,6 @@ private: //std::vector - const double m_CaptureTimeToTakeOver = 15.0; bool m_ResetTimers = false; //vectors which will keep track of enter/leave changes diff --git a/resources/Schema/Components/CapturePoint.xml b/resources/Schema/Components/CapturePoint.xml index ba164fd9..638b16c3 100644 --- a/resources/Schema/Components/CapturePoint.xml +++ b/resources/Schema/Components/CapturePoint.xml @@ -2,5 +2,6 @@ 0 0 + 15 \ No newline at end of file diff --git a/resources/Schema/Components/CapturePoint.xsd b/resources/Schema/Components/CapturePoint.xsd index fbdb3568..3c91dfdd 100644 --- a/resources/Schema/Components/CapturePoint.xsd +++ b/resources/Schema/Components/CapturePoint.xsd @@ -20,7 +20,11 @@ CapturePointNumber specify an int number for this - + + + The time needed to take over a Capture Point + + Specify if this is a HomePoint for either team diff --git a/resources/Schema/Entities/CaptureTestState5.xml b/resources/Schema/Entities/CaptureTestState5.xml index 8fe85068..c733706c 100644 --- a/resources/Schema/Entities/CaptureTestState5.xml +++ b/resources/Schema/Entities/CaptureTestState5.xml @@ -2,12 +2,246 @@ - - - + + + + + + + + + Models/LevelBase/MapVersion1.mesh + + + + + + + + + 2 + + + Models/Widgets/Lights/DirectionalLightWidget.mesh + false + + + + + + + + + + + + + 8 + 2.7999999523162842 + + + + + + + + + + + 8 + 2.7999999523162842 + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + false + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + false + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -15,10 +249,12 @@ + 15 Models/Core/UnitSphere.mesh - + + true @@ -26,7 +262,7 @@ - + @@ -40,11 +276,12 @@ Models/Core/UnitSphere.mesh - + + true - + @@ -58,15 +295,12 @@ Models/Core/UnitSphere.mesh - + + true - - - - - + - + @@ -76,11 +310,13 @@ + -15 3 Models/Core/UnitSphere.mesh - + + true @@ -88,7 +324,7 @@ - + @@ -101,11 +337,13 @@ + -15 4 Models/Core/UnitSphere.mesh - + + true @@ -113,61 +351,12 @@ - + - - - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - - - - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - - - - - Models/Test/DummyScene.mesh - - - - - - - diff --git a/src/Game/Systems/CapturePointSystem.cpp b/src/Game/Systems/CapturePointSystem.cpp index a943e234..971c194c 100644 --- a/src/Game/Systems/CapturePointSystem.cpp +++ b/src/Game/Systems/CapturePointSystem.cpp @@ -1,7 +1,7 @@ #include "Systems/CapturePointSystem.h" #include -CapturePointSystem::CapturePointSystem(World* world, EventBroker* eventBroker) +CapturePointSystem::CapturePointSystem(World* world, EventBroker* eventBroker) : System(world, eventBroker) , PureSystem("CapturePoint") { @@ -32,6 +32,7 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp const int redTeam = (int)teamComponent["Team"].Enum("Red"); const int blueTeam = (int)teamComponent["Team"].Enum("Blue"); const int spectatorTeam = (int)teamComponent["Team"].Enum("Spectator"); + const double captureTimeToTakeOver = (double)cCapturePoint["CapturePointMaxTimer"]; int homePointForTeam = (int)cCapturePoint["HomePointForTeam"]; if (m_NumberOfCapturePoints == 0 && capturePointNumber != 0 && (homePointForTeam == redTeam || homePointForTeam == blueTeam)) { @@ -57,7 +58,7 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp int blueTeamPlayersStandingInside = 0; if (capturePointEntity.HasComponent("Model")) { //Now sets team color to the capturepoint, or white if it is uncaptured. - capturePointEntity["Model"]["Color"] = ownedBy == blueTeam ? glm::vec4(0, 0.2f, 1, 0.3) : ownedBy == redTeam ? glm::vec4(1, 0.2f, 0, 0.3) : glm::vec4(1, 1, 1, 0.3); + capturePointEntity["Model"]["Color"] = ownedBy == blueTeam ? glm::vec4(0, 0.0f, 1, 0.3) : ownedBy == redTeam ? glm::vec4(1, 0.0f, 0, 0.3) : glm::vec4(1, 1, 1, 0.3); } //calculate next possible capturePoint for both teams @@ -98,20 +99,16 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp ComponentWrapper& capturePoint = m_CapturePointNumberToEntityMap[i]["CapturePoint"]; if ((int)capturePoint["CapturePointNumber"] != nextPossibleCapturePoint["Red"] && (int)capturePoint["CapturePointNumber"] != nextPossibleCapturePoint["Blue"]) { - capturePoint["CaptureTimer"] = 0.0; + //RED = +, BLUE = -, NONE + auto teamOwners = (int)m_CapturePointNumberToEntityMap[i]["Team"]["Team"]; + if (teamOwners == redTeam || teamOwners == blueTeam) { + capturePoint["CaptureTimer"] = teamOwners == blueTeam ? -captureTimeToTakeOver : captureTimeToTakeOver; + } } } m_ResetTimers = false; } - //colorize next possible capturepoint - if (nextPossibleCapturePoint["Red"] == capturePointNumber) { - capturePointEntity["Model"]["Color"] = glm::vec4(1, 1, 0, 0.3); - } - if (nextPossibleCapturePoint["Blue"] == capturePointNumber) { - capturePointEntity["Model"]["Color"] = glm::vec4(0, 1, 1, 0.3); - } - //check how many players are standing inside and are healthy for (size_t i = m_ETriggerTouchVector.size(); i > 0; i--) { @@ -170,9 +167,6 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp //B. at most one of the teams have players inside //if capturePoint is not owned by the take-over team, just modify the CaptureTimer accordingly if (ownedBy != currentTeam && canCapture) { - if (abs((double)cCapturePoint["CaptureTimer"]) < 0.001f) { - LOG_DEBUG("Point is being captured by team %i", currentTeam); //Remove when we tested sufficiently. - } cCapturePoint["CaptureTimer"] = (double)cCapturePoint["CaptureTimer"] + timerDeltaChange; } //if capturePoint is owned by the team, and the other team has been trying to take it, then increase/decrease the timer towards 0.0 @@ -180,12 +174,11 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp (ownedBy == currentTeam && currentTeam == blueTeam && (double)cCapturePoint["CaptureTimer"] > 0.0)) { cCapturePoint["CaptureTimer"] = (double)cCapturePoint["CaptureTimer"] + timerDeltaChange; } - //check if captureTimer > m_CaptureTimeToTakeOver and if so change owner and publish the eCaptured event - if (abs((double)cCapturePoint["CaptureTimer"]) > abs(m_CaptureTimeToTakeOver) && canCapture) { + //check if captureTimer > captureTimeToTakeOver and if so change owner and publish the eCaptured event + if (abs((double)cCapturePoint["CaptureTimer"]) > captureTimeToTakeOver && canCapture) { teamComponent["Team"] = currentTeam; - cCapturePoint["CaptureTimer"] = 0.0; + cCapturePoint["CaptureTimer"] = glm::sign((double)cCapturePoint["CaptureTimer"])*captureTimeToTakeOver; //publish Captured event - LOG_DEBUG("Point is captured by team %i!", currentTeam); //Remove when we tested sufficiently. Events::Captured e; e.CapturePointID = cCapturePoint.EntityID; e.TeamNumberThatCapturedCapturePoint = currentTeam; From 2f640d224ced2eb89b32762a1351e964ea938a0b Mon Sep 17 00:00:00 2001 From: antc13 Date: Thu, 11 Feb 2016 12:23:20 +0100 Subject: [PATCH 199/355] New Map with Meshes WIP --- resources/Schema/Entities/NewMap.xml | 65 ++++++++++++++-------------- 1 file changed, 33 insertions(+), 32 deletions(-) diff --git a/resources/Schema/Entities/NewMap.xml b/resources/Schema/Entities/NewMap.xml index 8a5227aa..7a1d620b 100644 --- a/resources/Schema/Entities/NewMap.xml +++ b/resources/Schema/Entities/NewMap.xml @@ -338,7 +338,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -349,6 +349,7 @@ Models/Props/Walls/BigWall.mesh + @@ -363,7 +364,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -440,7 +441,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -452,7 +453,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -466,7 +467,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -482,7 +483,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -494,7 +495,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -507,7 +508,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -753,7 +754,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -764,7 +765,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -776,7 +777,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -803,7 +804,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -830,7 +831,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -841,7 +842,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -853,7 +854,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -879,7 +880,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -1030,7 +1031,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -1057,7 +1058,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -1068,7 +1069,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -1080,7 +1081,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -1092,7 +1093,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -1106,7 +1107,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -1118,7 +1119,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -1183,7 +1184,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -1195,7 +1196,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -1449,7 +1450,7 @@ Models/Props/Bridges/SciFiBridge.mesh - + @@ -1462,7 +1463,7 @@ Models/Props/Bridges/SciFiBridgeDefense.mesh - + @@ -1515,7 +1516,7 @@ Models/Props/Bridges/SciFiBridgeDefense.mesh - + @@ -1604,7 +1605,7 @@ Models/Props/Pillars/SciFiBridgePillar1.mesh - + @@ -2886,9 +2887,9 @@ Models/Props/PickUps/PickUpHolder.mesh - + - + @@ -3117,7 +3118,7 @@ Models/Props/SciFiHolder1.mesh - + From 97de31be65e4bc32ef9461f0cc6dd19716d025d1 Mon Sep 17 00:00:00 2001 From: viktorljung Date: Thu, 11 Feb 2016 13:36:27 +0100 Subject: [PATCH 200/355] Fixed BoneAttachment component --- include/Engine/Rendering/Skeleton.h | 2 + resources/Schema/Entities/AnimationTests2.xml | 28 +- src/Engine/Rendering/BoneAttachmentSystem.cpp | 46 +++- src/Engine/Rendering/Skeleton.cpp | 243 ++++++++++++++++++ 4 files changed, 294 insertions(+), 25 deletions(-) diff --git a/include/Engine/Rendering/Skeleton.h b/include/Engine/Rendering/Skeleton.h index ccf3e2b4..28a5ef6a 100644 --- a/include/Engine/Rendering/Skeleton.h +++ b/include/Engine/Rendering/Skeleton.h @@ -113,6 +113,8 @@ public: std::map Animations; glm::mat4 GetBoneTransform(const Bone* bone, const Animation* animation, float time, glm::mat4 childMatrix); + glm::mat4 GetBoneTransform(bool noRootMotion, const Bone* bone, std::vector animations, AnimationOffset animationOffset, glm::mat4 childMatrix); + glm::mat4 GetBoneTransform(bool noRootMotion, const Bone* bone, std::vector animations, glm::mat4 childMatrix); int GetKeyframe(const Animation& animation, double time); private: diff --git a/resources/Schema/Entities/AnimationTests2.xml b/resources/Schema/Entities/AnimationTests2.xml index f027dd1d..413c7e67 100644 --- a/resources/Schema/Entities/AnimationTests2.xml +++ b/resources/Schema/Entities/AnimationTests2.xml @@ -15,9 +15,7 @@ - - - + Models/Widgets/Lights/DirectionalLightWidget.mesh @@ -33,7 +31,7 @@ Run 0.5 - 0.99150007800799234 + 0.60188997954429357 -1 1 0.5 @@ -43,6 +41,7 @@ AimRifle + Models/Characters/Assault/AssaultAnimations.mesh @@ -62,8 +61,8 @@ Models/Weapons/Red/AssaultWeaponRed.mesh - - + + @@ -110,21 +109,17 @@ ShootFastRifle - 0.068159934509623099 + 0.056234247235838808 1 1 - Run + Idl 0.5 - 0.19240865965109588 - StrafeRight + 1.8308673495784191 + StrafeRigh 0.5 - 0.12533627444542628 + 0.32167823998061529 1 - - AimRifle - - Models/Characters/Assault/AssaultAnimations.mesh @@ -140,8 +135,7 @@ Models/Weapons/Red/AssaultWeaponRed.mesh - - + diff --git a/src/Engine/Rendering/BoneAttachmentSystem.cpp b/src/Engine/Rendering/BoneAttachmentSystem.cpp index c0c2b8de..3effaf2c 100644 --- a/src/Engine/Rendering/BoneAttachmentSystem.cpp +++ b/src/Engine/Rendering/BoneAttachmentSystem.cpp @@ -19,6 +19,9 @@ void BoneAttachmentSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapp return; } + if (!model->IsSkinned()) { + return; + } Skeleton* skeleton = model->m_RawModel->m_Skeleton; @@ -26,19 +29,46 @@ void BoneAttachmentSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapp return; } - const Skeleton::Animation* animation = skeleton->GetAnimation(parent["Animation"]["AnimationName1"]); - - if (!animation) { - return; - } - int id = skeleton->GetBoneID(entity["BoneAttachment"]["BoneName"]); - if(id == -1) { + if (id == -1) { return; } - glm::mat4 boneTransform = skeleton->GetBoneTransform(skeleton->Bones[id], animation, (double)parent["Animation"]["Time1"], glm::mat4(1)); + std::vector<::Skeleton::AnimationData> Animations; + ::Skeleton::AnimationOffset AnimationOffset; + glm::mat4 boneTransform; + + if (parent.HasComponent("Animation")) { + for (int i = 1; i <= 3; i++) { + ::Skeleton::AnimationData animationData; + animationData.animation = model->m_RawModel->m_Skeleton->GetAnimation(parent["Animation"]["AnimationName" + std::to_string(i)]); + if (animationData.animation == nullptr) { + continue; + } + animationData.time = (double)parent["Animation"]["Time" + std::to_string(i)]; + animationData.weight = (double)parent["Animation"]["Weight" + std::to_string(i)]; + + Animations.push_back(animationData); + } + } + + if (parent.HasComponent("AnimationOffset")) { + AnimationOffset.animation = model->m_RawModel->m_Skeleton->GetAnimation(parent["AnimationOffset"]["AnimationName"]); + AnimationOffset.time = (double)parent["AnimationOffset"]["Time"]; + + if(AnimationOffset.animation != nullptr) { + boneTransform = skeleton->GetBoneTransform(false, skeleton->Bones.at(id), Animations, AnimationOffset, glm::mat4(1)); + } else { + boneTransform = skeleton->GetBoneTransform(false, skeleton->Bones.at(id), Animations, glm::mat4(1)); + } + + } else { + boneTransform = skeleton->GetBoneTransform(false, skeleton->Bones.at(id), Animations, glm::mat4(1)); + } + + + glm::vec3 scale; glm::quat rotation; glm::vec3 translation; diff --git a/src/Engine/Rendering/Skeleton.cpp b/src/Engine/Rendering/Skeleton.cpp index f85efd17..e390d694 100644 --- a/src/Engine/Rendering/Skeleton.cpp +++ b/src/Engine/Rendering/Skeleton.cpp @@ -448,6 +448,249 @@ glm::mat4 Skeleton::GetBoneTransform(const Bone* bone, const Animation* animatio } } + +glm::mat4 Skeleton::GetBoneTransform(bool noRootMotion, const Bone* bone, std::vector animations, AnimationOffset animationOffset, glm::mat4 childMatrix) +{ + glm::mat4 boneMatrix; + + std::vector JointTransforms; + + for (const AnimationData animationData : animations) { + const Animation* animation = animationData.animation; + const float time = animationData.time; + + JointFrameTransform jointTransform; + jointTransform.Weight = animationData.weight;; + + if (animation->JointAnimations.find(bone->ID) != animation->JointAnimations.end()) { + std::vector boneKeyFrames = animation->JointAnimations.at(bone->ID); + + Animation::Keyframe currentFrame; + Animation::Keyframe nextFrame; + + if (boneKeyFrames.size() > 1) { // 2+ keyframes for the current bone + for (int index = boneKeyFrames.size()-1; index >= 0; index--) { // find the bone keyframes that surrounds the current frame + if (time >= boneKeyFrames.at(index).Time) { + currentFrame = boneKeyFrames.at(index); + nextFrame = boneKeyFrames.at((index + 1) % boneKeyFrames.size()); + break; + } + } + + float progress; + + if (nextFrame.Index == 0) { + nextFrame = currentFrame; + progress = (time - currentFrame.Time) / (animation->Duration - currentFrame.Time); + } else { + progress = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); + + } + + + if (progress > 1.0f || progress < 0.0f) { + LOG_INFO("Progress: %f", progress); + progress = glm::clamp(progress, 0.0f, 1.0f); + } + Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties; + Animation::Keyframe::BoneProperty nextBoneProperty = nextFrame.BoneProperties; + + jointTransform.PositionInterp = currentBoneProperty.Position * (1.f - progress) + nextBoneProperty.Position * progress; + jointTransform.RotationInterp = glm::slerp(currentBoneProperty.Rotation, nextBoneProperty.Rotation, progress); + jointTransform.ScaleInterp = currentBoneProperty.Scale * (1.f - progress) + nextBoneProperty.Scale * progress; + + // Flag for no root motion + if (bone == RootBone && noRootMotion) { + jointTransform.PositionInterp.x = 0; + jointTransform.PositionInterp.z = 0; + } + + JointTransforms.push_back(jointTransform); + + } else { // 1 keyframes for the current bone + currentFrame = boneKeyFrames.at(0); + jointTransform.PositionInterp = currentFrame.BoneProperties.Position; + jointTransform.RotationInterp = currentFrame.BoneProperties.Rotation; + jointTransform.ScaleInterp = currentFrame.BoneProperties.Scale; + JointTransforms.push_back(jointTransform); + + } + } else { // 0 keyframes for the current bone + + } + + } + + + glm::mat4 offset = GetOffsetTransform(bone, animationOffset); + + if (JointTransforms.size() == 0) { + if (bone->Parent) { + if (offset != glm::mat4(1)) { + boneMatrix = offset * childMatrix;// *((glm::inverse(bone->OffsetMatrix) * bone->Parent->OffsetMatrix)); + } else { + boneMatrix = ((glm::inverse(bone->OffsetMatrix) * bone->Parent->OffsetMatrix)) * childMatrix; + } + } else { + boneMatrix = offset * glm::inverse(bone->OffsetMatrix); + } + } else { + + glm::vec3 finalPosInterp; + glm::quat finalRotInterp; + glm::vec3 finalScaleInterp; + float totalWeight = 0; + + for (JointFrameTransform jointTransform : JointTransforms) { + totalWeight += jointTransform.Weight; + } + + + for (JointFrameTransform jointTransform : JointTransforms) { + if (jointTransform.Weight == 1.0f) { + finalPosInterp = jointTransform.PositionInterp; + finalRotInterp = jointTransform.RotationInterp; + finalScaleInterp = jointTransform.ScaleInterp; + break; + } else { + finalPosInterp += jointTransform.PositionInterp * (jointTransform.Weight/totalWeight); + finalRotInterp *= glm::slerp(glm::quat(), jointTransform.RotationInterp, (jointTransform.Weight/totalWeight)); + finalScaleInterp += jointTransform.ScaleInterp * (jointTransform.Weight/totalWeight); + } + + } + + if (offset != glm::mat4(1)) { + boneMatrix = ((glm::translate(finalPosInterp) * glm::toMat4(finalRotInterp) * glm::scale(finalScaleInterp)) + offset) * childMatrix; + } else { + boneMatrix = (glm::translate(finalPosInterp) * glm::toMat4(finalRotInterp) * glm::scale(finalScaleInterp)) * childMatrix; + } + } + + if (bone->Parent != nullptr) { + return GetBoneTransform(noRootMotion, bone->Parent, animations, animationOffset, boneMatrix); + } else { + return boneMatrix; + } +} + + +glm::mat4 Skeleton::GetBoneTransform(bool noRootMotion, const Bone* bone, std::vector animations, glm::mat4 childMatrix) +{ + glm::mat4 boneMatrix; + std::vector JointTransforms; + + for (const AnimationData animationData : animations) { + const Animation* animation = animationData.animation; + const float time = animationData.time; + + JointFrameTransform jointTransform; + jointTransform.Weight = animationData.weight;; + + if (animation->JointAnimations.find(bone->ID) != animation->JointAnimations.end()) { + std::vector boneKeyFrames = animation->JointAnimations.at(bone->ID); + + Animation::Keyframe currentFrame; + Animation::Keyframe nextFrame; + + if (boneKeyFrames.size() > 1) { // 2+ keyframes for the current bone + for (int index = boneKeyFrames.size()-1; index >= 0; index--) { // find the bone keyframes that surrounds the current frame + if (time >= boneKeyFrames.at(index).Time) { + currentFrame = boneKeyFrames.at(index); + nextFrame = boneKeyFrames.at((index + 1) % boneKeyFrames.size()); + break; + } + } + + float progress; + + if (nextFrame.Index == 0) { + nextFrame = currentFrame; + progress = (time - currentFrame.Time) / (animation->Duration - currentFrame.Time); + } else { + progress = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); + + } + + + if (progress > 1.0f || progress < 0.0f) { + LOG_INFO("Progress: %f", progress); + progress = glm::clamp(progress, 0.0f, 1.0f); + } + Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties; + Animation::Keyframe::BoneProperty nextBoneProperty = nextFrame.BoneProperties; + + jointTransform.PositionInterp = currentBoneProperty.Position * (1.f - progress) + nextBoneProperty.Position * progress; + jointTransform.RotationInterp = glm::slerp(currentBoneProperty.Rotation, nextBoneProperty.Rotation, progress); + jointTransform.ScaleInterp = currentBoneProperty.Scale * (1.f - progress) + nextBoneProperty.Scale * progress; + + // Flag for no root motion + if (bone == RootBone && noRootMotion) { + jointTransform.PositionInterp.x = 0; + jointTransform.PositionInterp.z = 0; + } + + JointTransforms.push_back(jointTransform); + + } else { // 1 keyframes for the current bone + currentFrame = boneKeyFrames.at(0); + jointTransform.PositionInterp = currentFrame.BoneProperties.Position; + jointTransform.RotationInterp = currentFrame.BoneProperties.Rotation; + jointTransform.ScaleInterp = currentFrame.BoneProperties.Scale; + JointTransforms.push_back(jointTransform); + + } + } else { // 0 keyframes for the current bone + + } + + } + + if (JointTransforms.size() <= 0) { + if (bone->Parent) { + boneMatrix = glm::inverse(bone->OffsetMatrix) * bone->Parent->OffsetMatrix * childMatrix; + } else { + boneMatrix = glm::inverse(bone->OffsetMatrix) * childMatrix; + } + } else if (JointTransforms.size() == 1) { + boneMatrix = (glm::translate(JointTransforms.at(0).PositionInterp) * glm::toMat4(JointTransforms.at(0).RotationInterp) * glm::scale(JointTransforms.at(0).ScaleInterp)) * childMatrix; + } else { + + glm::vec3 finalPosInterp; + glm::quat finalRotInterp; + glm::vec3 finalScaleInterp; + float totalWeight = 0; + + for (JointFrameTransform jointTransform : JointTransforms) { + totalWeight += jointTransform.Weight; + } + + + for (JointFrameTransform jointTransform : JointTransforms) { + if (jointTransform.Weight == 1.0f) { + finalPosInterp = jointTransform.PositionInterp; + finalRotInterp = jointTransform.RotationInterp; + finalScaleInterp = jointTransform.ScaleInterp; + break; + } else { + finalPosInterp += jointTransform.PositionInterp * (jointTransform.Weight/totalWeight); + finalRotInterp *= glm::slerp(glm::quat(), jointTransform.RotationInterp, (jointTransform.Weight/totalWeight)); + finalScaleInterp += jointTransform.ScaleInterp * (jointTransform.Weight/totalWeight); + } + } + + boneMatrix = (glm::translate(finalPosInterp) * glm::toMat4(finalRotInterp) * glm::scale(finalScaleInterp)) * childMatrix; + } + + + + if (bone->Parent != nullptr) { + return GetBoneTransform(noRootMotion, bone->Parent, animations, boneMatrix); + } else { + return boneMatrix; + } +} + int Skeleton::GetBoneID(std::string name) { if (m_BonesByName.find(name) == m_BonesByName.end()) { From fa2e556ab2d2865ea29c7ef1a4735f845bdbc83c Mon Sep 17 00:00:00 2001 From: Jocke Date: Thu, 11 Feb 2016 14:07:51 +0100 Subject: [PATCH 201/355] fixed some error handling in TCPClient. --- src/Engine/Network/Server.cpp | 2 +- src/Engine/Network/TCPClient.cpp | 16 +++++----------- 2 files changed, 6 insertions(+), 12 deletions(-) diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index 8a0ecd36..cc774c2f 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -272,7 +272,7 @@ void Server::parseTCPConnect(Packet & packet) m_ConnectedPlayers.at(playerID).TCPPort = m_Port; LOG_INFO("parseTCPConnect: Spectator \"%s\" connected on IP: %s", m_ConnectedPlayers.at(playerID).Name.c_str(), - m_ConnectedPlayers.at(playerID).TCPAddress); + m_ConnectedPlayers.at(playerID).TCPAddress.to_string().c_str()); // Send a message to the player that connected Packet connnectPacket(MessageType::Connect, m_ConnectedPlayers.at(playerID).PacketID); diff --git a/src/Engine/Network/TCPClient.cpp b/src/Engine/Network/TCPClient.cpp index 38bac621..df4f3826 100644 --- a/src/Engine/Network/TCPClient.cpp +++ b/src/Engine/Network/TCPClient.cpp @@ -19,17 +19,6 @@ void TCPClient::Connect(std::string playerName, std::string address, int port) Send(packet); LOG_INFO("Connect message sent again!"); } - else { - boost::system::error_code error = boost::asio::error::host_not_found; - m_Socket->connect(m_Endpoint, error); - if (!error) { - m_IsConnected = true; - Packet packet(MessageType::Connect, m_SendPacketID); - packet.WriteString(playerName); - Send(packet); - LOG_INFO("Connect message sent!"); - } - } } else if (!m_IsConnected) { boost::system::error_code error = boost::asio::error::host_not_found; @@ -46,6 +35,11 @@ void TCPClient::Connect(std::string playerName, std::string address, int port) Send(packet); LOG_INFO("Connect message sent!"); } + // If error + else { + m_Socket->close(); + m_Socket = nullptr; + } } } From 9f657ada4ebd5ed1177b7ca078c5870c8df5f1a4 Mon Sep 17 00:00:00 2001 From: Tleety Date: Thu, 11 Feb 2016 14:52:52 +0100 Subject: [PATCH 202/355] merge fixes --- include/Game/Systems/CapturePointHUDSystem.h | 2 +- src/Engine/Rendering/DrawFinalPass.cpp | 1 - src/Game/Systems/CapturePointHUDSystem.cpp | 4 ++-- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/include/Game/Systems/CapturePointHUDSystem.h b/include/Game/Systems/CapturePointHUDSystem.h index 102c52ce..94be3798 100644 --- a/include/Game/Systems/CapturePointHUDSystem.h +++ b/include/Game/Systems/CapturePointHUDSystem.h @@ -12,7 +12,7 @@ class CapturePointHUDSystem : public ImpureSystem { public: - CapturePointHUDSystem(World* world, EventBroker* eventBroker); + CapturePointHUDSystem(SystemParams params); virtual void Update(double dt) override; diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index 42cbd22b..362f2252 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -323,7 +323,6 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, m_LightCullingPass->LightGridSSBO()); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, m_LightCullingPass->LightIndexSSBO()); - for (auto &job : jobs) { auto explosionEffectJob = std::dynamic_pointer_cast(job); if (explosionEffectJob) { diff --git a/src/Game/Systems/CapturePointHUDSystem.cpp b/src/Game/Systems/CapturePointHUDSystem.cpp index ad8cc63a..c2d62c4b 100644 --- a/src/Game/Systems/CapturePointHUDSystem.cpp +++ b/src/Game/Systems/CapturePointHUDSystem.cpp @@ -1,7 +1,7 @@ #include "Systems/CapturePointHUDSystem.h" -CapturePointHUDSystem::CapturePointHUDSystem(World* world, EventBroker* eventBroker) - : System(world, eventBroker) +CapturePointHUDSystem::CapturePointHUDSystem(SystemParams params) + : System(params) , ImpureSystem() { //subscribe/listenTo playerdamage,healthpickup events (using the eventBroker) From 6ba1e95da77a8c5e7c4d34a6357d2026bab0ea9e Mon Sep 17 00:00:00 2001 From: Tleety Date: Thu, 11 Feb 2016 15:27:07 +0100 Subject: [PATCH 203/355] Fixed depth sorting for HUD elements. --- include/Engine/Rendering/SpriteJob.h | 9 ++++--- include/Game/Systems/CapturePointHUDSystem.h | 27 -------------------- resources/Schema/Components/Sprite.xml | 1 + resources/Schema/Components/Sprite.xsd | 3 +++ src/Engine/Rendering/DrawFinalPass.cpp | 6 ++++- src/Engine/Rendering/RenderSystem.cpp | 4 ++- 6 files changed, 18 insertions(+), 32 deletions(-) diff --git a/include/Engine/Rendering/SpriteJob.h b/include/Engine/Rendering/SpriteJob.h index 2708ab0e..3bb43a1c 100644 --- a/include/Engine/Rendering/SpriteJob.h +++ b/include/Engine/Rendering/SpriteJob.h @@ -17,7 +17,7 @@ struct SpriteJob : RenderJob { - SpriteJob(ComponentWrapper cSprite, Camera* camera, glm::mat4 matrix, World* world, glm::vec4 fillColor, float fillPercentage) + SpriteJob(ComponentWrapper cSprite, Camera* camera, glm::mat4 matrix, World* world, glm::vec4 fillColor, float fillPercentage, bool depthSorted) : RenderJob() { Model = ResourceManager::Load<::Model>("Models/Core/UnitQuad.mesh"); @@ -34,8 +34,11 @@ struct SpriteJob : RenderJob Color = cSprite["Color"]; Entity = cSprite.EntityID; Position = Transform::AbsolutePosition(world, cSprite.EntityID); - glm::vec3 viewpos = glm::vec3(camera->ViewMatrix() * glm::vec4(Position, 1)); - Depth = viewpos.z; + Depth = 0; + if (depthSorted) { + glm::vec3 viewpos = glm::vec3(camera->ViewMatrix() * glm::vec4(Position, 1)); + Depth = viewpos.z; + } World = world; FillColor = fillColor; diff --git a/include/Game/Systems/CapturePointHUDSystem.h b/include/Game/Systems/CapturePointHUDSystem.h index 94be3798..41db0c12 100644 --- a/include/Game/Systems/CapturePointHUDSystem.h +++ b/include/Game/Systems/CapturePointHUDSystem.h @@ -17,33 +17,6 @@ public: virtual void Update(double dt) override; private: - //methods which will take care of specific events - /* EventRelay m_ETriggerTouch; - bool CapturePointSystem::OnTriggerTouch(const Events::TriggerTouch& e); - EventRelay m_ETriggerLeave; - bool CapturePointSystem::OnTriggerLeave(const Events::TriggerLeave& e); - EventRelay m_ECaptured; - bool CapturePointSystem::OnCaptured(const Events::Captured& e);*/ - - //bool m_WinnerWasFound = false; - ////need to track these variables for the captureSystem to work as per design! - //const int m_NotACapturePoint = 999; - //int m_RedTeamNextPossibleCapturePoint = m_NotACapturePoint; - //int m_BlueTeamNextPossibleCapturePoint = m_NotACapturePoint; - //int m_RedTeamHomeCapturePoint = m_NotACapturePoint; - //int m_BlueTeamHomeCapturePoint = m_NotACapturePoint; - - //int m_NumberOfCapturePoints = 0; - //std::map m_CapturePointNumberToEntityMap; - - ////std::vector - - //const double m_CaptureTimeToTakeOver = 15.0; - //bool m_ResetTimers = false; - - ////vectors which will keep track of enter/leave changes - //std::vector> m_ETriggerTouchVector; - //std::vector> m_ETriggerLeaveVector; }; #endif \ No newline at end of file diff --git a/resources/Schema/Components/Sprite.xml b/resources/Schema/Components/Sprite.xml index c2a2057f..ce4a6e1b 100644 --- a/resources/Schema/Components/Sprite.xml +++ b/resources/Schema/Components/Sprite.xml @@ -4,4 +4,5 @@ true + true diff --git a/resources/Schema/Components/Sprite.xsd b/resources/Schema/Components/Sprite.xsd index c8f0c187..3c3d124a 100644 --- a/resources/Schema/Components/Sprite.xsd +++ b/resources/Schema/Components/Sprite.xsd @@ -21,6 +21,9 @@ Whether the model is visible or not + + Whether the sprite should be sorted with depth or not. Only use false for textures that are on HUD + diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index 362f2252..83bacd37 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -623,9 +623,13 @@ void DrawFinalPass::DrawSprites(std::list>&jobs, Rend for(auto& job : jobs) { auto spriteJob = std::dynamic_pointer_cast(job); + RenderState jobState; if (spriteJob) { - + if(spriteJob->Depth == 0) + { + jobState.Disable(GL_DEPTH_TEST); + } glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(spriteJob->Matrix)); 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())); diff --git a/src/Engine/Rendering/RenderSystem.cpp b/src/Engine/Rendering/RenderSystem.cpp index f10e6043..6600bc4f 100644 --- a/src/Engine/Rendering/RenderSystem.cpp +++ b/src/Engine/Rendering/RenderSystem.cpp @@ -62,6 +62,7 @@ void RenderSystem::fillSprites(std::list>& jobs, Worl std::string diffuseResource = cSprite["DiffuseTexture"]; std::string glowResource = cSprite["GlowMap"]; + bool depthSorted = cSprite["DepthSort"]; if (diffuseResource.empty() && glowResource.empty()) { continue; } @@ -77,7 +78,8 @@ void RenderSystem::fillSprites(std::list>& jobs, Worl glm::mat4 modelMatrix = Transform::ModelMatrix(entity.ID, world); //modelMatrix *= m_Camera->BillboardMatrix(); - std::shared_ptr spriteJob = std::shared_ptr(new SpriteJob(cSprite, m_Camera, modelMatrix, world, fillColor, fillPercentage)); + + std::shared_ptr spriteJob = std::shared_ptr(new SpriteJob(cSprite, m_Camera, modelMatrix, world, fillColor, fillPercentage, depthSorted)); jobs.push_back(spriteJob); } From 7ccaf5b040363df66989c749780b367ac9a16cab Mon Sep 17 00:00:00 2001 From: Tleety Date: Thu, 11 Feb 2016 15:42:27 +0100 Subject: [PATCH 204/355] Removed commeted code --- src/Game/Systems/CapturePointHUDSystem.cpp | 236 +-------------------- 1 file changed, 3 insertions(+), 233 deletions(-) diff --git a/src/Game/Systems/CapturePointHUDSystem.cpp b/src/Game/Systems/CapturePointHUDSystem.cpp index c2d62c4b..784c7e16 100644 --- a/src/Game/Systems/CapturePointHUDSystem.cpp +++ b/src/Game/Systems/CapturePointHUDSystem.cpp @@ -4,10 +4,6 @@ CapturePointHUDSystem::CapturePointHUDSystem(SystemParams params) : System(params) , ImpureSystem() { - //subscribe/listenTo playerdamage,healthpickup events (using the eventBroker) - //EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &CapturePointSystem::OnTriggerTouch); - //EVENT_SUBSCRIBE_MEMBER(m_ETriggerLeave, &CapturePointSystem::OnTriggerLeave); - //EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &CapturePointSystem::OnCaptured); } @@ -21,12 +17,12 @@ void CapturePointHUDSystem::Update(double dt) auto CapturePointHUDElements = m_World->GetComponents("CapturePointHUD"); auto CapturePoints = m_World->GetComponents("CapturePoint"); - for(auto& cCapturePointHUD : *CapturePointHUDElements) { + for (auto& cCapturePointHUD : *CapturePointHUDElements) { int HUD_ID = cCapturePointHUD["CapturePointNumber"]; EntityWrapper entityHUD = EntityWrapper(m_World, cCapturePointHUD.EntityID); EntityWrapper entityHUDparent = entityHUD.Parent(); - for(auto& cCapturePoint : *CapturePoints) { + for (auto& cCapturePoint : *CapturePoints) { EntityWrapper entityCP = EntityWrapper(m_World, cCapturePoint.EntityID); //Check if the HUD corresponds to the Capture Point Number @@ -53,230 +49,4 @@ void CapturePointHUDSystem::Update(double dt) } } } - - //if (m_WinnerWasFound) { - // return; - //} - //const int capturePointNumber = cCapturePoint["CapturePointNumber"]; - //const bool hasTeamComponent = capturePointEntity.HasComponent("Team"); - - ////if point doesnt have a teamComponent yet, add one. since: - ////what if capture point has no team -> we cant get/use the team enum from it... - //if (!hasTeamComponent) { - // m_World->AttachComponent(cCapturePoint.EntityID, "Team"); - // ComponentWrapper& teamComponent = capturePointEntity["Team"]; - // teamComponent["Team"] = (int)teamComponent["Team"].Enum("Spectator"); - //} - //ComponentWrapper& teamComponent = capturePointEntity["Team"]; - //const int redTeam = (int)teamComponent["Team"].Enum("Red"); - //const int blueTeam = (int)teamComponent["Team"].Enum("Blue"); - //const int spectatorTeam = (int)teamComponent["Team"].Enum("Spectator"); - - //int homePointForTeam = (int)cCapturePoint["HomePointForTeam"]; - //if (m_NumberOfCapturePoints == 0 && capturePointNumber != 0 && (homePointForTeam == redTeam || homePointForTeam == blueTeam)) { - // m_NumberOfCapturePoints = capturePointNumber + 1;//ex 2 -> 0,1,2 = 3 - // if (homePointForTeam == redTeam) { - // m_RedTeamHomeCapturePoint = capturePointNumber; - // m_BlueTeamHomeCapturePoint = 0; - // } else { - // m_BlueTeamHomeCapturePoint = capturePointNumber; - // m_RedTeamHomeCapturePoint = 0; - // } - //} - - ////if we havent received all capturepoints yet, just return - //if (m_NumberOfCapturePoints == 0 || m_NumberOfCapturePoints != m_CapturePointNumberToEntityMap.size()) { - // m_CapturePointNumberToEntityMap.insert(std::make_pair(capturePointNumber, capturePointEntity)); - // return; - //} - - ////we have all capturepoints now - process stuff - //int ownedBy = teamComponent["Team"]; - //int redTeamPlayersStandingInside = 0; - //int blueTeamPlayersStandingInside = 0; - //if (capturePointEntity.HasComponent("Model")) { - // //Now sets team color to the capturepoint, or white if it is uncaptured. - // capturePointEntity["Model"]["Color"] = ownedBy == blueTeam ? glm::vec4(0, 0.2f, 1, 0.3) : ownedBy == redTeam ? glm::vec4(1, 0.2f, 0, 0.3) : glm::vec4(1, 1, 1, 0.3); - //} - - ////calculate next possible capturePoint for both teams - //std::map nextPossibleCapturePoint; - //nextPossibleCapturePoint["Red"] = -1; - //nextPossibleCapturePoint["Blue"] = -1; - //for (int i = 0; i < m_NumberOfCapturePoints; i++) - //{ - // if (!m_CapturePointNumberToEntityMap[i].HasComponent("Team")) { - // continue; - // } - // ComponentWrapper& capturePointOwnedBy = m_CapturePointNumberToEntityMap[i]["Team"]; - // if ((int)capturePointOwnedBy["Team"] == redTeam && m_RedTeamHomeCapturePoint == 0) { - // nextPossibleCapturePoint["Red"] = i + 1; - // } - // if ((int)capturePointOwnedBy["Team"] == blueTeam && m_BlueTeamHomeCapturePoint == 0) { - // nextPossibleCapturePoint["Blue"] = i + 1; - // } - //} - //for (int i = m_NumberOfCapturePoints - 1; i >= 0; i--) - //{ - // if (!m_CapturePointNumberToEntityMap[i].HasComponent("Team")) { - // continue; - // } - // ComponentWrapper& capturePointOwnedBy = m_CapturePointNumberToEntityMap[i]["Team"]; - // if ((int)capturePointOwnedBy["Team"] == redTeam && m_RedTeamHomeCapturePoint != 0) { - // nextPossibleCapturePoint["Red"] = i - 1; - // } - // if ((int)capturePointOwnedBy["Team"] == blueTeam && m_BlueTeamHomeCapturePoint != 0) { - // nextPossibleCapturePoint["Blue"] = i - 1; - // } - //} - - ////reset timers and reset the bool that triggers this - //if (m_ResetTimers) { - // for (int i = 0; i < m_NumberOfCapturePoints; i++) - // { - // ComponentWrapper& capturePoint = m_CapturePointNumberToEntityMap[i]["CapturePoint"]; - // if ((int)capturePoint["CapturePointNumber"] != nextPossibleCapturePoint["Red"] && - // (int)capturePoint["CapturePointNumber"] != nextPossibleCapturePoint["Blue"]) { - // capturePoint["CaptureTimer"] = 0.0; - // } - // } - // m_ResetTimers = false; - //} - - ////colorize next possible capturepoint - //if (nextPossibleCapturePoint["Red"] == capturePointNumber) { - // capturePointEntity["Model"]["Color"] = glm::vec4(1, 1, 0, 0.3); - //} - //if (nextPossibleCapturePoint["Blue"] == capturePointNumber) { - // capturePointEntity["Model"]["Color"] = glm::vec4(0, 1, 1, 0.3); - //} - - ////check how many players are standing inside and are healthy - //for (size_t i = m_ETriggerTouchVector.size(); i > 0; i--) - //{ - // auto triggerTouched = m_ETriggerTouchVector[i - 1]; - // if (std::get<1>(triggerTouched) == capturePointEntity) { - // //some player has touched this - lets figure out: what team, health - // EntityWrapper player = std::get<0>(triggerTouched); - // //check if its really a player that has triggered the touch - // if (!player.HasComponent("Player")) { - // //if a non-player has entered the capturePoint, just erase that event and continue - // m_ETriggerTouchVector.erase(m_ETriggerTouchVector.begin() + i - 1); - // continue; - // } - // bool hasHealthComponent = player.HasComponent("Health"); - // if (hasHealthComponent) { - // double currentHealth = player["Health"]["Health"]; - // //check if player is dead - // if ((int)currentHealth == 0) { - // continue; - // } - // } - // //check team - spectatorNumber = "no team" - // int teamNumber = player["Team"]["Team"]; - // if (teamNumber == redTeam) { - // redTeamPlayersStandingInside++; - // } else if (teamNumber == blueTeam) { - // blueTeamPlayersStandingInside++; - // } - // continue; - // } - //} - - ////create data to be used in option B - ////check so this is the next possible capture point for the take-over team and see if only one team is standing inside it - //double timerDeltaChange = 0.0; - //int currentTeam = 0; - //bool canCapture = false; - //if (redTeamPlayersStandingInside > 0 && blueTeamPlayersStandingInside == 0) { - // timerDeltaChange = redTeamPlayersStandingInside*dt; - // currentTeam = redTeam; - // canCapture = nextPossibleCapturePoint["Red"] == capturePointNumber; - //} - //if (redTeamPlayersStandingInside == 0 && blueTeamPlayersStandingInside > 0) { - // timerDeltaChange = -blueTeamPlayersStandingInside*dt; - // currentTeam = blueTeam; - // canCapture = nextPossibleCapturePoint["Blue"] == capturePointNumber; - //} - - //if (redTeamPlayersStandingInside == 0 && blueTeamPlayersStandingInside == 0) { - // //A.nobodys standing inside - // //do nothing (?) - //} else if (redTeamPlayersStandingInside > 0 && blueTeamPlayersStandingInside > 0) { - // //C.both teams have players inside - // //do nothing (?) - //} else { - // //B. at most one of the teams have players inside - // //if capturePoint is not owned by the take-over team, just modify the CaptureTimer accordingly - // if (ownedBy != currentTeam && canCapture) { - // if (abs((double)cCapturePoint["CaptureTimer"]) < 0.001f) { - // LOG_DEBUG("Point is being captured by team %i", currentTeam); //Remove when we tested sufficiently. - // } - // cCapturePoint["CaptureTimer"] = (double)cCapturePoint["CaptureTimer"] + timerDeltaChange; - // } - // //if capturePoint is owned by the team, and the other team has been trying to take it, then increase/decrease the timer towards 0.0 - // if ((ownedBy == currentTeam && currentTeam == redTeam && (double)cCapturePoint["CaptureTimer"] < 0.0) || - // (ownedBy == currentTeam && currentTeam == blueTeam && (double)cCapturePoint["CaptureTimer"] > 0.0)) { - // cCapturePoint["CaptureTimer"] = (double)cCapturePoint["CaptureTimer"] + timerDeltaChange; - // } - // //check if captureTimer > m_CaptureTimeToTakeOver and if so change owner and publish the eCaptured event - // if (abs((double)cCapturePoint["CaptureTimer"]) > abs(m_CaptureTimeToTakeOver) && canCapture) { - // teamComponent["Team"] = currentTeam; - // cCapturePoint["CaptureTimer"] = 0.0; - // //publish Captured event - // LOG_DEBUG("Point is captured by team %i!", currentTeam); //Remove when we tested sufficiently. - // Events::Captured e; - // e.CapturePointID = cCapturePoint.EntityID; - // e.TeamNumberThatCapturedCapturePoint = currentTeam; - // m_EventBroker->Publish(e); - // //NextPossibleCapturePoint will be calculated in the next update... - // } - //} - - ////check for possible winCondition = check if the homebase is owned by the other team - //bool checkForWinner = false; - //if (capturePointNumber == m_RedTeamHomeCapturePoint && ownedBy != redTeam) - //{ - // checkForWinner = true; - //} - //if (capturePointNumber == m_BlueTeamHomeCapturePoint && ownedBy != blueTeam) - //{ - // checkForWinner = true; - //} - - //if (checkForWinner && !m_WinnerWasFound) - //{ - // //publish Win event - // Events::Win e; - // e.TeamThatWon = ownedBy; - // m_EventBroker->Publish(e); - // m_WinnerWasFound = true; - //} - -} -// -//bool CapturePointSystem::OnTriggerTouch(const Events::TriggerTouch& e) -//{ -// //personEntered = e.Entity, thingEntered = e.Trigger -// m_ETriggerTouchVector.push_back(std::make_tuple(e.Entity, e.Trigger)); -// return true; -//} -// -//bool CapturePointSystem::OnTriggerLeave(const Events::TriggerLeave& e) -//{ -// for (size_t i = 0; i < m_ETriggerTouchVector.size(); i++) -// { -// auto triggerTouched = m_ETriggerTouchVector[i]; -// if (std::get<0>(triggerTouched) == e.Entity && std::get<1>(triggerTouched) == e.Trigger) { -// m_ETriggerTouchVector.erase(m_ETriggerTouchVector.begin() + i); -// break; -// } -// } -// return true; -//} -//bool CapturePointSystem::OnCaptured(const Events::Captured& e) -//{ -// //reset the timers in the next update since a capture has changed the "nextCapturePoint" for 1-2 teams -// m_ResetTimers = true; -// return true; -//} +} \ No newline at end of file From 51e0b852d2ef4ddb785a43be8fc4ad864274c596 Mon Sep 17 00:00:00 2001 From: Tleety Date: Thu, 11 Feb 2016 15:43:41 +0100 Subject: [PATCH 205/355] Adamfix --- src/Engine/Rendering/DrawFinalPass.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index 83bacd37..5e1d7f6e 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -626,8 +626,7 @@ void DrawFinalPass::DrawSprites(std::list>&jobs, Rend RenderState jobState; if (spriteJob) { - if(spriteJob->Depth == 0) - { + if(spriteJob->Depth == 0) { jobState.Disable(GL_DEPTH_TEST); } glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(spriteJob->Matrix)); From 4e23e7bf3097abd5ff60dbf1468dc89e435ff848 Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Thu, 11 Feb 2016 15:58:58 +0100 Subject: [PATCH 206/355] misc changes do the DoubleJumpHexagon.xml --- resources/Schema/Entities/DoubleJumpHexagon.xml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/resources/Schema/Entities/DoubleJumpHexagon.xml b/resources/Schema/Entities/DoubleJumpHexagon.xml index bbc41119..c1aaec34 100644 --- a/resources/Schema/Entities/DoubleJumpHexagon.xml +++ b/resources/Schema/Entities/DoubleJumpHexagon.xml @@ -3,8 +3,8 @@ - Models/JumpEffectHexagon.mesh - + Models/Effects/JumpEffectHexagon.mesh + true @@ -12,14 +12,14 @@ - 1.5 + 0.5 true true - 3 + 0.5 true From 8eea0c83953dc84be7e9769d1bb9a080be29e0b1 Mon Sep 17 00:00:00 2001 From: William Moberg Date: Thu, 11 Feb 2016 16:08:19 +0100 Subject: [PATCH 207/355] WIP respawning. --- include/Game/Systems/PlayerSpawnSystem.h | 13 ++- resources/DefaultConfig.ini | 1 + resources/Schema/Entities/MovementTest.xml | 117 --------------------- src/Game/Game.cpp | 3 +- src/Game/Systems/PlayerDeathSystem.cpp | 15 ++- src/Game/Systems/PlayerSpawnSystem.cpp | 76 ++++++++++++- src/Game/Systems/SoundSystem.cpp | 4 +- 7 files changed, 101 insertions(+), 128 deletions(-) diff --git a/include/Game/Systems/PlayerSpawnSystem.h b/include/Game/Systems/PlayerSpawnSystem.h index f5aa7b82..681620bb 100644 --- a/include/Game/Systems/PlayerSpawnSystem.h +++ b/include/Game/Systems/PlayerSpawnSystem.h @@ -13,6 +13,8 @@ public: PlayerSpawnSystem(World* world, EventBroker* eventBroker); virtual void Update(double dt) override; + + static void SetRespawnTime(float respawnTime) { m_RespawnTime = respawnTime; }; private: struct SpawnRequest @@ -23,10 +25,19 @@ private: bool m_NetworkEnabled = false; std::vector m_SpawnRequests; + + //Player ID -> EntityWrapper. std::map m_PlayerEntities; + //EntityWrapper ID -> Player ID. + std::map m_PlayerIDs; + + static float m_RespawnTime; + float m_Timer; EventRelay m_OnInputCommand; - bool OnInputCommand(const Events::InputCommand& e); + bool OnInputCommand(Events::InputCommand& e); EventRelay m_OnPlayerSpawnerd; bool OnPlayerSpawned(Events::PlayerSpawned& e); + EventRelay m_OnPlayerDeath; + bool OnPlayerDeath(Events::PlayerDeath& e); }; \ No newline at end of file diff --git a/resources/DefaultConfig.ini b/resources/DefaultConfig.ini index 12ec06c8..1b4fffc8 100644 --- a/resources/DefaultConfig.ini +++ b/resources/DefaultConfig.ini @@ -4,6 +4,7 @@ LoadMap= ; if true -> Pool allocation is not used when calling Allocate/Free, just use regular dynamic allocation. ; if false -> Use pool allocation. DisableMemoryPool=false +RespawnTime = 8.0 [Editor] CameraSpeed=3 diff --git a/resources/Schema/Entities/MovementTest.xml b/resources/Schema/Entities/MovementTest.xml index b8b68ef1..e7bbf236 100644 --- a/resources/Schema/Entities/MovementTest.xml +++ b/resources/Schema/Entities/MovementTest.xml @@ -120,123 +120,6 @@ - - - - - - - - - - false - - - 5 - - - - - - - - - - - - - - - - - - - - - - - - Fonts/DroidSans.ttf,100 - - false - - - - - - - - - - - - - Models/Widgets/Camera.mesh - - - - - - - - - - - - - - - Models/Widgets/Camera.mesh - false - - - - - - - - - - - - Models/Characters/Assault/AssaultHeadless.mesh - - - - - - - - - - - - Models/Core/UnitCube.mesh - - false - - - - - - - - - - - - Models/Core/UnitCube.mesh - - false - - - - - - - - - diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index 95310952..6d8933da 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -34,6 +34,7 @@ Game::Game(int argc, char* argv[]) ResourceManager::UseThreading = m_Config->Get("Multithreading.ResourceLoading", true); DisableMemoryPool::Value = m_Config->Get("Debug.DisableMemoryPool", false); LOG_LEVEL = static_cast<_LOG_LEVEL>(m_Config->Get("Debug.LogLevel", 1)); + PlayerSpawnSystem::SetRespawnTime(m_Config->Get("Debug.RespawnTime", 15.0f)); // Create the core event broker m_EventBroker = new EventBroker(); @@ -97,7 +98,6 @@ Game::Game(int argc, char* argv[]) m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); - m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); @@ -109,6 +109,7 @@ Game::Game(int argc, char* argv[]) m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeFrustrumCulling); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); + m_SystemPipeline->AddSystem(updateOrderLevel); // Collision and TriggerSystem should update after player. ++updateOrderLevel; diff --git a/src/Game/Systems/PlayerDeathSystem.cpp b/src/Game/Systems/PlayerDeathSystem.cpp index 60c31ce5..021056fd 100644 --- a/src/Game/Systems/PlayerDeathSystem.cpp +++ b/src/Game/Systems/PlayerDeathSystem.cpp @@ -34,14 +34,23 @@ void PlayerDeathSystem::createDeathEffect(EntityWrapper player) //components that we need from player auto playerCamera = player.FirstChildByName("Camera"); - auto playerEntityModel = player.FirstChildByName("PlayerModel")["Model"]; - auto playerEntityAnimation = player.FirstChildByName("PlayerModel")["Animation"]; + auto playerModel = player.FirstChildByName("PlayerModel"); + if (!playerCamera.Valid() || !playerModel.Valid()) { + return; + } + if (!playerModel.HasComponent("Model") || !playerModel.HasComponent("Animation")) { + return; + } + auto playerEntityModel = playerModel["Model"]; + auto playerEntityAnimation = playerModel["Animation"]; //copy the data from player to explisioneffectmodel playerEntityModel.Copy(deathEffectEW["Model"]); playerEntityAnimation.Copy(deathEffectEW["Animation"]); //freeze the animation - deathEffectEW["Animation"]["Speed"] = 0.0; + deathEffectEW["Animation"]["Speed1"] = 0.0; + deathEffectEW["Animation"]["Speed2"] = 0.0; + deathEffectEW["Animation"]["Speed3"] = 0.0; //copy the models position,orientation deathEffectEW["Transform"]["Position"] = (glm::vec3)player["Transform"]["Position"]; diff --git a/src/Game/Systems/PlayerSpawnSystem.cpp b/src/Game/Systems/PlayerSpawnSystem.cpp index 5f46cce3..0ca7bbac 100644 --- a/src/Game/Systems/PlayerSpawnSystem.cpp +++ b/src/Game/Systems/PlayerSpawnSystem.cpp @@ -1,20 +1,39 @@ #include "Systems/PlayerSpawnSystem.h" +//This should be set by the config anyway. +float PlayerSpawnSystem::m_RespawnTime = 15.0f; + PlayerSpawnSystem::PlayerSpawnSystem(World* m_World, EventBroker* eventBroker) : System(m_World, eventBroker) + , m_Timer(0.f) { EVENT_SUBSCRIBE_MEMBER(m_OnInputCommand, &PlayerSpawnSystem::OnInputCommand); EVENT_SUBSCRIBE_MEMBER(m_OnPlayerSpawnerd, &PlayerSpawnSystem::OnPlayerSpawned); + EVENT_SUBSCRIBE_MEMBER(m_OnPlayerDeath, &PlayerSpawnSystem::OnPlayerDeath); m_NetworkEnabled = ResourceManager::Load("Config.ini")->Get("Networking.StartNetwork", false); } void PlayerSpawnSystem::Update(double dt) { + //Increase timer. + m_Timer += dt; + if (m_Timer < m_RespawnTime) { + return; + } + //If respawn time has passed, we spawn all players that have requested to be spawned. + m_Timer = 0.f; + + //If there are no spawn requests, return immediately, if we are client the SpawnRequests should always be empty. + if (m_SpawnRequests.size() == 0) { + return; + } + auto playerSpawns = m_World->GetComponents("PlayerSpawn"); if (playerSpawns == nullptr) { return; } + int numSpawnedPlayers = 0; for (auto& req : m_SpawnRequests) { for (auto& cPlayerSpawn : *playerSpawns) { EntityWrapper spawner(m_World, cPlayerSpawn.EntityID); @@ -40,13 +59,19 @@ void PlayerSpawnSystem::Update(double dt) e.Player = player; e.Spawner = spawner; m_EventBroker->Publish(e); - + ++numSpawnedPlayers; + break; } } + if (numSpawnedPlayers != (int)m_SpawnRequests.size()) { + LOG_DEBUG("%i players were supposed to be spawned, but %i was spawned.", (int)m_SpawnRequests.size(), numSpawnedPlayers); + } else { + LOG_DEBUG("%i players were spawned.", numSpawnedPlayers); + } m_SpawnRequests.clear(); } -bool PlayerSpawnSystem::OnInputCommand(const Events::InputCommand& e) +bool PlayerSpawnSystem::OnInputCommand(Events::InputCommand& e) { if (e.Command != "PickTeam") { return false; @@ -58,11 +83,37 @@ bool PlayerSpawnSystem::OnInputCommand(const Events::InputCommand& e) return false; } - if (e.Value != 0) { + if (e.Value == 0) { + return false; + } + + //TODO: Spectating? + if (e.Player.Valid() && e.Player.HasComponent("Team")) { + ComponentWrapper cTeam = e.Player["Team"]; + if ((ComponentInfo::EnumType)e.Value == cTeam["Team"].Enum("Spectator")) { + return false; + } + } + + auto iter = m_SpawnRequests.begin(); + for (; iter != m_SpawnRequests.end(); ++iter) { + if (iter->PlayerID == e.PlayerID) { + break; + } + } + + if (iter != m_SpawnRequests.end()) { + //If player is in queue to spawn, then change their team affiliation. + iter->Team = (ComponentInfo::EnumType)e.Value; + } else if (m_PlayerEntities.count(e.PlayerID) == 0 || !m_PlayerEntities[e.PlayerID].Valid()) { + //If player is not in queue to spawn, then create a spawn request, + //but only if they are spectating and/or just connected. SpawnRequest req; req.PlayerID = e.PlayerID; req.Team = (ComponentInfo::EnumType)e.Value; m_SpawnRequests.push_back(req); + } else { + return false; } return true; @@ -82,6 +133,7 @@ bool PlayerSpawnSystem::OnPlayerSpawned(Events::PlayerSpawned& e) // Store the player for future reference m_PlayerEntities[e.PlayerID] = e.Player; + m_PlayerIDs[e.Player.ID] = e.PlayerID; // Set the camera to the correct entity EntityWrapper cameraEntity = e.Player.FirstChildByName("Camera"); @@ -110,4 +162,20 @@ bool PlayerSpawnSystem::OnPlayerSpawned(Events::PlayerSpawned& e) } return true; -} \ No newline at end of file +} + +bool PlayerSpawnSystem::OnPlayerDeath(Events::PlayerDeath& e) +{ + if (!e.Player.HasComponent("Team")) { + return false; + } + ComponentWrapper cTeam = e.Player["Team"]; + //A spectator can't die anyway + if ((ComponentInfo::EnumType)cTeam["Team"] == cTeam["Team"].Enum("Spectator")) { + return false; + } + SpawnRequest req; + req.PlayerID = m_PlayerIDs[e.Player.ID]; + req.Team = cTeam["Team"]; + m_SpawnRequests.push_back(req); +} diff --git a/src/Game/Systems/SoundSystem.cpp b/src/Game/Systems/SoundSystem.cpp index e3aa49b2..7026bfd3 100644 --- a/src/Game/Systems/SoundSystem.cpp +++ b/src/Game/Systems/SoundSystem.cpp @@ -57,10 +57,10 @@ bool SoundSystem::OnInputCommand(const Events::InputCommand & e) return true; } } - if (e.Command == "TakeDamage" && e.Value > 0) { + if (e.Command == "TakeDamage" && e.Value > 0 && m_LocalPlayer.Valid()) { Events::PlayerDamage ev; ev.Player = m_LocalPlayer; - ev.Damage = 1.0; + ev.Damage = e.Value; m_EventBroker->Publish(ev); } From 49d4a45ef87f86b56b9896f1cdd3250e4ba92086 Mon Sep 17 00:00:00 2001 From: Jocke Date: Thu, 11 Feb 2016 16:27:33 +0100 Subject: [PATCH 208/355] Client crashed when connecting, this was a hot fix. --- src/Engine/Rendering/PickingPass.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/Engine/Rendering/PickingPass.cpp b/src/Engine/Rendering/PickingPass.cpp index cc9837ff..07440749 100644 --- a/src/Engine/Rendering/PickingPass.cpp +++ b/src/Engine/Rendering/PickingPass.cpp @@ -104,8 +104,11 @@ void PickingPass::Draw(RenderScene& scene) std::vector frameBones; frameBones = modelJob->Skeleton->GetBones(); - glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - + // temp check revise later crashed client when connectiong + // frameBones.size() was 0 // Jocke + if (frameBones.size() > 0) { + glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + } } } else { m_PickingProgram->Bind(); From 1d14094e903ca7baa09263fcea33a52cb298232e Mon Sep 17 00:00:00 2001 From: antc13 Date: Thu, 11 Feb 2016 16:52:10 +0100 Subject: [PATCH 209/355] NewMap Updated. Still WIP --- assets | 2 +- resources/Schema/Entities/NewMap.xml | 422 ++++++++++++++++++++++----- 2 files changed, 353 insertions(+), 71 deletions(-) diff --git a/assets b/assets index c56f6380..66e2a73b 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit c56f6380ab05c23419beafe14190013d1432e32c +Subproject commit 66e2a73bdb2c385cac37476980809cc587e2e612 diff --git a/resources/Schema/Entities/NewMap.xml b/resources/Schema/Entities/NewMap.xml index 7a1d620b..f4c768f0 100644 --- a/resources/Schema/Entities/NewMap.xml +++ b/resources/Schema/Entities/NewMap.xml @@ -104,6 +104,100 @@ + + + + Models/Props/Walls/SciFiWallTop.mesh + + + + + + + + + Models/Props/Walls/SciFiWallBig.mesh + + + + + + + + + + Models/Props/Walls/SciFiWallMedium.mesh + + + + + + + + + + Models/Props/Walls/SciFiWallSmall1.mesh + + + + + + + + + + Models/Props/Walls/SciFiWallSmall2.mesh + + + + + + + + + + Models/Props/Walls/SciFiWallBig.mesh + + + + + + + + + + + + Models/Props/Walls/SciFiWallMedium.mesh + + + + + + + + + + + + Models/Props/Walls/SciFiWallSmall3.mesh + + + + + + + + + + Models/Props/Walls/SciFiWallSmall4.mesh + + + + + + + @@ -1436,12 +1530,117 @@ Models/Props/Bridges/SciFiBridge.mesh - + - + - + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + + + + @@ -1591,9 +1790,9 @@ Models/Props/Pillars/SciFiBridgePillar1.mesh - + - + @@ -2901,9 +3100,9 @@ Models/Props/PickUps/PickUpHolder.mesh - + - + @@ -3124,6 +3323,19 @@ + + + + + Models/Props/SciFiHolder1.mesh + + + + + + + + @@ -3135,106 +3347,176 @@ - - - - - + - Models/Props/CapturePoint.mesh - - true + Models/Props/CapturePoint/CapturePointBlue.mesh - - - - - - + - - + + + + + + + + + + Models/Core/UnitCylinder.mesh + + true + + + + + + + + + + + + + + + - - 1 - + - Models/Props/CapturePoint.mesh - - true + Models/Props/CapturePoint/CapturePointNeutral.mesh - - + - - + + + + + 1 + + + Models/Core/UnitCylinder.mesh + + true + + + + + + + + + + + - - 2 - + - Models/Props/CapturePoint.mesh - - true + Models/Props/CapturePoint/CapturePointNeutral.mesh - - + - - + + + + + 2 + + + Models/Core/UnitCylinder.mesh + + true + + + + + + + + + + + - - 3 - + - Models/Props/CapturePoint.mesh - - true + Models/Props/CapturePoint/CapturePointNeutral.mesh - - + - - + + + + + 3 + + + Models/Core/UnitCylinder.mesh + + true + + + + + + + + + + + - - - - - 4 - + - Models/Props/CapturePoint.mesh - - true + Models/Props/CapturePoint/CapturePointNeutral.mesh - - - - - - + - - + + + + + + + + 4 + + + Models/Core/UnitCylinder.mesh + + true + + + + + + + + + + + + + + + From e47201ff6108627fc7997bf7aa5e22f2658b70d8 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Thu, 11 Feb 2016 17:06:34 +0100 Subject: [PATCH 210/355] First person shoot animations --- .../Systems/Weapon/AssaultWeaponBehaviour.h | 34 ++++ include/Game/Systems/Weapon/WeaponBehaviour.h | 31 +++ include/Game/Systems/Weapon/WeaponSystem.h | 46 +++++ include/Game/Systems/WeaponSystem.h | 192 ------------------ resources/Schema/Components/AssaultWeapon.xml | 1 + resources/Schema/Components/AssaultWeapon.xsd | 3 + resources/Schema/Components/Player.xml | 1 + resources/Schema/Components/Player.xsd | 3 +- src/Engine/Rendering/AnimationSystem.cpp | 21 +- src/Game/CMakeLists.txt | 7 + src/Game/Game.cpp | 2 +- src/Game/Systems/PlayerMovementSystem.cpp | 3 +- .../Systems/Weapon/AssaultWeaponBehaviour.cpp | 190 +++++++++++++++++ .../Systems/{ => Weapon}/WeaponSystem.cpp | 5 +- 14 files changed, 338 insertions(+), 201 deletions(-) create mode 100644 include/Game/Systems/Weapon/AssaultWeaponBehaviour.h create mode 100644 include/Game/Systems/Weapon/WeaponBehaviour.h create mode 100644 include/Game/Systems/Weapon/WeaponSystem.h delete mode 100644 include/Game/Systems/WeaponSystem.h create mode 100644 src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp rename src/Game/Systems/{ => Weapon}/WeaponSystem.cpp (97%) diff --git a/include/Game/Systems/Weapon/AssaultWeaponBehaviour.h b/include/Game/Systems/Weapon/AssaultWeaponBehaviour.h new file mode 100644 index 00000000..58d7755f --- /dev/null +++ b/include/Game/Systems/Weapon/AssaultWeaponBehaviour.h @@ -0,0 +1,34 @@ +#include "Sound/EPlaySoundOnEntity.h" +#include "Rendering/AnimationSystem.h" +#include "WeaponBehaviour.h" +#include "../SpawnerSystem.h" + +class AssaultWeaponBehaviour : public WeaponBehaviour +{ +public: + AssaultWeaponBehaviour(SystemParams systemParams, Octree* collisionOctree, EntityWrapper weaponEntity); + + virtual void Fire() override; + virtual void CeaseFire() override; + virtual void Reload() override; + + virtual void Update(double dt) override; + +private: + EntityWrapper m_FirstPersonModel; + // State + bool m_Firing = false; + bool m_Reloading = false; + double m_TimeSinceLastFire = 0.0; + + EventRelay m_EAnimationComplete; + bool OnAnimationComplete(Events::AnimationComplete& e); + + void fireRound(); + void spawnTracer(); + float traceRayDistance(glm::vec3 origin, glm::vec3 direction); + void playSound(); + void viewPunch(); + void playShootAnimation(); + void playIdleAnimation(); +}; diff --git a/include/Game/Systems/Weapon/WeaponBehaviour.h b/include/Game/Systems/Weapon/WeaponBehaviour.h new file mode 100644 index 00000000..38ab5f58 --- /dev/null +++ b/include/Game/Systems/Weapon/WeaponBehaviour.h @@ -0,0 +1,31 @@ +#ifndef WeaponBehaviour_h__ +#define WeaponBehaviour_h__ + +#include "Core/System.h" +#include "Core/Octree.h" +#include "Collision/EntityAABB.h" + +class WeaponBehaviour : public System +{ +public: + WeaponBehaviour(SystemParams systemParams, Octree* collisionOctree, EntityWrapper weaponEntity) + : System(systemParams) + , m_CollisionOctree(collisionOctree) + , m_Entity(weaponEntity) + { } + virtual ~WeaponBehaviour() = default; + + WeaponBehaviour(const WeaponBehaviour&) = delete; + WeaponBehaviour& operator=(const WeaponBehaviour &) = delete; + + virtual void Fire() = 0; + virtual void CeaseFire() { } + virtual void Reload() { } + virtual void Update(double dt) { } + +protected: + Octree* m_CollisionOctree; + EntityWrapper m_Entity; +}; + +#endif diff --git a/include/Game/Systems/Weapon/WeaponSystem.h b/include/Game/Systems/Weapon/WeaponSystem.h new file mode 100644 index 00000000..68cf2ef3 --- /dev/null +++ b/include/Game/Systems/Weapon/WeaponSystem.h @@ -0,0 +1,46 @@ +#ifndef WeaponSystem_h__ +#define WeaponSystem_h__ + +#include "Rendering/IRenderer.h" + +#include "Common.h" +#include "Core/System.h" +#include "Core/EPlayerDamage.h" +#include "Core/EShoot.h" +#include "Core/EPlayerSpawned.h" +#include "Input/EInputCommand.h" +#include "Core/EntityFile.h" +#include "Core/EntityFileParser.h" +#include "Core/Octree.h" +#include "Collision/EntityAABB.h" +#include "Systems/SpawnerSystem.h" +#include "Sound/EPlaySoundOnEntity.h" +#include "AssaultWeaponBehaviour.h" + +class WeaponSystem : public PureSystem, ImpureSystem +{ +public: + WeaponSystem(SystemParams params, IRenderer* renderer, Octree* collisionOctree); + + virtual void Update(double dt) override; + virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& cPlayer, double dt) override; + +private: + SystemParams m_SystemParams; + IRenderer* m_Renderer; + Octree* m_CollisionOctree; + + std::unordered_map> m_ActiveWeapons; + + // Events + EventRelay m_EPlayerSpawned; + bool OnPlayerSpawned(Events::PlayerSpawned& e); + EventRelay m_EShoot; + bool OnShoot(Events::Shoot& e); + EventRelay m_EInputCommand; + bool OnInputCommand(Events::InputCommand& e); + + void selectWeapon(EntityWrapper player, ComponentInfo::EnumType slot); +}; + +#endif \ No newline at end of file diff --git a/include/Game/Systems/WeaponSystem.h b/include/Game/Systems/WeaponSystem.h deleted file mode 100644 index b118b8cd..00000000 --- a/include/Game/Systems/WeaponSystem.h +++ /dev/null @@ -1,192 +0,0 @@ -#ifndef WeaponSystem_h__ -#define WeaponSystem_h__ - -//#include -//#include -#include "Rendering/IRenderer.h" - -#include "Common.h" -#include "Core/System.h" -#include "Core/EPlayerDamage.h" -#include "Core/EShoot.h" -#include "Core/EPlayerSpawned.h" -#include "Input/EInputCommand.h" -#include "Core/EntityFile.h" -#include "Core/EntityFileParser.h" -#include "Core/Octree.h" -#include "Collision/EntityAABB.h" -#include "Systems/SpawnerSystem.h" -#include "Sound/EPlaySoundOnEntity.h" - -class WeaponBehaviour; - -class WeaponSystem : public PureSystem, ImpureSystem -{ -public: - WeaponSystem(SystemParams params, IRenderer* renderer, Octree* collisionOctree); - - virtual void Update(double dt) override; - virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& cPlayer, double dt) override; - -private: - SystemParams m_SystemParams; - IRenderer* m_Renderer; - Octree* m_CollisionOctree; - - std::unordered_map> m_ActiveWeapons; - - // Events - EventRelay m_EPlayerSpawned; - bool OnPlayerSpawned(Events::PlayerSpawned& e); - EventRelay m_EShoot; - bool OnShoot(Events::Shoot& e); - EventRelay m_EInputCommand; - bool OnInputCommand(Events::InputCommand& e); - - void selectWeapon(EntityWrapper player, ComponentInfo::EnumType slot); -}; - -class WeaponBehaviour : public System -{ -public: - WeaponBehaviour(SystemParams systemParams, Octree* collisionOctree, EntityWrapper weaponEntity) - : System(systemParams) - , m_CollisionOctree(collisionOctree) - , m_Entity(weaponEntity) - { } - virtual ~WeaponBehaviour() = default; - - WeaponBehaviour(const WeaponBehaviour&) = delete; - WeaponBehaviour& operator=(const WeaponBehaviour &) = delete; - - virtual void Fire() = 0; - virtual void CeaseFire() { } - virtual void Reload() { } - virtual void Update(double dt) { } - -protected: - Octree* m_CollisionOctree; - EntityWrapper m_Entity; -}; - -class AssaultWeaponBehaviour : public WeaponBehaviour -{ -public: - AssaultWeaponBehaviour(SystemParams systemParams, Octree* collisionOctree, EntityWrapper weaponEntity) - : WeaponBehaviour(systemParams, collisionOctree, weaponEntity) - { } - - virtual void Fire() override - { - m_TimeSinceLastFire = 0.0; - m_Firing = true; - fireRound(); - } - - virtual void CeaseFire() override - { - m_Firing = false; - } - - virtual void Reload() override - { - ComponentWrapper& cAssaultWeapon = m_Entity["AssaultWeapon"]; - - int& magAmmo = cAssaultWeapon["MagazineAmmo"]; - int magSize = cAssaultWeapon["MagazineSize"]; - int& ammo = cAssaultWeapon["Ammo"]; - - // Don't reload if we're already fully loaded - if (magAmmo == magSize) { - return; - } - - // Throw away rounds in magazine to incentivise ammo sharing - int toLoad = glm::min(magSize, ammo); - magAmmo = toLoad; - ammo -= toLoad; - } - - virtual void Update(double dt) override - { - if (!m_Firing) { - return; - } - - m_TimeSinceLastFire += dt; - - ComponentWrapper& cAssaultWeapon = m_Entity["AssaultWeapon"]; - if (m_TimeSinceLastFire >= 1.0 / ((double)cAssaultWeapon["RPM"] / 60.0)) { - fireRound(); - } - } - -private: - bool m_Firing = false; - double m_TimeSinceLastFire = 0.0; - EntityFile* m_RayRed = nullptr; - EntityFile* m_RayBlue = nullptr; - - void fireRound() - { - ComponentWrapper& cAssaultWeapon = m_Entity["AssaultWeapon"]; - - int& magAmmo = cAssaultWeapon["MagazineAmmo"]; - int ammo = cAssaultWeapon["Ammo"]; - - // Reload if our magazine is empty - if (magAmmo <= 0) { - Reload(); - return; - } - - // Fire - magAmmo -= 1; - spawnTracer(); - playSound(); - - m_TimeSinceLastFire = 0.0; - } - - void spawnTracer() - { - if (!IsClient) { - return; - } - - EntityWrapper spawner; - if (m_Entity == LocalPlayer) { - spawner = m_Entity.FirstChildByName("WeaponMuzzle"); - } else { - spawner = m_Entity.FirstChildByName("ThirdPersonWeaponMuzzle"); - } - - if (!spawner.Valid()) { - return; - } - - Events::SpawnerSpawn e; - e.Spawner = spawner; - m_EventBroker->Publish(e); - } - - float traceRayDistance(glm::vec3 origin, glm::vec3 direction) - { - // TODO: Cast a ray and size tracer appropriately - return 100.f; - } - - void playSound() - { - if (!IsClient) { - return; - } - - Events::PlaySoundOnEntity e; - e.EmitterID = m_Entity.ID; - e.FilePath = "Audio/laser/laser1.wav"; - m_EventBroker->Publish(e); - } -}; - -#endif \ No newline at end of file diff --git a/resources/Schema/Components/AssaultWeapon.xml b/resources/Schema/Components/AssaultWeapon.xml index 902795c1..c7dbfb0d 100755 --- a/resources/Schema/Components/AssaultWeapon.xml +++ b/resources/Schema/Components/AssaultWeapon.xml @@ -6,4 +6,5 @@ 360 5 120 + 0.01 \ No newline at end of file diff --git a/resources/Schema/Components/AssaultWeapon.xsd b/resources/Schema/Components/AssaultWeapon.xsd index 1b2704ea..65558db5 100755 --- a/resources/Schema/Components/AssaultWeapon.xsd +++ b/resources/Schema/Components/AssaultWeapon.xsd @@ -22,6 +22,9 @@ Rate of fire in rounds per minute + + View punch in radians for each bullet fired + diff --git a/resources/Schema/Components/Player.xml b/resources/Schema/Components/Player.xml index b51326aa..00cff257 100644 --- a/resources/Schema/Components/Player.xml +++ b/resources/Schema/Components/Player.xml @@ -2,4 +2,5 @@ 3 1.5 + \ No newline at end of file diff --git a/resources/Schema/Components/Player.xsd b/resources/Schema/Components/Player.xsd index 13948dc2..1b33d222 100644 --- a/resources/Schema/Components/Player.xsd +++ b/resources/Schema/Components/Player.xsd @@ -5,12 +5,13 @@ - The player charachter + The player entity + diff --git a/src/Engine/Rendering/AnimationSystem.cpp b/src/Engine/Rendering/AnimationSystem.cpp index 48681e6e..d5b5984d 100644 --- a/src/Engine/Rendering/AnimationSystem.cpp +++ b/src/Engine/Rendering/AnimationSystem.cpp @@ -34,19 +34,32 @@ void AnimationSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& a if (!(bool)animationComponent["Loop" + std::to_string(i)]) { if (nextTime > animation->Duration) { nextTime = animation->Duration; + Events::AnimationComplete e; + e.Entity = entity; + e.Name = (std::string)animationComponent["AnimationName" + std::to_string(i)]; + m_EventBroker->Publish(e); } else if (nextTime < 0) { + Events::AnimationComplete e; + e.Entity = entity; + e.Name = (std::string)animationComponent["AnimationName" + std::to_string(i)]; + m_EventBroker->Publish(e); nextTime = 0; } (double&)animationComponent["Speed" + std::to_string(i)] = 0.0; - Events::AnimationComplete e; - e.Entity = entity; - e.Name = (std::string)animationComponent["AnimationName" + std::to_string(i)]; - m_EventBroker->Publish(e); + } else { if (nextTime > animation->Duration) { + Events::AnimationComplete e; + e.Entity = entity; + e.Name = (std::string)animationComponent["AnimationName" + std::to_string(i)]; + m_EventBroker->Publish(e); nextTime -= animation->Duration; } else if (nextTime < 0) { + Events::AnimationComplete e; + e.Entity = entity; + e.Name = (std::string)animationComponent["AnimationName" + std::to_string(i)]; + m_EventBroker->Publish(e); nextTime += animation->Duration; } } diff --git a/src/Game/CMakeLists.txt b/src/Game/CMakeLists.txt index db923364..f188d7fa 100644 --- a/src/Game/CMakeLists.txt +++ b/src/Game/CMakeLists.txt @@ -16,6 +16,12 @@ file(GLOB SOURCE_FILES_Systems ) source_group(Systems FILES ${SOURCE_FILES_Systems}) +file(GLOB SOURCE_FILES_Systems_Weapon + "${INCLUDE_PATH}/Systems/Weapon/*.h" + "Systems/Weapon/*.cpp" +) +source_group(Systems\\Weapon FILES ${SOURCE_FILES_Systems_Weapon}) + file(GLOB SOURCE_FILES_Events "${INCLUDE_PATH}/Events/*.h" "Events/*.cpp" @@ -31,6 +37,7 @@ set(SOURCE_FILES ${SOURCE_FILES} "Game.cpp" ${SOURCE_FILES_Systems} + ${SOURCE_FILES_Systems_Weapon} ${SOURCE_FILES_Events} ${SOURCE_FILES_Network} ) diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index 6057d463..cf14fc76 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -13,7 +13,7 @@ #include "Core/EntityFileWriter.h" #include "Game/Systems/CapturePointSystem.h" #include "Game/Systems/PickupSpawnSystem.h" -#include "Game/Systems/WeaponSystem.h" +#include "Game/Systems/Weapon/WeaponSystem.h" #include "Rendering/AnimationSystem.h" #include "Game/Systems/PlayerHUDSystem.h" #include "Rendering/BoneAttachmentSystem.h" diff --git a/src/Game/Systems/PlayerMovementSystem.cpp b/src/Game/Systems/PlayerMovementSystem.cpp index 7c69f0ce..65f7c302 100644 --- a/src/Game/Systems/PlayerMovementSystem.cpp +++ b/src/Game/Systems/PlayerMovementSystem.cpp @@ -51,6 +51,7 @@ void PlayerMovementSystem::updateMovementControllers(double dt) float playerMovementSpeed = player["Player"]["MovementSpeed"]; float playerCrouchSpeed = player["Player"]["CrouchSpeed"]; + glm::vec3& wishDirection = player["Player"]["CurrentWishDirection"]; if (player.HasComponent("Physics")) { ComponentWrapper cPhysics = player["Physics"]; @@ -58,7 +59,7 @@ void PlayerMovementSystem::updateMovementControllers(double dt) if (player.HasComponent("DashAbility")) { controller->AssaultDashCheck(dt, ((glm::vec3)cPhysics["Velocity"]).y != 0.0f, player["DashAbility"]["CoolDownMaxTimer"]); } - glm::vec3 wishDirection = controller->Movement() * glm::inverse(glm::quat(ori)); + wishDirection = controller->Movement() * glm::inverse(glm::quat(ori)); //this makes sure you can only dash in the 4 directions: forw,backw,left,right if (controller->AssaultDashDoubleTapped() && controller->Movement().z != 0 && controller->Movement().x != 0) { wishDirection = glm::vec3(controller->Movement().x, 0, 0)* glm::inverse(glm::quat(ori)); diff --git a/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp b/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp new file mode 100644 index 00000000..bb5a025f --- /dev/null +++ b/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp @@ -0,0 +1,190 @@ +#include "Systems/Weapon/AssaultWeaponBehaviour.h" + +AssaultWeaponBehaviour::AssaultWeaponBehaviour(SystemParams systemParams, Octree* collisionOctree, EntityWrapper weaponEntity) + : WeaponBehaviour(systemParams, collisionOctree, weaponEntity) +{ + m_FirstPersonModel = m_Entity.FirstChildByName("Hands"); + EVENT_SUBSCRIBE_MEMBER(m_EAnimationComplete, &AssaultWeaponBehaviour::OnAnimationComplete); +} + +void AssaultWeaponBehaviour::Fire() +{ + m_TimeSinceLastFire = 0.0; + m_Firing = true; + fireRound(); + playShootAnimation(); +} + +void AssaultWeaponBehaviour::CeaseFire() +{ + m_Firing = false; +} + +void AssaultWeaponBehaviour::Reload() +{ + ComponentWrapper& cAssaultWeapon = m_Entity["AssaultWeapon"]; + + int& magAmmo = cAssaultWeapon["MagazineAmmo"]; + int magSize = cAssaultWeapon["MagazineSize"]; + int& ammo = cAssaultWeapon["Ammo"]; + + // Don't reload if we're already fully loaded + if (magAmmo == magSize) { + return; + } + + // Throw away rounds in magazine to incentivise ammo sharing + int toLoad = glm::min(magSize, ammo); + magAmmo = toLoad; + ammo -= toLoad; +} + +void AssaultWeaponBehaviour::Update(double dt) +{ + if (m_Firing) { + m_TimeSinceLastFire += dt; + + ComponentWrapper& cAssaultWeapon = m_Entity["AssaultWeapon"]; + if (m_TimeSinceLastFire >= 1.0 / ((double)cAssaultWeapon["RPM"] / 60.0)) { + fireRound(); + } + } + + if (!m_Firing && !m_Reloading) { + playIdleAnimation(); + } +} + +bool AssaultWeaponBehaviour::OnAnimationComplete(Events::AnimationComplete& e) +{ + if (e.Entity != m_FirstPersonModel) { + return false; + } + + //if (e.Name == "ShootRifle") { + // if (!m_Firing) { + // playIdleAnimation(); + // } + //} + + return true; +} + +void AssaultWeaponBehaviour::fireRound() +{ + ComponentWrapper& cAssaultWeapon = m_Entity["AssaultWeapon"]; + + int& magAmmo = cAssaultWeapon["MagazineAmmo"]; + int ammo = cAssaultWeapon["Ammo"]; + + // Reload if our magazine is empty + if (magAmmo <= 0) { + Reload(); + return; + } + + // Fire + magAmmo -= 1; + spawnTracer(); + playSound(); + viewPunch(); + + m_TimeSinceLastFire = 0.0; +} + +void AssaultWeaponBehaviour::spawnTracer() +{ + if (!IsClient) { + return; + } + + EntityWrapper spawner; + if (m_Entity == LocalPlayer) { + spawner = m_Entity.FirstChildByName("WeaponMuzzle"); + } else { + spawner = m_Entity.FirstChildByName("ThirdPersonWeaponMuzzle"); + } + + if (!spawner.Valid()) { + return; + } + + Events::SpawnerSpawn e; + e.Spawner = spawner; + m_EventBroker->Publish(e); +} + +float AssaultWeaponBehaviour::traceRayDistance(glm::vec3 origin, glm::vec3 direction) +{ + // TODO: Cast a ray and size tracer appropriately + return 100.f; +} + +void AssaultWeaponBehaviour::playSound() +{ + if (!IsClient) { + return; + } + + Events::PlaySoundOnEntity e; + e.EmitterID = m_Entity.ID; + e.FilePath = "Audio/laser/laser1.wav"; + m_EventBroker->Publish(e); +} + +void AssaultWeaponBehaviour::viewPunch() +{ + EntityWrapper playerCamera = m_Entity.FirstChildByName("Camera"); + if (!playerCamera.Valid()) { + return; + } + float viewPunch = m_Entity["AssaultWeapon"]["ViewPunch"]; + ComponentWrapper cTransform = playerCamera["Transform"]; + glm::vec3& orientation = cTransform["Orientation"]; + orientation.x += viewPunch; +} + +void AssaultWeaponBehaviour::playShootAnimation() +{ + EntityWrapper firstPersonWeapon = m_Entity.FirstChildByName("Hands"); + ComponentWrapper cAnimation = firstPersonWeapon["Animation"]; + cAnimation["AnimationName1"] = "ShootRifle"; + cAnimation["Weight1"] = 1.0; + cAnimation["Time1"] = 0.0; + cAnimation["Speed1"] = 1.0; + cAnimation["Loop1"] = true; +} + +void AssaultWeaponBehaviour::playIdleAnimation() +{ + if (!m_FirstPersonModel.Valid()) { + return; + } + + ComponentWrapper cAnimation = m_FirstPersonModel["Animation"]; + std::string& animationName1 = cAnimation["AnimationName1"]; + double& animationSpeed1 = cAnimation["Speed1"]; + + std::string animationToPlay = "Idle"; + double speedToSet = 1.0; + + ComponentWrapper cPlayer = m_Entity["Player"]; + glm::vec3 movementDirection = cPlayer["CurrentWishDirection"]; + if (glm::length2(movementDirection) > 0) { + animationToPlay = "Run"; + ComponentWrapper cPhysics = m_Entity["Physics"]; + speedToSet = glm::length((glm::vec3)cPhysics["Velocity"]) / (float)cPlayer["MovementSpeed"]; + } + + if (animationName1 != animationToPlay) { + cAnimation["AnimationName1"] = animationToPlay; + cAnimation["Weight1"] = 1.0; + cAnimation["Time1"] = 0.0; + cAnimation["Loop1"] = true; + } + + if (animationSpeed1 != speedToSet) { + cAnimation["Speed1"] = speedToSet; + } +} + diff --git a/src/Game/Systems/WeaponSystem.cpp b/src/Game/Systems/Weapon/WeaponSystem.cpp similarity index 97% rename from src/Game/Systems/WeaponSystem.cpp rename to src/Game/Systems/Weapon/WeaponSystem.cpp index eeb7dd00..bdd27ea9 100644 --- a/src/Game/Systems/WeaponSystem.cpp +++ b/src/Game/Systems/Weapon/WeaponSystem.cpp @@ -1,4 +1,4 @@ -#include "Systems/WeaponSystem.h" +#include "Systems/Weapon/WeaponSystem.h" WeaponSystem::WeaponSystem(SystemParams params, IRenderer* renderer, Octree* collisionOctree) : System(params) @@ -24,7 +24,8 @@ void WeaponSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& cPla if (it == m_ActiveWeapons.end()) { selectWeapon(entity, 1); } - + + m_EventBroker->Process(); m_ActiveWeapons.at(entity)->Update(dt); } From 14054ad8987ebfd5041a52951da822bcf5b57872 Mon Sep 17 00:00:00 2001 From: William Moberg Date: Thu, 11 Feb 2016 17:08:45 +0100 Subject: [PATCH 211/355] WIP respawning. --- src/Game/Systems/PlayerSpawnSystem.cpp | 14 +++++++++----- src/Game/Systems/SoundSystem.cpp | 2 +- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/src/Game/Systems/PlayerSpawnSystem.cpp b/src/Game/Systems/PlayerSpawnSystem.cpp index aaca4551..0d84bb5d 100644 --- a/src/Game/Systems/PlayerSpawnSystem.cpp +++ b/src/Game/Systems/PlayerSpawnSystem.cpp @@ -95,6 +95,7 @@ bool PlayerSpawnSystem::OnInputCommand(Events::InputCommand& e) } } + //Check if the player already requested spawn. auto iter = m_SpawnRequests.begin(); for (; iter != m_SpawnRequests.end(); ++iter) { if (iter->PlayerID == e.PlayerID) { @@ -103,7 +104,7 @@ bool PlayerSpawnSystem::OnInputCommand(Events::InputCommand& e) } if (iter != m_SpawnRequests.end()) { - //If player is in queue to spawn, then change their team affiliation. + //If player is in queue to spawn, then change their team affiliation in the request. iter->Team = (ComponentInfo::EnumType)e.Value; } else if (m_PlayerEntities.count(e.PlayerID) == 0 || !m_PlayerEntities[e.PlayerID].Valid()) { //If player is not in queue to spawn, then create a spawn request, @@ -121,6 +122,10 @@ bool PlayerSpawnSystem::OnInputCommand(Events::InputCommand& e) bool PlayerSpawnSystem::OnPlayerSpawned(Events::PlayerSpawned& e) { + // Store the player for future reference + m_PlayerEntities[e.PlayerID] = e.Player; + m_PlayerIDs[e.Player.ID] = e.PlayerID; + // When a player is actually spawned (since the actual spawning is handled on the server) if (!IsClient) { return false; @@ -134,10 +139,6 @@ bool PlayerSpawnSystem::OnPlayerSpawned(Events::PlayerSpawned& e) } } - // Store the player for future reference - m_PlayerEntities[e.PlayerID] = e.Player; - m_PlayerIDs[e.Player.ID] = e.PlayerID; - // Set the camera to the correct entity EntityWrapper cameraEntity = e.Player.FirstChildByName("Camera"); if (cameraEntity.Valid()) { @@ -169,6 +170,9 @@ bool PlayerSpawnSystem::OnPlayerSpawned(Events::PlayerSpawned& e) bool PlayerSpawnSystem::OnPlayerDeath(Events::PlayerDeath& e) { + if (!IsServer && m_NetworkEnabled) { + return false; + } if (!e.Player.HasComponent("Team")) { return false; } diff --git a/src/Game/Systems/SoundSystem.cpp b/src/Game/Systems/SoundSystem.cpp index 9788817f..a9b1ccaf 100644 --- a/src/Game/Systems/SoundSystem.cpp +++ b/src/Game/Systems/SoundSystem.cpp @@ -52,7 +52,7 @@ bool SoundSystem::OnInputCommand(const Events::InputCommand & e) return true; } } - if (e.Command == "TakeDamage" && e.Value > 0 && m_LocalPlayer.Valid()) { + if (e.Command == "TakeDamage" && e.Value > 0 && LocalPlayer.Valid()) { Events::PlayerDamage ev; ev.Player = LocalPlayer; ev.Damage = e.Value; From 6caa7e94a4945cfd7bf2944cfe0bb8b515a6a701 Mon Sep 17 00:00:00 2001 From: Teejoon Date: Thu, 11 Feb 2016 18:28:33 +0100 Subject: [PATCH 212/355] RGB is now the only channels thats beeing usesed in splatmap --- assets | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/assets b/assets index c56f6380..0107c7df 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit c56f6380ab05c23419beafe14190013d1432e32c +Subproject commit 0107c7dfdfd02bc4966b35ed6ee0f0f3e366f23d From f088aa1d85d82bbc78a50006a6effc19c7330bfa Mon Sep 17 00:00:00 2001 From: Teejoon Date: Thu, 11 Feb 2016 18:45:48 +0100 Subject: [PATCH 213/355] Commit the files now.... --- .../Shaders/ForwardPlusSplatMapRGB.frag.glsl | 245 ++++++++++++++++++ src/Engine/Rendering/DrawFinalPass.cpp | 16 +- 2 files changed, 253 insertions(+), 8 deletions(-) create mode 100644 resources/Shaders/ForwardPlusSplatMapRGB.frag.glsl diff --git a/resources/Shaders/ForwardPlusSplatMapRGB.frag.glsl b/resources/Shaders/ForwardPlusSplatMapRGB.frag.glsl new file mode 100644 index 00000000..e862d926 --- /dev/null +++ b/resources/Shaders/ForwardPlusSplatMapRGB.frag.glsl @@ -0,0 +1,245 @@ +#version 430 + +uniform mat4 M; +uniform mat4 V; +uniform mat4 P; +uniform vec2 ScreenDimensions; +uniform float FillPercentage; +uniform vec4 DiffuseColor; +uniform vec4 FillColor; +uniform vec4 Color; +uniform vec4 AmbientColor; + +//Get bineded at the same time as the textures +uniform vec2 DiffuseUVRepeat1; +uniform vec2 DiffuseUVRepeat2; +uniform vec2 DiffuseUVRepeat3; +uniform vec2 NormalUVRepeat1; +uniform vec2 NormalUVRepeat2; +uniform vec2 NormalUVRepeat3; +uniform vec2 SpecularUVRepeat1; +uniform vec2 SpecularUVRepeat2; +uniform vec2 SpecularUVRepeat3; +uniform vec2 GlowUVRepeat1; +uniform vec2 GlowUVRepeat2; +uniform vec2 GlowUVRepeat3; +layout (binding = 0) uniform sampler2D SplatMapTexture; +layout (binding = 1) uniform sampler2D DiffuseTexture1; +layout (binding = 2) uniform sampler2D DiffuseTexture2; +layout (binding = 3) uniform sampler2D DiffuseTexture3; +layout (binding = 4) uniform sampler2D NormalMapTexture1; +layout (binding = 5) uniform sampler2D NormalMapTexture2; +layout (binding = 6) uniform sampler2D NormalMapTexture3; +layout (binding = 7) uniform sampler2D SpecularMapTexture1; +layout (binding = 8) uniform sampler2D SpecularMapTexture2; +layout (binding = 9) uniform sampler2D SpecularMapTexture3; +layout (binding = 10) uniform sampler2D GlowMapTexture1; +layout (binding = 11) uniform sampler2D GlowMapTexture2; +layout (binding = 12) uniform sampler2D GlowMapTexture3; + +#define TILE_SIZE 16 + +struct LightSource { + vec4 Position; + vec4 Direction; + vec4 Color; + float Radius; + float Intensity; + float Falloff; + int Type; +}; + +layout (std430, binding = 1) buffer LightBuffer +{ + LightSource List[]; +} LightSources; + +struct LightGrid { + float Start; + float Amount; + vec2 Padding; +}; + +layout (std430, binding = 2) buffer LightGridBuffer +{ + LightGrid Data[]; +} LightGrids; + +layout (std430, binding = 4) buffer LightIndexBuffer +{ + float LightIndex[]; +}; + + +in VertexData{ + vec3 Position; + vec3 Normal; + vec3 Tangent; + vec3 BiTangent; + vec2 TextureCoordinate; + vec4 ExplosionColor; + float ExplosionPercentageElapsed; +}Input; + +out vec4 sceneColor; +out vec4 bloomColor; + +struct LightResult { + vec4 Diffuse; + vec4 Specular; +}; + +float CalcAttenuation(float radius, float dist, float falloff) { + return 1.0 - smoothstep(radius * 0.3, radius, dist); +} + +vec4 CalcSpecular(vec4 lightColor, vec4 viewVec, vec4 lightVec, vec4 normal) { + vec4 R = normalize( reflect(-lightVec, normal)); + float RdotV = max( dot(R, viewVec), 0.0); + return lightColor * pow(RdotV, 90.0); +} + +vec4 CalcDiffuse(vec4 lightColor, vec4 lightVec, vec4 normal) { + float power = max( dot(normal, lightVec), 0.0); + return lightColor * power; +} + +LightResult CalcPointLightSource(vec4 lightPos, float lightRadius, vec4 lightColor, float intensity, vec4 viewVec, vec4 position, vec4 normal, float falloff) +{ + vec4 L = lightPos - position; + float dist = length(L); + L = normalize(L); + + float attenuation = CalcAttenuation(lightRadius, dist, falloff); + + LightResult result; + result.Diffuse = CalcDiffuse(lightColor, L, normal) * attenuation * intensity; + result.Specular = CalcSpecular(lightColor, viewVec, L, normal) * attenuation * intensity; + return result; +} + +LightResult CalcDirectionalLightSource(vec4 direction, vec4 color, float intensity, vec4 viewVec, vec4 vertNormal) +{ + vec4 L = normalize( -vec4(direction.xyz, 0) ); + + LightResult result; + result.Diffuse = CalcDiffuse(color, L, vertNormal) * intensity; + result.Specular = CalcSpecular(color, viewVec, L, vertNormal) * intensity; + return result; +} + +vec4 CalcNormalMappedValue(vec3 normal, vec3 tangent, vec3 bitangent, vec2 textureCoordinate, sampler2D normalMap) +{ + mat3 TBN = mat3(tangent, bitangent, normal); + vec3 NormalMap = texture(normalMap, textureCoordinate).xyz * 2.0 - vec3(1.0); + return vec4(TBN * normalize(NormalMap), 0.0); +} + +vec4 CalcBlendedTexel(vec4 blendValue, sampler2D R, sampler2D G, sampler2D B, + vec2 R_TileValues, vec2 G_TileValues, vec2 B_TileValues){ + vec4 R_Channel = texture2D(R, Input.TextureCoordinate * R_TileValues); + vec4 G_Channel = texture2D(G, Input.TextureCoordinate * G_TileValues); + vec4 B_Channel = texture2D(B, Input.TextureCoordinate * B_TileValues); + + float total = blendValue.r + blendValue.g + blendValue.b; + float totalDiv = 1.0f / total; + blendValue.r = blendValue.r * totalDiv; + blendValue.g = blendValue.g * totalDiv; + blendValue.b = blendValue.b * totalDiv; + + return blendValue.r * R_Channel + + blendValue.g * G_Channel + + blendValue.b * B_Channel; +} + +vec4 CalcBlendedNormal(vec4 blendValue, sampler2D R, sampler2D G, sampler2D B, + vec2 R_TileValues, vec2 G_TileValues, vec2 B_TileValues){ + mat3 TBN = mat3(Input.Tangent, Input.BiTangent, Input.Normal); + vec3 R_Channel = texture(R, Input.TextureCoordinate * R_TileValues).xyz * 2.0 - vec3(1.0); + vec3 G_Channel = texture(G, Input.TextureCoordinate * G_TileValues).xyz * 2.0 - vec3(1.0); + vec3 B_Channel = texture(B, Input.TextureCoordinate * B_TileValues).xyz * 2.0 - vec3(1.0); + + float total = blendValue.r + blendValue.g + blendValue.b + blendValue.a; + float totalDiv = 1 / total; + blendValue.r = blendValue.r * totalDiv; + blendValue.g = blendValue.g * totalDiv; + blendValue.b = blendValue.b * totalDiv; + + vec3 Normal_result = blendValue.r * R_Channel + + blendValue.g * G_Channel + + blendValue.b * B_Channel; + + return vec4(TBN * normalize(Normal_result), 0.0); +} + +void main() +{ + vec4 splatTexel = texture2D(SplatMapTexture, Input.TextureCoordinate); + + vec4 diffuseTexel = CalcBlendedTexel(splatTexel, DiffuseTexture1, DiffuseTexture2, DiffuseTexture3, + DiffuseUVRepeat1, DiffuseUVRepeat2, DiffuseUVRepeat3); + vec4 glowTexel = CalcBlendedTexel(splatTexel, GlowMapTexture1, GlowMapTexture2, GlowMapTexture3, + GlowUVRepeat1, GlowUVRepeat2, GlowUVRepeat3); + vec4 specularTexel = CalcBlendedTexel(splatTexel, SpecularMapTexture1, SpecularMapTexture2, SpecularMapTexture3, + SpecularUVRepeat1, SpecularUVRepeat2, SpecularUVRepeat3); + vec4 position = V * M * vec4(Input.Position, 1.0); + //vec4 normal = V * CalcNormalMappedValue(Input.Normal, Input.Tangent, Input.BiTangent, Input.TextureCoordinate, SplatMapTexture); + vec4 normal = V * CalcBlendedNormal(splatTexel, NormalMapTexture1, NormalMapTexture2, NormalMapTexture3, + NormalUVRepeat1, NormalUVRepeat2, NormalUVRepeat3); + normal = normalize(normal); + //vec4 normal = normalize(V * vec4(Input.Normal, 0.0)); + vec4 viewVec = normalize(-position); + + vec2 tilePos; + tilePos.x = int(gl_FragCoord.x/TILE_SIZE); + tilePos.y = int(gl_FragCoord.y/TILE_SIZE); + + LightResult totalLighting; + totalLighting.Diffuse = vec4(AmbientColor.rgb, 1.0); + int currentTile = int(floor(gl_FragCoord.x/TILE_SIZE) + (floor(gl_FragCoord.y/TILE_SIZE) * int(ScreenDimensions.x/TILE_SIZE))); + + int start = int(LightGrids.Data[currentTile].Start); + int amount = int(LightGrids.Data[currentTile].Amount); + + for(int i = start; i < start + amount; i++) { + + int l = int(LightIndex[i]); + LightSource light = LightSources.List[l]; + + LightResult light_result; + //These if statements should be removed. + if(light.Type == 1) { // point + light_result = CalcPointLightSource(V * light.Position, light.Radius, light.Color, light.Intensity, viewVec, position, normal, light.Falloff); + } else if (light.Type == 2) { //Directional + light_result = CalcDirectionalLightSource(V * light.Direction, light.Color, light.Intensity, viewVec, normal); + } + totalLighting.Diffuse += light_result.Diffuse; + totalLighting.Specular += light_result.Specular; + } + + vec4 color_result = mix((Color * diffuseTexel * DiffuseColor), Input.ExplosionColor, Input.ExplosionPercentageElapsed); + color_result = color_result * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)); + //vec4 color_result = (DiffuseColor + Input.ExplosionColor) * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)) * diffuseTexel * Color; + + + float pos = ((P * vec4(Input.Position, 1)).y + 1.0)/2.0; + + if(pos <= FillPercentage) { + color_result += FillColor; + } + sceneColor = vec4(color_result.xyz, clamp(color_result.a, 0, 1)); + color_result += glowTexel*3; + + bloomColor = vec4(clamp(color_result.xyz - 1.0, 0, 100), 1.0); + + //Tiled Debug Code + /* + if(int(gl_FragCoord.x)%16 == 0 || int(gl_FragCoord.y)%16 == 0 ) { + sceneColor += vec4(0.5, 0, 0, 0); + } else { + sceneColor += vec4(LightGrids.Data[int(tilePos.x + tilePos.y*80)].Amount/LightSources.List.length(), 0, 0, 1); + } + */ +} + + diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index 0d08b98f..bd57df3a 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -81,7 +81,7 @@ void DrawFinalPass::InitializeShaderPrograms() m_ForwardPlusSplatMapProgram = ResourceManager::Load("#ForwardPlusSplatMapProgram"); m_ForwardPlusSplatMapProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ForwardPlus.vert.glsl"))); - m_ForwardPlusSplatMapProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ForwardPlusSplatMap.frag.glsl"))); + m_ForwardPlusSplatMapProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ForwardPlusSplatMapRGB.frag.glsl"))); m_ForwardPlusSplatMapProgram->Compile(); m_ForwardPlusSplatMapProgram->BindFragDataLocation(0, "sceneColor"); m_ForwardPlusSplatMapProgram->BindFragDataLocation(1, "bloomColor"); @@ -91,7 +91,7 @@ void DrawFinalPass::InitializeShaderPrograms() m_ExplosionEffectSplatMapProgram = ResourceManager::Load("#ExplosionEffectSplatMapProgram"); m_ExplosionEffectSplatMapProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ForwardPlus.vert.glsl"))); m_ExplosionEffectSplatMapProgram->AddShader(std::shared_ptr(new GeometryShader("Shaders/ExplosionEffect.geom.glsl"))); - m_ExplosionEffectSplatMapProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ForwardPlusSplatMap.frag.glsl"))); + m_ExplosionEffectSplatMapProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ForwardPlusSplatMapRGB.frag.glsl"))); m_ExplosionEffectSplatMapProgram->Compile(); m_ExplosionEffectSplatMapProgram->BindFragDataLocation(0, "sceneColor"); m_ExplosionEffectSplatMapProgram->BindFragDataLocation(1, "bloomColor"); @@ -119,7 +119,7 @@ void DrawFinalPass::InitializeShaderPrograms() m_ExplosionEffectSplatMapSkinnedProgram = ResourceManager::Load("#ExplosionEffectSplatMapSkinnedProgram"); m_ExplosionEffectSplatMapSkinnedProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ForwardPlusSkinned.vert.glsl"))); - m_ExplosionEffectSplatMapSkinnedProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ForwardPlusSplatMap.frag.glsl"))); + m_ExplosionEffectSplatMapSkinnedProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ForwardPlusSplatMapRGB.frag.glsl"))); m_ExplosionEffectSplatMapSkinnedProgram->Compile(); m_ExplosionEffectSplatMapSkinnedProgram->BindFragDataLocation(0, "sceneColor"); m_ExplosionEffectSplatMapSkinnedProgram->BindFragDataLocation(1, "bloomColor"); @@ -128,7 +128,7 @@ void DrawFinalPass::InitializeShaderPrograms() m_ForwardPlusSplatMapSkinnedProgram = ResourceManager::Load("#ForwardPlusSplatMapSkinnedProgram"); m_ForwardPlusSplatMapSkinnedProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/ForwardPlusSkinned.vert.glsl"))); - m_ForwardPlusSplatMapSkinnedProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ForwardPlusSplatMap.frag.glsl"))); + m_ForwardPlusSplatMapSkinnedProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ForwardPlusSplatMapRGB.frag.glsl"))); m_ForwardPlusSplatMapSkinnedProgram->Compile(); m_ForwardPlusSplatMapSkinnedProgram->BindFragDataLocation(0, "sceneColor"); m_ForwardPlusSplatMapSkinnedProgram->BindFragDataLocation(1, "bloomColor"); @@ -892,7 +892,7 @@ void DrawFinalPass::BindModelTextures(GLuint shaderHandle, std::shared_ptrDiffuseTexture.size() > i && job->DiffuseTexture[i]->Texture != nullptr) { glBindTexture(GL_TEXTURE_2D, job->DiffuseTexture[i]->Texture->m_Texture); @@ -906,7 +906,7 @@ void DrawFinalPass::BindModelTextures(GLuint shaderHandle, std::shared_ptrNormalTexture.size() > i && job->NormalTexture[i]->Texture != nullptr) { glBindTexture(GL_TEXTURE_2D, job->NormalTexture[i]->Texture->m_Texture); @@ -920,7 +920,7 @@ void DrawFinalPass::BindModelTextures(GLuint shaderHandle, std::shared_ptrSpecularTexture.size() > i && job->SpecularTexture[i]->Texture != nullptr) { glBindTexture(GL_TEXTURE_2D, job->SpecularTexture[i]->Texture->m_Texture); @@ -934,7 +934,7 @@ void DrawFinalPass::BindModelTextures(GLuint shaderHandle, std::shared_ptrIncandescenceTexture.size() > i && job->IncandescenceTexture[i]->Texture != nullptr) { glBindTexture(GL_TEXTURE_2D, job->IncandescenceTexture[i]->Texture->m_Texture); From 99747c518efec59e8270caf5b410fcdc915be44a Mon Sep 17 00:00:00 2001 From: Teejoon Date: Thu, 11 Feb 2016 18:48:07 +0100 Subject: [PATCH 214/355] commit assets --- assets | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/assets b/assets index 66e2a73b..105b22fc 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit 66e2a73bdb2c385cac37476980809cc587e2e612 +Subproject commit 105b22fc67b68993db43deec3250084ed625d893 From f79649cf9a5a80eed6699581342d34516a12172d Mon Sep 17 00:00:00 2001 From: Teejoon Date: Thu, 11 Feb 2016 19:38:43 +0100 Subject: [PATCH 215/355] Fixed material file reading bug --- src/Engine/Rendering/RawModelCustom.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Engine/Rendering/RawModelCustom.cpp b/src/Engine/Rendering/RawModelCustom.cpp index 4ebf80b6..dd6a96de 100644 --- a/src/Engine/Rendering/RawModelCustom.cpp +++ b/src/Engine/Rendering/RawModelCustom.cpp @@ -277,8 +277,8 @@ void RawModelCustom::ReadMaterialTextureProperties(RawModelCustom::TextureProper throw Resource::FailedLoadingException("Reading Material texture UVTiling failed"); } memcpy(&texture.UVRepeat[0], fileData + offset, sizeof(glm::vec2)); - offset += sizeof(glm::vec2); } + offset += sizeof(glm::vec2); } void RawModelCustom::ReadAnimationFile(std::string filePath) From fee1ed6d6d4e65e51403b5da162900c5a82fb624 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Thu, 11 Feb 2016 20:00:59 +0100 Subject: [PATCH 216/355] FIXME: Temporarily removed glow from sprite shader to prevent transparent sprite from occluding other glow --- resources/Shaders/Sprite.frag.glsl | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/resources/Shaders/Sprite.frag.glsl b/resources/Shaders/Sprite.frag.glsl index a1ff3025..9ce2bbdf 100644 --- a/resources/Shaders/Sprite.frag.glsl +++ b/resources/Shaders/Sprite.frag.glsl @@ -34,7 +34,8 @@ void main() } sceneColor = vec4(color_result.xyz, clamp(color_result.a, 0, 1)); - bloomColor = vec4(clamp((glowTexel.xyz*3) - 1.0, 0, 100), 1.0); + //bloomColor = vec4(clamp((glowTexel.xyz*3) - 1.0, 0, 100), 1.0); + bloomColor = vec4(1.0, 1.0, 1.0, 0.0); } From 5e05e51309d2eae3434c0d368710b2bec776aa71 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Thu, 11 Feb 2016 20:01:23 +0100 Subject: [PATCH 217/355] Fixed EntityFirstHitByRay not returning outDistance properly --- include/Engine/Collision/Collision.h | 4 ++-- src/Engine/Collision/Collision.cpp | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/include/Engine/Collision/Collision.h b/include/Engine/Collision/Collision.h index 5b4150d8..546d03f5 100644 --- a/include/Engine/Collision/Collision.h +++ b/include/Engine/Collision/Collision.h @@ -90,10 +90,10 @@ boost::optional AbsoluteAABBExplosionEffect(EntityWrapper& entity); //Returns the first entity hit by the input ray. entitiesPotentiallyHitSorted needs to be sorted //by their distance to the ray, e.g. result from Octree::ObjectsPossiblyHitByRay. //Returns boost::none if none was hit. outDistance will be the distance to the intersection point if the ray intersects. -boost::optional EntityFirstHitByRay(const Ray& ray, std::vector entitiesPotentiallyHitSorted, float outDistance, glm::vec3& outIntersectPos); +boost::optional EntityFirstHitByRay(const Ray& ray, std::vector entitiesPotentiallyHitSorted, float& outDistance, glm::vec3& outIntersectPos); //Returns the first entity hit by the input ray that exists in the octree. //outDistance will be the distance to the intersection point if the ray intersects. -boost::optional EntityFirstHitByRay(const Ray& ray, Octree* octree, float outDistance, glm::vec3& outIntersectPos); +boost::optional EntityFirstHitByRay(const Ray& ray, Octree* octree, float& outDistance, glm::vec3& outIntersectPos); } diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index 7b182de1..ab2098b7 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -642,7 +642,7 @@ boost::optional AbsoluteAABBExplosionEffect(EntityWrapper& entity) return aabb; } -boost::optional EntityFirstHitByRay(const Ray& ray, std::vector entitiesPotentiallyHitSorted, float outDistance, glm::vec3& outIntersectPos) +boost::optional EntityFirstHitByRay(const Ray& ray, std::vector entitiesPotentiallyHitSorted, float& outDistance, glm::vec3& outIntersectPos) { for (EntityAABB& entityBox : entitiesPotentiallyHitSorted) { if (!entityBox.Entity.HasComponent("Model")) { @@ -667,7 +667,7 @@ boost::optional EntityFirstHitByRay(const Ray& ray, std::vector EntityFirstHitByRay(const Ray& ray, Octree* octree, float outDistance, glm::vec3& outIntersectPos) +boost::optional EntityFirstHitByRay(const Ray& ray, Octree* octree, float& outDistance, glm::vec3& outIntersectPos) { std::vector outObjects; octree->ObjectsPossiblyHitByRay(ray, outObjects); From bd385a0d59a90edec4aca9beb5de614e59a4b17b Mon Sep 17 00:00:00 2001 From: viktorljung Date: Thu, 11 Feb 2016 20:15:56 +0100 Subject: [PATCH 218/355] new assets --- assets | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/assets b/assets index c56f6380..01df0799 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit c56f6380ab05c23419beafe14190013d1432e32c +Subproject commit 01df07998ba0d7ddc2e32168bd88b6adf502e094 From 8f500965d481a2621a8f4a9e5d8536f5938d9d92 Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Thu, 11 Feb 2016 20:34:25 +0100 Subject: [PATCH 219/355] Changed DamageIndicator.xml to not use a glowmap and not a depthsort. --- include/Game/Systems/DamageIndicatorSystem.h | 5 ++++- resources/Schema/Entities/DamageIndicator.xml | 5 +++-- resources/Schema/Entities/DamageIndicatorTest.xml | 8 ++------ src/Game/Systems/CapturePointHUDSystem.cpp | 3 +++ src/Game/Systems/DamageIndicatorSystem.cpp | 10 +++++++--- 5 files changed, 19 insertions(+), 12 deletions(-) diff --git a/include/Game/Systems/DamageIndicatorSystem.h b/include/Game/Systems/DamageIndicatorSystem.h index fd3ba33f..e70a69a9 100644 --- a/include/Game/Systems/DamageIndicatorSystem.h +++ b/include/Game/Systems/DamageIndicatorSystem.h @@ -13,10 +13,12 @@ #include #include +#include "Rendering/Util/CommonFunctions.h" + class DamageIndicatorSystem : public System { public: - DamageIndicatorSystem(World* world, EventBroker* eventBroker); + DamageIndicatorSystem(SystemParams params); private: EventRelay m_DamageTakenFromPlayer; @@ -26,5 +28,6 @@ private: bool OnSetCamera(const Events::SetCamera& e); EntityID m_CurrentCamera = -1; + }; #endif diff --git a/resources/Schema/Entities/DamageIndicator.xml b/resources/Schema/Entities/DamageIndicator.xml index 2d02443c..3e9e4fef 100644 --- a/resources/Schema/Entities/DamageIndicator.xml +++ b/resources/Schema/Entities/DamageIndicator.xml @@ -3,8 +3,9 @@ - Textures/TempDamageIndicator.png - Textures/TempDamageIndicator.png + Textures/DamageIndicator.png + + false diff --git a/resources/Schema/Entities/DamageIndicatorTest.xml b/resources/Schema/Entities/DamageIndicatorTest.xml index ee68da96..1155ddd5 100644 --- a/resources/Schema/Entities/DamageIndicatorTest.xml +++ b/resources/Schema/Entities/DamageIndicatorTest.xml @@ -382,14 +382,10 @@ - - Hold Pos - - 1 - + - Models/AssaultAnimated.mesh + Models/Characters/Assault/AssaultAnimations.mesh diff --git a/src/Game/Systems/CapturePointHUDSystem.cpp b/src/Game/Systems/CapturePointHUDSystem.cpp index 784c7e16..21737fbe 100644 --- a/src/Game/Systems/CapturePointHUDSystem.cpp +++ b/src/Game/Systems/CapturePointHUDSystem.cpp @@ -16,6 +16,9 @@ void CapturePointHUDSystem::Update(double dt) auto CapturePointHUDElements = m_World->GetComponents("CapturePointHUD"); auto CapturePoints = m_World->GetComponents("CapturePoint"); + if (CapturePointHUDElements == nullptr) { + return; + } for (auto& cCapturePointHUD : *CapturePointHUDElements) { int HUD_ID = cCapturePointHUD["CapturePointNumber"]; diff --git a/src/Game/Systems/DamageIndicatorSystem.cpp b/src/Game/Systems/DamageIndicatorSystem.cpp index 638307bf..93385e48 100644 --- a/src/Game/Systems/DamageIndicatorSystem.cpp +++ b/src/Game/Systems/DamageIndicatorSystem.cpp @@ -1,11 +1,15 @@ #include "Systems/DamageIndicatorSystem.h" -DamageIndicatorSystem::DamageIndicatorSystem(World* m_World, EventBroker* eventBroker) - : System(m_World, eventBroker) +DamageIndicatorSystem::DamageIndicatorSystem(SystemParams params) + : System(params) { EVENT_SUBSCRIBE_MEMBER(m_DamageTakenFromPlayer, &DamageIndicatorSystem::OnPlayerDamageTaken); //current camera EVENT_SUBSCRIBE_MEMBER(m_ESetCamera, &DamageIndicatorSystem::OnSetCamera); + + //load texture to cache + auto texture = CommonFunctions::LoadTexture("Textures/DamageIndicator.png", false); + auto entityFile = ResourceManager::Load("Schema/Entities/DamageIndicator.xml"); } bool DamageIndicatorSystem::OnPlayerDamageTaken(Events::PlayerDamage& e) @@ -58,4 +62,4 @@ bool DamageIndicatorSystem::OnPlayerDamageTaken(Events::PlayerDamage& e) bool DamageIndicatorSystem::OnSetCamera(const Events::SetCamera& e) { m_CurrentCamera = e.CameraEntity.ID; return true; -} \ No newline at end of file +} From 3a15550b57faf975d0e651199b748f933d0e49b2 Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Thu, 11 Feb 2016 21:07:47 +0100 Subject: [PATCH 220/355] maybe a good commit --- assets | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/assets b/assets index 8ffd0a99..dfa0fc61 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit 8ffd0a99b9a2e5c140307d382a25c4a470cc8f33 +Subproject commit dfa0fc61ab88456f3461779bd7c6ac97d15f6493 From fee50ba3b6e0b025c6f0ae4ec17be5153ca1b306 Mon Sep 17 00:00:00 2001 From: viktorljung Date: Thu, 11 Feb 2016 21:16:10 +0100 Subject: [PATCH 221/355] Crash fix --- src/Game/Systems/CapturePointHUDSystem.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/Game/Systems/CapturePointHUDSystem.cpp b/src/Game/Systems/CapturePointHUDSystem.cpp index 784c7e16..5369b830 100644 --- a/src/Game/Systems/CapturePointHUDSystem.cpp +++ b/src/Game/Systems/CapturePointHUDSystem.cpp @@ -17,6 +17,10 @@ void CapturePointHUDSystem::Update(double dt) auto CapturePointHUDElements = m_World->GetComponents("CapturePointHUD"); auto CapturePoints = m_World->GetComponents("CapturePoint"); + if(!CapturePointHUDElements) { + return; + } + for (auto& cCapturePointHUD : *CapturePointHUDElements) { int HUD_ID = cCapturePointHUD["CapturePointNumber"]; EntityWrapper entityHUD = EntityWrapper(m_World, cCapturePointHUD.EntityID); From afd9e24df64d0c4d7541aee9c327180ee2427fa0 Mon Sep 17 00:00:00 2001 From: stiffly Date: Thu, 11 Feb 2016 21:23:53 +0100 Subject: [PATCH 222/355] Reverted last commit. Also testing to delay OnPlayerSpawn event for clients. No progress... --- include/Engine/Network/Client.h | 2 + src/Engine/Network/Client.cpp | 29 ++++++++++++-- src/Engine/Rendering/PickingPass.cpp | 59 +++++++++++++--------------- 3 files changed, 54 insertions(+), 36 deletions(-) diff --git a/include/Engine/Network/Client.h b/include/Engine/Network/Client.h index 7ea63ad8..f2b18eee 100644 --- a/include/Engine/Network/Client.h +++ b/include/Engine/Network/Client.h @@ -35,6 +35,8 @@ public: void Connect(std::string address, int port); void Update() override; + std::vector m_PlayerSpawnEvents; + void parseSpawnEvents(); // Save for children std::unique_ptr m_SnapshotFilter = nullptr; diff --git a/src/Engine/Network/Client.cpp b/src/Engine/Network/Client.cpp index 7c19d852..d88becdb 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -54,7 +54,6 @@ void Client::Update() parseMessageType(packet); } } - while (m_Reliable.IsSocketAvailable()) { // Packet will get real data in receive Packet packet(MessageType::Invalid); @@ -177,14 +176,35 @@ void Client::parseKick() m_IsConnected = false; } +void Client::parseSpawnEvents() +{ + for (int i = 0; i < m_PlayerSpawnEvents.size(); i++) { + Events::PlayerSpawned e; + e.Player = EntityWrapper(m_World, m_ServerIDToClientID[m_PlayerSpawnEvents[i].Player.ID]); + e.Spawner = EntityWrapper(m_World, m_ServerIDToClientID[m_PlayerSpawnEvents[i].Spawner.ID]); + e.PlayerID = -1; + e.PlayerName = m_PlayerSpawnEvents[i].PlayerName; + m_EventBroker->Publish(e); + } + m_PlayerSpawnEvents.clear(); +} + void Client::parsePlayersSpawned(Packet& packet) { + //Events::PlayerSpawned e; + //e.Player = EntityWrapper(m_World, m_ServerIDToClientID[packet.ReadPrimitive()]); + //e.Spawner = EntityWrapper(m_World, m_ServerIDToClientID[packet.ReadPrimitive()]); + //e.PlayerID = -1; + //e.PlayerName = packet.ReadString(); + //m_EventBroker->Publish(e); + Events::PlayerSpawned e; - e.Player = EntityWrapper(m_World, m_ServerIDToClientID[packet.ReadPrimitive()]); - e.Spawner = EntityWrapper(m_World, m_ServerIDToClientID[packet.ReadPrimitive()]); + e.Player = EntityWrapper(m_World, packet.ReadPrimitive()); + e.Spawner = EntityWrapper(m_World, packet.ReadPrimitive()); e.PlayerID = -1; e.PlayerName = packet.ReadString(); - m_EventBroker->Publish(e); + m_PlayerSpawnEvents.push_back(e); + parseSpawnEvents(); } void Client::parseEntityDeletion(Packet & packet) @@ -322,6 +342,7 @@ void Client::parseSnapshot(Packet& packet) m_World->SetParent(localEntityID, m_ServerIDToClientID.at(serverParentID)); } } + // parseSpawnEvents(); } void Client::disconnect() diff --git a/src/Engine/Rendering/PickingPass.cpp b/src/Engine/Rendering/PickingPass.cpp index 07440749..2a0a8cf8 100644 --- a/src/Engine/Rendering/PickingPass.cpp +++ b/src/Engine/Rendering/PickingPass.cpp @@ -42,22 +42,22 @@ void PickingPass::InitializeShaderPrograms() m_PickingProgram->BindFragDataLocation(0, "TextureFragment"); m_PickingProgram->Link(); - m_PickingSkinnedProgram = ResourceManager::Load("#PickingSkinnedProgram"); + m_PickingSkinnedProgram = ResourceManager::Load("#PickingSkinnedProgram"); - m_PickingSkinnedProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/PickingSkinned.vert.glsl"))); - m_PickingSkinnedProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/Picking.frag.glsl"))); - m_PickingSkinnedProgram->Compile(); - m_PickingSkinnedProgram->BindFragDataLocation(0, "TextureFragment"); - m_PickingSkinnedProgram->Link(); + m_PickingSkinnedProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/PickingSkinned.vert.glsl"))); + m_PickingSkinnedProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/Picking.frag.glsl"))); + m_PickingSkinnedProgram->Compile(); + m_PickingSkinnedProgram->BindFragDataLocation(0, "TextureFragment"); + m_PickingSkinnedProgram->Link(); } void PickingPass::Draw(RenderScene& scene) { PickingPassState* state = new PickingPassState(m_PickingBuffer.GetHandle()); - + //TODO: Render: Add code for more jobs than modeljobs. GLuint shaderHandle = m_PickingProgram->GetHandle(); - GLuint shaderSkinnedHandle = m_PickingSkinnedProgram->GetHandle(); + GLuint shaderSkinnedHandle = m_PickingSkinnedProgram->GetHandle(); m_PickingProgram->Bind(); if (scene.ClearDepth) { @@ -92,31 +92,26 @@ void PickingPass::Draw(RenderScene& scene) m_PickingColorsToEntity[glm::ivec2(pickColor[0], pickColor[1])] = pickInfo; - if (modelJob->Model->IsSkinned()) - { - m_PickingSkinnedProgram->Bind(); - glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); - glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "V"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix())); - glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix())); - glUniform2fv(glGetUniformLocation(shaderSkinnedHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1]))); + if (modelJob->Model->IsSkinned()) { + m_PickingSkinnedProgram->Bind(); + glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); + glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "V"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix())); + glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "P"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix())); + glUniform2fv(glGetUniformLocation(shaderSkinnedHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1]))); - if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { + if (modelJob->Model->m_RawModel->m_Skeleton != nullptr) { std::vector frameBones; frameBones = modelJob->Skeleton->GetBones(); - // temp check revise later crashed client when connectiong - // frameBones.size() was 0 // Jocke - if (frameBones.size() > 0) { - glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); - } - } - } else { + glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "Bones"), frameBones.size(), GL_FALSE, glm::value_ptr(frameBones[0])); + } + } else { m_PickingProgram->Bind(); - glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); - 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())); - glUniform2fv(glGetUniformLocation(shaderHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1]))); - } + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); + 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())); + glUniform2fv(glGetUniformLocation(shaderHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1]))); + } glBindVertexArray(modelJob->Model->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer); @@ -202,7 +197,7 @@ void PickingPass::Draw(RenderScene& scene) m_PickingColorsToEntity[glm::ivec2(pickColor[0], pickColor[1])] = pickInfo; - if(modelJob->Model->IsSkinned()) { + if (modelJob->Model->IsSkinned()) { m_PickingSkinnedProgram->Bind(); glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "V"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix())); @@ -257,7 +252,7 @@ void PickingPass::Draw(RenderScene& scene) if (modelJob->Model->IsSkinned()) { m_PickingSkinnedProgram->Bind(); - + glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "M"), 1, GL_FALSE, glm::value_ptr(modelJob->Matrix)); glUniformMatrix4fv(glGetUniformLocation(shaderSkinnedHandle, "V"), 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix())); @@ -280,7 +275,7 @@ void PickingPass::Draw(RenderScene& scene) glUniform2fv(glGetUniformLocation(shaderHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1]))); } - + glBindVertexArray(modelJob->Model->VAO); @@ -288,7 +283,7 @@ void PickingPass::Draw(RenderScene& scene) glDrawElements(GL_TRIANGLES, modelJob->EndIndex - modelJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(modelJob->StartIndex * sizeof(unsigned int))); } } - + m_PickingBuffer.Unbind(); GLERROR("PickingPass Error"); From 4a17e3c8f384dc2a998d75f55baeb5a350d978cd Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Thu, 11 Feb 2016 21:42:29 +0100 Subject: [PATCH 223/355] airFriction changed to 2.0 to fix the dash ability in the air --- src/Game/Systems/PlayerMovementSystem.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Game/Systems/PlayerMovementSystem.cpp b/src/Game/Systems/PlayerMovementSystem.cpp index 93f0cd3d..bad512df 100644 --- a/src/Game/Systems/PlayerMovementSystem.cpp +++ b/src/Game/Systems/PlayerMovementSystem.cpp @@ -233,7 +233,8 @@ void PlayerMovementSystem::updateVelocity(double dt) float speed = glm::length(velocity); static float groundFriction = 7.f; ImGui::InputFloat("groundFriction", &groundFriction); - static float airFriction = 0.f; + static float airFriction = 2.f; + ImGui::InputFloat("airFriction", &airFriction); float friction = isOnGround ? groundFriction : airFriction; if (speed > 0) { From b66e3d36309da8b1dffe736ed37d22848d22525f Mon Sep 17 00:00:00 2001 From: stiffly Date: Thu, 11 Feb 2016 22:15:47 +0100 Subject: [PATCH 224/355] WIP trying to hot fix --- src/Engine/Network/Client.cpp | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/Engine/Network/Client.cpp b/src/Engine/Network/Client.cpp index d88becdb..d6aece06 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -178,15 +178,22 @@ void Client::parseKick() void Client::parseSpawnEvents() { + std::vector tempSpawn; for (int i = 0; i < m_PlayerSpawnEvents.size(); i++) { Events::PlayerSpawned e; - e.Player = EntityWrapper(m_World, m_ServerIDToClientID[m_PlayerSpawnEvents[i].Player.ID]); - e.Spawner = EntityWrapper(m_World, m_ServerIDToClientID[m_PlayerSpawnEvents[i].Spawner.ID]); + if (!serverClientMapsHasEntity(m_PlayerSpawnEvents.at(i).Player.ID) || + !serverClientMapsHasEntity(m_PlayerSpawnEvents.at(i).Spawner.ID)) { + tempSpawn.push_back(m_PlayerSpawnEvents.at(i)); + continue; + } + e.Player = EntityWrapper(m_World, m_ServerIDToClientID.at(m_PlayerSpawnEvents.at(i).Player.ID)); + e.Spawner = EntityWrapper(m_World, m_ServerIDToClientID.at(m_PlayerSpawnEvents.at(i).Spawner.ID)); e.PlayerID = -1; - e.PlayerName = m_PlayerSpawnEvents[i].PlayerName; + e.PlayerName = m_PlayerSpawnEvents.at(i).PlayerName; m_EventBroker->Publish(e); } - m_PlayerSpawnEvents.clear(); + m_PlayerSpawnEvents = tempSpawn; + // m_PlayerSpawnEvents.clear(); } void Client::parsePlayersSpawned(Packet& packet) From dd131e7652a93623baa0723a7a2967076b970df7 Mon Sep 17 00:00:00 2001 From: William Moberg Date: Thu, 11 Feb 2016 22:49:31 +0100 Subject: [PATCH 225/355] Respawning may work, not been tested over network yet. --- src/Game/Systems/PlayerSpawnSystem.cpp | 23 ++++++++--------------- 1 file changed, 8 insertions(+), 15 deletions(-) diff --git a/src/Game/Systems/PlayerSpawnSystem.cpp b/src/Game/Systems/PlayerSpawnSystem.cpp index 0d84bb5d..65184384 100644 --- a/src/Game/Systems/PlayerSpawnSystem.cpp +++ b/src/Game/Systems/PlayerSpawnSystem.cpp @@ -78,8 +78,8 @@ bool PlayerSpawnSystem::OnInputCommand(Events::InputCommand& e) } // Team picks should be processed ONLY server-side! - // Don't make a spawn request if PlayerID is -1, i.e. we're the client. - if (e.PlayerID == -1 && m_NetworkEnabled) { + // Don't make a spawn request if we're the client. + if (!IsServer && m_NetworkEnabled) { return false; } @@ -88,11 +88,10 @@ bool PlayerSpawnSystem::OnInputCommand(Events::InputCommand& e) } //TODO: Spectating? - if (e.Player.Valid() && e.Player.HasComponent("Team")) { - ComponentWrapper cTeam = e.Player["Team"]; - if ((ComponentInfo::EnumType)e.Value == cTeam["Team"].Enum("Spectator")) { - return false; - } + //Right now, return if someone picks spectator. + //1 signifies spectator here, could not get Playerteam component since it may be invalid or without team comp. + if ((ComponentInfo::EnumType)e.Value == 1) { + return false; } //Check if the player already requested spawn. @@ -131,13 +130,6 @@ bool PlayerSpawnSystem::OnPlayerSpawned(Events::PlayerSpawned& e) return false; } - // Check if a player already exists - if (m_PlayerEntities.count(e.PlayerID) != 0) { - // TODO: Disallow infinite respawning here - if (m_PlayerEntities[e.PlayerID].Valid()) { - m_World->DeleteEntity(m_PlayerEntities[e.PlayerID].ID); - } - } // Set the camera to the correct entity EntityWrapper cameraEntity = e.Player.FirstChildByName("Camera"); @@ -170,6 +162,7 @@ bool PlayerSpawnSystem::OnPlayerSpawned(Events::PlayerSpawned& e) bool PlayerSpawnSystem::OnPlayerDeath(Events::PlayerDeath& e) { + //Only spawn request if network is disabled or we are server. if (!IsServer && m_NetworkEnabled) { return false; } @@ -182,7 +175,7 @@ bool PlayerSpawnSystem::OnPlayerDeath(Events::PlayerDeath& e) return false; } SpawnRequest req; - req.PlayerID = m_PlayerIDs[e.Player.ID]; + req.PlayerID = m_PlayerIDs.at(e.Player.ID); req.Team = cTeam["Team"]; m_SpawnRequests.push_back(req); } From d1213f9f59d36d25813e8a5cd90f6106edcdd322 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Thu, 11 Feb 2016 22:50:44 +0100 Subject: [PATCH 226/355] Working damage dealing, a super cool reload effect and hit markers! --- assets | 2 +- include/Engine/Core/EPlayerDamage.h | 4 +- include/Engine/Core/EShoot.h | 3 +- .../Systems/Weapon/AssaultWeaponBehaviour.h | 12 +- include/Game/Systems/Weapon/WeaponBehaviour.h | 9 +- include/Game/Systems/Weapon/WeaponSystem.h | 2 - resources/Schema/Components/AssaultWeapon.xml | 1 + resources/Schema/Components/AssaultWeapon.xsd | 3 + resources/Schema/Entities/HitMarker.xml | 20 ++ resources/Schema/Entities/MovementTest.xml | 158 ++++++++++++- resources/Schema/Entities/Player.xml | 46 +++- .../Schema/Entities/WeaponReloadEffect.xml | 31 +++ src/Engine/Core/EntityFilePreprocessor.cpp | 1 - src/Engine/Network/Client.cpp | 3 +- src/Engine/Network/Server.cpp | 3 +- src/Game/Systems/HealthSystem.cpp | 4 +- src/Game/Systems/PlayerDeathSystem.cpp | 14 +- src/Game/Systems/SoundSystem.cpp | 2 +- src/Game/Systems/SpawnerSystem.cpp | 10 +- .../Systems/Weapon/AssaultWeaponBehaviour.cpp | 218 +++++++++++++++--- src/Game/Systems/Weapon/WeaponSystem.cpp | 60 +---- src/Tests/HealthSystemTest.cpp | 2 +- 22 files changed, 473 insertions(+), 135 deletions(-) create mode 100644 resources/Schema/Entities/HitMarker.xml create mode 100644 resources/Schema/Entities/WeaponReloadEffect.xml diff --git a/assets b/assets index 8ffd0a99..4d36fdce 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit 8ffd0a99b9a2e5c140307d382a25c4a470cc8f33 +Subproject commit 4d36fdced7007a594a56b7371bb26861876889aa diff --git a/include/Engine/Core/EPlayerDamage.h b/include/Engine/Core/EPlayerDamage.h index 8ba3907e..6f3f2c12 100644 --- a/include/Engine/Core/EPlayerDamage.h +++ b/include/Engine/Core/EPlayerDamage.h @@ -9,8 +9,8 @@ namespace Events struct PlayerDamage : Event { - //NOTE: this struct is missing information on what the damageSource is - EntityWrapper Player; + EntityWrapper Inflictor; + EntityWrapper Victim; double Damage; }; diff --git a/include/Engine/Core/EShoot.h b/include/Engine/Core/EShoot.h index 76821a24..28346abb 100644 --- a/include/Engine/Core/EShoot.h +++ b/include/Engine/Core/EShoot.h @@ -9,7 +9,8 @@ namespace Events struct Shoot : Event { - EntityWrapper Player; + EntityWrapper Inflictor; + double Damage; }; } diff --git a/include/Game/Systems/Weapon/AssaultWeaponBehaviour.h b/include/Game/Systems/Weapon/AssaultWeaponBehaviour.h index 58d7755f..915854ff 100644 --- a/include/Game/Systems/Weapon/AssaultWeaponBehaviour.h +++ b/include/Game/Systems/Weapon/AssaultWeaponBehaviour.h @@ -1,12 +1,15 @@ #include "Sound/EPlaySoundOnEntity.h" +#include "Collision/Collision.h" #include "Rendering/AnimationSystem.h" #include "WeaponBehaviour.h" #include "../SpawnerSystem.h" +#include "Core/EPlayerDamage.h" +#include "Core/EShoot.h" class AssaultWeaponBehaviour : public WeaponBehaviour { public: - AssaultWeaponBehaviour(SystemParams systemParams, Octree* collisionOctree, EntityWrapper weaponEntity); + AssaultWeaponBehaviour(SystemParams systemParams, IRenderer* renderer, Octree* collisionOctree, EntityWrapper weaponEntity); virtual void Fire() override; virtual void CeaseFire() override; @@ -19,16 +22,23 @@ private: // State bool m_Firing = false; bool m_Reloading = false; + double m_ReloadTimer = 0.0; + EntityWrapper m_ReloadImpersonator; double m_TimeSinceLastFire = 0.0; EventRelay m_EAnimationComplete; bool OnAnimationComplete(Events::AnimationComplete& e); + bool hasAmmo(); void fireRound(); void spawnTracer(); float traceRayDistance(glm::vec3 origin, glm::vec3 direction); void playSound(); void viewPunch(); + void finishReload(); void playShootAnimation(); void playIdleAnimation(); + void playReloadAnimation(); + bool shoot(double damage); + void showHitMarker(); }; diff --git a/include/Game/Systems/Weapon/WeaponBehaviour.h b/include/Game/Systems/Weapon/WeaponBehaviour.h index 38ab5f58..7a0b4626 100644 --- a/include/Game/Systems/Weapon/WeaponBehaviour.h +++ b/include/Game/Systems/Weapon/WeaponBehaviour.h @@ -2,16 +2,18 @@ #define WeaponBehaviour_h__ #include "Core/System.h" +#include "Rendering/IRenderer.h" #include "Core/Octree.h" #include "Collision/EntityAABB.h" class WeaponBehaviour : public System { public: - WeaponBehaviour(SystemParams systemParams, Octree* collisionOctree, EntityWrapper weaponEntity) + WeaponBehaviour(SystemParams systemParams, IRenderer* renderer, Octree* collisionOctree, EntityWrapper player) : System(systemParams) + , m_Renderer(renderer) , m_CollisionOctree(collisionOctree) - , m_Entity(weaponEntity) + , m_Player(player) { } virtual ~WeaponBehaviour() = default; @@ -24,8 +26,9 @@ public: virtual void Update(double dt) { } protected: + IRenderer* m_Renderer; Octree* m_CollisionOctree; - EntityWrapper m_Entity; + EntityWrapper m_Player; }; #endif diff --git a/include/Game/Systems/Weapon/WeaponSystem.h b/include/Game/Systems/Weapon/WeaponSystem.h index 68cf2ef3..b8278bc4 100644 --- a/include/Game/Systems/Weapon/WeaponSystem.h +++ b/include/Game/Systems/Weapon/WeaponSystem.h @@ -35,8 +35,6 @@ private: // Events EventRelay m_EPlayerSpawned; bool OnPlayerSpawned(Events::PlayerSpawned& e); - EventRelay m_EShoot; - bool OnShoot(Events::Shoot& e); EventRelay m_EInputCommand; bool OnInputCommand(Events::InputCommand& e); diff --git a/resources/Schema/Components/AssaultWeapon.xml b/resources/Schema/Components/AssaultWeapon.xml index c7dbfb0d..6c645624 100755 --- a/resources/Schema/Components/AssaultWeapon.xml +++ b/resources/Schema/Components/AssaultWeapon.xml @@ -7,4 +7,5 @@ 5 120 0.01 + 2 \ No newline at end of file diff --git a/resources/Schema/Components/AssaultWeapon.xsd b/resources/Schema/Components/AssaultWeapon.xsd index 65558db5..95df64b7 100755 --- a/resources/Schema/Components/AssaultWeapon.xsd +++ b/resources/Schema/Components/AssaultWeapon.xsd @@ -25,6 +25,9 @@ View punch in radians for each bullet fired + + Time it takes to reload the weapon in seconds + diff --git a/resources/Schema/Entities/HitMarker.xml b/resources/Schema/Entities/HitMarker.xml new file mode 100644 index 00000000..74a539d0 --- /dev/null +++ b/resources/Schema/Entities/HitMarker.xml @@ -0,0 +1,20 @@ + + + + + + 0.1 + + + Textures/Weapons/Crosshair/SmallThickHoleDot.png + false + + + + + + + + + + diff --git a/resources/Schema/Entities/MovementTest.xml b/resources/Schema/Entities/MovementTest.xml index 16a28684..84aaa03a 100644 --- a/resources/Schema/Entities/MovementTest.xml +++ b/resources/Schema/Entities/MovementTest.xml @@ -124,10 +124,14 @@ + + 600 + - + + - false + 5 @@ -138,8 +142,7 @@ - - + @@ -147,7 +150,7 @@ - + @@ -156,10 +159,9 @@ Fonts/DroidSans.ttf,100 - false - + @@ -170,6 +172,7 @@ Models/Widgets/Camera.mesh + false @@ -178,6 +181,100 @@ + + + + + + + + + + + 1 + + + + + Models/Core/UnitHexagon.mesh + + + + + + + + + + + + + + Textures/Weapons/Crosshair/SmallThickHoleDot.png + false + + + + + + + + + + + + + + Idle + 1.9569972344146196 + 1 + + + Models/Characters/Assault/FirstPerson.mesh + true + + + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + true + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + + + Schema/Entities/WeaponReloadEffect.xml + + + + + + + @@ -196,15 +293,52 @@ + + Idle + 1.8055945618467364 + 1 + + + AimRifle + + + - Models/Characters/Assault/AssaultHeadless.mesh + Models/Characters/Assault/AssaultAnimations.mesh - - - + - + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + false + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + diff --git a/resources/Schema/Entities/Player.xml b/resources/Schema/Entities/Player.xml index 4ba23a0d..9f8e0955 100644 --- a/resources/Schema/Entities/Player.xml +++ b/resources/Schema/Entities/Player.xml @@ -23,7 +23,9 @@ - + + + @@ -90,24 +92,33 @@ - - Models/Weapons/CrosshairQuad.mesh - + + Textures/Weapons/Crosshair/SmallThickHoleDot.png + false + - - + + + + + Schema/Entities/HitMarker.xml + + + + + Idle - 0.52743271827223559 + 0.1719161089749548 1 @@ -124,10 +135,11 @@ Models/Weapons/Blue/AssaultWeaponBlue.mesh + true - - + + @@ -144,6 +156,15 @@ + + + + Schema/Entities/WeaponReloadEffect.xml + + + + + @@ -166,7 +187,7 @@ Idle - 0.69666320633760392 + 1.8038469763698401 1 @@ -188,10 +209,11 @@ Models/Weapons/Blue/AssaultWeaponBlue.mesh + false - - + + diff --git a/resources/Schema/Entities/WeaponReloadEffect.xml b/resources/Schema/Entities/WeaponReloadEffect.xml new file mode 100644 index 00000000..3099b405 --- /dev/null +++ b/resources/Schema/Entities/WeaponReloadEffect.xml @@ -0,0 +1,31 @@ + + + + + + R_Arm_Weapon_Joint + + + 2 + + + true + + + true + + true + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + true + + + + + + + + + + diff --git a/src/Engine/Core/EntityFilePreprocessor.cpp b/src/Engine/Core/EntityFilePreprocessor.cpp index 86217979..a1370dd2 100644 --- a/src/Engine/Core/EntityFilePreprocessor.cpp +++ b/src/Engine/Core/EntityFilePreprocessor.cpp @@ -65,7 +65,6 @@ void EntityFilePreprocessor::parseComponentInfo() // Name compInfo.Name = XS::ToString(element->getName()); - bool brk = compInfo.Name == "HiddenForLocalPlayer"; // Known allocation compInfo.Meta->Allocation = m_ComponentCounts[compInfo.Name]; // Annotation diff --git a/src/Engine/Network/Client.cpp b/src/Engine/Network/Client.cpp index 7d2c8f92..b03aad07 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -390,8 +390,9 @@ bool Client::OnInputCommand(const Events::InputCommand & e) bool Client::OnPlayerDamage(const Events::PlayerDamage & e) { Packet packet(MessageType::OnPlayerDamage, m_SendPacketID); + packet.WritePrimitive(m_ClientIDToServerID.at(e.Inflictor.ID)); + packet.WritePrimitive(m_ClientIDToServerID.at(e.Victim.ID)); packet.WritePrimitive(e.Damage); - packet.WritePrimitive(m_ClientIDToServerID.at(e.Player.ID)); send(packet); return false; } diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index 7ad1cc76..1f0b3bc7 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -299,8 +299,9 @@ void Server::parseOnInputCommand(Packet& packet) void Server::parseOnPlayerDamage(Packet & packet) { Events::PlayerDamage e; + e.Inflictor = EntityWrapper(m_World, packet.ReadPrimitive()); + e.Victim = EntityWrapper(m_World, packet.ReadPrimitive()); e.Damage = packet.ReadPrimitive(); - e.Player = EntityWrapper(m_World, packet.ReadPrimitive()); m_EventBroker->Publish(e); //LOG_DEBUG("Server::parseOnPlayerDamage: Command is %s. Value is %f. PlayerID is %i.", e.DamageAmount, e.PlayerDamagedID, e.TypeOfDamage.c_str()); } diff --git a/src/Game/Systems/HealthSystem.cpp b/src/Game/Systems/HealthSystem.cpp index bb02ea13..29d8790d 100644 --- a/src/Game/Systems/HealthSystem.cpp +++ b/src/Game/Systems/HealthSystem.cpp @@ -15,13 +15,13 @@ void HealthSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& comp bool HealthSystem::OnPlayerDamaged(Events::PlayerDamage& e) { - ComponentWrapper cHealth = e.Player["Health"]; + ComponentWrapper cHealth = e.Victim["Health"]; double& health = cHealth["Health"]; health -= e.Damage; if (health <= 0.0) { Events::PlayerDeath ePlayerDeath; - ePlayerDeath.Player = e.Player; + ePlayerDeath.Player = e.Victim; m_EventBroker->Publish(ePlayerDeath); //Note: we will delete the entity in PlayerDeathSystem } diff --git a/src/Game/Systems/PlayerDeathSystem.cpp b/src/Game/Systems/PlayerDeathSystem.cpp index 29ed9832..78e20490 100644 --- a/src/Game/Systems/PlayerDeathSystem.cpp +++ b/src/Game/Systems/PlayerDeathSystem.cpp @@ -41,7 +41,9 @@ void PlayerDeathSystem::createDeathEffect(EntityWrapper player) playerEntityModel.Copy(deathEffectEW["Model"]); playerEntityAnimation.Copy(deathEffectEW["Animation"]); //freeze the animation - deathEffectEW["Animation"]["Speed"] = 0.0; + deathEffectEW["Animation"]["Speed1"] = 0.0; + deathEffectEW["Animation"]["Speed2"] = 0.0; + deathEffectEW["Animation"]["Speed3"] = 0.0; //copy the models position,orientation deathEffectEW["Transform"]["Position"] = (glm::vec3)player["Transform"]["Position"]; @@ -50,8 +52,10 @@ void PlayerDeathSystem::createDeathEffect(EntityWrapper player) //deathEffectEW["ExplosionEffect"]["ExplosionOrigin"] = glm::vec3(0, 0, 0); //camera (with lifetime) behind the player - auto cam = deathEffectEW.FirstChildByName("Camera"); - Events::SetCamera eSetCamera; - eSetCamera.CameraEntity = cam; - m_EventBroker->Publish(eSetCamera); + if (player == LocalPlayer) { + auto cam = deathEffectEW.FirstChildByName("Camera"); + Events::SetCamera eSetCamera; + eSetCamera.CameraEntity = cam; + m_EventBroker->Publish(eSetCamera); + } } diff --git a/src/Game/Systems/SoundSystem.cpp b/src/Game/Systems/SoundSystem.cpp index 10dc61f7..d6ac7dab 100644 --- a/src/Game/Systems/SoundSystem.cpp +++ b/src/Game/Systems/SoundSystem.cpp @@ -54,7 +54,7 @@ bool SoundSystem::OnInputCommand(const Events::InputCommand & e) } if (e.Command == "TakeDamage" && e.Value > 0) { Events::PlayerDamage ev; - ev.Player = LocalPlayer; + ev.Victim = LocalPlayer; ev.Damage = 1.0; m_EventBroker->Publish(ev); } diff --git a/src/Game/Systems/SpawnerSystem.cpp b/src/Game/Systems/SpawnerSystem.cpp index 99f5df93..b3c556f1 100644 --- a/src/Game/Systems/SpawnerSystem.cpp +++ b/src/Game/Systems/SpawnerSystem.cpp @@ -48,10 +48,12 @@ EntityWrapper SpawnerSystem::Spawn(EntityWrapper spawner, EntityWrapper parent / EntityFileParser parser(entityFile); EntityWrapper spawnedEntity(world, parser.MergeEntities(world, parent.ID)); - // Set its position and orientation to that of the SpawnPoint - spawnedEntity["Transform"]["Position"] = Transform::AbsolutePosition(spawnPoint.World, spawnPoint.ID); - // TODO: Quaternions, bitch - spawnedEntity["Transform"]["Orientation"] = glm::eulerAngles(Transform::AbsoluteOrientation(spawnPoint)); + if (spawnPoint != parent) { + // Set its position and orientation to that of the SpawnPoint + spawnedEntity["Transform"]["Position"] = Transform::AbsolutePosition(spawnPoint.World, spawnPoint.ID); + // TODO: Quaternions, bitch + spawnedEntity["Transform"]["Orientation"] = glm::eulerAngles(Transform::AbsoluteOrientation(spawnPoint)); + } return spawnedEntity; } diff --git a/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp b/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp index bb5a025f..724e1f2c 100644 --- a/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp +++ b/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp @@ -1,9 +1,9 @@ #include "Systems/Weapon/AssaultWeaponBehaviour.h" -AssaultWeaponBehaviour::AssaultWeaponBehaviour(SystemParams systemParams, Octree* collisionOctree, EntityWrapper weaponEntity) - : WeaponBehaviour(systemParams, collisionOctree, weaponEntity) +AssaultWeaponBehaviour::AssaultWeaponBehaviour(SystemParams systemParams, IRenderer* renderer, Octree* collisionOctree, EntityWrapper player) + : WeaponBehaviour(systemParams, renderer, collisionOctree, player) { - m_FirstPersonModel = m_Entity.FirstChildByName("Hands"); + m_FirstPersonModel = m_Player.FirstChildByName("Hands"); EVENT_SUBSCRIBE_MEMBER(m_EAnimationComplete, &AssaultWeaponBehaviour::OnAnimationComplete); } @@ -12,7 +12,6 @@ void AssaultWeaponBehaviour::Fire() m_TimeSinceLastFire = 0.0; m_Firing = true; fireRound(); - playShootAnimation(); } void AssaultWeaponBehaviour::CeaseFire() @@ -22,29 +21,48 @@ void AssaultWeaponBehaviour::CeaseFire() void AssaultWeaponBehaviour::Reload() { - ComponentWrapper& cAssaultWeapon = m_Entity["AssaultWeapon"]; + if (m_Reloading) { + return; + } - int& magAmmo = cAssaultWeapon["MagazineAmmo"]; + ComponentWrapper& cAssaultWeapon = m_Player["AssaultWeapon"]; + int magAmmo = cAssaultWeapon["MagazineAmmo"]; int magSize = cAssaultWeapon["MagazineSize"]; - int& ammo = cAssaultWeapon["Ammo"]; + int ammo = cAssaultWeapon["Ammo"]; // Don't reload if we're already fully loaded if (magAmmo == magSize) { return; } - // Throw away rounds in magazine to incentivise ammo sharing - int toLoad = glm::min(magSize, ammo); - magAmmo = toLoad; - ammo -= toLoad; + // Don't reload if we're completly out of ammo + if (ammo == 0) { + return; + } + + m_Reloading = true; + m_ReloadTimer = cAssaultWeapon["ReloadTime"]; + playReloadAnimation(); } void AssaultWeaponBehaviour::Update(double dt) { - if (m_Firing) { - m_TimeSinceLastFire += dt; + if (m_Reloading) { + m_ReloadTimer -= dt; + // Re-enable glow on reload impersonator half-way through the animation + if (m_ReloadTimer <= (double)m_Player["AssaultWeapon"]["ReloadTime"] / 2.0) { + if (m_ReloadImpersonator.Valid()) { + m_ReloadImpersonator["Model"]["GlowMap"] = true; + } + } + if (m_ReloadTimer <= 0) { + finishReload(); + } + } - ComponentWrapper& cAssaultWeapon = m_Entity["AssaultWeapon"]; + if (m_Firing && !m_Reloading) { + m_TimeSinceLastFire += dt; + ComponentWrapper& cAssaultWeapon = m_Player["AssaultWeapon"]; if (m_TimeSinceLastFire >= 1.0 / ((double)cAssaultWeapon["RPM"] / 60.0)) { fireRound(); } @@ -53,6 +71,13 @@ void AssaultWeaponBehaviour::Update(double dt) if (!m_Firing && !m_Reloading) { playIdleAnimation(); } + + // Disable glow map on weapon if it's out of ammo + // Make real first person weapon model visible again + EntityWrapper firstPersonWeaponModel = m_Player.FirstChildByName("WeaponModel"); + if (firstPersonWeaponModel.Valid()) { + firstPersonWeaponModel["Model"]["GlowMap"] = hasAmmo(); + } } bool AssaultWeaponBehaviour::OnAnimationComplete(Events::AnimationComplete& e) @@ -70,9 +95,20 @@ bool AssaultWeaponBehaviour::OnAnimationComplete(Events::AnimationComplete& e) return true; } +bool AssaultWeaponBehaviour::hasAmmo() +{ + ComponentWrapper& cAssaultWeapon = m_Player["AssaultWeapon"]; + int& magAmmo = cAssaultWeapon["MagazineAmmo"]; + return magAmmo > 0; +} + void AssaultWeaponBehaviour::fireRound() { - ComponentWrapper& cAssaultWeapon = m_Entity["AssaultWeapon"]; + if (m_Reloading) { + return; + } + + ComponentWrapper& cAssaultWeapon = m_Player["AssaultWeapon"]; int& magAmmo = cAssaultWeapon["MagazineAmmo"]; int ammo = cAssaultWeapon["Ammo"]; @@ -88,6 +124,11 @@ void AssaultWeaponBehaviour::fireRound() spawnTracer(); playSound(); viewPunch(); + playShootAnimation(); + bool hit = shoot(cAssaultWeapon["BaseDamage"]); + if (hit) { + showHitMarker(); + } m_TimeSinceLastFire = 0.0; } @@ -99,25 +140,32 @@ void AssaultWeaponBehaviour::spawnTracer() } EntityWrapper spawner; - if (m_Entity == LocalPlayer) { - spawner = m_Entity.FirstChildByName("WeaponMuzzle"); + if (m_Player == LocalPlayer) { + spawner = m_Player.FirstChildByName("WeaponMuzzle"); } else { - spawner = m_Entity.FirstChildByName("ThirdPersonWeaponMuzzle"); + spawner = m_Player.FirstChildByName("ThirdPersonWeaponMuzzle"); } if (!spawner.Valid()) { return; } - Events::SpawnerSpawn e; - e.Spawner = spawner; - m_EventBroker->Publish(e); + float distance = traceRayDistance(Transform::AbsolutePosition(spawner), Transform::AbsoluteOrientation(spawner) * glm::vec3(0, 0, -1)); + EntityWrapper ray = SpawnerSystem::Spawn(spawner); + ((glm::vec3&)ray["Transform"]["Scale"]).z = (distance / 100.f); } float AssaultWeaponBehaviour::traceRayDistance(glm::vec3 origin, glm::vec3 direction) { // TODO: Cast a ray and size tracer appropriately - return 100.f; + float distance; + glm::vec3 pos; + auto entity = Collision::EntityFirstHitByRay(Ray(origin, direction), m_CollisionOctree, distance, pos); + if (entity) { + return distance; + } else { + return 100.f; + } } void AssaultWeaponBehaviour::playSound() @@ -127,32 +175,52 @@ void AssaultWeaponBehaviour::playSound() } Events::PlaySoundOnEntity e; - e.EmitterID = m_Entity.ID; + e.EmitterID = m_Player.ID; e.FilePath = "Audio/laser/laser1.wav"; m_EventBroker->Publish(e); } void AssaultWeaponBehaviour::viewPunch() { - EntityWrapper playerCamera = m_Entity.FirstChildByName("Camera"); + EntityWrapper playerCamera = m_Player.FirstChildByName("Camera"); if (!playerCamera.Valid()) { return; } - float viewPunch = m_Entity["AssaultWeapon"]["ViewPunch"]; + float viewPunch = m_Player["AssaultWeapon"]["ViewPunch"]; ComponentWrapper cTransform = playerCamera["Transform"]; glm::vec3& orientation = cTransform["Orientation"]; orientation.x += viewPunch; } +void AssaultWeaponBehaviour::finishReload() +{ + ComponentWrapper& cAssaultWeapon = m_Player["AssaultWeapon"]; + int& magAmmo = cAssaultWeapon["MagazineAmmo"]; + int magSize = cAssaultWeapon["MagazineSize"]; + int& ammo = cAssaultWeapon["Ammo"]; + + // Throw away rounds in magazine to incentivise ammo sharing + int toLoad = glm::min(magSize, ammo); + magAmmo = toLoad; + ammo -= toLoad; + + // Make real first person weapon model visible again + EntityWrapper firstPersonWeaponModel = m_Player.FirstChildByName("WeaponModel"); + firstPersonWeaponModel["Model"]["Visible"] = true; + + m_Reloading = false; +} + void AssaultWeaponBehaviour::playShootAnimation() { - EntityWrapper firstPersonWeapon = m_Entity.FirstChildByName("Hands"); - ComponentWrapper cAnimation = firstPersonWeapon["Animation"]; - cAnimation["AnimationName1"] = "ShootRifle"; - cAnimation["Weight1"] = 1.0; - cAnimation["Time1"] = 0.0; - cAnimation["Speed1"] = 1.0; - cAnimation["Loop1"] = true; + ComponentWrapper cAnimation = m_FirstPersonModel["Animation"]; + if (cAnimation["AnimationName1"] != "ShootRifle") { + cAnimation["AnimationName1"] = "ShootRifle"; + cAnimation["Weight1"] = 1.0; + cAnimation["Time1"] = 0.0; + cAnimation["Speed1"] = 1.0; + cAnimation["Loop1"] = true; + } } void AssaultWeaponBehaviour::playIdleAnimation() @@ -168,11 +236,11 @@ void AssaultWeaponBehaviour::playIdleAnimation() std::string animationToPlay = "Idle"; double speedToSet = 1.0; - ComponentWrapper cPlayer = m_Entity["Player"]; + ComponentWrapper cPlayer = m_Player["Player"]; glm::vec3 movementDirection = cPlayer["CurrentWishDirection"]; if (glm::length2(movementDirection) > 0) { animationToPlay = "Run"; - ComponentWrapper cPhysics = m_Entity["Physics"]; + ComponentWrapper cPhysics = m_Player["Physics"]; speedToSet = glm::length((glm::vec3)cPhysics["Velocity"]) / (float)cPlayer["MovementSpeed"]; } @@ -188,3 +256,85 @@ void AssaultWeaponBehaviour::playIdleAnimation() } } +void AssaultWeaponBehaviour::playReloadAnimation() +{ + // Play animation + ComponentWrapper cAnimation = m_FirstPersonModel["Animation"]; + cAnimation["AnimationName1"] = "ReloadSwitch"; + cAnimation["Weight1"] = 1.0; + cAnimation["Time1"] = 0.0; + cAnimation["Speed1"] = 0.5; + cAnimation["Loop1"] = true; + + // Hide weapon model and spawn the exploding version + EntityWrapper firstPersonWeaponModel = m_Player.FirstChildByName("WeaponModel"); + EntityWrapper reloadSpawner = m_Player.FirstChildByName("FirstPersonReloadSpawner"); + m_ReloadImpersonator = SpawnerSystem::Spawn(reloadSpawner, reloadSpawner); + firstPersonWeaponModel["Model"].Copy(m_ReloadImpersonator["Model"]); + firstPersonWeaponModel["Model"]["Visible"] = false; +} + +bool AssaultWeaponBehaviour::shoot(double damage) +{ + // Only do shooting clientside + if (!IsClient) { + return false; + } + + // Only handle shooting for the local player + if (m_Player != LocalPlayer) { + return false; + } + + // Make sure the player isn't shooting from the grave + if (!m_Player.Valid()) { + return false; + } + + // Screen center, based on current resolution! + Rectangle screenResolution = m_Renderer->GetViewportSize(); + glm::vec2 centerScreen = glm::vec2(screenResolution.Width / 2, screenResolution.Height / 2); + + // Pick middle of screen + PickData pickData = m_Renderer->Pick(centerScreen); + if (pickData.Entity == EntityID_Invalid) { + return false; + } + + EntityWrapper victim(m_World, pickData.Entity); + + // Don't let us shoot ourselves in the foot + if (victim == LocalPlayer) { + return false; + } + + // Only care about players being hit + if (!victim.HasComponent("Player")) { + victim = victim.FirstParentWithComponent("Player"); + } + if (!victim.Valid()) { + return false; + } + + // Check for friendly fire + if ((ComponentInfo::EnumType)victim["Team"]["Team"] == (ComponentInfo::EnumType)m_Player["Team"]["Team"]) { + return false; + } + + // Deal damage! + Events::PlayerDamage ePlayerDamage; + ePlayerDamage.Victim = victim; + ePlayerDamage.Damage = damage; + m_EventBroker->Publish(ePlayerDamage); + + return true; +} + +void AssaultWeaponBehaviour::showHitMarker() +{ + // Show hit marker + EntityWrapper hitMarkerSpawner = m_Player.FirstChildByName("HitMarkerSpawner"); + if (hitMarkerSpawner.Valid()) { + SpawnerSystem::Spawn(hitMarkerSpawner, hitMarkerSpawner); + } +} diff --git a/src/Game/Systems/Weapon/WeaponSystem.cpp b/src/Game/Systems/Weapon/WeaponSystem.cpp index bdd27ea9..34d5fd43 100644 --- a/src/Game/Systems/Weapon/WeaponSystem.cpp +++ b/src/Game/Systems/Weapon/WeaponSystem.cpp @@ -8,7 +8,6 @@ WeaponSystem::WeaponSystem(SystemParams params, IRenderer* renderer, OctreeReload(); + } + } + return true; } @@ -69,7 +76,7 @@ void WeaponSystem::selectWeapon(EntityWrapper player, ComponentInfo::EnumType sl if (slot == 1) { // TODO: if class... if (m_ActiveWeapons.count(player) == 0) { - m_ActiveWeapons.insert(std::make_pair(player, std::make_shared(m_SystemParams, m_CollisionOctree, player))); + m_ActiveWeapons.insert(std::make_pair(player, std::make_shared(m_SystemParams, m_Renderer, m_CollisionOctree, player))); } else { //m_ActiveWeapons.erase(player); } @@ -87,52 +94,3 @@ bool WeaponSystem::OnPlayerSpawned(Events::PlayerSpawned& e) // TODO: Select the active one specified by player component return true; } - -bool WeaponSystem::OnShoot(Events::Shoot& eShoot) -{ - if (!eShoot.Player.Valid()) { - return false; - } - - // Only run further picking code for the local player! - if (eShoot.Player != LocalPlayer) { - return false; - } - - // Screen center, based on current resolution! - // TODO: check if player has enough ammo and if weapon has a cooldown or not - Rectangle screenResolution = m_Renderer->GetViewportSize(); - glm::vec2 centerScreen = glm::vec2(screenResolution.Width / 2, screenResolution.Height / 2); - - // TODO: check if player has enough ammo and if weapon has a cooldown or not - - // Pick middle of screen - PickData pickData = m_Renderer->Pick(centerScreen); - if (pickData.Entity == EntityID_Invalid) { - return false; - } - - EntityWrapper player(m_World, pickData.Entity); - - // Only care about players being hit - if (!player.HasComponent("Player")) { - player = player.FirstParentWithComponent("Player"); - } - if (!player.Valid()) { - return false; - } - - // Check for friendly fire - EntityWrapper shooter = eShoot.Player; - if ((ComponentInfo::EnumType)player["Team"]["Team"] == (ComponentInfo::EnumType)shooter["Team"]["Team"]) { - return false; - } - - // TODO: Weapon damage calculations etc - Events::PlayerDamage ePlayerDamage; - ePlayerDamage.Player = player; - ePlayerDamage.Damage = 100; - m_EventBroker->Publish(ePlayerDamage); - - return true; -} \ No newline at end of file diff --git a/src/Tests/HealthSystemTest.cpp b/src/Tests/HealthSystemTest.cpp index 36608f8f..8bf16024 100644 --- a/src/Tests/HealthSystemTest.cpp +++ b/src/Tests/HealthSystemTest.cpp @@ -71,7 +71,7 @@ GameHealthSystemTest::GameHealthSystemTest() //damage player with 50 Events::PlayerDamage e; e.Damage = 50.0f; - e.Player = EntityWrapper(m_World, player.EntityID); + e.Victim = EntityWrapper(m_World, player.EntityID); m_EventBroker->Publish(e); //heal some other player with 40 From 1bb1a1445ee23982189736389ed6edd6cbf094ed Mon Sep 17 00:00:00 2001 From: Teejoon Date: Thu, 11 Feb 2016 22:51:39 +0100 Subject: [PATCH 227/355] Commit assets --- assets | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/assets b/assets index 105b22fc..4d36fdce 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit 105b22fc67b68993db43deec3250084ed625d893 +Subproject commit 4d36fdced7007a594a56b7371bb26861876889aa From c1860ae383faacdce63f2b374f5c9c645bdbde8b Mon Sep 17 00:00:00 2001 From: viktorljung Date: Thu, 11 Feb 2016 23:38:25 +0100 Subject: [PATCH 228/355] AmmunitionHUD now working --- include/Game/Systems/HealthHUDSystem - Copy.h | 17 ++ .../{PlayerHUDSystem.h => HealthHUDSystem.h} | 6 +- resources/Schema/Components.xsd | 1 + resources/Schema/Components/AmmunitionHUD.xml | 3 + resources/Schema/Components/AmmunitionHUD.xsd | 10 + ...PointHUDGroup => CapturePointHUDGroup.xml} | 0 resources/Schema/Entities/Player.xml | 235 ++++++++++++++++-- resources/Schema/Types/Entity.xsd | 1 + src/Game/Game.cpp | 7 +- ...layerHUDSystem.cpp => HealthHUDSystem.cpp} | 8 +- 10 files changed, 263 insertions(+), 25 deletions(-) create mode 100644 include/Game/Systems/HealthHUDSystem - Copy.h rename include/Game/Systems/{PlayerHUDSystem.h => HealthHUDSystem.h} (57%) create mode 100644 resources/Schema/Components/AmmunitionHUD.xml create mode 100644 resources/Schema/Components/AmmunitionHUD.xsd rename resources/Schema/Entities/{CapturePointHUDGroup => CapturePointHUDGroup.xml} (100%) rename src/Game/Systems/{PlayerHUDSystem.cpp => HealthHUDSystem.cpp} (85%) diff --git a/include/Game/Systems/HealthHUDSystem - Copy.h b/include/Game/Systems/HealthHUDSystem - Copy.h new file mode 100644 index 00000000..b22a85b5 --- /dev/null +++ b/include/Game/Systems/HealthHUDSystem - Copy.h @@ -0,0 +1,17 @@ +#ifndef AmmunitionHUDSystem_h__ +#define AmmunitionHUDSystem_h__ + +#include "../../Engine/Core/System.h" +#include "../../Engine/GLM.h" + +class AmmunitionHUDSystem : public ImpureSystem +{ +public: + AmmunitionHUDSystem(SystemParams params) + : System(params) + { } + + virtual void Update(double dt) override; +}; + +#endif \ No newline at end of file diff --git a/include/Game/Systems/PlayerHUDSystem.h b/include/Game/Systems/HealthHUDSystem.h similarity index 57% rename from include/Game/Systems/PlayerHUDSystem.h rename to include/Game/Systems/HealthHUDSystem.h index 50b6a258..49a40041 100644 --- a/include/Game/Systems/PlayerHUDSystem.h +++ b/include/Game/Systems/HealthHUDSystem.h @@ -3,13 +3,11 @@ #include "../../Engine/Core/System.h" #include "../../Engine/GLM.h" -#include "../../Engine/Rendering/ESetCamera.h" -#include -class PlayerHUDSystem : public ImpureSystem +class HealthHUDSystem : public ImpureSystem { public: - PlayerHUDSystem(SystemParams params) + HealthHUDSystem(SystemParams params) : System(params) { } diff --git a/resources/Schema/Components.xsd b/resources/Schema/Components.xsd index f950e8c8..2a1b67e0 100644 --- a/resources/Schema/Components.xsd +++ b/resources/Schema/Components.xsd @@ -39,4 +39,5 @@ + \ No newline at end of file diff --git a/resources/Schema/Components/AmmunitionHUD.xml b/resources/Schema/Components/AmmunitionHUD.xml new file mode 100644 index 00000000..63b86150 --- /dev/null +++ b/resources/Schema/Components/AmmunitionHUD.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/resources/Schema/Components/AmmunitionHUD.xsd b/resources/Schema/Components/AmmunitionHUD.xsd new file mode 100644 index 00000000..1a48d8d1 --- /dev/null +++ b/resources/Schema/Components/AmmunitionHUD.xsd @@ -0,0 +1,10 @@ + + + + + + + Hud element for tracking ammunition from parent with AssaultWeapon component. Child with the name "MagazineAmmo" tracks clip ammunition. Child with the name "Ammo" tracks ammo. + + + \ No newline at end of file diff --git a/resources/Schema/Entities/CapturePointHUDGroup b/resources/Schema/Entities/CapturePointHUDGroup.xml similarity index 100% rename from resources/Schema/Entities/CapturePointHUDGroup rename to resources/Schema/Entities/CapturePointHUDGroup.xml diff --git a/resources/Schema/Entities/Player.xml b/resources/Schema/Entities/Player.xml index 4ba23a0d..8a5a4d24 100644 --- a/resources/Schema/Entities/Player.xml +++ b/resources/Schema/Entities/Player.xml @@ -12,9 +12,7 @@ - - - + 5 @@ -73,17 +71,17 @@ 1 - + + + Textures/Core/UnitHexagon.png + + - - Models/Core/UnitHexagon.mesh - - - + @@ -101,13 +99,182 @@ + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + 2 + + + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + 3 + + + 0.80222018197612788 + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + 4 + + + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + 1 + + + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + Idle - 0.52743271827223559 + 0.14471987707210765 1 @@ -126,8 +293,8 @@ Models/Weapons/Blue/AssaultWeaponBlue.mesh - - + + @@ -142,6 +309,44 @@ + + + + + + + + + + + + + 32 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + 360 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + @@ -166,7 +371,7 @@ Idle - 0.69666320633760392 + 1.7139414005989018 1 @@ -190,8 +395,8 @@ Models/Weapons/Blue/AssaultWeaponBlue.mesh - - + + diff --git a/resources/Schema/Types/Entity.xsd b/resources/Schema/Types/Entity.xsd index ffe3421a..3e521007 100644 --- a/resources/Schema/Types/Entity.xsd +++ b/resources/Schema/Types/Entity.xsd @@ -43,6 +43,7 @@ + diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index 8ee6dbed..cd8abb87 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -17,12 +17,14 @@ #include "Game/Systems/DamageIndicatorSystem.h" #include "Game/Systems/WeaponSystem.h" #include "Rendering/AnimationSystem.h" -#include "Game/Systems/PlayerHUDSystem.h" +#include "Game/Systems/HealthHUDSystem.h" #include "Rendering/BoneAttachmentSystem.h" #include "Game/Systems/LifetimeSystem.h" #include "../Engine/Core/UniformScaleSystem.h" #include "Rendering/AnimationSystem.h" #include "Network/MultiplayerSnapshotFilter.h" +#include "Game/Systems/AmmunitionHUDSystem.h" + Game::Game(int argc, char* argv[]) { @@ -125,6 +127,7 @@ Game::Game(int argc, char* argv[]) m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); + m_SystemPipeline->AddSystem(updateOrderLevel); // Populate Octree with collidables ++updateOrderLevel; m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeCollision, "Collidable"); @@ -132,7 +135,7 @@ Game::Game(int argc, char* argv[]) m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeFrustrumCulling); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); - m_SystemPipeline->AddSystem(updateOrderLevel); + m_SystemPipeline->AddSystem(updateOrderLevel); // Collision and TriggerSystem should update after player. ++updateOrderLevel; m_SystemPipeline->AddSystem(updateOrderLevel); diff --git a/src/Game/Systems/PlayerHUDSystem.cpp b/src/Game/Systems/HealthHUDSystem.cpp similarity index 85% rename from src/Game/Systems/PlayerHUDSystem.cpp rename to src/Game/Systems/HealthHUDSystem.cpp index 898d8bea..49b2d0c1 100644 --- a/src/Game/Systems/PlayerHUDSystem.cpp +++ b/src/Game/Systems/HealthHUDSystem.cpp @@ -1,6 +1,6 @@ -#include "Game/Systems/PlayerHUDSystem.h" +#include "Game/Systems/HealthHUDSystem.h" -void PlayerHUDSystem::Update(double dt) +void HealthHUDSystem::Update(double dt) { auto healthHUDs = m_World->GetComponents("HealthHUD"); if (healthHUDs == nullptr) { @@ -27,13 +27,13 @@ void PlayerHUDSystem::Update(double dt) s = s + "/"; s = s + std::to_string((int)(double)entityIDParent["Health"]["MaxHealth"]); float healthPercentage = (double)entityIDParent["Health"]["Health"]/(double)entityIDParent["Health"]["MaxHealth"]; - (glm::vec4&)entity["Text"]["Color"] = glm::vec4(1.0 - healthPercentage, 0.f, healthPercentage, 1.f); + (glm::vec4&)entity["Text"]["Color"] = glm::vec4(1.0 - healthPercentage, 0.f, healthPercentage, glm::vec4(entity["Fill"]["Color"]).a); entity["Text"]["Content"] = s; } if(entity.HasComponent("Fill")) { float healthPercentage = (double)entityIDParent["Health"]["Health"]/(double)entityIDParent["Health"]["MaxHealth"]; - (glm::vec4&)entity["Fill"]["Color"] = glm::vec4(1.0 - healthPercentage, 0.f, healthPercentage, 0.f); + (glm::vec4&)entity["Fill"]["Color"] = glm::vec4(1.0 - healthPercentage, 0.f, healthPercentage, glm::vec4(entity["Fill"]["Color"]).a); (double&)entity["Fill"]["Percentage"] = healthPercentage; } From 44a73ef88376cf22665e4189069aa5d484ae383d Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Thu, 11 Feb 2016 23:44:20 +0100 Subject: [PATCH 229/355] fixup! Merge remote-tracking branch 'origin/master' into WeaponSystem --- include/Game/Systems/DamageIndicatorSystem.h | 4 ++-- src/Game/Systems/DamageIndicatorSystem.cpp | 18 +++++++++++------- .../Systems/Weapon/AssaultWeaponBehaviour.cpp | 1 + src/Game/Systems/Weapon/WeaponSystem.cpp | 4 +--- 4 files changed, 15 insertions(+), 12 deletions(-) diff --git a/include/Game/Systems/DamageIndicatorSystem.h b/include/Game/Systems/DamageIndicatorSystem.h index e70a69a9..053b196b 100644 --- a/include/Game/Systems/DamageIndicatorSystem.h +++ b/include/Game/Systems/DamageIndicatorSystem.h @@ -21,8 +21,8 @@ public: DamageIndicatorSystem(SystemParams params); private: - EventRelay m_DamageTakenFromPlayer; - bool OnPlayerDamageTaken(Events::PlayerDamage& e); + EventRelay m_EPlayerDamage; + bool OnPlayerDamage(Events::PlayerDamage& e); EventRelay m_ESetCamera; bool OnSetCamera(const Events::SetCamera& e); diff --git a/src/Game/Systems/DamageIndicatorSystem.cpp b/src/Game/Systems/DamageIndicatorSystem.cpp index 93385e48..a29309b5 100644 --- a/src/Game/Systems/DamageIndicatorSystem.cpp +++ b/src/Game/Systems/DamageIndicatorSystem.cpp @@ -3,7 +3,7 @@ DamageIndicatorSystem::DamageIndicatorSystem(SystemParams params) : System(params) { - EVENT_SUBSCRIBE_MEMBER(m_DamageTakenFromPlayer, &DamageIndicatorSystem::OnPlayerDamageTaken); + EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &DamageIndicatorSystem::OnPlayerDamage); //current camera EVENT_SUBSCRIBE_MEMBER(m_ESetCamera, &DamageIndicatorSystem::OnSetCamera); @@ -12,23 +12,27 @@ DamageIndicatorSystem::DamageIndicatorSystem(SystemParams params) auto entityFile = ResourceManager::Load("Schema/Entities/DamageIndicator.xml"); } -bool DamageIndicatorSystem::OnPlayerDamageTaken(Events::PlayerDamage& e) +bool DamageIndicatorSystem::OnPlayerDamage(Events::PlayerDamage& e) { - if (m_CurrentCamera == -1) { + if (m_CurrentCamera == EntityID_Invalid) { + return false; + } + + if (e.Victim != LocalPlayer) { return false; } //grab players direction - auto playerOrientation = glm::quat((glm::vec3)e.Player["Transform"]["Orientation"]); + auto playerOrientation = glm::quat((glm::vec3)e.Victim["Transform"]["Orientation"]); //get the position vectors, but ignore the y-height - auto enemyPosition = (glm::vec3) e.PlayerShooter["Transform"]["Position"]; - auto playerPosition = (glm::vec3) e.Player["Transform"]["Position"]; + auto enemyPosition = (glm::vec3)e.Inflictor["Transform"]["Position"]; + auto playerPosition = (glm::vec3)e.Victim["Transform"]["Position"]; enemyPosition.y = 0.0f; playerPosition.y = 0.0f; //calculate the enemy to player vector - auto enemyPlayerVector = glm::normalize((glm::vec3) playerPosition - enemyPosition); + auto enemyPlayerVector = glm::normalize(playerPosition - enemyPosition); //get angle from players current rotation, this angle is how much you rotate around the y-axis auto playerAngle = glm::angle(playerOrientation); diff --git a/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp b/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp index 724e1f2c..54c3a590 100644 --- a/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp +++ b/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp @@ -323,6 +323,7 @@ bool AssaultWeaponBehaviour::shoot(double damage) // Deal damage! Events::PlayerDamage ePlayerDamage; + ePlayerDamage.Inflictor = m_Player; ePlayerDamage.Victim = victim; ePlayerDamage.Damage = damage; m_EventBroker->Publish(ePlayerDamage); diff --git a/src/Game/Systems/Weapon/WeaponSystem.cpp b/src/Game/Systems/Weapon/WeaponSystem.cpp index 4a25b811..3a49ae90 100644 --- a/src/Game/Systems/Weapon/WeaponSystem.cpp +++ b/src/Game/Systems/Weapon/WeaponSystem.cpp @@ -93,6 +93,4 @@ bool WeaponSystem::OnPlayerSpawned(Events::PlayerSpawned& e) // Select primary weapon on player spawn // TODO: Select the active one specified by player component return true; -} - - ePlayerDamage.PlayerShooter = eShoot.Player; \ No newline at end of file +} \ No newline at end of file From b761439c843bb85ab189f9432b5ac1881f78683c Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Thu, 11 Feb 2016 23:45:30 +0100 Subject: [PATCH 230/355] Added config flag Debug.OutOfBodyExperience that allows you to spawn and view a player from a third person perspective, without the active camera being changed. --- include/Engine/Rendering/RenderSystem.h | 4 +++ resources/DefaultConfig.ini | 2 ++ src/Engine/Rendering/RenderSystem.cpp | 40 +++++++++++++++---------- src/Game/Systems/PlayerSpawnSystem.cpp | 3 +- tools/deploy.bat | 2 ++ 5 files changed, 34 insertions(+), 17 deletions(-) diff --git a/include/Engine/Rendering/RenderSystem.h b/include/Engine/Rendering/RenderSystem.h index d73d8680..7580d654 100644 --- a/include/Engine/Rendering/RenderSystem.h +++ b/include/Engine/Rendering/RenderSystem.h @@ -18,6 +18,7 @@ #include "../Core/EPlayerSpawned.h" #include "../Core/Octree.h" #include "../Collision/EntityAABB.h" +#include "../Core/ConfigFile.h" class RenderSystem : public ImpureSystem { @@ -48,6 +49,9 @@ private: void fillDirectionalLights(std::list>& jobs, World* world); void fillLight(std::list>& jobs); void fillSprites(std::list>& jobs, World* world); + + bool isEntityVisible(EntityWrapper& entity); + bool isChildOfACamera(EntityWrapper entity); bool isChildOfCurrentCamera(EntityWrapper entity); }; diff --git a/resources/DefaultConfig.ini b/resources/DefaultConfig.ini index 12ec06c8..6911632f 100644 --- a/resources/DefaultConfig.ini +++ b/resources/DefaultConfig.ini @@ -4,6 +4,8 @@ LoadMap= ; if true -> Pool allocation is not used when calling Allocate/Free, just use regular dynamic allocation. ; if false -> Use pool allocation. DisableMemoryPool=false +EditorEnabled=false +OutOfBodyExperience=false [Editor] CameraSpeed=3 diff --git a/src/Engine/Rendering/RenderSystem.cpp b/src/Engine/Rendering/RenderSystem.cpp index 6600bc4f..7beb85db 100644 --- a/src/Engine/Rendering/RenderSystem.cpp +++ b/src/Engine/Rendering/RenderSystem.cpp @@ -47,16 +47,8 @@ void RenderSystem::fillSprites(std::list>& jobs, Worl continue; } - EntityWrapper entity(world, cSprite.EntityID); - - // Only render children of a camera if that camera is currently active - if (isChildOfACamera(entity) && !isChildOfCurrentCamera(entity)) { - continue; - } - - // Hide things parented to local player if they have the HiddenFromLocalPlayer component - if (entity.HasComponent("HiddenForLocalPlayer") && (entity == m_LocalPlayer || entity.IsChildOf(m_LocalPlayer))) { + if (!isEntityVisible(entity)) { continue; } @@ -85,6 +77,23 @@ void RenderSystem::fillSprites(std::list>& jobs, Worl } } +bool RenderSystem::isEntityVisible(EntityWrapper& entity) +{ + + // Only render children of a camera if that camera is currently active + if (isChildOfACamera(entity) && !isChildOfCurrentCamera(entity)) { + return false; + } + + // Hide things parented to local player if they have the HiddenFromLocalPlayer component + bool outOfBodyExperience = ResourceManager::Load("Config.ini")->Get("Debug.OutOfBodyExperience", false); + if (entity.HasComponent("HiddenForLocalPlayer") && (entity == m_LocalPlayer || entity.IsChildOf(m_LocalPlayer)) && !outOfBodyExperience) { + return false; + } + + return true; +} + bool RenderSystem::isChildOfACamera(EntityWrapper entity) { return entity.FirstParentWithComponent("Camera").Valid(); @@ -112,13 +121,7 @@ void RenderSystem::fillModels(RenderScene::Queues &Jobs) continue; } - // Only render children of a camera if that camera is currently active - if (isChildOfACamera(entity) && !isChildOfCurrentCamera(entity)) { - continue; - } - - // Hide things parented to local player if they have the HiddenFromLocalPlayer component - if ((entity.HasComponent("HiddenForLocalPlayer") || entity.FirstParentWithComponent("HiddenForLocalPlayer").Valid()) && (entity == m_LocalPlayer || entity.IsChildOf(m_LocalPlayer))) { + if (!isEntityVisible(entity)) { continue; } @@ -299,6 +302,11 @@ void RenderSystem::fillText(std::list>& jobs, World* continue; } + EntityWrapper entity(world, textComponent.EntityID); + if (!isEntityVisible(entity)) { + continue; + } + Font* font; try { font = ResourceManager::Load(resource); diff --git a/src/Game/Systems/PlayerSpawnSystem.cpp b/src/Game/Systems/PlayerSpawnSystem.cpp index 507ed0f5..444fc08f 100644 --- a/src/Game/Systems/PlayerSpawnSystem.cpp +++ b/src/Game/Systems/PlayerSpawnSystem.cpp @@ -88,7 +88,8 @@ bool PlayerSpawnSystem::OnPlayerSpawned(Events::PlayerSpawned& e) // Set the camera to the correct entity EntityWrapper cameraEntity = e.Player.FirstChildByName("Camera"); - if (cameraEntity.Valid()) { + bool outOfBodyExperience = ResourceManager::Load("Config.ini")->Get("Debug.OutOfBodyExperience", false); + if (cameraEntity.Valid() && !outOfBodyExperience) { Events::SetCamera e; e.CameraEntity = cameraEntity; m_EventBroker->Publish(e); diff --git a/tools/deploy.bat b/tools/deploy.bat index 29dc9e62..cd7a44bc 100755 --- a/tools/deploy.bat +++ b/tools/deploy.bat @@ -22,7 +22,9 @@ MKLINK "%DeployLocation%\Schema\" "resources\Schema" /J RMDIR /S /Q "%DeployLocation%\Shaders" MKLINK "%DeployLocation%\Shaders\" "resources\Shaders" /J :: Configuration files +DEL "%DeployLocation%\DefaultConfig.ini" MKLINK "%DeployLocation%\DefaultConfig.ini" "resources\DefaultConfig.ini" /H +DEL "%DeployLocation%\DefaultInput.ini" MKLINK "%DeployLocation%\DefaultInput.ini" "resources\DefaultInput.ini" /H :: Platform specific binaries From 30f454e6a44d31de85cfd87b64f701f970bd491a Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Thu, 11 Feb 2016 23:50:57 +0100 Subject: [PATCH 231/355] Entity fixes --- resources/Schema/Entities/PlayerDeathExplosionWithCamera.xml | 4 +--- resources/Schema/Types/Entity.xsd | 1 + 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/resources/Schema/Entities/PlayerDeathExplosionWithCamera.xml b/resources/Schema/Entities/PlayerDeathExplosionWithCamera.xml index 8a9f5e5b..3ec16e4e 100644 --- a/resources/Schema/Entities/PlayerDeathExplosionWithCamera.xml +++ b/resources/Schema/Entities/PlayerDeathExplosionWithCamera.xml @@ -2,9 +2,7 @@ - - Hold Pos - + 2.5 diff --git a/resources/Schema/Types/Entity.xsd b/resources/Schema/Types/Entity.xsd index ffe3421a..b8a863e2 100644 --- a/resources/Schema/Types/Entity.xsd +++ b/resources/Schema/Types/Entity.xsd @@ -43,6 +43,7 @@ + From e24a84c52d87591d58d848a9c229dfc0f73911f1 Mon Sep 17 00:00:00 2001 From: stiffly Date: Thu, 11 Feb 2016 23:52:55 +0100 Subject: [PATCH 232/355] Server now deletes the player on a new player spawn. --- src/Engine/Network/Client.cpp | 5 +++-- src/Game/Systems/PlayerSpawnSystem.cpp | 9 ++++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/Engine/Network/Client.cpp b/src/Engine/Network/Client.cpp index d6aece06..d75b8412 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -287,7 +287,8 @@ void Client::parseSnapshot(Packet& packet) for (std::size_t i = 0; i < numInputCommands; ++i) { Events::InputCommand e; e.PlayerID = packet.ReadPrimitive(); - e.Player = EntityWrapper(m_World, m_ServerIDToClientID.at(packet.ReadPrimitive())); + EntityID player = packet.ReadPrimitive(); + e.Player = EntityWrapper(m_World, m_ServerIDToClientID.at(player)); e.Command = packet.ReadString(); e.Value = packet.ReadPrimitive(); m_EventBroker->Publish(e); @@ -349,7 +350,7 @@ void Client::parseSnapshot(Packet& packet) m_World->SetParent(localEntityID, m_ServerIDToClientID.at(serverParentID)); } } - // parseSpawnEvents(); + parseSpawnEvents(); } void Client::disconnect() diff --git a/src/Game/Systems/PlayerSpawnSystem.cpp b/src/Game/Systems/PlayerSpawnSystem.cpp index 507ed0f5..e2775280 100644 --- a/src/Game/Systems/PlayerSpawnSystem.cpp +++ b/src/Game/Systems/PlayerSpawnSystem.cpp @@ -71,18 +71,17 @@ bool PlayerSpawnSystem::OnInputCommand(const Events::InputCommand& e) bool PlayerSpawnSystem::OnPlayerSpawned(Events::PlayerSpawned& e) { // When a player is actually spawned (since the actual spawning is handled on the server) - if (!IsClient) { - return false; - } - // Check if a player already exists + // Hack should be moved. if (m_PlayerEntities.count(e.PlayerID) != 0) { // TODO: Disallow infinite respawning here if (m_PlayerEntities[e.PlayerID].Valid()) { m_World->DeleteEntity(m_PlayerEntities[e.PlayerID].ID); } } - + if (!IsClient) { + return false; + } // Store the player for future reference m_PlayerEntities[e.PlayerID] = e.Player; From af30e515641711dc83e8c4ad42b3f0da68279d97 Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Thu, 11 Feb 2016 23:56:40 +0100 Subject: [PATCH 233/355] Added AmmoPickupSystem with Component, Entity. Changed so PlayerDeathSystem gets updated after Health/Ammo systems, credits to William. --- include/Engine/Core/EAmmoPickup.h | 18 ++ include/Game/Systems/AmmoPickupSystem.h | 32 ++ resources/Schema/Components.xsd | 1 + resources/Schema/Components/AmmoPickup.xml | 5 + resources/Schema/Components/AmmoPickup.xsd | 21 ++ resources/Schema/Entities/AmmoPickup.xml | 18 ++ resources/Schema/Entities/AmmoPickupTest.xml | 294 +++++++++++++++++++ src/Game/Game.cpp | 4 +- src/Game/Systems/AmmoPickupSystem.cpp | 78 +++++ 9 files changed, 470 insertions(+), 1 deletion(-) create mode 100644 include/Engine/Core/EAmmoPickup.h create mode 100644 include/Game/Systems/AmmoPickupSystem.h create mode 100644 resources/Schema/Components/AmmoPickup.xml create mode 100644 resources/Schema/Components/AmmoPickup.xsd create mode 100644 resources/Schema/Entities/AmmoPickup.xml create mode 100644 resources/Schema/Entities/AmmoPickupTest.xml create mode 100644 src/Game/Systems/AmmoPickupSystem.cpp diff --git a/include/Engine/Core/EAmmoPickup.h b/include/Engine/Core/EAmmoPickup.h new file mode 100644 index 00000000..6d854d48 --- /dev/null +++ b/include/Engine/Core/EAmmoPickup.h @@ -0,0 +1,18 @@ +#ifndef EAmmoPickup_h__ +#define EAmmoPickup_h__ + +#include "EventBroker.h" +#include "../Core/EntityWrapper.h" + +namespace Events +{ + + struct AmmoPickup : Event + { + EntityWrapper Player; + int AmmoGain; + }; + +} + +#endif \ No newline at end of file diff --git a/include/Game/Systems/AmmoPickupSystem.h b/include/Game/Systems/AmmoPickupSystem.h new file mode 100644 index 00000000..a54b8495 --- /dev/null +++ b/include/Game/Systems/AmmoPickupSystem.h @@ -0,0 +1,32 @@ +#ifndef AmmoPickupSystem_h__ +#define AmmoPickupSystem_h__ + +#include "Core/System.h" +#include "Core/Transform.h" +#include "Core/ResourceManager.h" +#include "Core/EntityFileParser.h" +#include "Core/EPickupSpawned.h" +#include "Core/EAmmoPickup.h" +#include "Engine/Collision/ETrigger.h" +#include "Common.h" + +class AmmoPickupSystem : public ImpureSystem +{ +public: + AmmoPickupSystem(SystemParams params); + + virtual void Update(double dt) override; + +private: + EventRelay m_ETriggerTouch; + bool OnTriggerTouch(Events::TriggerTouch& e); + + struct NewAmmoPickup { + glm::vec3 Pos; + double AmmoGain; + double RespawnTimer; + double DecreaseThisRespawnTimer; + }; + std::vector m_ETriggerTouchVector; +}; +#endif diff --git a/resources/Schema/Components.xsd b/resources/Schema/Components.xsd index f950e8c8..53e666de 100644 --- a/resources/Schema/Components.xsd +++ b/resources/Schema/Components.xsd @@ -32,6 +32,7 @@ + diff --git a/resources/Schema/Components/AmmoPickup.xml b/resources/Schema/Components/AmmoPickup.xml new file mode 100644 index 00000000..6da0b6fa --- /dev/null +++ b/resources/Schema/Components/AmmoPickup.xml @@ -0,0 +1,5 @@ + + + 3 + 30 + \ No newline at end of file diff --git a/resources/Schema/Components/AmmoPickup.xsd b/resources/Schema/Components/AmmoPickup.xsd new file mode 100644 index 00000000..1970eb78 --- /dev/null +++ b/resources/Schema/Components/AmmoPickup.xsd @@ -0,0 +1,21 @@ + + + + + + + + An Ammo Pickup + + + + + The respawn timer for a ammo pickup + + + How much percent ammo gain the player will get + + + + + diff --git a/resources/Schema/Entities/AmmoPickup.xml b/resources/Schema/Entities/AmmoPickup.xml new file mode 100644 index 00000000..534b76e2 --- /dev/null +++ b/resources/Schema/Entities/AmmoPickup.xml @@ -0,0 +1,18 @@ + + + + + + + + Models/Core/UnitSphere.mesh + + + + + + + + + + diff --git a/resources/Schema/Entities/AmmoPickupTest.xml b/resources/Schema/Entities/AmmoPickupTest.xml new file mode 100644 index 00000000..22690c65 --- /dev/null +++ b/resources/Schema/Entities/AmmoPickupTest.xml @@ -0,0 +1,294 @@ + + + + + + + + + + + + Models/LevelBase/MapVersion1.mesh + + + + + + + + + 2 + + + Models/DirectionalLightWidget.mesh + false + + + + + + + + + + + + + 8 + 2.7999999523162842 + + + + + + + + + + + 8 + 2.7999999523162842 + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + false + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + false + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1 + 22 + + + Models/Core/UnitSphere.mesh + + + + + + + + + + + + + 1 + 22 + + + Models/Core/UnitSphere.mesh + + + + + + + + + + + + + 4 + 44 + + + Models/Core/UnitSphere.mesh + + + + + + + + + + + diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index 8ee6dbed..e555923c 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -14,6 +14,7 @@ #include "Game/Systems/CapturePointSystem.h" #include "Game/Systems/CapturePointHUDSystem.h" #include "Game/Systems/PickupSpawnSystem.h" +#include "Game/Systems/AmmoPickupSystem.h" #include "Game/Systems/DamageIndicatorSystem.h" #include "Game/Systems/WeaponSystem.h" #include "Rendering/AnimationSystem.h" @@ -118,12 +119,12 @@ Game::Game(int argc, char* argv[]) m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); - m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer, m_OctreeCollision); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); + m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); // Populate Octree with collidables ++updateOrderLevel; @@ -132,6 +133,7 @@ Game::Game(int argc, char* argv[]) m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeFrustrumCulling); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); + m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); // Collision and TriggerSystem should update after player. ++updateOrderLevel; diff --git a/src/Game/Systems/AmmoPickupSystem.cpp b/src/Game/Systems/AmmoPickupSystem.cpp new file mode 100644 index 00000000..f6778fe4 --- /dev/null +++ b/src/Game/Systems/AmmoPickupSystem.cpp @@ -0,0 +1,78 @@ +#include "Systems/AmmoPickupSystem.h" + +AmmoPickupSystem::AmmoPickupSystem(SystemParams params) + : System(params) +{ + EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &AmmoPickupSystem::OnTriggerTouch); +} + +void AmmoPickupSystem::Update(double dt) +{ + for (auto it = m_ETriggerTouchVector.begin(); it != m_ETriggerTouchVector.end(); ++it) + { + auto& ammoPickupPosition = *it; + //set the double timer value (value 3) + ammoPickupPosition.DecreaseThisRespawnTimer -= dt; + if (ammoPickupPosition.DecreaseThisRespawnTimer < 0.0) { + //spawn and delete the vector item + auto entityFile = ResourceManager::Load("Schema/Entities/AmmoPickup.xml"); + EntityFileParser parser(entityFile); + EntityID ammoPickupID = parser.MergeEntities(m_World); + + //let the world know a pickup has spawned (graphics effects, etc) + Events::PickupSpawned ePickupSpawned; + ePickupSpawned.Pickup = EntityWrapper(m_World, ammoPickupID); + m_EventBroker->Publish(ePickupSpawned); + + //set values from the old entity to the new entity + auto& newAmmoPickupEntity = EntityWrapper(m_World, ammoPickupID); + newAmmoPickupEntity["Transform"]["Position"] = ammoPickupPosition.Pos; + newAmmoPickupEntity["AmmoPickup"]["AmmoGain"] = ammoPickupPosition.AmmoGain; + newAmmoPickupEntity["AmmoPickup"]["RespawnTimer"] = ammoPickupPosition.RespawnTimer; + + //erase the current element (AmmoPickupPosition) + m_ETriggerTouchVector.erase(it); + break; + } + } +} + + +bool AmmoPickupSystem::OnTriggerTouch(Events::TriggerTouch& e) +{ + if (e.Entity != LocalPlayer) { + return false; + } + //TODO: add other weapontypes + if (!e.Entity.HasComponent("AssaultWeapon")) { + return false; + } + if (!e.Trigger.HasComponent("AmmoPickup")) { + return false; + } + int maxWeaponAmmo = (int)e.Entity["AssaultWeapon"]["MaxAmmo"]; + int& currentAmmo = (int)e.Entity["AssaultWeapon"]["Ammo"]; + + int ammoGiven = 0.01*(double)e.Trigger["AmmoPickup"]["AmmoGain"] * maxWeaponAmmo; + //cant pick up ammopacks if you are already at MaxAmmo + if (currentAmmo >= maxWeaponAmmo) { + return false; + } + + //personEntered = e.Entity, thingEntered = e.Trigger + Events::AmmoPickup ePlayerAmmoPickup; + ePlayerAmmoPickup.AmmoGain = ammoGiven; + ePlayerAmmoPickup.Player = e.Entity; + m_EventBroker->Publish(ePlayerAmmoPickup); + //immediately give the player the ammo + currentAmmo = std::min(currentAmmo + ammoGiven, maxWeaponAmmo); + + //copy position, ammogain, respawntimer (twice since one of the values will be counted down to 0, the other will be set in the new object) + //we need to copy all values since each value can be different for each ammoPickup + m_ETriggerTouchVector.push_back({ (glm::vec3)e.Trigger["Transform"]["Position"] ,e.Trigger["AmmoPickup"]["AmmoGain"], + e.Trigger["AmmoPickup"]["RespawnTimer"],e.Trigger["AmmoPickup"]["RespawnTimer"] }); + + //delete the ammopickup + m_World->DeleteEntity(e.Trigger.ID); + return true; +} From a36ed76a4e42bf0a4ad116b86b4b8f603fcf3021 Mon Sep 17 00:00:00 2001 From: viktorljung Date: Fri, 12 Feb 2016 00:26:59 +0100 Subject: [PATCH 234/355] AmmunitionHUDSystem now really working --- assets | 2 +- ...DSystem - Copy.h => AmmunitionHUDSystem.h} | 0 resources/Schema/Entities/Player.xml | 17 ++++----- src/Game/Systems/AmmunitionHUDSystem.cpp | 36 +++++++++++++++++++ 4 files changed, 46 insertions(+), 9 deletions(-) rename include/Game/Systems/{HealthHUDSystem - Copy.h => AmmunitionHUDSystem.h} (100%) create mode 100644 src/Game/Systems/AmmunitionHUDSystem.cpp diff --git a/assets b/assets index dfa0fc61..4d36fdce 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit dfa0fc61ab88456f3461779bd7c6ac97d15f6493 +Subproject commit 4d36fdced7007a594a56b7371bb26861876889aa diff --git a/include/Game/Systems/HealthHUDSystem - Copy.h b/include/Game/Systems/AmmunitionHUDSystem.h similarity index 100% rename from include/Game/Systems/HealthHUDSystem - Copy.h rename to include/Game/Systems/AmmunitionHUDSystem.h diff --git a/resources/Schema/Entities/Player.xml b/resources/Schema/Entities/Player.xml index 8a5a4d24..910e440f 100644 --- a/resources/Schema/Entities/Player.xml +++ b/resources/Schema/Entities/Player.xml @@ -274,7 +274,7 @@ Idle - 0.14471987707210765 + 1.9901368826444736 1 @@ -293,8 +293,8 @@ Models/Weapons/Blue/AssaultWeaponBlue.mesh - - + + @@ -313,8 +313,9 @@ - - + + + @@ -371,7 +372,7 @@ Idle - 1.7139414005989018 + 0.22602443705505681 1 @@ -395,8 +396,8 @@ Models/Weapons/Blue/AssaultWeaponBlue.mesh - - + + diff --git a/src/Game/Systems/AmmunitionHUDSystem.cpp b/src/Game/Systems/AmmunitionHUDSystem.cpp new file mode 100644 index 00000000..c9d87072 --- /dev/null +++ b/src/Game/Systems/AmmunitionHUDSystem.cpp @@ -0,0 +1,36 @@ +#include "Game/Systems/AmmunitionHUDSystem.h" + +void AmmunitionHUDSystem::Update(double dt) +{ + //Hud element for tracking ammunition from parent with AssaultWeapon component.Child with the name "MagazineAmmo" tracks clip ammunition.Child with the name "Ammo" tracks ammo. + + auto ammunitionHUDs = m_World->GetComponents("AmmunitionHUD"); + if (ammunitionHUDs == nullptr) { + return; + } + + for (auto& ammunitionHUDComponent : *ammunitionHUDs) { + EntityWrapper entity = EntityWrapper(m_World, ammunitionHUDComponent.EntityID); + + EntityWrapper playerEntity = entity.FirstParentWithComponent("AssaultWeapon"); + + if (!playerEntity.Valid()) { + return; + } + + + EntityWrapper magazineAmmo = entity.FirstChildByName("MagazineAmmo"); + if(magazineAmmo.Valid()) { + if(magazineAmmo.HasComponent("Text")) { + (std::string&)magazineAmmo["Text"]["Content"] = std::to_string((int)playerEntity["AssaultWeapon"]["MagazineAmmo"]); + } + } + + EntityWrapper ammo = entity.FirstChildByName("Ammo"); + if (ammo.Valid()) { + if (ammo.HasComponent("Text")) { + (std::string&)ammo["Text"]["Content"] = std::to_string((int)playerEntity["AssaultWeapon"]["Ammo"]); + } + } + } +} From f1c2413cf930c7d05601bda62d6bee0deb4072a4 Mon Sep 17 00:00:00 2001 From: William Moberg Date: Fri, 12 Feb 2016 00:39:27 +0100 Subject: [PATCH 235/355] Respawning and team picking seems to be working well. --- src/Game/Systems/DamageIndicatorSystem.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/Game/Systems/DamageIndicatorSystem.cpp b/src/Game/Systems/DamageIndicatorSystem.cpp index a29309b5..8d586ac1 100644 --- a/src/Game/Systems/DamageIndicatorSystem.cpp +++ b/src/Game/Systems/DamageIndicatorSystem.cpp @@ -22,6 +22,10 @@ bool DamageIndicatorSystem::OnPlayerDamage(Events::PlayerDamage& e) return false; } + if (!e.Inflictor.Valid() || !e.Victim.Valid()) { + return false; + } + //grab players direction auto playerOrientation = glm::quat((glm::vec3)e.Victim["Transform"]["Orientation"]); From 40ae2b8cbbe5bb72d5ed24578930ad6ef396e5e2 Mon Sep 17 00:00:00 2001 From: William Moberg Date: Fri, 12 Feb 2016 00:52:58 +0100 Subject: [PATCH 236/355] DefaultInput key 'K' to kill player, since we can't respawn when alive. Also moved TakeDamage InputCommand to HealthSystem. --- include/Game/Systems/HealthSystem.h | 5 ++++- resources/DefaultInput.ini | 3 ++- src/Game/Systems/HealthSystem.cpp | 12 ++++++++++++ src/Game/Systems/SoundSystem.cpp | 6 ------ 4 files changed, 18 insertions(+), 8 deletions(-) diff --git a/include/Game/Systems/HealthSystem.h b/include/Game/Systems/HealthSystem.h index b66d8eb0..21a52330 100644 --- a/include/Game/Systems/HealthSystem.h +++ b/include/Game/Systems/HealthSystem.h @@ -9,6 +9,7 @@ #include "Core/EPlayerDamage.h" #include "Core/EPlayerHealthPickup.h" #include "Core/EPlayerDeath.h" +#include "../Engine/Input/EInputCommand.h" #include #include @@ -28,7 +29,9 @@ private: bool HealthSystem::OnPlayerDamaged(Events::PlayerDamage& e); EventRelay m_EPlayerHealthPickup; bool HealthSystem::OnPlayerHealthPickup(Events::PlayerHealthPickup& e); - + EventRelay m_InputCommand; + bool HealthSystem::OnInputCommand(Events::InputCommand& e); + //vector which will keep track of health changes std::vector> m_DeltaHealthVector; diff --git a/resources/DefaultInput.ini b/resources/DefaultInput.ini index 683d48e2..d5489c3a 100644 --- a/resources/DefaultInput.ini +++ b/resources/DefaultInput.ini @@ -24,4 +24,5 @@ F1=ToggleEditor C=ConnectToServer N=SwitchToServer M=SwitchToClient -P=SwitchToPlayer \ No newline at end of file +P=SwitchToPlayer +K=TakeDamage,1500 \ No newline at end of file diff --git a/src/Game/Systems/HealthSystem.cpp b/src/Game/Systems/HealthSystem.cpp index 29d8790d..0fc113b9 100644 --- a/src/Game/Systems/HealthSystem.cpp +++ b/src/Game/Systems/HealthSystem.cpp @@ -7,6 +7,7 @@ HealthSystem::HealthSystem(SystemParams params) //subscribe/listenTo playerdamage,healthpickup events (using the eventBroker) EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &HealthSystem::OnPlayerDamaged); EVENT_SUBSCRIBE_MEMBER(m_EPlayerHealthPickup, &HealthSystem::OnPlayerHealthPickup); + EVENT_SUBSCRIBE_MEMBER(m_InputCommand, &HealthSystem::OnInputCommand); } void HealthSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) @@ -29,6 +30,17 @@ bool HealthSystem::OnPlayerDamaged(Events::PlayerDamage& e) return true; } +bool HealthSystem::OnInputCommand(Events::InputCommand& e) +{ + if (e.Command == "TakeDamage" && e.Value > 0 && LocalPlayer.Valid()) { + Events::PlayerDamage ev; + ev.Victim = LocalPlayer; + ev.Damage = e.Value; + m_EventBroker->Publish(ev); + } + return true; +} + bool HealthSystem::OnPlayerHealthPickup(Events::PlayerHealthPickup& e) { ComponentWrapper cHealth = e.Player["Health"]; diff --git a/src/Game/Systems/SoundSystem.cpp b/src/Game/Systems/SoundSystem.cpp index db3575ab..59fd4a7f 100644 --- a/src/Game/Systems/SoundSystem.cpp +++ b/src/Game/Systems/SoundSystem.cpp @@ -52,12 +52,6 @@ bool SoundSystem::OnInputCommand(const Events::InputCommand & e) return true; } } - if (e.Command == "TakeDamage" && e.Value > 0 && LocalPlayer.Valid()) { - Events::PlayerDamage ev; - ev.Victim = LocalPlayer; - ev.Damage = e.Value; - m_EventBroker->Publish(ev); - } return false; } From 3b42f5dbf412e972efbf7f52d27eccf5a49e530f Mon Sep 17 00:00:00 2001 From: Jocke Date: Fri, 12 Feb 2016 01:33:45 +0100 Subject: [PATCH 237/355] Fixed server so it now deletes. --- src/Game/Systems/PlayerSpawnSystem.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Game/Systems/PlayerSpawnSystem.cpp b/src/Game/Systems/PlayerSpawnSystem.cpp index e2775280..108fa502 100644 --- a/src/Game/Systems/PlayerSpawnSystem.cpp +++ b/src/Game/Systems/PlayerSpawnSystem.cpp @@ -79,11 +79,12 @@ bool PlayerSpawnSystem::OnPlayerSpawned(Events::PlayerSpawned& e) m_World->DeleteEntity(m_PlayerEntities[e.PlayerID].ID); } } + // Store the player for future reference + m_PlayerEntities[e.PlayerID] = e.Player; + if (!IsClient) { return false; } - // Store the player for future reference - m_PlayerEntities[e.PlayerID] = e.Player; // Set the camera to the correct entity EntityWrapper cameraEntity = e.Player.FirstChildByName("Camera"); From 3e42c067ab02723e16b22203e96c855cd1cdacc6 Mon Sep 17 00:00:00 2001 From: antc13 Date: Fri, 12 Feb 2016 01:43:20 +0100 Subject: [PATCH 238/355] New Map with meshes WIP Update. --- resources/Schema/Entities/NewMap.xml | 3587 ++++++++++++++++++++++---- 1 file changed, 3096 insertions(+), 491 deletions(-) diff --git a/resources/Schema/Entities/NewMap.xml b/resources/Schema/Entities/NewMap.xml index a79fee7b..e0fcf912 100644 --- a/resources/Schema/Entities/NewMap.xml +++ b/resources/Schema/Entities/NewMap.xml @@ -104,6 +104,100 @@ + + + + Models/Props/Walls/SciFiWallTop.mesh + + + + + + + + + Models/Props/Walls/SciFiWallBig.mesh + + + + + + + + + + Models/Props/Walls/SciFiWallMedium.mesh + + + + + + + + + + Models/Props/Walls/SciFiWallSmall1.mesh + + + + + + + + + + Models/Props/Walls/SciFiWallSmall2.mesh + + + + + + + + + + Models/Props/Walls/SciFiWallBig.mesh + + + + + + + + + + + + Models/Props/Walls/SciFiWallMedium.mesh + + + + + + + + + + + + Models/Props/Walls/SciFiWallSmall3.mesh + + + + + + + + + + Models/Props/Walls/SciFiWallSmall4.mesh + + + + + + + @@ -116,8 +210,7 @@ - Models/Props/Pillars/SciFiPillar1.mesh - + Models/Props/Pillars/SciFiPillar1Blue.mesh @@ -130,12 +223,11 @@ - Models/Props/Pillars/SciFiPillar1.mesh - + Models/Props/Pillars/SciFiPillar1Red.mesh - - + + @@ -169,7 +261,7 @@ - Models/Props/Pillars/SciFiPillar2.mesh + Models/Props/Pillars/SciFiPillar2Red.mesh @@ -182,7 +274,7 @@ - Models/Props/Pillars/SciFiPillar3.mesh + Models/Props/Pillars/SciFiPillar3Blue.mesh @@ -196,10 +288,10 @@ - Models/Props/Pillars/SciFiPillar1.mesh + Models/Props/Pillars/SciFiPillar1Blue.mesh - + @@ -210,10 +302,10 @@ - Models/Props/Pillars/SciFiPillar1.mesh + Models/Props/Pillars/SciFiPillar1Red.mesh - + @@ -224,7 +316,7 @@ - Models/Props/Pillars/SciFiPillar3.mesh + Models/Props/Pillars/SciFiPillar3Red.mesh @@ -266,8 +358,8 @@ Models/Props/Pillars/StonePillar.mesh - - + + @@ -292,7 +384,7 @@ Models/Props/Pillars/SciFiPillar2.mesh - + @@ -324,6 +416,141 @@ + + + + + Models/Props/Pillars/SciFiPillar2Blue.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar2Blue.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar2Blue.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar2Blue.mesh + + + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar2Red.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar2Red.mesh + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar2Red.mesh + + + + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar2Red.mesh + + + + + + + + @@ -338,7 +565,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -349,6 +576,7 @@ Models/Props/Walls/BigWall.mesh + @@ -363,7 +591,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -388,7 +616,8 @@ Models/Props/Walls/BigWall.mesh - + + @@ -399,6 +628,7 @@ Models/Props/Walls/BigWall.mesh + @@ -413,7 +643,8 @@ Models/Props/Walls/BigWall.mesh - + + @@ -424,7 +655,8 @@ Models/Props/Walls/BigWall.mesh - + + @@ -438,7 +670,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -450,7 +682,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -464,7 +696,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -480,7 +712,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -492,7 +724,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -505,7 +737,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -585,8 +817,8 @@ Models/Props/Walls/SmallWall2.mesh - - + + @@ -710,11 +942,11 @@ - Models/Props/Walls/MediumWall3.mesh + Models/Props/Walls/MediumWall1.mesh - - + + @@ -722,10 +954,10 @@ - Models/Props/Walls/MediumWall3.mesh + Models/Props/Walls/MediumWall1.mesh - + @@ -734,10 +966,10 @@ - Models/Props/Walls/MediumWall3.mesh + Models/Props/Walls/MediumWall1.mesh - + @@ -751,7 +983,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -762,7 +994,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -774,7 +1006,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -801,7 +1033,8 @@ Models/Props/Walls/BigWall.mesh - + + @@ -813,7 +1046,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -827,7 +1060,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -838,7 +1071,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -850,7 +1083,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -876,7 +1109,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -966,7 +1199,8 @@ Models/Props/Walls/BigWall.mesh - + + @@ -977,7 +1211,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -988,6 +1222,7 @@ Models/Props/Walls/BigWall.mesh + @@ -1016,7 +1251,7 @@ Models/Props/Walls/SmallWall2.mesh - + @@ -1027,7 +1262,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -1054,7 +1289,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -1065,7 +1300,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -1077,7 +1312,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -1089,7 +1324,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -1103,7 +1338,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -1115,7 +1350,7 @@ Models/Props/Walls/BigWall.mesh - + @@ -1130,8 +1365,479 @@ Models/Props/Walls/MediumWall3.mesh - - + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + Models/Props/Walls/BigWall.mesh + + + + + + + + + + + + + + Models/Props/Walls/SmallWall3.mesh + + + + + + + + + + + + Models/Props/Walls/SpecialWall1.mesh + + + + + + + + + + + + + + Models/Props/Flora/SpecialRoot.mesh + + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall2.mesh + + + + + + + + + + + Models/Props/Walls/MediumWall2.mesh + + + + + + + + + + + + + Models/Props/Walls/SmallWall3.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall4.mesh + + + + + + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + + + Models/Props/Walls/MediumWall2.mesh + + + + + + + + + + + + + Models/Props/Walls/SpecialWall1.mesh + + + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + + Models/Props/Walls/SpecialWall1.mesh + + + + + + + + + + + + Models/Props/Walls/SpecialWall1.mesh + + + + + + + + + + + + + Models/Props/Walls/SpecialWall1.mesh + + + + + + + + + + + + + Models/Props/Walls/SpecialWall1.mesh + + + + + + + + + + + + + Models/Props/Walls/SpecialWall1.mesh + + + + + + + + + + + + + + Models/Props/Walls/SpecialWall1.mesh + + + + + @@ -1150,9 +1856,9 @@ Models/Props/Bridges/WoodenBridge.mesh - + - + @@ -1164,9 +1870,9 @@ Models/Props/Bridges/WoodenBridge.mesh - - - + + + @@ -1178,8 +1884,8 @@ Models/Props/Bridges/WoodenBridge.mesh - - + + @@ -1191,12 +1897,117 @@ Models/Props/Bridges/SciFiBridge.mesh - + - + - + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + + + + @@ -1205,23 +2016,209 @@ Models/Props/Bridges/SciFiBridge.mesh - + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + + + + + + + + + + Models/Props/Pillars/SciFiBridgePillar1.mesh + + + + + + + - Models/Props/Flora/TreeLog.mesh + Models/Props/Bridges/SciFiBridge.mesh - - - + + + + + + + + + + + Models/Props/Bridges/SciFiBridge.mesh + + + + + + + + + + + + + Models/Props/Pillars/SciFiBridgePillar1.mesh + + + + + + + + + + + + + + Models/Props/Bridges/SciFiBridge.mesh + + + + + + + + + + + + + Models/Props/Bridges/SciFiBridge.mesh + + + + + + + + + + + + + Models/Props/Bridges/WoodenBridge.mesh + + + + + @@ -1240,9 +2237,9 @@ Models/Props/Pillars/SciFiBridgePillar1.mesh - + - + @@ -1254,7 +2251,7 @@ Models/Props/Pillars/SciFiBridgePillar1.mesh - + @@ -1319,8 +2316,7 @@ Models/Props/Pillars/SciFiBridgePillar1.mesh - - + @@ -1347,8 +2343,8 @@ Models/Props/Walls/MediumWall1.mesh - - + + @@ -1431,6 +2427,93 @@ + + + + Models/Core/UnitPlane.mesh + + true + + + + + + + + + + + + + Models/Core/UnitPlane.mesh + + true + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + + + Models/Props/Pillars/SciFiBridgePillar1.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiBridgePillar1.mesh + + + + + + + + + @@ -1445,59 +2528,11 @@ true - + + - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - + @@ -1506,7 +2541,7 @@ true - + @@ -1517,7 +2552,7 @@ true - + @@ -1529,7 +2564,7 @@ true - + @@ -1541,7 +2576,7 @@ true - + @@ -1553,7 +2588,7 @@ true - + @@ -1565,7 +2600,7 @@ true - + @@ -1605,13 +2640,444 @@ true - + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + + Models/Props/Flora/SpecialRoot.mesh + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + + Models/Props/Flora/SpecialRoot.mesh + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + + Models/Props/Flora/SpecialRoot.mesh + + + + + + + + @@ -1636,28 +3102,15 @@ - Models/Props/Stones/BigStone.mesh + Models/Props/Stones/MediumStone2.mesh - - + + + - - - - - - Models/Props/Stones/BigStone.mesh - - - - - - - - - + @@ -1672,161 +3125,6 @@ - - - - - Models/Props/Stones/MediumStone1.mesh - - - - - - - - - - - - Models/Props/Stones/MediumStone1.mesh - - - - - - - - - - - - - Models/Props/Stones/MediumStone1.mesh - - - - - - - - - - - - - Models/Props/Stones/MediumStone1.mesh - - - - - - - - - - - - - Models/Props/Stones/MediumStone1.mesh - - - - - - - - - - - - - Models/Props/Stones/MediumStone1.mesh - - - - - - - - - - - - - Models/Props/Stones/MediumStone1.mesh - - - - - - - - - - - - Models/Props/Stones/MediumStone1.mesh - - - - - - - - - - - - - Models/Props/Stones/BigStone.mesh - - - - - - - - - - - - - Models/Props/Stones/MediumStone1.mesh - - - - - - - - - - - - Models/Props/Stones/MediumStone1.mesh - - - - - - - - - - - - - Models/Props/Stones/MediumStone1.mesh - - - - - - - - - - @@ -1834,8 +3132,9 @@ Models/Props/Stones/BigStone.mesh - - + + + @@ -1888,8 +3187,8 @@ Models/Props/Stones/BigStone.mesh - - + + @@ -1901,8 +3200,9 @@ Models/Props/Stones/MediumStone1.mesh - - + + + @@ -1911,11 +3211,12 @@ - Models/Props/Stones/MediumStone1.mesh + Models/Props/Stones/SmallStone1.mesh - - + + + @@ -1967,91 +3268,12 @@ Models/Props/Stones/MediumStone1.mesh - - + + + - - - - - - Models/Props/Stones/MediumStone1.mesh - - - - - - - - - - - - - - - Models/Props/Stones/MediumStone1.mesh - - - - - - - - - - - - Models/Props/Stones/MediumStone1.mesh - - - - - - - - - - - - - Models/Props/Stones/MediumStone1.mesh - - - - - - - - - - - - - Models/Props/Stones/MediumStone1.mesh - - - - - - - - - - - - Models/Props/Stones/MediumStone1.mesh - - - - - - - - - - + @@ -2060,7 +3282,7 @@ Models/Props/Stones/BigStone.mesh - + @@ -2072,8 +3294,8 @@ Models/Props/Stones/BigStone.mesh - - + + @@ -2085,14 +3307,683 @@ Models/Props/Stones/BigStone.mesh - - + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + Models/Props/Stones/SmallStone2.mesh + + + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalRed.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalRed.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalRed.mesh + + + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/SmallStone1.mesh + + + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + + Models/Props/Stones/SmallStone2.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + + + Models/Props/Stones/SmallStone1.mesh + + + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + + + Models/Props/Stones/SmallStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/SmallStone2.mesh + + + + + + + + + + + + + + Models/Props/Stones/SmallStone1.mesh + + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + + + + + + + Models/Props/Stones/SmallStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/SmallStone2.mesh + + + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + + Models/Props/Stones/SmallStone1.mesh + + + + + + + + + + + + + + + Models/Props/Stones/SmallStone1.mesh + + + + + + + + + + + + + + Models/Props/Stones/SmallStone1.mesh + + + + + + + + + + + + + + + + Models/Props/Stones/SmallStone2.mesh + + + + + + + + + + + + + + Models/Props/Stones/SmallStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/SmallStone2.mesh + + + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + + Models/Props/Stones/SmallStone1.mesh + + + + + + + + + + + + + + + + Models/Props/Stones/SmallStone2.mesh + + + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/SmallStone2.mesh + + + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + @@ -2107,9 +3998,9 @@ Models/Props/PickUps/PickUpHolder.mesh - - - + + + @@ -2121,9 +4012,9 @@ Models/Props/PickUps/PickUpHolder.mesh - - - + + + @@ -2136,7 +4027,7 @@ - + @@ -2149,8 +4040,58 @@ Models/Props/PickUps/PickUpHolder.mesh - - + + + + + + + + + + + + + + + + + + + + Models/Props/PickUps/PickUpHolder.mesh + + + + + + + + + + + + + Models/Props/PickUps/HealthPickUp.mesh + + + + + + + + + + + + + + + Models/Props/PickUps/PickUpHolder.mesh + + + + @@ -2162,9 +4103,9 @@ Models/Props/PickUps/PickUpHolder.mesh - - - + + + @@ -2176,8 +4117,547 @@ Models/Props/PickUps/PickUpHolder.mesh - + + + + + + + + + + + + Models/Props/PickUps/PickUpHolder.mesh + + + + + + + + + + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + + + + + + + + + + Models/Props/SciFiHolder1.mesh + + + + + + + + + + + + + Models/Props/SciFiHolder1.mesh + + + + + + + + + + + + + Models/Props/SciFiHolder1.mesh + + + + + + + + + + + + + Models/Props/SciFiHolder1.mesh + + + + + + + + + + + + + Models/Props/SciFiHolder1.mesh + + + + + + + + + + + + + Models/Props/SciFiHolder1.mesh + + + + + + + + + + + + + Models/Props/SciFiHolder1.mesh + + + + + + + + + + + + + Models/Props/SciFiHolder1.mesh + + + + + + + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalRed.mesh + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalRed.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalRed.mesh + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalBlue.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalBlue.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalBlue.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalBlue.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalBlue.mesh + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalRed.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalRed.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalBlue.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalBlue.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalRed.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalRed.mesh + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalBlue.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalBlue.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalRed.mesh + + + + + @@ -2193,107 +4673,177 @@ - - - - - - - - + - Models/Props/CapturePoint.mesh - + Models/Props/CapturePoint/CapturePointBlue.mesh - - - - - - + - - + + + + + + + + + + Models/Core/UnitCylinder.mesh + + true + + + + + + + + + + + + + + + - - - 1 - + - Models/Props/CapturePoint.mesh - + Models/Props/CapturePoint/CapturePointNeutral.mesh - - + - - + + + + + 1 + + + Models/Core/UnitCylinder.mesh + + true + + + + + + + + + + + - - - 2 - + - Models/Props/CapturePoint.mesh + Models/Props/CapturePoint/CapturePointNeutral.mesh - - + - - + + + + + 2 + + + Models/Core/UnitCylinder.mesh + + true + + + + + + + + + + + - - - 3 - + - Models/Props/CapturePoint.mesh - + Models/Props/CapturePoint/CapturePointNeutral.mesh - - + - - + + + + + 1.5498908015879351 + 3 + + + Models/Core/UnitCylinder.mesh + + true + + + + + + + + + + + - - - - - - 4 - + - Models/Props/CapturePoint.mesh - + Models/Props/CapturePoint/CapturePointRed.mesh - - - - - - + - - + + + + + + + + 4 + + + Models/Core/UnitCylinder.mesh + + true + + + + + + + + + + + + + + + @@ -2373,23 +4923,78 @@ 1 - + - + - - Models/Characters/Assault/AssaultTPose.mesh - + + + Schema/Entities/Player.xml + + + + + + - + - + + + + + + Models/Characters/Assault/AssaultTPose.mesh + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + + + + + + + + From 529513331121a9ee0c5598029c490ec782b356c6 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Fri, 12 Feb 2016 01:45:54 +0100 Subject: [PATCH 239/355] Hack to sync ammo over network until we have input replaying + Reload effect from all views --- .../Systems/Weapon/AssaultWeaponBehaviour.h | 5 +- .../Schema/Entities/DoubleJumpHexagon.xml | 23 ++-- resources/Schema/Entities/Player.xml | 38 ++++--- ...nReloadEffect.xml => ReloadEffectView.xml} | 9 +- .../Schema/Entities/ReloadEffectWorld.xml | 24 ++++ resources/Schema/Types/Entity.xsd | 1 + src/Engine/Network/Client.cpp | 12 +- src/Engine/Network/Server.cpp | 16 ++- src/Engine/Rendering/RenderSystem.cpp | 7 +- src/Game/Systems/PlayerMovementSystem.cpp | 3 +- .../Systems/Weapon/AssaultWeaponBehaviour.cpp | 104 +++++++++++++----- 11 files changed, 171 insertions(+), 71 deletions(-) rename resources/Schema/Entities/{WeaponReloadEffect.xml => ReloadEffectView.xml} (72%) create mode 100644 resources/Schema/Entities/ReloadEffectWorld.xml diff --git a/include/Game/Systems/Weapon/AssaultWeaponBehaviour.h b/include/Game/Systems/Weapon/AssaultWeaponBehaviour.h index 915854ff..0473cec3 100644 --- a/include/Game/Systems/Weapon/AssaultWeaponBehaviour.h +++ b/include/Game/Systems/Weapon/AssaultWeaponBehaviour.h @@ -1,6 +1,7 @@ #include "Sound/EPlaySoundOnEntity.h" #include "Collision/Collision.h" #include "Rendering/AnimationSystem.h" +#include "Core/ConfigFile.h" #include "WeaponBehaviour.h" #include "../SpawnerSystem.h" #include "Core/EPlayerDamage.h" @@ -19,11 +20,13 @@ public: private: EntityWrapper m_FirstPersonModel; + EntityWrapper m_ThirdPersonModel; // State bool m_Firing = false; bool m_Reloading = false; double m_ReloadTimer = 0.0; - EntityWrapper m_ReloadImpersonator; + EntityWrapper m_FirstPersonReloadImpersonator; + EntityWrapper m_ThirdPersonReloadImpersonator; double m_TimeSinceLastFire = 0.0; EventRelay m_EAnimationComplete; diff --git a/resources/Schema/Entities/DoubleJumpHexagon.xml b/resources/Schema/Entities/DoubleJumpHexagon.xml index c1aaec34..f4596efd 100644 --- a/resources/Schema/Entities/DoubleJumpHexagon.xml +++ b/resources/Schema/Entities/DoubleJumpHexagon.xml @@ -2,27 +2,26 @@ - - Models/Effects/JumpEffectHexagon.mesh - - true - - - - - 0.5 true - - + true 0.5 - + true + + Models/Effects/JumpEffectHexagon.mesh + + true + + + + + diff --git a/resources/Schema/Entities/Player.xml b/resources/Schema/Entities/Player.xml index 9f8e0955..05dc79e2 100644 --- a/resources/Schema/Entities/Player.xml +++ b/resources/Schema/Entities/Player.xml @@ -24,7 +24,7 @@ - + @@ -138,8 +138,8 @@ true - - + + @@ -154,17 +154,17 @@ + + + + Schema/Entities/ReloadEffectView.xml + + + + + - - - - Schema/Entities/WeaponReloadEffect.xml - - - - - @@ -209,11 +209,10 @@ Models/Weapons/Blue/AssaultWeaponBlue.mesh - false - - + + @@ -228,6 +227,15 @@ + + + + Schema/Entities/ReloadEffectWorld.xml + + + + + diff --git a/resources/Schema/Entities/WeaponReloadEffect.xml b/resources/Schema/Entities/ReloadEffectView.xml similarity index 72% rename from resources/Schema/Entities/WeaponReloadEffect.xml rename to resources/Schema/Entities/ReloadEffectView.xml index 3099b405..ca7e6e1a 100644 --- a/resources/Schema/Entities/WeaponReloadEffect.xml +++ b/resources/Schema/Entities/ReloadEffectView.xml @@ -2,9 +2,6 @@ - - R_Arm_Weapon_Joint - 2 @@ -18,12 +15,8 @@ Models/Weapons/Blue/AssaultWeaponBlue.mesh - true - - - - + diff --git a/resources/Schema/Entities/ReloadEffectWorld.xml b/resources/Schema/Entities/ReloadEffectWorld.xml new file mode 100644 index 00000000..97236897 --- /dev/null +++ b/resources/Schema/Entities/ReloadEffectWorld.xml @@ -0,0 +1,24 @@ + + + + + + 2 + + + true + + + true + + true + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + + + + + + + diff --git a/resources/Schema/Types/Entity.xsd b/resources/Schema/Types/Entity.xsd index b8a863e2..42b5d030 100644 --- a/resources/Schema/Types/Entity.xsd +++ b/resources/Schema/Types/Entity.xsd @@ -44,6 +44,7 @@ + diff --git a/src/Engine/Network/Client.cpp b/src/Engine/Network/Client.cpp index b03aad07..b0c8697f 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -411,16 +411,26 @@ void Client::sendLocalPlayerTransform() return; } + Packet packet(MessageType::PlayerTransform, m_SendPacketID); + ComponentWrapper cTransform = m_LocalPlayer["Transform"]; glm::vec3& position = cTransform["Position"]; glm::vec3& orientation = cTransform["Orientation"]; - Packet packet(MessageType::PlayerTransform, m_SendPacketID); packet.WritePrimitive(position.x); packet.WritePrimitive(position.y); packet.WritePrimitive(position.z); packet.WritePrimitive(orientation.x); packet.WritePrimitive(orientation.y); packet.WritePrimitive(orientation.z); + + bool hasAssaultWeapon = m_LocalPlayer.HasComponent("AssaultWeapon"); + packet.WritePrimitive(hasAssaultWeapon); + if (hasAssaultWeapon) { + ComponentWrapper cAssaultWeapon = m_LocalPlayer["AssaultWeapon"]; + packet.WritePrimitive((int)cAssaultWeapon["MagazineAmmo"]); + packet.WritePrimitive((int)cAssaultWeapon["Ammo"]); + } + send(packet); } diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index 1f0b3bc7..a6174f7a 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -288,7 +288,7 @@ void Server::parseOnInputCommand(Packet& packet) e.Value = packet.ReadPrimitive(); m_EventBroker->Publish(e); - if (e.Command == "PrimaryFire") { + if (e.Command == "PrimaryFire" || e.Command == "Reload") { m_InputCommandsToBroadcast.push_back(e); } //LOG_INFO("Server::parseOnInputCommand: Command is %s. Value is %f. PlayerID is %i.", e.Command.c_str(), e.Value, e.PlayerID); @@ -464,11 +464,23 @@ void Server::parsePlayerTransform(Packet& packet) orientation.y = packet.ReadPrimitive(); orientation.z = packet.ReadPrimitive(); + bool hasAssaultWeapon = packet.ReadPrimitive(); + int magazineAmmo; + int ammo; + if (hasAssaultWeapon) { + magazineAmmo = packet.ReadPrimitive(); + ammo = packet.ReadPrimitive(); + } + PlayerID playerID = GetPlayerIDFromEndpoint(m_ReceiverEndpoint); EntityWrapper player(m_World, m_ConnectedPlayers.at(playerID).EntityID); - if (player.Valid()) { player["Transform"]["Position"] = position; player["Transform"]["Orientation"] = orientation; + + if (hasAssaultWeapon) { + player["AssaultWeapon"]["MagazineAmmo"] = magazineAmmo; + player["AssaultWeapon"]["Ammo"] = ammo; + } } } diff --git a/src/Engine/Rendering/RenderSystem.cpp b/src/Engine/Rendering/RenderSystem.cpp index 7beb85db..665c4027 100644 --- a/src/Engine/Rendering/RenderSystem.cpp +++ b/src/Engine/Rendering/RenderSystem.cpp @@ -79,7 +79,6 @@ void RenderSystem::fillSprites(std::list>& jobs, Worl bool RenderSystem::isEntityVisible(EntityWrapper& entity) { - // Only render children of a camera if that camera is currently active if (isChildOfACamera(entity) && !isChildOfCurrentCamera(entity)) { return false; @@ -87,7 +86,11 @@ bool RenderSystem::isEntityVisible(EntityWrapper& entity) // Hide things parented to local player if they have the HiddenFromLocalPlayer component bool outOfBodyExperience = ResourceManager::Load("Config.ini")->Get("Debug.OutOfBodyExperience", false); - if (entity.HasComponent("HiddenForLocalPlayer") && (entity == m_LocalPlayer || entity.IsChildOf(m_LocalPlayer)) && !outOfBodyExperience) { + if ( + (entity.HasComponent("HiddenForLocalPlayer") || entity.FirstParentWithComponent("HiddenForLocalPlayer").Valid()) + && (entity == m_LocalPlayer || entity.IsChildOf(m_LocalPlayer)) + && !outOfBodyExperience + ) { return false; } diff --git a/src/Game/Systems/PlayerMovementSystem.cpp b/src/Game/Systems/PlayerMovementSystem.cpp index 461c7098..badaf638 100644 --- a/src/Game/Systems/PlayerMovementSystem.cpp +++ b/src/Game/Systems/PlayerMovementSystem.cpp @@ -40,7 +40,8 @@ void PlayerMovementSystem::updateMovementControllers(double dt) EntityWrapper playerModel = player.FirstChildByName("PlayerModel"); if (playerModel.Valid()) { ComponentWrapper cAnimationOffset = playerModel["AnimationOffset"]; - double time = (cameraOrientation.x + glm::half_pi()) / glm::pi(); + float pitch = cameraOrientation.x + 0.2; + double time = (pitch + glm::half_pi()) / glm::pi(); cAnimationOffset["Time"] = time; } } diff --git a/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp b/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp index 54c3a590..72b98639 100644 --- a/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp +++ b/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp @@ -4,6 +4,7 @@ AssaultWeaponBehaviour::AssaultWeaponBehaviour(SystemParams systemParams, IRende : WeaponBehaviour(systemParams, renderer, collisionOctree, player) { m_FirstPersonModel = m_Player.FirstChildByName("Hands"); + m_ThirdPersonModel = m_Player.FirstChildByName("PlayerModel"); EVENT_SUBSCRIBE_MEMBER(m_EAnimationComplete, &AssaultWeaponBehaviour::OnAnimationComplete); } @@ -50,9 +51,14 @@ void AssaultWeaponBehaviour::Update(double dt) if (m_Reloading) { m_ReloadTimer -= dt; // Re-enable glow on reload impersonator half-way through the animation - if (m_ReloadTimer <= (double)m_Player["AssaultWeapon"]["ReloadTime"] / 2.0) { - if (m_ReloadImpersonator.Valid()) { - m_ReloadImpersonator["Model"]["GlowMap"] = true; + if (IsClient) { + if (m_ReloadTimer <= (double)m_Player["AssaultWeapon"]["ReloadTime"] / 2.0) { + if (m_FirstPersonReloadImpersonator.Valid()) { + m_FirstPersonReloadImpersonator["Model"]["GlowMap"] = true; + } + if (m_ThirdPersonReloadImpersonator.Valid()) { + m_ThirdPersonReloadImpersonator["Model"]["GlowMap"] = true; + } } } if (m_ReloadTimer <= 0) { @@ -69,14 +75,18 @@ void AssaultWeaponBehaviour::Update(double dt) } if (!m_Firing && !m_Reloading) { - playIdleAnimation(); + if (IsClient) { + playIdleAnimation(); + } } // Disable glow map on weapon if it's out of ammo // Make real first person weapon model visible again - EntityWrapper firstPersonWeaponModel = m_Player.FirstChildByName("WeaponModel"); - if (firstPersonWeaponModel.Valid()) { - firstPersonWeaponModel["Model"]["GlowMap"] = hasAmmo(); + if (IsClient) { + EntityWrapper firstPersonWeaponModel = m_Player.FirstChildByName("WeaponModel"); + if (firstPersonWeaponModel.Valid()) { + firstPersonWeaponModel["Model"]["GlowMap"] = hasAmmo(); + } } } @@ -121,16 +131,19 @@ void AssaultWeaponBehaviour::fireRound() // Fire magAmmo -= 1; - spawnTracer(); - playSound(); - viewPunch(); - playShootAnimation(); - bool hit = shoot(cAssaultWeapon["BaseDamage"]); - if (hit) { - showHitMarker(); - } - m_TimeSinceLastFire = 0.0; + + // Effects + if (IsClient) { + spawnTracer(); + playSound(); + viewPunch(); + playShootAnimation(); + bool hit = shoot(cAssaultWeapon["BaseDamage"]); + if (hit) { + showHitMarker(); + } + } } void AssaultWeaponBehaviour::spawnTracer() @@ -140,7 +153,8 @@ void AssaultWeaponBehaviour::spawnTracer() } EntityWrapper spawner; - if (m_Player == LocalPlayer) { + bool outOfBodyExperience = ResourceManager::Load("Config.ini")->Get("Debug.OutOfBodyExperience", false); + if (m_Player == LocalPlayer && !outOfBodyExperience) { spawner = m_Player.FirstChildByName("WeaponMuzzle"); } else { spawner = m_Player.FirstChildByName("ThirdPersonWeaponMuzzle"); @@ -206,7 +220,13 @@ void AssaultWeaponBehaviour::finishReload() // Make real first person weapon model visible again EntityWrapper firstPersonWeaponModel = m_Player.FirstChildByName("WeaponModel"); - firstPersonWeaponModel["Model"]["Visible"] = true; + if (firstPersonWeaponModel.Valid()) { + firstPersonWeaponModel["Model"]["Visible"] = true; + } + EntityWrapper thirdPersonWeaponModel = m_Player.FirstChildByName("ThirdPersonWeaponModel"); + if (thirdPersonWeaponModel.Valid()) { + thirdPersonWeaponModel["Model"]["Visible"] = true; + } m_Reloading = false; } @@ -259,19 +279,45 @@ void AssaultWeaponBehaviour::playIdleAnimation() void AssaultWeaponBehaviour::playReloadAnimation() { // Play animation - ComponentWrapper cAnimation = m_FirstPersonModel["Animation"]; - cAnimation["AnimationName1"] = "ReloadSwitch"; - cAnimation["Weight1"] = 1.0; - cAnimation["Time1"] = 0.0; - cAnimation["Speed1"] = 0.5; - cAnimation["Loop1"] = true; + // First person + if (IsClient) + { + ComponentWrapper cAnimation = m_FirstPersonModel["Animation"]; + cAnimation["AnimationName1"] = "ReloadSwitch"; + cAnimation["Weight1"] = 1.0; + cAnimation["Time1"] = 0.0; + cAnimation["Speed1"] = 0.5; + cAnimation["Loop1"] = true; + } + // TODO: Third person + //{ + // ComponentWrapper cAnimation = m_ThirdPersonModel["Animation"]; + // cAnimation["AnimationName1"] = "ReloadSwitch"; + // cAnimation["Weight1"] = 1.0; + // cAnimation["Time1"] = 0.0; + // cAnimation["Speed1"] = 0.5; + // cAnimation["Loop1"] = true; + //} // Hide weapon model and spawn the exploding version - EntityWrapper firstPersonWeaponModel = m_Player.FirstChildByName("WeaponModel"); - EntityWrapper reloadSpawner = m_Player.FirstChildByName("FirstPersonReloadSpawner"); - m_ReloadImpersonator = SpawnerSystem::Spawn(reloadSpawner, reloadSpawner); - firstPersonWeaponModel["Model"].Copy(m_ReloadImpersonator["Model"]); - firstPersonWeaponModel["Model"]["Visible"] = false; + { + EntityWrapper firstPersonWeaponModel = m_Player.FirstChildByName("WeaponModel"); + EntityWrapper reloadSpawner = m_Player.FirstChildByName("FirstPersonReloadSpawner"); + if (IsClient) { + m_FirstPersonReloadImpersonator = SpawnerSystem::Spawn(reloadSpawner, reloadSpawner); + firstPersonWeaponModel["Model"].Copy(m_FirstPersonReloadImpersonator["Model"]); + } + firstPersonWeaponModel["Model"]["Visible"] = false; + } + { + EntityWrapper thirdPersonWeaponModel = m_Player.FirstChildByName("ThirdPersonWeaponModel"); + EntityWrapper reloadSpawner = m_Player.FirstChildByName("ThirdPersonReloadSpawner"); + if (IsClient) { + m_ThirdPersonReloadImpersonator = SpawnerSystem::Spawn(reloadSpawner, reloadSpawner); + thirdPersonWeaponModel["Model"].Copy(m_ThirdPersonReloadImpersonator["Model"]); + } + thirdPersonWeaponModel["Model"]["Visible"] = false; + } } bool AssaultWeaponBehaviour::shoot(double damage) From fb5164221f8ec45b191c6395dfcfcc35a48e863c Mon Sep 17 00:00:00 2001 From: viktorljung Date: Fri, 12 Feb 2016 01:57:53 +0100 Subject: [PATCH 240/355] HealthHUD redesigned --- assets | 2 +- resources/Schema/Entities/AmmoHUD | 98 +++++++++++++++++++++++++++ resources/Schema/Entities/Player.xml | 99 +++++++++++++++++++--------- resources/Schema/Entities/temp | 38 +++++++++++ src/Engine/Rendering/Renderer.cpp | 1 + src/Game/Systems/HealthHUDSystem.cpp | 2 +- 6 files changed, 208 insertions(+), 32 deletions(-) create mode 100644 resources/Schema/Entities/AmmoHUD create mode 100644 resources/Schema/Entities/temp diff --git a/assets b/assets index 4d36fdce..0fd6b66b 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit 4d36fdced7007a594a56b7371bb26861876889aa +Subproject commit 0fd6b66b599ab98a441f91d5cc53c603009f488c diff --git a/resources/Schema/Entities/AmmoHUD b/resources/Schema/Entities/AmmoHUD new file mode 100644 index 00000000..6cdb6568 --- /dev/null +++ b/resources/Schema/Entities/AmmoHUD @@ -0,0 +1,98 @@ + + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + + + + + + + 0 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + 360 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + + + + + + + 0 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + 360 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/Player.xml b/resources/Schema/Entities/Player.xml index 39e7331f..30ae942e 100644 --- a/resources/Schema/Entities/Player.xml +++ b/resources/Schema/Entities/Player.xml @@ -76,14 +76,14 @@ - Textures/Core/UnitHexagon.png - + Textures/HealthHUD3.png + - - - + + + @@ -279,13 +279,33 @@ + + + + 1 + + + + + 100/100 + Fonts/DroidSans.ttf,64 + + + + + + + + + + Idle - 0.1719161089749548 + 1.1017089512865343 1 @@ -305,8 +325,8 @@ true - - + + @@ -327,36 +347,55 @@ - - + - - 32 - Fonts/DroidSans.ttf,64 - - + + Textures/Core/UnitHexagon.png + + - + + - + - - 360 - Fonts/DroidSans.ttf,64 - - - - - - + - + + + + + 32 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + 360 + Fonts/DroidSans.ttf,64 + + + + + + + + + + @@ -393,7 +432,7 @@ Idle - 1.8038469763698401 + 1.5336333336960681 1 @@ -418,8 +457,8 @@ false - - + + diff --git a/resources/Schema/Entities/temp b/resources/Schema/Entities/temp new file mode 100644 index 00000000..baf4ce61 --- /dev/null +++ b/resources/Schema/Entities/temp @@ -0,0 +1,38 @@ + + + + + + + + + + + + 0 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + 360 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + diff --git a/src/Engine/Rendering/Renderer.cpp b/src/Engine/Rendering/Renderer.cpp index 173ddb2b..be84160c 100644 --- a/src/Engine/Rendering/Renderer.cpp +++ b/src/Engine/Rendering/Renderer.cpp @@ -168,6 +168,7 @@ void Renderer::SortRenderJobsByDepth(RenderScene &scene) //Sort all forward jobs so transparency is good. scene.Jobs.TransparentObjects.sort(Renderer::DepthSort); scene.Jobs.SpriteJob.sort(Renderer::DepthSort); + scene.Jobs.Text.sort(Renderer::DepthSort); } void Renderer::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) diff --git a/src/Game/Systems/HealthHUDSystem.cpp b/src/Game/Systems/HealthHUDSystem.cpp index 49b2d0c1..b35bce12 100644 --- a/src/Game/Systems/HealthHUDSystem.cpp +++ b/src/Game/Systems/HealthHUDSystem.cpp @@ -27,7 +27,7 @@ void HealthHUDSystem::Update(double dt) s = s + "/"; s = s + std::to_string((int)(double)entityIDParent["Health"]["MaxHealth"]); float healthPercentage = (double)entityIDParent["Health"]["Health"]/(double)entityIDParent["Health"]["MaxHealth"]; - (glm::vec4&)entity["Text"]["Color"] = glm::vec4(1.0 - healthPercentage, 0.f, healthPercentage, glm::vec4(entity["Fill"]["Color"]).a); + (glm::vec4&)entity["Text"]["Color"] = glm::vec4(1.0 - healthPercentage, 0.f, healthPercentage, glm::vec4(entity["Text"]["Color"]).a); entity["Text"]["Content"] = s; } From 241717591430c5c871ac29f2c6876bd6b380eec3 Mon Sep 17 00:00:00 2001 From: antc13 Date: Fri, 12 Feb 2016 02:06:52 +0100 Subject: [PATCH 241/355] New Map with Meshes WIP. Probably final for Playtest. --- assets | 2 +- resources/Schema/Entities/NewMap.xml | 99 +++++++++++++--------------- 2 files changed, 46 insertions(+), 55 deletions(-) diff --git a/assets b/assets index 4d36fdce..078e014f 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit 4d36fdced7007a594a56b7371bb26861876889aa +Subproject commit 078e014f3d24a100c4cb544ac6807aa2b54149b2 diff --git a/resources/Schema/Entities/NewMap.xml b/resources/Schema/Entities/NewMap.xml index e0fcf912..d67540da 100644 --- a/resources/Schema/Entities/NewMap.xml +++ b/resources/Schema/Entities/NewMap.xml @@ -562,7 +562,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallBlue.mesh @@ -573,7 +573,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallBlue.mesh @@ -588,7 +588,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallBlue.mesh @@ -599,7 +599,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallBlue.mesh @@ -613,7 +613,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallRed.mesh @@ -625,7 +625,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallRed.mesh @@ -640,7 +640,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallRed.mesh @@ -652,7 +652,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallRed.mesh @@ -667,7 +667,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallRed.mesh @@ -679,7 +679,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallRed.mesh @@ -693,7 +693,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallRed.mesh @@ -709,7 +709,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallBlue.mesh @@ -721,7 +721,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallBlue.mesh @@ -734,7 +734,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallBlue.mesh @@ -980,7 +980,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallRed.mesh @@ -991,7 +991,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallRed.mesh @@ -1003,7 +1003,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallRed.mesh @@ -1014,7 +1014,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallRed.mesh @@ -1030,7 +1030,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallRed.mesh @@ -1043,7 +1043,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallRed.mesh @@ -1057,7 +1057,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallBlue.mesh @@ -1068,7 +1068,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallBlue.mesh @@ -1080,7 +1080,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallBlue.mesh @@ -1092,7 +1092,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallBlue.mesh @@ -1106,7 +1106,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallBlue.mesh @@ -1196,7 +1196,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallBlue.mesh @@ -1208,7 +1208,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallBlue.mesh @@ -1219,7 +1219,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallBlue.mesh @@ -1259,7 +1259,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallBlue.mesh @@ -1270,7 +1270,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallBlue.mesh @@ -1286,7 +1286,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallBlue.mesh @@ -1297,7 +1297,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallBlue.mesh @@ -1309,7 +1309,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallBlue.mesh @@ -1321,7 +1321,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallBlue.mesh @@ -1335,7 +1335,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallBlue.mesh @@ -1347,7 +1347,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallBlue.mesh @@ -1375,7 +1375,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallRed.mesh @@ -1386,7 +1386,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallRed.mesh @@ -1398,7 +1398,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallRed.mesh @@ -1412,7 +1412,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallRed.mesh @@ -1424,7 +1424,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallRed.mesh @@ -1438,7 +1438,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallRed.mesh @@ -1450,7 +1450,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallRed.mesh @@ -1474,7 +1474,7 @@ - Models/Props/Walls/BigWall.mesh + Models/Props/Walls/BigWallRed.mesh @@ -1611,16 +1611,7 @@ - - - - - - - - - - + From 021c4e36d75567a8cf36a860767bea666ad6ad03 Mon Sep 17 00:00:00 2001 From: viktorljung Date: Fri, 12 Feb 2016 02:08:24 +0100 Subject: [PATCH 242/355] New HUD XML files --- resources/Schema/Entities/AmmunitionHUD.xml | 62 +++++++++++++ .../Schema/Entities/CapturePointHUDGroup.xml | 5 +- resources/Schema/Entities/HealthHUD.xml | 50 ++++++++++ resources/Schema/Entities/Player.xml | 93 ++++++++++--------- 4 files changed, 165 insertions(+), 45 deletions(-) create mode 100644 resources/Schema/Entities/AmmunitionHUD.xml create mode 100644 resources/Schema/Entities/HealthHUD.xml diff --git a/resources/Schema/Entities/AmmunitionHUD.xml b/resources/Schema/Entities/AmmunitionHUD.xml new file mode 100644 index 00000000..2eaf2753 --- /dev/null +++ b/resources/Schema/Entities/AmmunitionHUD.xml @@ -0,0 +1,62 @@ + + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + + + + + + + 32 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + 360 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/CapturePointHUDGroup.xml b/resources/Schema/Entities/CapturePointHUDGroup.xml index 9dce0ffb..d35e1bde 100644 --- a/resources/Schema/Entities/CapturePointHUDGroup.xml +++ b/resources/Schema/Entities/CapturePointHUDGroup.xml @@ -1,9 +1,10 @@ - + - + + diff --git a/resources/Schema/Entities/HealthHUD.xml b/resources/Schema/Entities/HealthHUD.xml new file mode 100644 index 00000000..ec781d8f --- /dev/null +++ b/resources/Schema/Entities/HealthHUD.xml @@ -0,0 +1,50 @@ + + + + + + + + + + + + 1 + + + + + 100/100 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + 1 + + + + Textures/HealthHUD3.png + + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/Player.xml b/resources/Schema/Entities/Player.xml index 30ae942e..b34669ca 100644 --- a/resources/Schema/Entities/Player.xml +++ b/resources/Schema/Entities/Player.xml @@ -69,25 +69,6 @@ - - - - 1 - - - - Textures/HealthHUD3.png - - - - - - - - - - - @@ -279,25 +260,51 @@ - + - - 1 - - - - - 100/100 - Fonts/DroidSans.ttf,64 - - - - - - - + - + + + + + 1 + + + + + 100/100 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + 1 + + + + Textures/HealthHUD3.png + + + + + + + + + + + + @@ -305,7 +312,7 @@ Idle - 1.1017089512865343 + 0.24990652025910975 1 @@ -325,8 +332,8 @@ true - - + + @@ -363,7 +370,7 @@ - + @@ -432,7 +439,7 @@ Idle - 1.5336333336960681 + 1.6484966474501377 1 @@ -457,8 +464,8 @@ false - - + + From 71533b52aed61273516fab17a873860c1e25cf25 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Fri, 12 Feb 2016 02:10:42 +0100 Subject: [PATCH 243/355] Map fix --- resources/Schema/Entities/NewMap.xml | 76 ++++- resources/Schema/Entities/PlayerRed.xml | 272 ++++++++++++++++++ resources/Schema/Entities/RayRed.xml | 6 +- .../Systems/Weapon/AssaultWeaponBehaviour.cpp | 3 + 4 files changed, 349 insertions(+), 8 deletions(-) create mode 100644 resources/Schema/Entities/PlayerRed.xml diff --git a/resources/Schema/Entities/NewMap.xml b/resources/Schema/Entities/NewMap.xml index f4c768f0..1ae09247 100644 --- a/resources/Schema/Entities/NewMap.xml +++ b/resources/Schema/Entities/NewMap.xml @@ -3365,7 +3365,7 @@ Models/Core/UnitCylinder.mesh - + true @@ -3401,7 +3401,7 @@ Models/Core/UnitCylinder.mesh - + true @@ -3465,7 +3465,7 @@ Models/Core/UnitCylinder.mesh - + true @@ -3500,7 +3500,7 @@ Models/Core/UnitCylinder.mesh - + true @@ -3618,7 +3618,7 @@ - Schema/Entities/Player.xml + Schema/Entities/PlayerRed.xml @@ -3829,6 +3829,72 @@ + + + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + + + + + + + + + diff --git a/resources/Schema/Entities/PlayerRed.xml b/resources/Schema/Entities/PlayerRed.xml new file mode 100644 index 00000000..ae11fa00 --- /dev/null +++ b/resources/Schema/Entities/PlayerRed.xml @@ -0,0 +1,272 @@ + + + + + + + + + + 600 + + + + + + + + + 5 + + + + + + + + + + + + + + + + + + + + + + + + Fonts/DroidSans.ttf,100 + + + + + + + + + + + + + + Models/Widgets/Camera.mesh + false + + + + + + + + + + + + + + + + + + + 1 + + + + + Models/Core/UnitHexagon.mesh + + + + + + + + + + + + + + Textures/Weapons/Crosshair/SmallThickHoleDot.png + false + + + + + + + + + + + + Schema/Entities/HitMarker.xml + + + + + + + + + + + Idle + 0.1719161089749548 + 1 + + + Models/Characters/Assault/FirstPerson.mesh + true + + + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Red/AssaultWeaponRed.mesh + true + + + + + + + + + + + Schema/Entities/RayRed.xml + + + + + + + + + + + Schema/Entities/ReloadEffectView.xml + + + + + + + + + + + + + + + + Models/Widgets/Camera.mesh + false + + + + + + + + + + + + Idle + 1.8038469763698401 + 1 + + + AimRifle + + + + + Models/Characters/Assault/AssaultAnimations.mesh + + + + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Red/AssaultWeaponRed.mesh + + + + + + + + + + + Schema/Entities/RayRed.xml + + + + + + + + + + + Schema/Entities/ReloadEffectWorld.xml + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + false + + + + + + + + + + + + Models/Core/UnitCube.mesh + + false + + + + + + + + + + diff --git a/resources/Schema/Entities/RayRed.xml b/resources/Schema/Entities/RayRed.xml index 11a9b077..0a20f148 100644 --- a/resources/Schema/Entities/RayRed.xml +++ b/resources/Schema/Entities/RayRed.xml @@ -6,12 +6,12 @@ 0.25 - Models/Weapons/CylinderBullet.mesh - + Models/Effects/CylinderShot.mesh + true - + diff --git a/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp b/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp index 72b98639..706adaa0 100644 --- a/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp +++ b/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp @@ -348,6 +348,9 @@ bool AssaultWeaponBehaviour::shoot(double damage) } EntityWrapper victim(m_World, pickData.Entity); + if (!victim.Valid()) { + return false; + } // Don't let us shoot ourselves in the foot if (victim == LocalPlayer) { From e1196204eb381673f06dd22c38ef58573ccf2cd1 Mon Sep 17 00:00:00 2001 From: Tleety Date: Fri, 12 Feb 2016 02:20:40 +0100 Subject: [PATCH 244/355] asdfsdaferf --- src/Engine/Rendering/PickingPass.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Engine/Rendering/PickingPass.cpp b/src/Engine/Rendering/PickingPass.cpp index fa1b3ca3..33649b3a 100644 --- a/src/Engine/Rendering/PickingPass.cpp +++ b/src/Engine/Rendering/PickingPass.cpp @@ -125,7 +125,7 @@ void PickingPass::Draw(RenderScene& scene) } } - for (auto &job : scene.Jobs.TransparentObjects) { + /* for (auto &job : scene.Jobs.TransparentObjects) { auto modelJob = std::dynamic_pointer_cast(job); int pickColor[2] = { m_ColorCounter[0], m_ColorCounter[1] }; @@ -178,7 +178,7 @@ void PickingPass::Draw(RenderScene& scene) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer); glDrawElements(GL_TRIANGLES, modelJob->EndIndex - modelJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(modelJob->StartIndex * sizeof(unsigned int))); } - } + }*/ for (auto &job : scene.Jobs.OpaqueShieldedObjects) { auto modelJob = std::dynamic_pointer_cast(job); @@ -236,7 +236,7 @@ void PickingPass::Draw(RenderScene& scene) } } - for (auto &job : scene.Jobs.TransparentShieldedObjects) { + /* for (auto &job : scene.Jobs.TransparentShieldedObjects) { auto modelJob = std::dynamic_pointer_cast(job); if (modelJob) { @@ -300,7 +300,7 @@ void PickingPass::Draw(RenderScene& scene) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, modelJob->Model->ElementBuffer); glDrawElements(GL_TRIANGLES, modelJob->EndIndex - modelJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(modelJob->StartIndex * sizeof(unsigned int))); } - } + }*/ m_PickingBuffer.Unbind(); GLERROR("PickingPass Error"); From 1dc37565334e1745e80e5dfe5718d645188ce0e2 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Fri, 12 Feb 2016 02:23:13 +0100 Subject: [PATCH 245/355] Fixed respawn crash when a player died that had never spawned --- src/Game/Systems/PlayerSpawnSystem.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/Game/Systems/PlayerSpawnSystem.cpp b/src/Game/Systems/PlayerSpawnSystem.cpp index ac0ecdf3..e43cee13 100644 --- a/src/Game/Systems/PlayerSpawnSystem.cpp +++ b/src/Game/Systems/PlayerSpawnSystem.cpp @@ -175,8 +175,15 @@ bool PlayerSpawnSystem::OnPlayerDeath(Events::PlayerDeath& e) if ((ComponentInfo::EnumType)cTeam["Team"] == cTeam["Team"].Enum("Spectator")) { return false; } + + if (m_PlayerIDs.count(e.Player.ID) == 0) { + return false; + } + SpawnRequest req; req.PlayerID = m_PlayerIDs.at(e.Player.ID); req.Team = cTeam["Team"]; m_SpawnRequests.push_back(req); + + return true; } From 987dafb44aa0c24fb7f2814291dfaceae9611f9d Mon Sep 17 00:00:00 2001 From: viktorljung Date: Fri, 12 Feb 2016 02:38:11 +0100 Subject: [PATCH 246/355] Fixed Health text color --- src/Game/Systems/HealthHUDSystem.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Game/Systems/HealthHUDSystem.cpp b/src/Game/Systems/HealthHUDSystem.cpp index b35bce12..74258d6e 100644 --- a/src/Game/Systems/HealthHUDSystem.cpp +++ b/src/Game/Systems/HealthHUDSystem.cpp @@ -27,7 +27,7 @@ void HealthHUDSystem::Update(double dt) s = s + "/"; s = s + std::to_string((int)(double)entityIDParent["Health"]["MaxHealth"]); float healthPercentage = (double)entityIDParent["Health"]["Health"]/(double)entityIDParent["Health"]["MaxHealth"]; - (glm::vec4&)entity["Text"]["Color"] = glm::vec4(1.0 - healthPercentage, 0.f, healthPercentage, glm::vec4(entity["Text"]["Color"]).a); + //(glm::vec4&)entity["Text"]["Color"] = glm::vec4(1.0 - healthPercentage, 0.f, healthPercentage, glm::vec4(entity["Text"]["Color"]).a); entity["Text"]["Content"] = s; } From 4f7a17ff620d44b9893505d440c182a55f7bfb29 Mon Sep 17 00:00:00 2001 From: Tleety Date: Fri, 12 Feb 2016 02:38:36 +0100 Subject: [PATCH 247/355] ColorFix --- src/Game/Systems/CapturePointHUDSystem.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Game/Systems/CapturePointHUDSystem.cpp b/src/Game/Systems/CapturePointHUDSystem.cpp index 21737fbe..3ca4601d 100644 --- a/src/Game/Systems/CapturePointHUDSystem.cpp +++ b/src/Game/Systems/CapturePointHUDSystem.cpp @@ -39,14 +39,14 @@ void CapturePointHUDSystem::Update(double dt) } //Color hud with team color auto capturePointTeam = (int)teamComponent["Team"]; - entityHUDparent["Sprite"]["Color"] = capturePointTeam == blueTeam ? glm::vec4(0, 0.2f, 1, 0.7) : capturePointTeam == redTeam ? glm::vec4(1, 0.2f, 0, 0.7) : glm::vec4(1, 1, 1, 0.3); + entityHUDparent["Sprite"]["Color"] = capturePointTeam == blueTeam ? glm::vec4(0, 0.2f, 1, 0.7f) : capturePointTeam == redTeam ? glm::vec4(1, 0.0f, 0, 0.7f) : glm::vec4(1, 1, 1, 0.3f); //Progress is scaled with time double currentCaptureTime = (double)entityCP["CapturePoint"]["CaptureTimer"]; double progress = glm::abs(currentCaptureTime)/15.0; int currentCapturingTeam = currentCaptureTime > 0 ? redTeam : currentCaptureTime < 0 ? blueTeam : spectatorTeam; ((glm::vec3&)entityHUD["Transform"]["Orientation"]).z = currentCapturingTeam == redTeam ? glm::half_pi()+glm::pi() : glm::half_pi(); - glm::vec4 fillColor = currentCapturingTeam == redTeam ? glm::vec4(1, 0.2f, 0, 0.7) : glm::vec4(0, 0.2f, 1, 0.7); + glm::vec4 fillColor = currentCapturingTeam == redTeam ? glm::vec4(1, 0.f, 0, 0.7f) : glm::vec4(0, 0.2f, 1, 0.7f); entityHUD["Fill"]["Color"] = fillColor; entityHUD["Fill"]["Percentage"] = progress; } From a54156fab3513ec3334d540f96262c6b5e997dfe Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Fri, 12 Feb 2016 02:46:16 +0100 Subject: [PATCH 248/355] Added HUD elements to player --- resources/Schema/Entities/Player.xml | 305 ++++++++++++++++++++++++--- 1 file changed, 279 insertions(+), 26 deletions(-) diff --git a/resources/Schema/Entities/Player.xml b/resources/Schema/Entities/Player.xml index 05dc79e2..54d95e83 100644 --- a/resources/Schema/Entities/Player.xml +++ b/resources/Schema/Entities/Player.xml @@ -23,9 +23,7 @@ - - - + @@ -71,25 +69,6 @@ - - - - 1 - - - - - Models/Core/UnitHexagon.mesh - - - - - - - - - - @@ -112,6 +91,221 @@ + + + + + + + + + 1 + + + + + 100/100 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + 1 + + + + Textures/HealthHUD3.png + + + + + + + + + + + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + 2 + + + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + 3 + + + 0.80222018197612788 + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + 4 + + + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + 1 + + + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + @@ -138,8 +332,8 @@ true - - + + @@ -163,6 +357,64 @@ + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + + + + + + + 32 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + 360 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + @@ -198,6 +450,7 @@ Models/Characters/Assault/AssaultAnimations.mesh + false @@ -211,8 +464,8 @@ Models/Weapons/Blue/AssaultWeaponBlue.mesh - - + + From b5e372896f00f84f13e7b87405c75bcdefe1cd63 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Fri, 12 Feb 2016 02:46:42 +0100 Subject: [PATCH 249/355] Added spawner? --- resources/Schema/Entities/NewMap.xml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/resources/Schema/Entities/NewMap.xml b/resources/Schema/Entities/NewMap.xml index a74b7ef2..7d1f47ca 100644 --- a/resources/Schema/Entities/NewMap.xml +++ b/resources/Schema/Entities/NewMap.xml @@ -4986,11 +4986,6 @@ - - - - - @@ -5004,7 +4999,7 @@ - + @@ -5053,6 +5048,11 @@ + + + + + From 784e1eb69b6a042c92ad2ca0752630707c818960 Mon Sep 17 00:00:00 2001 From: antc13 Date: Fri, 12 Feb 2016 02:46:44 +0100 Subject: [PATCH 250/355] Changed Colors on some materials and changed bridges to red and blue bridges. --- assets | 2 +- resources/Schema/Entities/NewMap.xml | 18 ++++++++++++------ 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/assets b/assets index 078e014f..41ddd103 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit 078e014f3d24a100c4cb544ac6807aa2b54149b2 +Subproject commit 41ddd1033501350e1a71d09c489da1aa0acc2f82 diff --git a/resources/Schema/Entities/NewMap.xml b/resources/Schema/Entities/NewMap.xml index d67540da..fd2b71a4 100644 --- a/resources/Schema/Entities/NewMap.xml +++ b/resources/Schema/Entities/NewMap.xml @@ -89,6 +89,7 @@ Models/Props/Highground5.mesh + @@ -99,6 +100,7 @@ Models/Props/Highground6.mesh + @@ -1515,6 +1517,7 @@ Models/Props/Flora/SpecialRoot.mesh + @@ -1885,7 +1888,7 @@ - Models/Props/Bridges/SciFiBridge.mesh + Models/Props/Bridges/SciFiBridge1Red.mesh @@ -2004,7 +2007,7 @@ - Models/Props/Bridges/SciFiBridge.mesh + Models/Props/Bridges/SciFiBridge1Blue.mesh @@ -2138,7 +2141,7 @@ - Models/Props/Bridges/SciFiBridge.mesh + Models/Props/Bridges/SciFiBridge1Blue.mesh @@ -2151,7 +2154,7 @@ - Models/Props/Bridges/SciFiBridge.mesh + Models/Props/Bridges/SciFiBridge1Blue.mesh @@ -2178,7 +2181,7 @@ - Models/Props/Bridges/SciFiBridge.mesh + Models/Props/Bridges/SciFiBridge1Red.mesh @@ -2191,7 +2194,7 @@ - Models/Props/Bridges/SciFiBridge.mesh + Models/Props/Bridges/SciFiBridge1Red.mesh @@ -2730,6 +2733,7 @@ Models/Props/Flora/SpecialRoot.mesh + @@ -2948,6 +2952,7 @@ Models/Props/Flora/SpecialRoot.mesh + @@ -3061,6 +3066,7 @@ Models/Props/Flora/SpecialRoot.mesh + From 215b1b1aa4bb6deaf978ed2255643142886e4697 Mon Sep 17 00:00:00 2001 From: William Moberg Date: Fri, 12 Feb 2016 03:32:42 +0100 Subject: [PATCH 251/355] On crash, takes minidump, then show MessageBox, and exit app. --- include/Game/MiniDump.h | 8 +++ src/Game/MiniDump.cpp | 106 ++++++++++++++++++++++++++++++++++++++++ src/Game/main.cpp | 22 +++++++-- 3 files changed, 132 insertions(+), 4 deletions(-) create mode 100644 include/Game/MiniDump.h create mode 100644 src/Game/MiniDump.cpp diff --git a/include/Game/MiniDump.h b/include/Game/MiniDump.h new file mode 100644 index 00000000..4ad4548d --- /dev/null +++ b/include/Game/MiniDump.h @@ -0,0 +1,8 @@ +#ifndef MiniDump_h__ +#define MiniDump_h__ + +#include + +void WINAPI Create_Dump(PEXCEPTION_POINTERS pException, BOOL File_Flag, BOOL Show_Flag); + +#endif diff --git a/src/Game/MiniDump.cpp b/src/Game/MiniDump.cpp new file mode 100644 index 00000000..0547e54e --- /dev/null +++ b/src/Game/MiniDump.cpp @@ -0,0 +1,106 @@ +/* + Author: Vladimir Sedach. + + Purpose: demo of Call Stack creation by our own means, + and with MiniDumpWriteDump() function of DbgHelp.dll. +*/ + +#include + +#include +#include +//#include "dbghelp.h" + +//#define DEBUG_DPRINTF 1 //allow d() +//#include "wfun.h" + +#pragma optimize("y", off) //generate stack frame pointers for all functions - same as /Oy- in the project +#pragma warning(disable: 4200) //nonstandard extension used : zero-sized array in struct/union +#pragma warning(disable: 4100) //unreferenced formal parameter + +// In case you don't have dbghelp.h. +#ifndef _DBGHELP_ + +typedef struct _MINIDUMP_EXCEPTION_INFORMATION { + DWORD ThreadId; + PEXCEPTION_POINTERS ExceptionPointers; + BOOL ClientPointers; +} MINIDUMP_EXCEPTION_INFORMATION, *PMINIDUMP_EXCEPTION_INFORMATION; + +typedef enum _MINIDUMP_TYPE { + MiniDumpNormal = 0x00000000, + MiniDumpWithDataSegs = 0x00000001, +} MINIDUMP_TYPE; + +typedef BOOL (WINAPI * MINIDUMP_WRITE_DUMP)( + IN HANDLE hProcess, + IN DWORD ProcessId, + IN HANDLE hFile, + IN MINIDUMP_TYPE DumpType, + IN CONST PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam, OPTIONAL + IN PVOID UserStreamParam, OPTIONAL + IN PVOID CallbackParam OPTIONAL + ); + +#else + +typedef BOOL (WINAPI * MINIDUMP_WRITE_DUMP)( + IN HANDLE hProcess, + IN DWORD ProcessId, + IN HANDLE hFile, + IN MINIDUMP_TYPE DumpType, + IN CONST PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam, OPTIONAL + IN PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam, OPTIONAL + IN PMINIDUMP_CALLBACK_INFORMATION CallbackParam OPTIONAL + ); +#endif //#ifndef _DBGHELP_ + +HMODULE hDbgHelp; +MINIDUMP_WRITE_DUMP MiniDumpWriteDump_; + +// Tool Help functions. +typedef HANDLE (WINAPI * CREATE_TOOL_HELP32_SNAPSHOT)(DWORD dwFlags, DWORD th32ProcessID); + +//************************************************************************************* +void WINAPI Create_Dump(PEXCEPTION_POINTERS pException, BOOL File_Flag, BOOL Show_Flag) +//************************************************************************************* +// Create dump. +// pException can be either GetExceptionInformation() or NULL. +// If File_Flag = TRUE - write dump files (.dmz and .dmp) with the name of the current process. +// If Show_Flag = TRUE - show message with Get_Exception_Info() dump. +{ + // Try to get MiniDumpWriteDump() address. + hDbgHelp = LoadLibrary("DBGHELP.DLL"); + MiniDumpWriteDump_ = (MINIDUMP_WRITE_DUMP)GetProcAddress(hDbgHelp, "MiniDumpWriteDump"); + + // If MiniDumpWriteDump() of DbgHelp.dll available. + if (MiniDumpWriteDump_) + { + HANDLE hDump_File; + CHAR Dump_Path[MAX_PATH]; + + GetModuleFileName(NULL, Dump_Path, sizeof(Dump_Path)); //path of current process + + MINIDUMP_EXCEPTION_INFORMATION M; + + M.ThreadId = GetCurrentThreadId(); + M.ExceptionPointers = pException; + M.ClientPointers = 0; + + lstrcpy(Dump_Path + lstrlen(Dump_Path) - 3, "dmp"); + + hDump_File = CreateFile(Dump_Path, + GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + + MiniDumpWriteDump_(GetCurrentProcess(), GetCurrentProcessId(), hDump_File, + MiniDumpNormal, (pException) ? &M : NULL, NULL, NULL); + + CloseHandle(hDump_File); + + std::cout << "Memory dumped to: \"" << Dump_Path << "\""; + MessageBox(NULL, ("Application crashed, memory dumped to: " + std::string(Dump_Path)).c_str(), "MiniDump", MB_ICONHAND | MB_OK); + } else { + MessageBox(NULL, "Application crashed, memory dump failed.", "MiniDump", MB_ICONHAND | MB_OK); + } +} + diff --git a/src/Game/main.cpp b/src/Game/main.cpp index 613165dd..dd2a5a84 100644 --- a/src/Game/main.cpp +++ b/src/Game/main.cpp @@ -1,11 +1,25 @@ #include "Game.h" +#include "MiniDump.h" + +LONG WINAPI CrashHandler(EXCEPTION_POINTERS* pException); int main(int argc, char* argv[]) { - Game game(argc, argv); - while (game.Running()) { - game.Tick(); - } + ::SetUnhandledExceptionFilter(CrashHandler); + + Game game(argc, argv); + while (game.Running()) { + game.Tick(); + } return 0; +} + +LONG WINAPI CrashHandler(EXCEPTION_POINTERS* pException) +{ + //Take minidump. path should be bin/TacticalZ.dmp + //Then show MessageBox, and exit application. + Create_Dump(pException, 1, 1); + + return EXCEPTION_EXECUTE_HANDLER;// EXCEPTION_CONTINUE_SEARCH } \ No newline at end of file From 787eecce26917e917f5aed99bfdf46b87541b335 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Fri, 12 Feb 2016 04:03:22 +0100 Subject: [PATCH 252/355] WIP --- include/Engine/Network/Server.h | 1 + src/Engine/Network/Server.cpp | 30 +++++++++++++++++++++++------- 2 files changed, 24 insertions(+), 7 deletions(-) diff --git a/include/Engine/Network/Server.h b/include/Engine/Network/Server.h index f16c6c16..fbba5340 100644 --- a/include/Engine/Network/Server.h +++ b/include/Engine/Network/Server.h @@ -89,6 +89,7 @@ private: EventRelay m_EComponentDeleted; bool OnComponentDeleted(const Events::ComponentDeleted& e); void parsePlayerTransform(Packet& packet); + bool shouldSendToClient(EntityWrapper childEntity); }; #endif diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index a6174f7a..ff6e0433 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -185,11 +185,18 @@ void Server::addInputCommandsToPacket(Packet& packet) void Server::addChildrenToPacket(Packet & packet, EntityID entityID) { + // HACK: Only sync players for now, since the map turned out to be TOO LARGE to send in one snapshot and Simon's computer shits itself + EntityWrapper entity(m_World, entityID); + if (entityID != EntityID_Invalid && !shouldSendToClient(entity)) { + return; + } + auto itPair = m_World->GetChildren(entityID); std::unordered_map worldComponentPools = m_World->GetComponentPools(); // Loop through every child for (auto it = itPair.first; it != itPair.second; it++) { EntityID childEntityID = it->second; + // Write EntityID and parentsID and Entity name packet.WritePrimitive(childEntityID); packet.WritePrimitive(entityID); @@ -435,9 +442,11 @@ bool Server::OnPlayerSpawned(const Events::PlayerSpawned & e) bool Server::OnEntityDeleted(const Events::EntityDeleted & e) { if (!e.Cascaded) { - Packet packet = Packet(MessageType::EntityDeleted); - packet.WritePrimitive(e.DeletedEntity); - broadcast(packet); + if (shouldSendToClient(EntityWrapper(m_World, e.DeletedEntity))) { + Packet packet = Packet(MessageType::EntityDeleted); + packet.WritePrimitive(e.DeletedEntity); + broadcast(packet); + } } return false; } @@ -445,10 +454,12 @@ bool Server::OnEntityDeleted(const Events::EntityDeleted & e) bool Server::OnComponentDeleted(const Events::ComponentDeleted & e) { if (!e.Cascaded) { - Packet packet = Packet(MessageType::ComponentDeleted); - packet.WritePrimitive(e.Entity); - packet.WriteString(e.ComponentType); - broadcast(packet); + if (shouldSendToClient(EntityWrapper(m_World, e.Entity))) { + Packet packet = Packet(MessageType::ComponentDeleted); + packet.WritePrimitive(e.Entity); + packet.WriteString(e.ComponentType); + broadcast(packet); + } } return false; } @@ -484,3 +495,8 @@ void Server::parsePlayerTransform(Packet& packet) } } } + +bool Server::shouldSendToClient(EntityWrapper childEntity) +{ + return childEntity.HasComponent("Player") || childEntity.FirstParentWithComponent("Player").Valid(); +} From 1da432ba23da062cf35120053af631aa812e20b7 Mon Sep 17 00:00:00 2001 From: stiffly Date: Fri, 12 Feb 2016 04:03:03 +0100 Subject: [PATCH 253/355] WIP sounds --- assets | 2 +- include/Game/Systems/Weapon/AssaultWeaponBehaviour.h | 1 + src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp | 8 ++++++++ 3 files changed, 10 insertions(+), 1 deletion(-) diff --git a/assets b/assets index 078e014f..8d180f2a 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit 078e014f3d24a100c4cb544ac6807aa2b54149b2 +Subproject commit 8d180f2a54154191587107e6569bbae0a049be46 diff --git a/include/Game/Systems/Weapon/AssaultWeaponBehaviour.h b/include/Game/Systems/Weapon/AssaultWeaponBehaviour.h index 915854ff..90959d0e 100644 --- a/include/Game/Systems/Weapon/AssaultWeaponBehaviour.h +++ b/include/Game/Systems/Weapon/AssaultWeaponBehaviour.h @@ -6,6 +6,7 @@ #include "Core/EPlayerDamage.h" #include "Core/EShoot.h" + class AssaultWeaponBehaviour : public WeaponBehaviour { public: diff --git a/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp b/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp index 54c3a590..a59397d1 100644 --- a/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp +++ b/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp @@ -43,6 +43,10 @@ void AssaultWeaponBehaviour::Reload() m_Reloading = true; m_ReloadTimer = cAssaultWeapon["ReloadTime"]; playReloadAnimation(); + Events::PlaySoundOnEntity e; + e.EmitterID = cAssaultWeapon.EntityID; + e.FilePath = "Audio/weapon/reload.wav"; + m_EventBroker->Publish(e); } void AssaultWeaponBehaviour::Update(double dt) @@ -337,5 +341,9 @@ void AssaultWeaponBehaviour::showHitMarker() EntityWrapper hitMarkerSpawner = m_Player.FirstChildByName("HitMarkerSpawner"); if (hitMarkerSpawner.Valid()) { SpawnerSystem::Spawn(hitMarkerSpawner, hitMarkerSpawner); + Events::PlaySoundOnEntity e; + e.EmitterID = hitMarkerSpawner.ID; // This might not be the optimal spawner entity + e.FilePath = "Audio/weapon/hitclick.wav"; + m_EventBroker->Publish(e); } } From 422bedb844c6f3dbbe18e4304270b2502cff95d3 Mon Sep 17 00:00:00 2001 From: William Moberg Date: Fri, 12 Feb 2016 04:22:11 +0100 Subject: [PATCH 254/355] MiniDump name now depends on time e.g. TacticalZ Fri 04-20-49. --- src/Game/MiniDump.cpp | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/src/Game/MiniDump.cpp b/src/Game/MiniDump.cpp index 0547e54e..bd8ee2de 100644 --- a/src/Game/MiniDump.cpp +++ b/src/Game/MiniDump.cpp @@ -6,6 +6,7 @@ */ #include +#include #include #include @@ -80,25 +81,28 @@ void WINAPI Create_Dump(PEXCEPTION_POINTERS pException, BOOL File_Flag, BOOL Sho CHAR Dump_Path[MAX_PATH]; GetModuleFileName(NULL, Dump_Path, sizeof(Dump_Path)); //path of current process + std::time_t t = std::time(NULL); + char tStr[16]; + std::strftime(tStr, 32, " %a %H-%M-%S", std::localtime(&t)); + std::string time(tStr); + std::string path(Dump_Path); + path = path.substr(0, path.length() - 4); + path += time + ".dmp"; MINIDUMP_EXCEPTION_INFORMATION M; - M.ThreadId = GetCurrentThreadId(); M.ExceptionPointers = pException; M.ClientPointers = 0; - lstrcpy(Dump_Path + lstrlen(Dump_Path) - 3, "dmp"); - - hDump_File = CreateFile(Dump_Path, - GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + hDump_File = CreateFile(path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); MiniDumpWriteDump_(GetCurrentProcess(), GetCurrentProcessId(), hDump_File, MiniDumpNormal, (pException) ? &M : NULL, NULL, NULL); CloseHandle(hDump_File); - std::cout << "Memory dumped to: \"" << Dump_Path << "\""; - MessageBox(NULL, ("Application crashed, memory dumped to: " + std::string(Dump_Path)).c_str(), "MiniDump", MB_ICONHAND | MB_OK); + std::cout << "Memory dumped to: \"" << path.c_str() << "\""; + MessageBox(NULL, ("Application crashed, memory dumped to: " + path).c_str(), "MiniDump", MB_ICONHAND | MB_OK); } else { MessageBox(NULL, "Application crashed, memory dump failed.", "MiniDump", MB_ICONHAND | MB_OK); } From a8a3366e8a424b4fb56265ae57ba1f7025907fff Mon Sep 17 00:00:00 2001 From: Tleety Date: Fri, 12 Feb 2016 05:17:09 +0100 Subject: [PATCH 255/355] Hopeless attempts to fix network bugs --- resources/DefaultConfig.ini | 2 +- src/Engine/Network/Server.cpp | 2 +- src/Game/Systems/CapturePointSystem.cpp | 12 +++++++++--- src/Game/Systems/PlayerMovementSystem.cpp | 20 +++++++++++--------- src/Game/Systems/SoundSystem.cpp | 20 +++++++++++++------- 5 files changed, 35 insertions(+), 21 deletions(-) diff --git a/resources/DefaultConfig.ini b/resources/DefaultConfig.ini index 9c6dfd8f..60ee4823 100644 --- a/resources/DefaultConfig.ini +++ b/resources/DefaultConfig.ini @@ -23,7 +23,7 @@ StartNetwork=false IsServer=false Name=Bob Address=127.0.0.1 -Port=13 +Port=27666 MaxConnections=8 SnapshotInterval=0.05 SendInputIntervalMs=33 diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index ff6e0433..bb2115de 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -187,7 +187,7 @@ void Server::addChildrenToPacket(Packet & packet, EntityID entityID) { // HACK: Only sync players for now, since the map turned out to be TOO LARGE to send in one snapshot and Simon's computer shits itself EntityWrapper entity(m_World, entityID); - if (entityID != EntityID_Invalid && !shouldSendToClient(entity)) { + if (!entity.Valid() || !shouldSendToClient(entity)) { return; } diff --git a/src/Game/Systems/CapturePointSystem.cpp b/src/Game/Systems/CapturePointSystem.cpp index f938ecd0..5fdd74cd 100644 --- a/src/Game/Systems/CapturePointSystem.cpp +++ b/src/Game/Systems/CapturePointSystem.cpp @@ -6,15 +6,21 @@ CapturePointSystem::CapturePointSystem(SystemParams params) , PureSystem("CapturePoint") { //subscribe/listenTo playerdamage,healthpickup events (using the eventBroker) - EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &CapturePointSystem::OnTriggerTouch); - EVENT_SUBSCRIBE_MEMBER(m_ETriggerLeave, &CapturePointSystem::OnTriggerLeave); - EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &CapturePointSystem::OnCaptured); + if (IsClient) { + EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &CapturePointSystem::OnTriggerTouch); + EVENT_SUBSCRIBE_MEMBER(m_ETriggerLeave, &CapturePointSystem::OnTriggerLeave); + EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &CapturePointSystem::OnCaptured); + } } //here all capturepoints will update their component //NOTE: needs to run each frame, since we're possibly modifying the captureTimer for the capturePoints by dt void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, ComponentWrapper& cCapturePoint, double dt) { + if (!IsClient) { + return; + } + if (m_WinnerWasFound) { return; } diff --git a/src/Game/Systems/PlayerMovementSystem.cpp b/src/Game/Systems/PlayerMovementSystem.cpp index badaf638..9bf1d25e 100644 --- a/src/Game/Systems/PlayerMovementSystem.cpp +++ b/src/Game/Systems/PlayerMovementSystem.cpp @@ -114,15 +114,17 @@ void PlayerMovementSystem::updateMovementControllers(double dt) if (isOnGround) { controller->SetDoubleJumping(false); } else { - //put a hexagon at the players feet - auto hexagonEffect = ResourceManager::Load("Schema/Entities/DoubleJumpHexagon.xml"); - EntityFileParser parser(hexagonEffect); - EntityID hexagonEffectID = parser.MergeEntities(m_World); - EntityWrapper hexagonEW = EntityWrapper(m_World, hexagonEffectID); - hexagonEW["Transform"]["Position"] = (glm::vec3)player["Transform"]["Position"]; - controller->SetDoubleJumping(true); - Events::DoubleJump e; - m_EventBroker->Publish(e); + if (IsClient) { + //put a hexagon at the players feet + auto hexagonEffect = ResourceManager::Load("Schema/Entities/DoubleJumpHexagon.xml"); + EntityFileParser parser(hexagonEffect); + EntityID hexagonEffectID = parser.MergeEntities(m_World); + EntityWrapper hexagonEW = EntityWrapper(m_World, hexagonEffectID); + hexagonEW["Transform"]["Position"] = (glm::vec3)player["Transform"]["Position"]; + controller->SetDoubleJumping(true); + Events::DoubleJump e; + m_EventBroker->Publish(e); + } } velocity.y = 4.f; } diff --git a/src/Game/Systems/SoundSystem.cpp b/src/Game/Systems/SoundSystem.cpp index 59fd4a7f..7101311d 100644 --- a/src/Game/Systems/SoundSystem.cpp +++ b/src/Game/Systems/SoundSystem.cpp @@ -6,13 +6,15 @@ SoundSystem::SoundSystem(SystemParams params) { ConfigFile* config = ResourceManager::Load("Config.ini"); m_Announcer = ResourceManager::Load("Config.ini")->Get("Sound.Announcer", "female"); - EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &SoundSystem::OnPlayerSpawned); - EVENT_SUBSCRIBE_MEMBER(m_InputCommand, &SoundSystem::OnInputCommand); - EVENT_SUBSCRIBE_MEMBER(m_EDoubleJump, &SoundSystem::OnDoubleJump); - EVENT_SUBSCRIBE_MEMBER(m_EDashAbility, &SoundSystem::OnDashAbility); - EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &SoundSystem::OnPlayerDamage); - EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &SoundSystem::OnCaptured); - EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &SoundSystem::OnTriggerTouch); + if (IsClient) { + EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &SoundSystem::OnPlayerSpawned); + EVENT_SUBSCRIBE_MEMBER(m_InputCommand, &SoundSystem::OnInputCommand); + EVENT_SUBSCRIBE_MEMBER(m_EDoubleJump, &SoundSystem::OnDoubleJump); + EVENT_SUBSCRIBE_MEMBER(m_EDashAbility, &SoundSystem::OnDashAbility); + EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &SoundSystem::OnPlayerDamage); + EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &SoundSystem::OnCaptured); + EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &SoundSystem::OnTriggerTouch); + } } void SoundSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& cComponent, double dt) @@ -20,6 +22,10 @@ void SoundSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& cComp void SoundSystem::Update(double dt) { + if (!IsClient) { + return; + } + // Temp for play test. if (m_DrumsIsPlaying) { m_DrumsIsPlaying = !drumTimer(dt); From 60b2c9bc9b256bc498571bd984d364d074abef5c Mon Sep 17 00:00:00 2001 From: viktorljung Date: Fri, 12 Feb 2016 05:41:05 +0100 Subject: [PATCH 256/355] KillFeed --- include/Game/Systems/KillFeedSystem.h | 39 + resources/Schema/Components.xsd | 1 + resources/Schema/Components/KillFeed.xml | 3 + resources/Schema/Components/KillFeed.xsd | 9 + resources/Schema/Components/Text.xml | 2 +- resources/Schema/Entities/DeadGirl.xlm | 255 +++++ resources/Schema/Entities/DeadGirls.xml | 1137 ++++++++++++++++++++++ resources/Schema/Entities/Player.xml | 66 +- resources/Schema/Types/Entity.xsd | 1 + src/Game/Game.cpp | 2 + src/Game/Systems/KillFeedSystem.cpp | 74 ++ src/Game/Systems/PlayerSpawnSystem.cpp | 11 +- 12 files changed, 1589 insertions(+), 11 deletions(-) create mode 100644 include/Game/Systems/KillFeedSystem.h create mode 100644 resources/Schema/Components/KillFeed.xml create mode 100644 resources/Schema/Components/KillFeed.xsd create mode 100644 resources/Schema/Entities/DeadGirl.xlm create mode 100644 resources/Schema/Entities/DeadGirls.xml create mode 100644 src/Game/Systems/KillFeedSystem.cpp diff --git a/include/Game/Systems/KillFeedSystem.h b/include/Game/Systems/KillFeedSystem.h new file mode 100644 index 00000000..31423999 --- /dev/null +++ b/include/Game/Systems/KillFeedSystem.h @@ -0,0 +1,39 @@ +#ifndef KillFeedSystem_h__ +#define KillFeedSystem_h__ + +#include "../../Engine/Core/System.h" +#include "../../Engine/GLM.h" +#include "Core/EPlayerDeath.h" + +class KillFeedSystem : public ImpureSystem +{ +public: + KillFeedSystem(SystemParams params) + : System(params) + { + EVENT_SUBSCRIBE_MEMBER(m_EPlayerDeath, &KillFeedSystem::OnPlayerDeath); + + } + + virtual void Update(double dt) override; + +private: + + + + + EventRelay m_EPlayerDeath; + bool KillFeedSystem::OnPlayerDeath(Events::PlayerDeath& e); + + struct KillFeedInfo + { + std::string Content; + glm::vec4 Color; + float TimeToLive = 5.f; + }; + + std::list m_DeathQueue; + +}; + +#endif \ No newline at end of file diff --git a/resources/Schema/Components.xsd b/resources/Schema/Components.xsd index ee4d7424..61e49ae3 100644 --- a/resources/Schema/Components.xsd +++ b/resources/Schema/Components.xsd @@ -41,4 +41,5 @@ + \ No newline at end of file diff --git a/resources/Schema/Components/KillFeed.xml b/resources/Schema/Components/KillFeed.xml new file mode 100644 index 00000000..558d4983 --- /dev/null +++ b/resources/Schema/Components/KillFeed.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/resources/Schema/Components/KillFeed.xsd b/resources/Schema/Components/KillFeed.xsd new file mode 100644 index 00000000..fedce9fb --- /dev/null +++ b/resources/Schema/Components/KillFeed.xsd @@ -0,0 +1,9 @@ + + + + + + HUD element for tracking the 3 last kills, printed on the children with the names "KillFeed1", "KillFeed2", "KillFeed3" + + + \ No newline at end of file diff --git a/resources/Schema/Components/Text.xml b/resources/Schema/Components/Text.xml index 9ca629d1..d38d3961 100644 --- a/resources/Schema/Components/Text.xml +++ b/resources/Schema/Components/Text.xml @@ -1,6 +1,6 @@ - Text + true diff --git a/resources/Schema/Entities/DeadGirl.xlm b/resources/Schema/Entities/DeadGirl.xlm new file mode 100644 index 00000000..90a0411d --- /dev/null +++ b/resources/Schema/Entities/DeadGirl.xlm @@ -0,0 +1,255 @@ + + + + + + + + + + 600 + + + + + + + + + 5 + + + + + + + + + + + + + + + + + + + + + + + + Fonts/DroidSans.ttf,100 + + + + + + + + + + + + + + Models/Widgets/Camera.mesh + false + + + + + + + + + + + + + + + + + + + 1 + + + + + Models/Core/UnitHexagon.mesh + + + + + + + + + + + + + + Textures/Weapons/Crosshair/SmallThickHoleDot.png + false + + + + + + + + + + + + + + Idle + 0.28963486380924053 + 1 + + + Models/Characters/Assault/FirstPerson.mesh + true + + + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + true + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + + + Schema/Entities/WeaponReloadEffect.xml + + + + + + + + + + + + + + Models/Widgets/Camera.mesh + false + + + + + + + + + + + + Idle + 0.42156525436696768 + 1 + + + AimRifle + + + + + Models/Characters/Assault/AssaultAnimations.mesh + + + + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + false + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + false + + + + + + + + + + + + Models/Core/UnitCube.mesh + + false + + + + + + + + + + diff --git a/resources/Schema/Entities/DeadGirls.xml b/resources/Schema/Entities/DeadGirls.xml new file mode 100644 index 00000000..2b004c34 --- /dev/null +++ b/resources/Schema/Entities/DeadGirls.xml @@ -0,0 +1,1137 @@ + + + + + + + + + + + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + + + + + + + + + + + + + + + + sModels/Widgets/Lights/DirectionalLightWidget.mesh + + + + + + + + + + + + + Models/Test/ObstacleCourse.mesh + + + + + + + + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + + + + + + + + + + + + + + + + + + 600 + + + + + 1 + + + + + + 5 + + + + + + + + + + + + + + + + + + + + + + + Fonts/DroidSans.ttf,100 + + + + + + + + + + + + + + Models/Widgets/Camera.mesh + false + + + + + + + + + + + + + + + + + + + 0.0099999997764825821 + + + + + Models/Core/UnitHexagon.mesh + + + + + + + + + + + + + + Textures/Weapons/Crosshair/SmallThickHoleDot.png + false + + + + + + + + + + + + + + Idle + 1.9484546004984589 + 1 + + + Models/Characters/Assault/FirstPerson.mesh + true + + + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + true + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + + + Schema/Entities/WeaponReloadEffect.xml + + + + + + + + + + + + + + Models/Widgets/Camera.mesh + false + + + + + + + + + + + + Idle + 0.83038427580044871 + 1 + + + AimRifle + + + + + Models/Characters/Assault/AssaultAnimations.mesh + + + + + + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + false + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + false + + + + + + + + + + + + Models/Core/UnitCube.mesh + + false + + + + + + + + + + + + + + + + + 600 + + + + + 1 + + + + + + 5 + + + + + + + + + + + + + + + + + + + + + + + Fonts/DroidSans.ttf,100 + + + + + + + + + + + + + + Models/Widgets/Camera.mesh + false + + + + + + + + + + + + + + + + + + + 0.0099999997764825821 + + + + + Models/Core/UnitHexagon.mesh + + + + + + + + + + + + + + Textures/Weapons/Crosshair/SmallThickHoleDot.png + false + + + + + + + + + + + + + + Idle + 1.6865388023565906 + 1 + + + Models/Characters/Assault/FirstPerson.mesh + true + + + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + true + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + + + Schema/Entities/WeaponReloadEffect.xml + + + + + + + + + + + + + + Models/Widgets/Camera.mesh + false + + + + + + + + + + + + Idle + 0.71846833460743298 + 1 + + + AimRifle + + + + + Models/Characters/Assault/AssaultAnimations.mesh + + + + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + false + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + false + + + + + + + + + + + + Models/Core/UnitCube.mesh + + false + + + + + + + + + + + + + + + + + 600 + + + + + 1 + + + + + + 5 + + + + + + + + + + + + + + + + + + + + + + + Fonts/DroidSans.ttf,100 + + + + + + + + + + + + + + Models/Widgets/Camera.mesh + false + + + + + + + + + + + + + + + + + + + 0.0099999997764825821 + + + + + Models/Core/UnitHexagon.mesh + + + + + + + + + + + + + + Textures/Weapons/Crosshair/SmallThickHoleDot.png + false + + + + + + + + + + + + + + Idle + 1.4291906531606173 + 1 + + + Models/Characters/Assault/FirstPerson.mesh + true + + + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + true + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + + + Schema/Entities/WeaponReloadEffect.xml + + + + + + + + + + + + + + Models/Widgets/Camera.mesh + false + + + + + + + + + + + + Idle + 0.34445363000679663 + 1 + + + AimRifle + + + + + Models/Characters/Assault/AssaultAnimations.mesh + + + + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + false + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + false + + + + + + + + + + + + Models/Core/UnitCube.mesh + + false + + + + + + + + + + + + + + + + + 600 + + + + + 1 + + + + + + 5 + + + + + + + + + + + + + + + + + + + + + + + Fonts/DroidSans.ttf,100 + + + + + + + + + + + + + + Models/Widgets/Camera.mesh + false + + + + + + + + + + + + + + + + + + + 0.0099999997764825821 + + + + + Models/Core/UnitHexagon.mesh + + + + + + + + + + + + + + Textures/Weapons/Crosshair/SmallThickHoleDot.png + false + + + + + + + + + + + + + + Idle + 0.94316388255725769 + 1 + + + Models/Characters/Assault/FirstPerson.mesh + true + + + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + true + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + + + Schema/Entities/WeaponReloadEffect.xml + + + + + + + + + + + + + + Models/Widgets/Camera.mesh + false + + + + + + + + + + + + Idle + 1.7750936055429634 + 1 + + + AimRifle + + + + + Models/Characters/Assault/AssaultAnimations.mesh + + + + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + false + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + false + + + + + + + + + + + + Models/Core/UnitCube.mesh + + false + + + + + + + + + + + + diff --git a/resources/Schema/Entities/Player.xml b/resources/Schema/Entities/Player.xml index b34669ca..d2063814 100644 --- a/resources/Schema/Entities/Player.xml +++ b/resources/Schema/Entities/Player.xml @@ -306,13 +306,67 @@ + + + + + + + + + + + + + + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + Idle - 0.24990652025910975 + 1.6050530664521858 1 @@ -332,8 +386,8 @@ true - - + + @@ -439,7 +493,7 @@ Idle - 1.6484966474501377 + 1.620305457513453 1 @@ -464,8 +518,8 @@ false - - + + diff --git a/resources/Schema/Types/Entity.xsd b/resources/Schema/Types/Entity.xsd index 3e521007..3e45cca0 100644 --- a/resources/Schema/Types/Entity.xsd +++ b/resources/Schema/Types/Entity.xsd @@ -44,6 +44,7 @@ + diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index e7e1eb48..49b1a963 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -25,6 +25,7 @@ #include "Rendering/AnimationSystem.h" #include "Network/MultiplayerSnapshotFilter.h" #include "Game/Systems/AmmunitionHUDSystem.h" +#include "Game/Systems/KillFeedSystem.h" Game::Game(int argc, char* argv[]) @@ -130,6 +131,7 @@ Game::Game(int argc, char* argv[]) m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); + m_SystemPipeline->AddSystem(updateOrderLevel); // Populate Octree with collidables ++updateOrderLevel; m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeCollision, "Collidable"); diff --git a/src/Game/Systems/KillFeedSystem.cpp b/src/Game/Systems/KillFeedSystem.cpp new file mode 100644 index 00000000..373b1ff5 --- /dev/null +++ b/src/Game/Systems/KillFeedSystem.cpp @@ -0,0 +1,74 @@ +#include "Game/Systems/KillFeedSystem.h" + +void KillFeedSystem::Update(double dt) +{ + auto killFeeds = m_World->GetComponents("KillFeed"); + if (killFeeds == nullptr) { + return; + } + + for (auto& killFeedComponent : *killFeeds) { + EntityWrapper entity = EntityWrapper(m_World, killFeedComponent.EntityID); + + for (int i = 1; i <= 3; i++) { + EntityWrapper child = entity.FirstChildByName("KillFeed" + std::to_string(i)); + if (child.HasComponent("Text")) { + (std::string&)child["Text"]["Content"] = ""; + } + } + + + + + int feedIndex = 1; + for (auto it = m_DeathQueue.begin(); it != m_DeathQueue.end(); ) { + bool remove = false; + + EntityWrapper child = entity.FirstChildByName("KillFeed" + std::to_string(feedIndex)); + + if (child.HasComponent("Text")) { + (std::string&)child["Text"]["Content"] = (*it).Content; + (glm::vec4&)child["Text"]["Color"] = (*it).Color; + + (*it).TimeToLive -= dt; + + if ((*it).TimeToLive <= 0.f) { + (std::string&)child["Text"]["Content"] = ""; + (glm::vec4&)child["Text"]["Color"] = (*it).Color; + remove = true; + } + } + feedIndex++; + if(feedIndex > 3) { + break; + } + + if(remove) { + it = m_DeathQueue.erase(it); + } else { + it++; + } + } + } +} + +bool KillFeedSystem::OnPlayerDeath(Events::PlayerDeath& e) +{ + KillFeedInfo kfInfo; + + if (e.Player.HasComponent("Team")) { + int red = e.Player["Team"].Enum("Team", "Red"); + int blue = e.Player["Team"].Enum("Team", "Blue"); + + if ((int)e.Player["Team"]["Team"] == red) { + kfInfo.Content = "Blue Player killed Red Player"; + kfInfo.Color = glm::vec4(0.f, 0.2f, 1.f, 0.8f); + m_DeathQueue.push_back(kfInfo); + } else if ((int)e.Player["Team"]["Team"] == blue) { + kfInfo.Content = "Red Player killed blue Player"; + kfInfo.Color = glm::vec4(1.f, 0.f, 0.f, 0.8f); + m_DeathQueue.push_back(kfInfo); + } + } + return true; +} diff --git a/src/Game/Systems/PlayerSpawnSystem.cpp b/src/Game/Systems/PlayerSpawnSystem.cpp index ac0ecdf3..c92585ba 100644 --- a/src/Game/Systems/PlayerSpawnSystem.cpp +++ b/src/Game/Systems/PlayerSpawnSystem.cpp @@ -175,8 +175,11 @@ bool PlayerSpawnSystem::OnPlayerDeath(Events::PlayerDeath& e) if ((ComponentInfo::EnumType)cTeam["Team"] == cTeam["Team"].Enum("Spectator")) { return false; } - SpawnRequest req; - req.PlayerID = m_PlayerIDs.at(e.Player.ID); - req.Team = cTeam["Team"]; - m_SpawnRequests.push_back(req); + + if (m_PlayerIDs.find(e.Player.ID) != m_PlayerIDs.end()) { + SpawnRequest req; + req.PlayerID = m_PlayerIDs.at(e.Player.ID); + req.Team = cTeam["Team"]; + m_SpawnRequests.push_back(req); + } } From f146971db0ce9af7e1287a0eadb6d8ebc5635821 Mon Sep 17 00:00:00 2001 From: viktorljung Date: Fri, 12 Feb 2016 05:45:17 +0100 Subject: [PATCH 257/355] Fixed size --- src/Game/Systems/KillFeedSystem.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/Game/Systems/KillFeedSystem.cpp b/src/Game/Systems/KillFeedSystem.cpp index 373b1ff5..8a16d708 100644 --- a/src/Game/Systems/KillFeedSystem.cpp +++ b/src/Game/Systems/KillFeedSystem.cpp @@ -70,5 +70,11 @@ bool KillFeedSystem::OnPlayerDeath(Events::PlayerDeath& e) m_DeathQueue.push_back(kfInfo); } } + + + if(m_DeathQueue.size() > 3) { + m_DeathQueue.pop_front(); + } + return true; } From 1e042445907e5ef58a6af879be6897c233976187 Mon Sep 17 00:00:00 2001 From: Tleety Date: Fri, 12 Feb 2016 06:00:42 +0100 Subject: [PATCH 258/355] Fixed network bug sorta --- src/Engine/Network/Client.cpp | 7 +++---- src/Engine/Network/Server.cpp | 21 +++++++++------------ 2 files changed, 12 insertions(+), 16 deletions(-) diff --git a/src/Engine/Network/Client.cpp b/src/Engine/Network/Client.cpp index 020e0cb7..10af98b7 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -181,14 +181,13 @@ void Client::parseSpawnEvents() std::vector tempSpawn; for (int i = 0; i < m_PlayerSpawnEvents.size(); i++) { Events::PlayerSpawned e; - if (!serverClientMapsHasEntity(m_PlayerSpawnEvents.at(i).Player.ID) || - !serverClientMapsHasEntity(m_PlayerSpawnEvents.at(i).Spawner.ID)) { + if (!serverClientMapsHasEntity(m_PlayerSpawnEvents.at(i).Player.ID)) { tempSpawn.push_back(m_PlayerSpawnEvents.at(i)); continue; } e.Player = EntityWrapper(m_World, m_ServerIDToClientID.at(m_PlayerSpawnEvents.at(i).Player.ID)); - e.Spawner = EntityWrapper(m_World, m_ServerIDToClientID.at(m_PlayerSpawnEvents.at(i).Spawner.ID)); - e.PlayerID = -1; + //e.Spawner = EntityWrapper(m_World, m_ServerIDToClientID.at(m_PlayerSpawnEvents.at(i).Spawner.ID)); + e.PlayerID = -1; e.PlayerName = m_PlayerSpawnEvents.at(i).PlayerName; m_EventBroker->Publish(e); } diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index 1500377a..7bb2722c 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -165,17 +165,16 @@ void Server::addInputCommandsToPacket(Packet& packet) void Server::addChildrenToPacket(Packet & packet, EntityID entityID) { - // HACK: Only sync players for now, since the map turned out to be TOO LARGE to send in one snapshot and Simon's computer shits itself - EntityWrapper entity(m_World, entityID); - if (!entity.Valid() || !shouldSendToClient(entity)) { - return; - } - auto itPair = m_World->GetChildren(entityID); std::unordered_map worldComponentPools = m_World->GetComponentPools(); // Loop through every child for (auto it = itPair.first; it != itPair.second; it++) { EntityID childEntityID = it->second; + // HACK: Only sync players for now, since the map turned out to be TOO LARGE to send in one snapshot and Simon's computer shits itself + EntityWrapper childEntity(m_World, childEntityID); + if (!shouldSendToClient(childEntity)) { + continue; + } // Write EntityID and parentsID and Entity name packet.WritePrimitive(childEntityID); @@ -398,11 +397,9 @@ bool Server::OnPlayerSpawned(const Events::PlayerSpawned & e) bool Server::OnEntityDeleted(const Events::EntityDeleted & e) { if (!e.Cascaded) { - if (shouldSendToClient(EntityWrapper(m_World, e.DeletedEntity))) { - Packet packet = Packet(MessageType::EntityDeleted); - packet.WritePrimitive(e.DeletedEntity); - reliableBroadcast(packet); - } + Packet packet = Packet(MessageType::EntityDeleted); + packet.WritePrimitive(e.DeletedEntity); + reliableBroadcast(packet); } return false; } @@ -458,7 +455,7 @@ void Server::parseOnInputCommand(Packet& packet) e.Player = EntityWrapper(m_World, m_ConnectedPlayers.at(player).EntityID); e.Value = packet.ReadPrimitive(); m_EventBroker->Publish(e); - if (e.Command == "PrimaryFire") { + if (e.Command == "PrimaryFire" || e.Command == "Reload") { m_InputCommandsToBroadcast.push_back(e); } //LOG_INFO("Server::parseOnInputCommand: Command is %s. Value is %f. PlayerID is %i.", e.Command.c_str(), e.Value, e.PlayerID); From 2e5ee633cea4c47d305bc18d477ea16b5193e06b Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Fri, 12 Feb 2016 06:10:20 +0100 Subject: [PATCH 259/355] Fixed bug when client would recieve input command from an entity that the client didn't know about --- src/Engine/Network/Client.cpp | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/Engine/Network/Client.cpp b/src/Engine/Network/Client.cpp index 10af98b7..8de62cb5 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -287,10 +287,14 @@ void Client::parseSnapshot(Packet& packet) Events::InputCommand e; e.PlayerID = packet.ReadPrimitive(); EntityID player = packet.ReadPrimitive(); - e.Player = EntityWrapper(m_World, m_ServerIDToClientID.at(player)); - e.Command = packet.ReadString(); - e.Value = packet.ReadPrimitive(); - m_EventBroker->Publish(e); + std::string command = packet.ReadString(); + float value = packet.ReadPrimitive(); + if (m_ServerIDToClientID.find(player) != m_ServerIDToClientID.end()) { + e.Player = EntityWrapper(m_World, m_ServerIDToClientID.at(player)); + e.Command = command; + e.Value = value; + m_EventBroker->Publish(e); + } } // Read world state From cc422cf73ab6d72378641d74bca647c838910c9a Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Fri, 12 Feb 2016 06:30:19 +0100 Subject: [PATCH 260/355] Fixed PlayerDeath being fired multiple times per frame on the server, causing multiple spawns and other weirdness --- src/Game/Systems/HealthSystem.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/Game/Systems/HealthSystem.cpp b/src/Game/Systems/HealthSystem.cpp index 0fc113b9..719f6c9f 100644 --- a/src/Game/Systems/HealthSystem.cpp +++ b/src/Game/Systems/HealthSystem.cpp @@ -10,8 +10,15 @@ HealthSystem::HealthSystem(SystemParams params) EVENT_SUBSCRIBE_MEMBER(m_InputCommand, &HealthSystem::OnInputCommand); } -void HealthSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) +void HealthSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& cHealth, double dt) { + double& health = cHealth["Health"]; + if (health <= 0.0) { + Events::PlayerDeath ePlayerDeath; + ePlayerDeath.Player = entity; + m_EventBroker->Publish(ePlayerDeath); + //Note: we will delete the entity in PlayerDeathSystem + } } bool HealthSystem::OnPlayerDamaged(Events::PlayerDamage& e) @@ -20,13 +27,6 @@ bool HealthSystem::OnPlayerDamaged(Events::PlayerDamage& e) double& health = cHealth["Health"]; health -= e.Damage; - if (health <= 0.0) { - Events::PlayerDeath ePlayerDeath; - ePlayerDeath.Player = e.Victim; - m_EventBroker->Publish(ePlayerDeath); - //Note: we will delete the entity in PlayerDeathSystem - } - return true; } From bb66f95d4375bd576b47562675bc3dde03049a51 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Fri, 12 Feb 2016 07:03:14 +0100 Subject: [PATCH 261/355] Enabled server broadcasting PlayerDamage events to other players to make damage indicators work --- include/Engine/Network/Client.h | 2 +- include/Engine/Network/Server.h | 4 +++- src/Engine/Network/Client.cpp | 22 +++++++++++++++++++++- src/Engine/Network/Server.cpp | 13 ++++++++++++- src/Game/Systems/DamageIndicatorSystem.cpp | 7 +++++-- src/Game/Systems/HealthSystem.cpp | 4 ++++ 6 files changed, 46 insertions(+), 6 deletions(-) diff --git a/include/Engine/Network/Client.h b/include/Engine/Network/Client.h index f2b18eee..978c9b65 100644 --- a/include/Engine/Network/Client.h +++ b/include/Engine/Network/Client.h @@ -109,7 +109,7 @@ public: bool OnPlayerDamage(const Events::PlayerDamage& e); EventRelay m_EPlayerSpawned; bool OnPlayerSpawned(const Events::PlayerSpawned& e); - + void parsePlayerDamage(Packet& packet); private: UDPClient m_Unreliable; TCPClient m_Reliable; diff --git a/include/Engine/Network/Server.h b/include/Engine/Network/Server.h index 8a1ee514..b37bffab 100644 --- a/include/Engine/Network/Server.h +++ b/include/Engine/Network/Server.h @@ -81,6 +81,7 @@ private: void parseUDPConnect(Packet & packet); void parseTCPConnect(Packet & packet); void parseDisconnect(); + bool shouldSendToClient(EntityWrapper childEntity); // Debug event EventRelay m_EInputCommand; @@ -91,7 +92,8 @@ private: bool OnEntityDeleted(const Events::EntityDeleted& e); EventRelay m_EComponentDeleted; bool OnComponentDeleted(const Events::ComponentDeleted& e); - bool shouldSendToClient(EntityWrapper childEntity); + EventRelay m_EPlayerDamage; + bool OnPlayerDamage(const Events::PlayerDamage& e); }; #endif diff --git a/src/Engine/Network/Client.cpp b/src/Engine/Network/Client.cpp index 8de62cb5..43ad8dfb 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -119,6 +119,9 @@ void Client::parseMessageType(Packet& packet) case MessageType::ComponentDeleted: parseComponentDeletion(packet); break; + case MessageType::OnPlayerDamage: + parsePlayerDamage(packet); + break; default: break; } @@ -409,12 +412,17 @@ bool Client::OnInputCommand(const Events::InputCommand & e) bool Client::OnPlayerDamage(const Events::PlayerDamage & e) { + if (e.Inflictor != m_LocalPlayer) { + return false; + } + Packet packet(MessageType::OnPlayerDamage, m_SendPacketID); packet.WritePrimitive(m_ClientIDToServerID.at(e.Inflictor.ID)); packet.WritePrimitive(m_ClientIDToServerID.at(e.Victim.ID)); packet.WritePrimitive(e.Damage); m_Reliable.Send(packet); - return false; + + return true; } bool Client::OnPlayerSpawned(const Events::PlayerSpawned& e) @@ -425,6 +433,18 @@ bool Client::OnPlayerSpawned(const Events::PlayerSpawned& e) return true; } +void Client::parsePlayerDamage(Packet& packet) +{ + Events::PlayerDamage e; + e.Inflictor = EntityWrapper(m_World, m_ServerIDToClientID.at(packet.ReadPrimitive())); + e.Victim = EntityWrapper(m_World, m_ServerIDToClientID.at(packet.ReadPrimitive())); + e.Damage = packet.ReadPrimitive(); + // Don't rebroadcast our own player damage events or we'll have an infinite loop! + if (e.Inflictor != m_LocalPlayer) { + m_EventBroker->Publish(e); + } +} + void Client::sendLocalPlayerTransform() { if (!m_LocalPlayer.Valid()) { diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index 7bb2722c..233fecbd 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -11,6 +11,7 @@ Server::Server(World* world, EventBroker* eventBroker, int port) EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &Server::OnPlayerSpawned); EVENT_SUBSCRIBE_MEMBER(m_EEntityDeleted, &Server::OnEntityDeleted); EVENT_SUBSCRIBE_MEMBER(m_EComponentDeleted, &Server::OnComponentDeleted); + EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &Server::OnPlayerDamage); // Bind if (port == 0) { @@ -411,12 +412,22 @@ bool Server::OnComponentDeleted(const Events::ComponentDeleted & e) Packet packet = Packet(MessageType::ComponentDeleted); packet.WritePrimitive(e.Entity); packet.WriteString(e.ComponentType); - reliableBroadcast(packet); + reliableBroadcast(packet); } } return false; } +bool Server::OnPlayerDamage(const Events::PlayerDamage& e) +{ + Packet packet(MessageType::OnPlayerDamage); + packet.WritePrimitive(e.Inflictor.ID); + packet.WritePrimitive(e.Victim.ID); + packet.WritePrimitive(e.Damage); + reliableBroadcast(packet); + + return false; +} void Server::parseClientPing() { diff --git a/src/Game/Systems/DamageIndicatorSystem.cpp b/src/Game/Systems/DamageIndicatorSystem.cpp index 8d586ac1..09db268c 100644 --- a/src/Game/Systems/DamageIndicatorSystem.cpp +++ b/src/Game/Systems/DamageIndicatorSystem.cpp @@ -18,12 +18,15 @@ bool DamageIndicatorSystem::OnPlayerDamage(Events::PlayerDamage& e) return false; } - if (e.Victim != LocalPlayer) { + //if (e.Victim != LocalPlayer) { + // return false; + //} + if (e.Victim != LocalPlayer && !e.Victim.IsChildOf(LocalPlayer)) { return false; } if (!e.Inflictor.Valid() || !e.Victim.Valid()) { - return false; + return false; } //grab players direction diff --git a/src/Game/Systems/HealthSystem.cpp b/src/Game/Systems/HealthSystem.cpp index 719f6c9f..b21c1352 100644 --- a/src/Game/Systems/HealthSystem.cpp +++ b/src/Game/Systems/HealthSystem.cpp @@ -23,6 +23,10 @@ void HealthSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& cHea bool HealthSystem::OnPlayerDamaged(Events::PlayerDamage& e) { + if (!IsServer) { + return false; + } + ComponentWrapper cHealth = e.Victim["Health"]; double& health = cHealth["Health"]; health -= e.Damage; From 78e318c032a9c47455fd2d55e0fad760b0f1a038 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Fri, 12 Feb 2016 07:14:36 +0100 Subject: [PATCH 262/355] Proper snapshot filtering --- src/Game/Network/MultiplayerSnapshotFilter.cpp | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/Game/Network/MultiplayerSnapshotFilter.cpp b/src/Game/Network/MultiplayerSnapshotFilter.cpp index 65d40189..52255ed3 100644 --- a/src/Game/Network/MultiplayerSnapshotFilter.cpp +++ b/src/Game/Network/MultiplayerSnapshotFilter.cpp @@ -9,7 +9,15 @@ MultiplayerSnapshotFilter::MultiplayerSnapshotFilter(EventBroker* eventBroker) bool MultiplayerSnapshotFilter::FilterComponent(EntityWrapper entity, SharedComponentWrapper& component) { if (entity == m_LocalPlayer || entity.IsChildOf(m_LocalPlayer)) { - return false; + if ( + component.Info.Name == "Transform" + || component.Info.Name == "Physics" + || component.Info.Name == "AssaultWeapon" + || component.Info.Name == "Animation" + || component.Info.Name == "AnimationOffset" + ) { + return false; + } } if (component.Info.Name == "Physics") { From 7d732c75caf98823c16658e87efabbcce00e3e5d Mon Sep 17 00:00:00 2001 From: Jocke Date: Fri, 12 Feb 2016 07:42:01 +0100 Subject: [PATCH 263/355] Server now removes players that have disconnected. --- src/Engine/Network/Server.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index 233fecbd..45af9823 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -335,6 +335,7 @@ void Server::disconnect(PlayerID playerID) //m_World->DeleteEntity(m_ConnectedPlayers[playerID].EntityID); m_ConnectedPlayers[playerID].TCPSocket->shutdown(boost::asio::ip::tcp::socket::shutdown_both); m_ConnectedPlayers[playerID].TCPSocket->close(); + m_World->DeleteEntity(m_ConnectedPlayers[playerID].EntityID); m_ConnectedPlayers.erase(playerID); // Send disconnect to the other players. } From b48d491ad780382ef1b7b8b38889b098ac2cf44a Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Fri, 12 Feb 2016 07:45:51 +0100 Subject: [PATCH 264/355] Complete blue and red player entities --- include/Game/Systems/HealthSystem.h | 7 +- resources/Schema/Entities/Player.xml | 16 +- resources/Schema/Entities/PlayerRed.xml | 366 ++++++++++++++++-- .../Schema/Entities/ReloadEffectViewRed.xml | 24 ++ .../Schema/Entities/ReloadEffectWorld.xml | 3 +- .../Schema/Entities/ReloadEffectWorldRed.xml | 25 ++ src/Game/Systems/HealthSystem.cpp | 3 +- 7 files changed, 401 insertions(+), 43 deletions(-) create mode 100644 resources/Schema/Entities/ReloadEffectViewRed.xml create mode 100644 resources/Schema/Entities/ReloadEffectWorldRed.xml diff --git a/include/Game/Systems/HealthSystem.h b/include/Game/Systems/HealthSystem.h index 21a52330..56f2f838 100644 --- a/include/Game/Systems/HealthSystem.h +++ b/include/Game/Systems/HealthSystem.h @@ -9,7 +9,8 @@ #include "Core/EPlayerDamage.h" #include "Core/EPlayerHealthPickup.h" #include "Core/EPlayerDeath.h" -#include "../Engine/Input/EInputCommand.h" +#include "Core/ConfigFile.h" +#include "Input/EInputCommand.h" #include #include @@ -24,6 +25,8 @@ public: virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) override; private: + bool m_NetworkEnabled; + //methods which will take care of specific events EventRelay m_EPlayerDamage; bool HealthSystem::OnPlayerDamaged(Events::PlayerDamage& e); @@ -34,7 +37,7 @@ private: //vector which will keep track of health changes std::vector> m_DeltaHealthVector; - + }; #endif \ No newline at end of file diff --git a/resources/Schema/Entities/Player.xml b/resources/Schema/Entities/Player.xml index 125bd571..1d72189e 100644 --- a/resources/Schema/Entities/Player.xml +++ b/resources/Schema/Entities/Player.xml @@ -23,7 +23,9 @@ - + + + @@ -106,7 +108,7 @@ 100/100 Fonts/DroidSans.ttf,64 - + @@ -120,7 +122,7 @@ 1 - + Textures/HealthHUD3.png @@ -310,15 +312,14 @@ - - + + - Fonts/DroidSans.ttf,64 @@ -331,7 +332,6 @@ - Fonts/DroidSans.ttf,64 @@ -346,7 +346,6 @@ - Fonts/DroidSans.ttf,64 @@ -371,6 +370,7 @@ Models/Characters/Assault/FirstPerson.mesh + true diff --git a/resources/Schema/Entities/PlayerRed.xml b/resources/Schema/Entities/PlayerRed.xml index ae11fa00..3031f27b 100644 --- a/resources/Schema/Entities/PlayerRed.xml +++ b/resources/Schema/Entities/PlayerRed.xml @@ -23,9 +23,7 @@ - - - + @@ -71,25 +69,6 @@ - - - - 1 - - - - - Models/Core/UnitHexagon.mesh - - - - - - - - - - @@ -112,17 +91,284 @@ + + + + + + + + + 1 + + + + + 100/100 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + 1 + + + + Textures/HealthHUD3.png + + + + + + + + + + + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + 2 + + + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + 3 + + + 0.80222018197612788 + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + 4 + + + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + 1 + + + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + + + + + + + + + + + + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + Idle - 0.1719161089749548 + 1.6050530664521858 1 Models/Characters/Assault/FirstPerson.mesh + true @@ -138,8 +384,8 @@ true - - + + @@ -157,12 +403,70 @@ - Schema/Entities/ReloadEffectView.xml + Schema/Entities/ReloadEffectViewRed.xml + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + + + + + + + 32 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + 360 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + @@ -187,7 +491,7 @@ Idle - 1.8038469763698401 + 1.620305457513453 1 @@ -197,7 +501,7 @@ Models/Characters/Assault/AssaultAnimations.mesh - + @@ -211,8 +515,8 @@ Models/Weapons/Red/AssaultWeaponRed.mesh - - + + @@ -230,7 +534,7 @@ - Schema/Entities/ReloadEffectWorld.xml + Schema/Entities/ReloadEffectWorldRed.xml diff --git a/resources/Schema/Entities/ReloadEffectViewRed.xml b/resources/Schema/Entities/ReloadEffectViewRed.xml new file mode 100644 index 00000000..56b9d140 --- /dev/null +++ b/resources/Schema/Entities/ReloadEffectViewRed.xml @@ -0,0 +1,24 @@ + + + + + + 2 + + + true + + + true + + true + + + Models/Weapons/Red/AssaultWeaponRed.mesh + + + + + + + diff --git a/resources/Schema/Entities/ReloadEffectWorld.xml b/resources/Schema/Entities/ReloadEffectWorld.xml index 97236897..ae6d3a3e 100644 --- a/resources/Schema/Entities/ReloadEffectWorld.xml +++ b/resources/Schema/Entities/ReloadEffectWorld.xml @@ -10,11 +10,12 @@ true - + true Models/Weapons/Blue/AssaultWeaponBlue.mesh + true diff --git a/resources/Schema/Entities/ReloadEffectWorldRed.xml b/resources/Schema/Entities/ReloadEffectWorldRed.xml new file mode 100644 index 00000000..55c37389 --- /dev/null +++ b/resources/Schema/Entities/ReloadEffectWorldRed.xml @@ -0,0 +1,25 @@ + + + + + + 2 + + + true + + + true + + true + + + Models/Weapons/Red/AssaultWeaponRed.mesh + true + + + + + + + diff --git a/src/Game/Systems/HealthSystem.cpp b/src/Game/Systems/HealthSystem.cpp index b21c1352..eac7bf2d 100644 --- a/src/Game/Systems/HealthSystem.cpp +++ b/src/Game/Systems/HealthSystem.cpp @@ -8,6 +8,7 @@ HealthSystem::HealthSystem(SystemParams params) EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &HealthSystem::OnPlayerDamaged); EVENT_SUBSCRIBE_MEMBER(m_EPlayerHealthPickup, &HealthSystem::OnPlayerHealthPickup); EVENT_SUBSCRIBE_MEMBER(m_InputCommand, &HealthSystem::OnInputCommand); + m_NetworkEnabled = ResourceManager::Load("Config.ini")->Get("Networking.StartNetwork", false); } void HealthSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& cHealth, double dt) @@ -23,7 +24,7 @@ void HealthSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& cHea bool HealthSystem::OnPlayerDamaged(Events::PlayerDamage& e) { - if (!IsServer) { + if (!IsServer && m_NetworkEnabled) { return false; } From eb7b22c7578ae8f63a7b1b10b3c53eafa6b5c074 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Fri, 12 Feb 2016 07:48:26 +0100 Subject: [PATCH 265/355] Latest assets --- assets | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/assets b/assets index 078e014f..8d180f2a 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit 078e014f3d24a100c4cb544ac6807aa2b54149b2 +Subproject commit 8d180f2a54154191587107e6569bbae0a049be46 From af39b892cd57f9b2af82e843f12a4d49d047a4a5 Mon Sep 17 00:00:00 2001 From: stiffly Date: Fri, 12 Feb 2016 08:05:35 +0100 Subject: [PATCH 266/355] Now plays a "Empty sound", "reload sound" and "hit mark sound" on appropriate occasions. --- assets | 2 +- .../Systems/Weapon/AssaultWeaponBehaviour.h | 3 ++- src/Game/Systems/PlayerSpawnSystem.cpp | 3 +++ .../Systems/Weapon/AssaultWeaponBehaviour.cpp | 23 +++++++++++++++---- 4 files changed, 25 insertions(+), 6 deletions(-) diff --git a/assets b/assets index 8d180f2a..1e7adc74 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit 8d180f2a54154191587107e6569bbae0a049be46 +Subproject commit 1e7adc749e02144615a20a82c847d3c8df46ee3d diff --git a/include/Game/Systems/Weapon/AssaultWeaponBehaviour.h b/include/Game/Systems/Weapon/AssaultWeaponBehaviour.h index 90959d0e..e827b5df 100644 --- a/include/Game/Systems/Weapon/AssaultWeaponBehaviour.h +++ b/include/Game/Systems/Weapon/AssaultWeaponBehaviour.h @@ -34,7 +34,8 @@ private: void fireRound(); void spawnTracer(); float traceRayDistance(glm::vec3 origin, glm::vec3 direction); - void playSound(); + void playFireSound(); + void playEmptySound(); void viewPunch(); void finishReload(); void playShootAnimation(); diff --git a/src/Game/Systems/PlayerSpawnSystem.cpp b/src/Game/Systems/PlayerSpawnSystem.cpp index ac0ecdf3..7a0b46ef 100644 --- a/src/Game/Systems/PlayerSpawnSystem.cpp +++ b/src/Game/Systems/PlayerSpawnSystem.cpp @@ -175,6 +175,9 @@ bool PlayerSpawnSystem::OnPlayerDeath(Events::PlayerDeath& e) if ((ComponentInfo::EnumType)cTeam["Team"] == cTeam["Team"].Enum("Spectator")) { return false; } + if (m_PlayerIDs.find(e.Player.ID) == m_PlayerIDs.end()) { + return false; + } SpawnRequest req; req.PlayerID = m_PlayerIDs.at(e.Player.ID); req.Team = cTeam["Team"]; diff --git a/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp b/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp index a59397d1..f6320c4c 100644 --- a/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp +++ b/src/Game/Systems/Weapon/AssaultWeaponBehaviour.cpp @@ -37,6 +37,8 @@ void AssaultWeaponBehaviour::Reload() // Don't reload if we're completly out of ammo if (ammo == 0) { + playEmptySound(); + m_TimeSinceLastFire = -0.0f; // HACK: To make empty sound play with interval return; } @@ -121,12 +123,12 @@ void AssaultWeaponBehaviour::fireRound() if (magAmmo <= 0) { Reload(); return; - } + } // Fire magAmmo -= 1; spawnTracer(); - playSound(); + playFireSound(); viewPunch(); playShootAnimation(); bool hit = shoot(cAssaultWeapon["BaseDamage"]); @@ -172,7 +174,7 @@ float AssaultWeaponBehaviour::traceRayDistance(glm::vec3 origin, glm::vec3 direc } } -void AssaultWeaponBehaviour::playSound() +void AssaultWeaponBehaviour::playFireSound() { if (!IsClient) { return; @@ -184,6 +186,19 @@ void AssaultWeaponBehaviour::playSound() m_EventBroker->Publish(e); } + +void AssaultWeaponBehaviour::playEmptySound() +{ + if (!IsClient) { + return; + } + + Events::PlaySoundOnEntity e; + e.EmitterID = m_Player.ID; + e.FilePath = "Audio/weapon/zeroAmmo.wav"; + m_EventBroker->Publish(e); +} + void AssaultWeaponBehaviour::viewPunch() { EntityWrapper playerCamera = m_Player.FirstChildByName("Camera"); @@ -342,7 +357,7 @@ void AssaultWeaponBehaviour::showHitMarker() if (hitMarkerSpawner.Valid()) { SpawnerSystem::Spawn(hitMarkerSpawner, hitMarkerSpawner); Events::PlaySoundOnEntity e; - e.EmitterID = hitMarkerSpawner.ID; // This might not be the optimal spawner entity + e.EmitterID = m_Player.ID; e.FilePath = "Audio/weapon/hitclick.wav"; m_EventBroker->Publish(e); } From ba4877c3f72ef202eafc6f2108b452b2ca8c5842 Mon Sep 17 00:00:00 2001 From: antc13 Date: Fri, 12 Feb 2016 08:16:12 +0100 Subject: [PATCH 267/355] Moved Spawn locations and added ammo/health pickups around the map. --- resources/Schema/Entities/NewMap.xml | 207 +++++++++++++++++++++++---- 1 file changed, 180 insertions(+), 27 deletions(-) diff --git a/resources/Schema/Entities/NewMap.xml b/resources/Schema/Entities/NewMap.xml index 60aa31be..86da1fde 100644 --- a/resources/Schema/Entities/NewMap.xml +++ b/resources/Schema/Entities/NewMap.xml @@ -370,7 +370,7 @@ - Models/Props/Pillars/SciFiPillar2.mesh + Models/Props/Pillars/SciFiPillar2Blue.mesh @@ -383,7 +383,7 @@ - Models/Props/Pillars/SciFiPillar2.mesh + Models/Props/Pillars/SciFiPillar2Red.mesh @@ -4064,21 +4064,7 @@ - - - - - - Models/Props/PickUps/HealthPickUp.mesh - - - - - - - - - + @@ -4939,7 +4925,7 @@ - + @@ -4948,9 +4934,10 @@ Models/Characters/Assault/AssaultTPose.mesh + false - + @@ -4960,9 +4947,10 @@ Models/Characters/Assault/AssaultTPose.mesh + false - + @@ -4972,9 +4960,10 @@ Models/Characters/Assault/AssaultTPose.mesh + false - + @@ -4984,9 +4973,10 @@ Models/Characters/Assault/AssaultTPose.mesh + false - + @@ -5005,7 +4995,7 @@ - + @@ -5014,9 +5004,10 @@ Models/Characters/Assault/AssaultTPose.mesh + false - + @@ -5026,9 +5017,10 @@ Models/Characters/Assault/AssaultTPose.mesh + false - + @@ -5038,9 +5030,10 @@ Models/Characters/Assault/AssaultTPose.mesh + false - + @@ -5050,15 +5043,175 @@ Models/Characters/Assault/AssaultTPose.mesh + false - + + + + + + + + + + + Models/Props/PickUps/HealthPickUp.mesh + + + 0.10000000149011612 + + + + + + + + + + + + + + + + Models/Props/PickUps/AmmoPickUp.mesh + + + 0.10000000149011612 + + + + + + + + + + + + + + + + Models/Props/PickUps/HealthPickUp.mesh + + + 0.10000000149011612 + + + + + + + + + + + + + + + + Models/Props/PickUps/HealthPickUp.mesh + + + 0.10000000149011612 + + + + + + + + + + + + + + + + Models/Props/PickUps/AmmoPickUp.mesh + + + 0.10000000149011612 + + + + + + + + + + + + + + + + Models/Props/PickUps/HealthPickUp.mesh + + + 0.10000000149011612 + + + + + + + + + + + + + + + + Models/Props/PickUps/AmmoPickUp.mesh + + + 0.10000000149011612 + + + + + + + + + + + + + + + + Models/Props/PickUps/AmmoPickUp.mesh + + + 0.10000000149011612 + + + + + + + + + + + + + From 3d4a7de59d8b510d5cce2d23664c726bbb908eca Mon Sep 17 00:00:00 2001 From: stiffly Date: Fri, 12 Feb 2016 08:19:47 +0100 Subject: [PATCH 268/355] MiniDump.cpp was not added to CMakeLists.txt. --- src/Game/CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Game/CMakeLists.txt b/src/Game/CMakeLists.txt index f188d7fa..d8ba8599 100644 --- a/src/Game/CMakeLists.txt +++ b/src/Game/CMakeLists.txt @@ -36,6 +36,7 @@ source_group(Network FILES ${SOURCE_FILES_Network}) set(SOURCE_FILES ${SOURCE_FILES} "Game.cpp" + "MiniDump.cpp" ${SOURCE_FILES_Systems} ${SOURCE_FILES_Systems_Weapon} ${SOURCE_FILES_Events} From 2c3122bbdb62520b3b269ff0570469e2fc175f8a Mon Sep 17 00:00:00 2001 From: Jocke Date: Fri, 12 Feb 2016 08:39:20 +0100 Subject: [PATCH 269/355] increased Network buffer size, fixed 2 crashes and re-added the ability to kill oneself with the use of a key bound to TakeDamage,Value. --- include/Engine/Network/NetworkClient.h | 2 +- include/Engine/Network/NetworkServer.h | 2 +- src/Engine/Network/Client.cpp | 6 +++++- src/Game/Systems/DamageIndicatorSystem.cpp | 2 +- src/Game/Systems/HealthSystem.cpp | 1 + 5 files changed, 9 insertions(+), 4 deletions(-) diff --git a/include/Engine/Network/NetworkClient.h b/include/Engine/Network/NetworkClient.h index 4c623209..d0339d84 100644 --- a/include/Engine/Network/NetworkClient.h +++ b/include/Engine/Network/NetworkClient.h @@ -2,7 +2,7 @@ #define NetworkClient_h__ #include "Network/Packet.h" -#define BUFFERSIZE 32000 +#define BUFFERSIZE 64000 typedef unsigned int PlayerID; typedef unsigned int PacketID; diff --git a/include/Engine/Network/NetworkServer.h b/include/Engine/Network/NetworkServer.h index d6406eab..ccec82cc 100644 --- a/include/Engine/Network/NetworkServer.h +++ b/include/Engine/Network/NetworkServer.h @@ -3,7 +3,7 @@ #include #include "Network/Packet.h" #include "Network/PlayerDefinition.h" -#define BUFFERSIZE 32000 +#define BUFFERSIZE 64000 typedef unsigned int PlayerID; typedef unsigned int PacketID; diff --git a/src/Engine/Network/Client.cpp b/src/Engine/Network/Client.cpp index 43ad8dfb..3406535a 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -436,7 +436,11 @@ bool Client::OnPlayerSpawned(const Events::PlayerSpawned& e) void Client::parsePlayerDamage(Packet& packet) { Events::PlayerDamage e; - e.Inflictor = EntityWrapper(m_World, m_ServerIDToClientID.at(packet.ReadPrimitive())); + PlayerID victimID = packet.ReadPrimitive(); + if(serverClientMapsHasEntity(victimID)){ + return; + } + e.Inflictor = EntityWrapper(m_World, m_ServerIDToClientID.at(victimID)); e.Victim = EntityWrapper(m_World, m_ServerIDToClientID.at(packet.ReadPrimitive())); e.Damage = packet.ReadPrimitive(); // Don't rebroadcast our own player damage events or we'll have an infinite loop! diff --git a/src/Game/Systems/DamageIndicatorSystem.cpp b/src/Game/Systems/DamageIndicatorSystem.cpp index 09db268c..235eced0 100644 --- a/src/Game/Systems/DamageIndicatorSystem.cpp +++ b/src/Game/Systems/DamageIndicatorSystem.cpp @@ -21,7 +21,7 @@ bool DamageIndicatorSystem::OnPlayerDamage(Events::PlayerDamage& e) //if (e.Victim != LocalPlayer) { // return false; //} - if (e.Victim != LocalPlayer && !e.Victim.IsChildOf(LocalPlayer)) { + if (e.Victim.Valid() && e.Victim != LocalPlayer && !e.Victim.IsChildOf(LocalPlayer)) { return false; } diff --git a/src/Game/Systems/HealthSystem.cpp b/src/Game/Systems/HealthSystem.cpp index b21c1352..ee8d8065 100644 --- a/src/Game/Systems/HealthSystem.cpp +++ b/src/Game/Systems/HealthSystem.cpp @@ -38,6 +38,7 @@ bool HealthSystem::OnInputCommand(Events::InputCommand& e) { if (e.Command == "TakeDamage" && e.Value > 0 && LocalPlayer.Valid()) { Events::PlayerDamage ev; + ev.Inflictor = LocalPlayer; ev.Victim = LocalPlayer; ev.Damage = e.Value; m_EventBroker->Publish(ev); From a08e54a1471512ddd4c1d45204832075c6afd446 Mon Sep 17 00:00:00 2001 From: antc13 Date: Fri, 12 Feb 2016 08:44:40 +0100 Subject: [PATCH 270/355] Blocked up a path in the Spawns a bit more. --- resources/Schema/Entities/NewMap.xml | 130 +++++++++++++++++++++++---- 1 file changed, 112 insertions(+), 18 deletions(-) diff --git a/resources/Schema/Entities/NewMap.xml b/resources/Schema/Entities/NewMap.xml index 86da1fde..faeb5338 100644 --- a/resources/Schema/Entities/NewMap.xml +++ b/resources/Schema/Entities/NewMap.xml @@ -593,7 +593,7 @@ Models/Props/Walls/BigWallBlue.mesh - + @@ -726,7 +726,7 @@ Models/Props/Walls/BigWallBlue.mesh - + @@ -739,7 +739,7 @@ Models/Props/Walls/BigWallBlue.mesh - + @@ -1291,7 +1291,7 @@ Models/Props/Walls/BigWallBlue.mesh - + @@ -1302,7 +1302,7 @@ Models/Props/Walls/BigWallBlue.mesh - + @@ -1314,7 +1314,7 @@ Models/Props/Walls/BigWallBlue.mesh - + @@ -1326,7 +1326,7 @@ Models/Props/Walls/BigWallBlue.mesh - + @@ -3310,6 +3310,60 @@ + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + @@ -3319,7 +3373,7 @@ Models/Props/Stones/BigStone.mesh - + @@ -3349,6 +3403,46 @@ + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/SmallStone1.mesh + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + @@ -3698,7 +3792,7 @@ Models/Props/Stones/SmallStone1.mesh - + @@ -3948,7 +4042,7 @@ - + @@ -5071,7 +5165,7 @@ - + @@ -5090,7 +5184,7 @@ - + @@ -5109,7 +5203,7 @@ - + @@ -5128,7 +5222,7 @@ - + @@ -5147,7 +5241,7 @@ - + @@ -5166,7 +5260,7 @@ - + @@ -5185,7 +5279,7 @@ - + @@ -5204,7 +5298,7 @@ - + From ca457d9c00c9e3a53e258153a1bee5e8bcd7195a Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Fri, 12 Feb 2016 09:07:59 +0100 Subject: [PATCH 271/355] Player names --- resources/Schema/Entities/Player.xml | 34 +++++++++---------- resources/Schema/Entities/PlayerRed.xml | 29 ++++++++-------- src/Engine/Rendering/Skeleton.cpp | 5 --- .../Network/MultiplayerSnapshotFilter.cpp | 1 + src/Game/Systems/PlayerMovementSystem.cpp | 14 ++++---- src/Game/Systems/PlayerSpawnSystem.cpp | 20 +++++------ 6 files changed, 49 insertions(+), 54 deletions(-) diff --git a/resources/Schema/Entities/Player.xml b/resources/Schema/Entities/Player.xml index 1d72189e..be6009ba 100644 --- a/resources/Schema/Entities/Player.xml +++ b/resources/Schema/Entities/Player.xml @@ -23,9 +23,7 @@ - - - + @@ -37,20 +35,6 @@ - - - - Fonts/DroidSans.ttf,100 - - - - - - - - - - @@ -504,7 +488,6 @@ Models/Characters/Assault/AssaultAnimations.mesh - false @@ -574,6 +557,21 @@ + + + + Insert name here + Fonts/DroidSans.ttf,100 + + + + + + + + + + diff --git a/resources/Schema/Entities/PlayerRed.xml b/resources/Schema/Entities/PlayerRed.xml index 3031f27b..d9839e9f 100644 --- a/resources/Schema/Entities/PlayerRed.xml +++ b/resources/Schema/Entities/PlayerRed.xml @@ -35,20 +35,6 @@ - - - - Fonts/DroidSans.ttf,100 - - - - - - - - - - @@ -571,6 +557,21 @@ + + + + Insert name here + Fonts/DroidSans.ttf,100 + + + + + + + + + + diff --git a/src/Engine/Rendering/Skeleton.cpp b/src/Engine/Rendering/Skeleton.cpp index e390d694..2957b1b6 100644 --- a/src/Engine/Rendering/Skeleton.cpp +++ b/src/Engine/Rendering/Skeleton.cpp @@ -121,7 +121,6 @@ void Skeleton::AccumulateBoneTransforms(bool noRootMotion, std::vector 1.0f || progress < 0.0f) { - LOG_INFO("Progress: %f", progress); progress = glm::clamp(progress, 0.0f, 1.0f); } Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties; @@ -241,7 +240,6 @@ void Skeleton::AccumulateBoneTransforms(bool noRootMotion, std::vector 1.0f || progress < 0.0f) { - LOG_INFO("Progress: %f", progress); progress = glm::clamp(progress, 0.0f, 1.0f); } Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties; @@ -489,7 +487,6 @@ glm::mat4 Skeleton::GetBoneTransform(bool noRootMotion, const Bone* bone, std::v if (progress > 1.0f || progress < 0.0f) { - LOG_INFO("Progress: %f", progress); progress = glm::clamp(progress, 0.0f, 1.0f); } Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties; @@ -609,12 +606,10 @@ glm::mat4 Skeleton::GetBoneTransform(bool noRootMotion, const Bone* bone, std::v progress = (time - currentFrame.Time) / (animation->Duration - currentFrame.Time); } else { progress = (time - currentFrame.Time) / (nextFrame.Time - currentFrame.Time); - } if (progress > 1.0f || progress < 0.0f) { - LOG_INFO("Progress: %f", progress); progress = glm::clamp(progress, 0.0f, 1.0f); } Animation::Keyframe::BoneProperty currentBoneProperty = currentFrame.BoneProperties; diff --git a/src/Game/Network/MultiplayerSnapshotFilter.cpp b/src/Game/Network/MultiplayerSnapshotFilter.cpp index 52255ed3..69b7f282 100644 --- a/src/Game/Network/MultiplayerSnapshotFilter.cpp +++ b/src/Game/Network/MultiplayerSnapshotFilter.cpp @@ -15,6 +15,7 @@ bool MultiplayerSnapshotFilter::FilterComponent(EntityWrapper entity, SharedComp || component.Info.Name == "AssaultWeapon" || component.Info.Name == "Animation" || component.Info.Name == "AnimationOffset" + || entity.Name() == "PlayerName" ) { return false; } diff --git a/src/Game/Systems/PlayerMovementSystem.cpp b/src/Game/Systems/PlayerMovementSystem.cpp index 9bf1d25e..71fb16ee 100644 --- a/src/Game/Systems/PlayerMovementSystem.cpp +++ b/src/Game/Systems/PlayerMovementSystem.cpp @@ -79,18 +79,18 @@ void PlayerMovementSystem::updateMovementControllers(double dt) } glm::vec3& velocity = cPhysics["Velocity"]; bool isOnGround = (bool)cPhysics["IsOnGround"]; - ImGui::Text(isOnGround ? "On ground" : "In air"); - ImGui::Text("velocity: (%f, %f, %f) |%f|", velocity.x, velocity.y, velocity.z, glm::length(velocity)); + //ImGui::Text(isOnGround ? "On ground" : "In air"); + //ImGui::Text("velocity: (%f, %f, %f) |%f|", velocity.x, velocity.y, velocity.z, glm::length(velocity)); glm::vec3 groundVelocity(0.f, 0.f, 0.f); groundVelocity.x = velocity.x; groundVelocity.z = velocity.z; - ImGui::Text("groundVelocity: (%f, %f, %f) |%f|", groundVelocity.x, groundVelocity.y, groundVelocity.z, glm::length(groundVelocity)); - ImGui::Text("wishDirection: (%f, %f, %f) |%f|", wishDirection.x, wishDirection.y, wishDirection.z, glm::length(wishDirection)); + //ImGui::Text("groundVelocity: (%f, %f, %f) |%f|", groundVelocity.x, groundVelocity.y, groundVelocity.z, glm::length(groundVelocity)); + //ImGui::Text("wishDirection: (%f, %f, %f) |%f|", wishDirection.x, wishDirection.y, wishDirection.z, glm::length(wishDirection)); float currentSpeedProj = glm::dot(groundVelocity, wishDirection); float addSpeed = wishSpeed - currentSpeedProj; - ImGui::Text("currentSpeedProj: %f", currentSpeedProj); - ImGui::Text("wishSpeed: %f", wishSpeed); - ImGui::Text("addSpeed: %f", addSpeed); + //ImGui::Text("currentSpeedProj: %f", currentSpeedProj); + //ImGui::Text("wishSpeed: %f", wishSpeed); + //ImGui::Text("addSpeed: %f", addSpeed); if (addSpeed > 0) { static float accel = 15.f; diff --git a/src/Game/Systems/PlayerSpawnSystem.cpp b/src/Game/Systems/PlayerSpawnSystem.cpp index 8183866b..5f53a1fc 100644 --- a/src/Game/Systems/PlayerSpawnSystem.cpp +++ b/src/Game/Systems/PlayerSpawnSystem.cpp @@ -128,6 +128,12 @@ bool PlayerSpawnSystem::OnPlayerSpawned(Events::PlayerSpawned& e) // When a player is actually spawned (since the actual spawning is handled on the server) // Hack should be moved. + // TODO: Set the player name to whatever + EntityWrapper playerName = e.Player.FirstChildByName("PlayerName"); + if (playerName.Valid()) { + playerName["Text"]["Content"] = e.PlayerName; + } + if (!IsClient) { return false; } @@ -153,12 +159,6 @@ bool PlayerSpawnSystem::OnPlayerSpawned(Events::PlayerSpawned& e) } } - // TODO: Set the player name to whatever - EntityWrapper playerName = e.Player.FirstChildByName("PlayerName"); - if (playerName.Valid()) { - playerName["Text"]["Content"] = e.PlayerName; - } - return true; } @@ -181,10 +181,10 @@ bool PlayerSpawnSystem::OnPlayerDeath(Events::PlayerDeath& e) return false; } - SpawnRequest req; - req.PlayerID = m_PlayerIDs.at(e.Player.ID); - req.Team = cTeam["Team"]; - m_SpawnRequests.push_back(req); + SpawnRequest req; + req.PlayerID = m_PlayerIDs.at(e.Player.ID); + req.Team = cTeam["Team"]; + m_SpawnRequests.push_back(req); return true; } From ba69c798213ec7a8a1d46df8d08742504f65ba17 Mon Sep 17 00:00:00 2001 From: Jocke Date: Fri, 12 Feb 2016 09:13:43 +0100 Subject: [PATCH 272/355] Fixed bug in Server. --- src/Engine/Network/Server.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index 45af9823..082849c7 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -477,6 +477,11 @@ void Server::parseOnInputCommand(Packet& packet) void Server::parsePlayerTransform(Packet& packet) { + PlayerID playerID = GetPlayerIDFromEndpoint(); + if (playerID == -1) { + return; + } + glm::vec3 position; glm::vec3 orientation; position.x = packet.ReadPrimitive(); @@ -486,7 +491,6 @@ void Server::parsePlayerTransform(Packet& packet) orientation.y = packet.ReadPrimitive(); orientation.z = packet.ReadPrimitive(); - PlayerID playerID = GetPlayerIDFromEndpoint(); bool hasAssaultWeapon = packet.ReadPrimitive(); int magazineAmmo; int ammo; From 71c03326aa2feb5d0804b8c3667e75797372c1a8 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Fri, 12 Feb 2016 09:17:28 +0100 Subject: [PATCH 273/355] Debug.EditorEnabled --- src/Engine/Editor/EditorSystem.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Engine/Editor/EditorSystem.cpp b/src/Engine/Editor/EditorSystem.cpp index 75b66bc9..4899519d 100644 --- a/src/Engine/Editor/EditorSystem.cpp +++ b/src/Engine/Editor/EditorSystem.cpp @@ -40,6 +40,7 @@ EditorSystem::EditorSystem(SystemParams params, IRenderer* renderer, RenderFrame m_EditorStats = new EditorStats(); + m_Enabled = ResourceManager::Load("Config.ini")->Get("Debug.EditorEnabled", false); if (m_Enabled) { Enable(); } From 47a365a8fc6025d80d15b0dfe62c90808e80ab74 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Fri, 12 Feb 2016 09:17:39 +0100 Subject: [PATCH 274/355] Inverted capture point numbers to fix HUD --- resources/Schema/Entities/NewMap.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/resources/Schema/Entities/NewMap.xml b/resources/Schema/Entities/NewMap.xml index faeb5338..dcdb7bec 100644 --- a/resources/Schema/Entities/NewMap.xml +++ b/resources/Schema/Entities/NewMap.xml @@ -4765,6 +4765,7 @@ + 4 Models/Core/UnitCylinder.mesh @@ -4800,7 +4801,7 @@ - 1 + 3 Models/Core/UnitCylinder.mesh @@ -4865,7 +4866,7 @@ 1.5498908015879351 - 3 + 1 Models/Core/UnitCylinder.mesh @@ -4900,7 +4901,6 @@ - 4 Models/Core/UnitCylinder.mesh From 717af2c4a4e79ebdc915063a3841a1bb1c9a7720 Mon Sep 17 00:00:00 2001 From: Jocke Date: Tue, 16 Feb 2016 10:22:15 +0000 Subject: [PATCH 275/355] Fixed bug in Client::parsePlayerDamage() --- src/Engine/Network/Client.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Engine/Network/Client.cpp b/src/Engine/Network/Client.cpp index 3406535a..62bc8e73 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -437,7 +437,7 @@ void Client::parsePlayerDamage(Packet& packet) { Events::PlayerDamage e; PlayerID victimID = packet.ReadPrimitive(); - if(serverClientMapsHasEntity(victimID)){ + if(!serverClientMapsHasEntity(victimID)){ return; } e.Inflictor = EntityWrapper(m_World, m_ServerIDToClientID.at(victimID)); From 4214bf10a102be4f276637abcf75f45798e32629 Mon Sep 17 00:00:00 2001 From: Tleety Date: Tue, 16 Feb 2016 14:05:57 +0100 Subject: [PATCH 276/355] Components for menu/buttons --- resources/Schema/Components.xsd | 3 +++ resources/Schema/Components/Button.xml | 3 +++ resources/Schema/Components/Button.xsd | 9 +++++++++ resources/Schema/Components/Menu.xml | 3 +++ resources/Schema/Components/Menu.xsd | 9 +++++++++ resources/Schema/Components/Page.xml | 4 ++++ resources/Schema/Components/Page.xsd | 14 ++++++++++++++ resources/Schema/Types/Entity.xsd | 3 +++ 8 files changed, 48 insertions(+) create mode 100644 resources/Schema/Components/Button.xml create mode 100644 resources/Schema/Components/Button.xsd create mode 100644 resources/Schema/Components/Menu.xml create mode 100644 resources/Schema/Components/Menu.xsd create mode 100644 resources/Schema/Components/Page.xml create mode 100644 resources/Schema/Components/Page.xsd diff --git a/resources/Schema/Components.xsd b/resources/Schema/Components.xsd index 61e49ae3..74423f56 100644 --- a/resources/Schema/Components.xsd +++ b/resources/Schema/Components.xsd @@ -41,5 +41,8 @@ + + + \ No newline at end of file diff --git a/resources/Schema/Components/Button.xml b/resources/Schema/Components/Button.xml new file mode 100644 index 00000000..cbfd80d4 --- /dev/null +++ b/resources/Schema/Components/Button.xml @@ -0,0 +1,3 @@ + + \ No newline at end of file diff --git a/resources/Schema/Components/Button.xsd b/resources/Schema/Components/Button.xsd new file mode 100644 index 00000000..07f2eafc --- /dev/null +++ b/resources/Schema/Components/Button.xsd @@ -0,0 +1,9 @@ + + + + + + Makes sprites klickable. + + + \ No newline at end of file diff --git a/resources/Schema/Components/Menu.xml b/resources/Schema/Components/Menu.xml new file mode 100644 index 00000000..f17427b8 --- /dev/null +++ b/resources/Schema/Components/Menu.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/resources/Schema/Components/Menu.xsd b/resources/Schema/Components/Menu.xsd new file mode 100644 index 00000000..18ea8565 --- /dev/null +++ b/resources/Schema/Components/Menu.xsd @@ -0,0 +1,9 @@ + + + + + + Attach this to the center point of a menu that uses several pages. + + + \ No newline at end of file diff --git a/resources/Schema/Components/Page.xml b/resources/Schema/Components/Page.xml new file mode 100644 index 00000000..db7b9cc2 --- /dev/null +++ b/resources/Schema/Components/Page.xml @@ -0,0 +1,4 @@ + + + 0 + \ No newline at end of file diff --git a/resources/Schema/Components/Page.xsd b/resources/Schema/Components/Page.xsd new file mode 100644 index 00000000..777124a2 --- /dev/null +++ b/resources/Schema/Components/Page.xsd @@ -0,0 +1,14 @@ + + + + + + Use this on a child to a Menu entity and make sure that ID is not the same as other pages. + + + + + + + + \ No newline at end of file diff --git a/resources/Schema/Types/Entity.xsd b/resources/Schema/Types/Entity.xsd index 9ea264d1..a9c5f641 100644 --- a/resources/Schema/Types/Entity.xsd +++ b/resources/Schema/Types/Entity.xsd @@ -47,6 +47,9 @@ + + + From 6bc713129016cae091acee7dd7e0fcd9a60fec49 Mon Sep 17 00:00:00 2001 From: Tleety Date: Tue, 16 Feb 2016 14:57:21 +0100 Subject: [PATCH 277/355] Glow Intencity can now be changed in the model component. --- include/Engine/Rendering/ModelJob.h | 3 ++- resources/Schema/Components/Model.xml | 1 + resources/Schema/Components/Model.xsd | 3 +++ resources/Shaders/ForwardPlus.frag.glsl | 3 ++- src/Engine/Rendering/DrawFinalPass.cpp | 7 +++++++ 5 files changed, 15 insertions(+), 2 deletions(-) diff --git a/include/Engine/Rendering/ModelJob.h b/include/Engine/Rendering/ModelJob.h index ba801f60..ccd0e093 100644 --- a/include/Engine/Rendering/ModelJob.h +++ b/include/Engine/Rendering/ModelJob.h @@ -108,6 +108,7 @@ struct ModelJob : RenderJob EndIndex = matGroup->EndIndex; Matrix = matrix; Color = modelComponent["Color"]; + GlowIntencity = ((double)modelComponent["GlowIntensity"]); Entity = modelComponent.EntityID; glm::vec3 abspos = Transform::AbsolutePosition(world, modelComponent.EntityID); glm::vec3 worldpos = glm::vec3(camera->ViewMatrix() * glm::vec4(abspos, 1)); @@ -170,7 +171,7 @@ struct ModelJob : RenderJob ::Skeleton::AnimationOffset AnimationOffset; - + float GlowIntencity = 8.0; glm::vec4 DiffuseColor; glm::vec4 SpecularColor; glm::vec4 IncandescenceColor; diff --git a/resources/Schema/Components/Model.xml b/resources/Schema/Components/Model.xml index 4b77dacb..f81c8210 100644 --- a/resources/Schema/Components/Model.xml +++ b/resources/Schema/Components/Model.xml @@ -8,4 +8,5 @@ true true true + 3.0 \ No newline at end of file diff --git a/resources/Schema/Components/Model.xsd b/resources/Schema/Components/Model.xsd index 9c0cd519..31203ff6 100644 --- a/resources/Schema/Components/Model.xsd +++ b/resources/Schema/Components/Model.xsd @@ -33,6 +33,9 @@ Whether the model should use the Glowmap or not + + Intensity of the glow map + diff --git a/resources/Shaders/ForwardPlus.frag.glsl b/resources/Shaders/ForwardPlus.frag.glsl index 471ee20b..d757ff36 100644 --- a/resources/Shaders/ForwardPlus.frag.glsl +++ b/resources/Shaders/ForwardPlus.frag.glsl @@ -9,6 +9,7 @@ uniform vec2 ScreenDimensions; uniform vec4 FillColor; uniform vec4 AmbientColor; uniform float FillPercentage; +uniform float GlowIntensity = 10; uniform vec2 DiffuseUVRepeat; uniform vec2 NormalUVRepeat; @@ -166,7 +167,7 @@ void main() color_result += FillColor; } sceneColor = vec4(color_result.xyz, clamp(color_result.a, 0, 1)); - color_result += glowTexel*3; + color_result += glowTexel*GlowIntensity; bloomColor = vec4(clamp(color_result.xyz - 1.0, 0, 100), 1.0); diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index 11db71f0..c98fb1f5 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -738,6 +738,8 @@ void DrawFinalPass::BindExplosionUniforms(GLuint shaderHandle, std::shared_ptrFillPercentage); GLERROR("Bind 19 uniform"); glUniform4fv(glGetUniformLocation(shaderHandle, "AmbientColor"), 1, glm::value_ptr(scene.AmbientColor)); + GLERROR("Bind 20 uniform"); + glUniform1f(glGetUniformLocation(shaderHandle, "GlowIntensity"), job->GlowIntencity); GLERROR("END"); } @@ -773,6 +775,11 @@ void DrawFinalPass::BindModelUniforms(GLuint shaderHandle, std::shared_ptrGlowIntencity); + GLERROR("END"); } From 17da9a8036ca6d23512aabcadb4c18106f5bb69e Mon Sep 17 00:00:00 2001 From: Teejoon Date: Tue, 16 Feb 2016 15:56:58 +0100 Subject: [PATCH 278/355] WIP --- include/Engine/Rendering/ModelJob.h | 2 +- include/Engine/Rendering/SpriteJob.h | 8 +- resources/Schema/Components.xsd | 1 + resources/Schema/Components/Indicator.xml | 3 + resources/Schema/Components/Indicator.xsd | 11 + resources/Schema/Entities/JohansTestMap.xml | 5379 +++++++++++++++++ resources/Schema/Entities/TestPlayerIndicator | 590 ++ .../Schema/Entities/TestPlayerIndicator.xml | 590 ++ src/Engine/Rendering/RenderSystem.cpp | 35 +- 9 files changed, 6612 insertions(+), 7 deletions(-) create mode 100644 resources/Schema/Components/Indicator.xml create mode 100644 resources/Schema/Components/Indicator.xsd create mode 100644 resources/Schema/Entities/JohansTestMap.xml create mode 100644 resources/Schema/Entities/TestPlayerIndicator create mode 100644 resources/Schema/Entities/TestPlayerIndicator.xml diff --git a/include/Engine/Rendering/ModelJob.h b/include/Engine/Rendering/ModelJob.h index ba801f60..41b0b8dd 100644 --- a/include/Engine/Rendering/ModelJob.h +++ b/include/Engine/Rendering/ModelJob.h @@ -183,7 +183,7 @@ struct ModelJob : RenderJob void CalculateHash() override { - Hash = TextureID + ModelID << 10 + ShaderID << 20; + Hash = ShaderID << 20 + ModelID << 10 + TextureID; } }; diff --git a/include/Engine/Rendering/SpriteJob.h b/include/Engine/Rendering/SpriteJob.h index 3bb43a1c..07636a97 100644 --- a/include/Engine/Rendering/SpriteJob.h +++ b/include/Engine/Rendering/SpriteJob.h @@ -17,7 +17,7 @@ struct SpriteJob : RenderJob { - SpriteJob(ComponentWrapper cSprite, Camera* camera, glm::mat4 matrix, World* world, glm::vec4 fillColor, float fillPercentage, bool depthSorted) + SpriteJob(ComponentWrapper cSprite, Camera* camera, glm::mat4 matrix, World* world, glm::vec4 fillColor, float fillPercentage, bool depthSorted, bool isIndicator) : RenderJob() { Model = ResourceManager::Load<::Model>("Models/Core/UnitQuad.mesh"); @@ -30,7 +30,7 @@ struct SpriteJob : RenderJob StartIndex = matProp.material->StartIndex; EndIndex = matProp.material->EndIndex; - Matrix = matrix; + Matrix = matrix; Color = cSprite["Color"]; Entity = cSprite.EntityID; Position = Transform::AbsolutePosition(world, cSprite.EntityID); @@ -40,7 +40,7 @@ struct SpriteJob : RenderJob Depth = viewpos.z; } World = world; - + IsIndicator = isIndicator; FillColor = fillColor; FillPercentage = fillPercentage; }; @@ -61,6 +61,8 @@ struct SpriteJob : RenderJob unsigned int EndIndex = 0; World* World; + bool IsIndicator = false; + glm::vec4 FillColor = glm::vec4(0); float FillPercentage = 0.0; diff --git a/resources/Schema/Components.xsd b/resources/Schema/Components.xsd index 61e49ae3..8a5f51f3 100644 --- a/resources/Schema/Components.xsd +++ b/resources/Schema/Components.xsd @@ -42,4 +42,5 @@ + \ No newline at end of file diff --git a/resources/Schema/Components/Indicator.xml b/resources/Schema/Components/Indicator.xml new file mode 100644 index 00000000..cd4e3f46 --- /dev/null +++ b/resources/Schema/Components/Indicator.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/resources/Schema/Components/Indicator.xsd b/resources/Schema/Components/Indicator.xsd new file mode 100644 index 00000000..54a6bfe5 --- /dev/null +++ b/resources/Schema/Components/Indicator.xsd @@ -0,0 +1,11 @@ + + + + + + + + Billbord and makes a Model or Sprite too always appare on players screen + + + \ No newline at end of file diff --git a/resources/Schema/Entities/JohansTestMap.xml b/resources/Schema/Entities/JohansTestMap.xml new file mode 100644 index 00000000..06e97bdc --- /dev/null +++ b/resources/Schema/Entities/JohansTestMap.xml @@ -0,0 +1,5379 @@ + + + + + + + + + + + + + + + + + + Models/Props/Ground.mesh + + + + + + + + + Models/Props/Highground1.mesh + + + + + + + + + + Models/Props/Highground2.mesh + + + + + + + + + + Models/Props/Highground1.mesh + + + + + + + + + + + + Models/Props/Highground2.mesh + + + + + + + + + + + + Models/Props/Highground3.mesh + + + + + + + + + + Models/Props/Highground4.mesh + + + + + + + + + + Models/Props/Highground5.mesh + + + + + + + + + + + Models/Props/Highground6.mesh + + + + + + + + + + Models/Props/Walls/SciFiWallTop.mesh + + + + + + + + + Models/Props/Walls/SciFiWallBig.mesh + + + + + + + + + + Models/Props/Walls/SciFiWallMedium.mesh + + + + + + + + + + Models/Props/Walls/SciFiWallSmall1.mesh + + + + + + + + + + Models/Props/Walls/SciFiWallSmall2.mesh + + + + + + + + + + Models/Props/Walls/SciFiWallBig.mesh + + + + + + + + + + + + Models/Props/Walls/SciFiWallMedium.mesh + + + + + + + + + + + + Models/Props/Walls/SciFiWallSmall3.mesh + + + + + + + + + + Models/Props/Walls/SciFiWallSmall4.mesh + + + + + + + + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar1Blue.mesh + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar1Red.mesh + + + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar2Red.mesh + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar3Blue.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar1Blue.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar1Red.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar3Red.mesh + + + + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar2Blue.mesh + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar2Red.mesh + + + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar2Blue.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar2Blue.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar2Blue.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar2Blue.mesh + + + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar2Red.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar2Red.mesh + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar2Red.mesh + + + + + + + + + + + + + + Models/Props/Pillars/StonePillar.mesh + + + + + + + + + + + + + Models/Props/Pillars/SciFiPillar2Red.mesh + + + + + + + + + + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + + + + Models/Props/Walls/SmallWall3.mesh + + + + + + + + + + + + + Models/Props/Walls/SmallWall3.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall3.mesh + + + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + + Models/Props/Walls/SmallWall4.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall3.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + + Models/Props/Walls/MediumWall2.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall2.mesh + + + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall3.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall3.mesh + + + + + + + + + + + + + Models/Props/Walls/SmallWall4.mesh + + + + + + + + + + + + + + Models/Props/Walls/SmallWall4.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + + Models/Props/Walls/BigWallBlue.mesh + + + + + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + Models/Props/Walls/BigWallRed.mesh + + + + + + + + + + + + + + Models/Props/Walls/SmallWall3.mesh + + + + + + + + + + + + Models/Props/Walls/SpecialWall1.mesh + + + + + + + + + + + + + + Models/Props/Flora/SpecialRoot.mesh + + + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall2.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall2.mesh + + + + + + + + + + + Models/Props/Walls/MediumWall2.mesh + + + + + + + + + + + + + Models/Props/Walls/SmallWall3.mesh + + + + + + + + + + + + Models/Props/Walls/SmallWall4.mesh + + + + + + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + + + Models/Props/Walls/MediumWall2.mesh + + + + + + + + + + + + + Models/Props/Walls/SpecialWall1.mesh + + + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + + Models/Props/Walls/SpecialWall1.mesh + + + + + + + + + + + + Models/Props/Walls/SpecialWall1.mesh + + + + + + + + + + + + + Models/Props/Walls/SpecialWall1.mesh + + + + + + + + + + + + + Models/Props/Walls/SpecialWall1.mesh + + + + + + + + + + + + + Models/Props/Walls/SpecialWall1.mesh + + + + + + + + + + + + + + Models/Props/Walls/SpecialWall1.mesh + + + + + + + + + + + + + + + + + + + + + Models/Props/Bridges/WoodenBridge.mesh + + + + + + + + + + + + + + Models/Props/Bridges/WoodenBridge.mesh + + + + + + + + + + + + + + Models/Props/Bridges/WoodenBridge.mesh + + + + + + + + + + + + + Models/Props/Bridges/SciFiBridge1Red.mesh + + + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + + + + + + + + + + Models/Props/Bridges/SciFiBridge1Blue.mesh + + + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + Models/Props/Bridges/SciFiBridgeDefense.mesh + + + + + + + + + + + + + + + + + + + + Models/Props/Pillars/SciFiBridgePillar1.mesh + + + + + + + + + + + + + + Models/Props/Bridges/SciFiBridge1Blue.mesh + + + + + + + + + + + + + Models/Props/Bridges/SciFiBridge1Blue.mesh + + + + + + + + + + + + + Models/Props/Pillars/SciFiBridgePillar1.mesh + + + + + + + + + + + + + + Models/Props/Bridges/SciFiBridge1Red.mesh + + + + + + + + + + + + + Models/Props/Bridges/SciFiBridge1Red.mesh + + + + + + + + + + + + + Models/Props/Bridges/WoodenBridge.mesh + + + + + + + + + + + + + + + + + + + + + Models/Props/Pillars/SciFiBridgePillar1.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiBridgePillar1.mesh + + + + + + + + + + + + + + Models/Props/Walls/MediumWall2.mesh + + + + + + + + + + + Models/Props/Walls/MediumWall2.mesh + + + + + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + Models/Props/Walls/MediumWall3.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiBridgePillar1.mesh + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + Models/Core/UnitPlane.mesh + + true + + + + + + + + + + + + + Models/Core/UnitPlane.mesh + + true + + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + + + + + + + + + + + + + + + Models/Props/Pillars/SciFiBridgePillar1.mesh + + + + + + + + + + + + + + Models/Props/Pillars/SciFiBridgePillar1.mesh + + + + + + + + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + + + Models/Props/Flora/TreeLog.mesh + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + + Models/Props/Flora/SpecialRoot.mesh + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + + Models/Props/Flora/SpecialRoot.mesh + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + + Models/Props/Flora/AliveBush.mesh + true + + + + + + + + + + + + + + Models/Props/Flora/SpecialRoot.mesh + + + + + + + + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + + Models/Props/Stones/SmallStone1.mesh + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/SmallStone1.mesh + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + Models/Props/Stones/SmallStone2.mesh + + + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalRed.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalRed.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalRed.mesh + + + + + + + + + + + + + + Models/Props/Walls/MediumWall1.mesh + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/SmallStone1.mesh + + + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + + Models/Props/Stones/SmallStone2.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + + + Models/Props/Stones/SmallStone1.mesh + + + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + + + Models/Props/Stones/SmallStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/SmallStone2.mesh + + + + + + + + + + + + + + Models/Props/Stones/SmallStone1.mesh + + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + + + + + + + Models/Props/Stones/SmallStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/SmallStone2.mesh + + + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + + Models/Props/Stones/SmallStone1.mesh + + + + + + + + + + + + + + + Models/Props/Stones/SmallStone1.mesh + + + + + + + + + + + + + + Models/Props/Stones/SmallStone1.mesh + + + + + + + + + + + + + + + + Models/Props/Stones/SmallStone2.mesh + + + + + + + + + + + + + + Models/Props/Stones/SmallStone1.mesh + + + + + + + + + + + + + Models/Props/Stones/SmallStone2.mesh + + + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + + Models/Props/Stones/SmallStone1.mesh + + + + + + + + + + + + + + + + Models/Props/Stones/SmallStone2.mesh + + + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + + + Models/Props/Stones/MediumStone1.mesh + + + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + + Models/Props/Stones/BigStone.mesh + + + + + + + + + + + + + Models/Props/Stones/SmallStone2.mesh + + + + + + + + + + + + + + Models/Props/Stones/MediumStone2.mesh + + + + + + + + + + + + + + + + + + + + + Models/Props/PickUps/PickUpHolder.mesh + + + + + + + + + + + + + + Models/Props/PickUps/PickUpHolder.mesh + + + + + + + + + + + + + + Models/Props/PickUps/PickUpHolder.mesh + + + + + + + + + + + + + + Models/Props/PickUps/PickUpHolder.mesh + + + + + + + + + + + + + + + + + + + + + + Models/Props/PickUps/PickUpHolder.mesh + + + + + + + + + + + + + + Models/Props/PickUps/PickUpHolder.mesh + + + + + + + + + + + + + Models/Props/PickUps/PickUpHolder.mesh + + + + + + + + + + + + + + Models/Props/PickUps/PickUpHolder.mesh + + + + + + + + + + + + + + Models/Props/PickUps/PickUpHolder.mesh + + + + + + + + + + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + + + Models/Props/Stones/AssaultHolder.mesh + + + + + + + + + + + + + + + + + + + + + Models/Props/SciFiHolder1.mesh + + + + + + + + + + + + + Models/Props/SciFiHolder1.mesh + + + + + + + + + + + + + Models/Props/SciFiHolder1.mesh + + + + + + + + + + + + + Models/Props/SciFiHolder1.mesh + + + + + + + + + + + + + Models/Props/SciFiHolder1.mesh + + + + + + + + + + + + + Models/Props/SciFiHolder1.mesh + + + + + + + + + + + + + Models/Props/SciFiHolder1.mesh + + + + + + + + + + + + + Models/Props/SciFiHolder1.mesh + + + + + + + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalRed.mesh + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalRed.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalRed.mesh + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalBlue.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalBlue.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalBlue.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalBlue.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalBlue.mesh + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalRed.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalRed.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalBlue.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalBlue.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalRed.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalRed.mesh + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalBlue.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalBlue.mesh + + + + + + + + + + + + + + Models/Props/Stones/ShinyStoneCrystalRed.mesh + + + + + + + + + + + + + + + + + + + + + + + Models/Props/CapturePoint/CapturePointBlue.mesh + + + + + + + + + + + + + 4 + + + Models/Core/UnitCylinder.mesh + + true + + + + + + + + + + + + + + + + + + + + + + + + + Textures/Test/aM4ME4GR.png + false + + + + + + + + + + + + Textures/Test/SmallDiff.png + false + + + + + + + + + + + + + + + + Models/Props/CapturePoint/CapturePointNeutral.mesh + + + + + + + + + + 3 + + + Models/Core/UnitCylinder.mesh + + true + + + + + + + + + + + + + + + + + Models/Props/CapturePoint/CapturePointNeutral.mesh + + + + + + + + + + 2 + + + Models/Core/UnitCylinder.mesh + + true + + + + + + + + + + + + + + + + + Models/Props/CapturePoint/CapturePointNeutral.mesh + + + + + + + + + + 1.5498908015879351 + 1 + + + Models/Core/UnitCylinder.mesh + + true + + + + + + + + + + + + + + + + + Models/Props/CapturePoint/CapturePointRed.mesh + + + + + + + + + + + + + + + Models/Core/UnitCylinder.mesh + + true + + + + + + + + + + + + + + + + + + + + + + + + + Textures/Test/aM4ME4GR.png + false + + + + + + + + + + Textures/Test/SmallDiff.png + false + + + + + + + + + + + + + + + + + + + + + + + + 1 + + + + + + + + + 10 + + + + + + + + + + 10 + + + + + + + + + + + + + 10 + + + + + + + + + + + 10 + + + + + + + + + + + 10 + + + + + + + + + + + 1 + + + + + + + + + + + + + + Schema/Entities/PlayerRed.xml + + + + + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + false + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + false + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + false + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + false + + + + + + + + + + + + + + Schema/Entities/Player.xml + + + + + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + false + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + false + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + false + + + + + + + + + + + + Models/Characters/Assault/AssaultTPose.mesh + false + + + + + + + + + + + + + + + + + + + Models/Props/PickUps/HealthPickUp.mesh + + + 0.10000000149011612 + + + + + + + + + + + + + + + + Models/Props/PickUps/AmmoPickUp.mesh + + + 0.10000000149011612 + + + + + + + + + + + + + + + + Models/Props/PickUps/HealthPickUp.mesh + + + 0.10000000149011612 + + + + + + + + + + + + + + + + Models/Props/PickUps/HealthPickUp.mesh + + + 0.10000000149011612 + + + + + + + + + + + + + + + + Models/Props/PickUps/AmmoPickUp.mesh + + + 0.10000000149011612 + + + + + + + + + + + + + + + + Models/Props/PickUps/HealthPickUp.mesh + + + 0.10000000149011612 + + + + + + + + + + + + + + + + Models/Props/PickUps/AmmoPickUp.mesh + + + 0.10000000149011612 + + + + + + + + + + + + + + + + Models/Props/PickUps/AmmoPickUp.mesh + + + 0.10000000149011612 + + + + + + + + + + + + + + + + diff --git a/resources/Schema/Entities/TestPlayerIndicator b/resources/Schema/Entities/TestPlayerIndicator new file mode 100644 index 00000000..504fa0db --- /dev/null +++ b/resources/Schema/Entities/TestPlayerIndicator @@ -0,0 +1,590 @@ + + + + + + + + + + 600 + + + + + + + + + 5 + + + + + + + + + + + + + + + + + + + + + + + + Models/Widgets/Camera.mesh + false + + + + + + + + + + + + + + + + + + + Textures/Weapons/Crosshair/SmallThickHoleDot.png + false + + + + + + + + + + + + Schema/Entities/HitMarker.xml + + + + + + + + + + + + + + 1 + + + + + 100/100 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + 1 + + + + Textures/HealthHUD3.png + + + + + + + + + + + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + 2 + + + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + 3 + + + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + 4 + + + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + 1 + + + 0.10332605343919568 + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + + + + + + + + + + + + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + + + Idle + 1.0214894690177836 + 1 + + + Models/Characters/Assault/FirstPerson.mesh + + true + + + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + true + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + Schema/Entities/ReloadEffectView.xml + + + + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + + + + + + + 32 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + 360 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + + + + + + + + + Models/Widgets/Camera.mesh + false + + + + + + + + + + + + Idle + 0.33673680560517383 + 1 + + + AimRifle + + + + + Models/Characters/Assault/AssaultAnimations.mesh + + + + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + Schema/Entities/ReloadEffectWorld.xml + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + false + + + + + + + + + + + + Models/Core/UnitCube.mesh + + false + + + + + + + + + + + Insert name here + Fonts/DroidSans.ttf,100 + + + + + + + + + + + + + + Textures/Test/aM4ME4GR.png + + + + + + + + + + diff --git a/resources/Schema/Entities/TestPlayerIndicator.xml b/resources/Schema/Entities/TestPlayerIndicator.xml new file mode 100644 index 00000000..56390bcb --- /dev/null +++ b/resources/Schema/Entities/TestPlayerIndicator.xml @@ -0,0 +1,590 @@ + + + + + + + + + + 600 + + + + + + + + + 5 + + + + + + + + + + + + + + + + + + + + + + + + Models/Widgets/Camera.mesh + false + + + + + + + + + + + + + + + + + + + Textures/Weapons/Crosshair/SmallThickHoleDot.png + false + + + + + + + + + + + + Schema/Entities/HitMarker.xml + + + + + + + + + + + + + + 1 + + + + + 100/100 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + 1 + + + + Textures/HealthHUD3.png + + + + + + + + + + + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + 2 + + + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + 3 + + + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + 4 + + + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + 1 + + + 0.10332605343919568 + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + + + + Textures/Core/UnitHexagon_Rotated.png + + + + + + + + + + + + + + + + + + + + + + + + + + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + + + Idle + 0.71065405191594166 + 1 + + + Models/Characters/Assault/FirstPerson.mesh + + true + + + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + true + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + Schema/Entities/ReloadEffectView.xml + + + + + + + + + + + + + + + + + + Textures/Core/UnitHexagon.png + + + + + + + + + + + + + + + + + + 32 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + 360 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + + + + + + + + + Models/Widgets/Camera.mesh + false + + + + + + + + + + + + Idle + 1.0759003871452997 + 1 + + + AimRifle + + + + + Models/Characters/Assault/AssaultAnimations.mesh + + + + + + + + + R_Arm_Weapon_Joint + + + Models/Weapons/Blue/AssaultWeaponBlue.mesh + + + + + + + + + + + Schema/Entities/RayBlue.xml + + + + + + + + + + + Schema/Entities/ReloadEffectWorld.xml + + + + + + + + + + + + + Models/Core/UnitCube.mesh + + false + + + + + + + + + + + + Models/Core/UnitCube.mesh + + false + + + + + + + + + + + Insert name here + Fonts/DroidSans.ttf,100 + + + + + + + + + + + + + + Textures/Test/aM4ME4GR.png + + + + + + + + + + diff --git a/src/Engine/Rendering/RenderSystem.cpp b/src/Engine/Rendering/RenderSystem.cpp index 665c4027..cd604b8c 100644 --- a/src/Engine/Rendering/RenderSystem.cpp +++ b/src/Engine/Rendering/RenderSystem.cpp @@ -67,11 +67,16 @@ void RenderSystem::fillSprites(std::list>& jobs, Worl fillColor = (glm::vec4)fillComponent["Color"]; } - glm::mat4 modelMatrix = Transform::ModelMatrix(entity.ID, world); - //modelMatrix *= m_Camera->BillboardMatrix(); + glm::mat4 modelMatrix = Transform::ModelMatrix(entity.ID, world); + bool isIndicator = false; + if (world->HasComponent(entity.ID, "Indicator") || entity.FirstParentWithComponent("Indicator").Valid()) + { + isIndicator = true; + modelMatrix = modelMatrix * m_Camera->BillboardMatrix(); + } - std::shared_ptr spriteJob = std::shared_ptr(new SpriteJob(cSprite, m_Camera, modelMatrix, world, fillColor, fillPercentage, depthSorted)); + std::shared_ptr spriteJob = std::shared_ptr(new SpriteJob(cSprite, m_Camera, modelMatrix, world, fillColor, fillPercentage, depthSorted, isIndicator)); jobs.push_back(spriteJob); } @@ -94,6 +99,30 @@ bool RenderSystem::isEntityVisible(EntityWrapper& entity) return false; } + // If a sprite is an Indicator, it's not local on player and object is in the same team, then dispaly it + if ( + (entity.HasComponent("Indicator")) + && (entity != m_LocalPlayer || !entity.IsChildOf(m_LocalPlayer)) + && (entity.HasComponent("Team") || entity.FirstParentWithComponent("Team").Valid()) + && entity.HasComponent("Sprite") + && m_LocalPlayer.World != nullptr + ) { + EntityWrapper entityTeam; + if (!entity.HasComponent("Team")) { + entityTeam = entity.FirstParentWithComponent("Team"); + } + else { + entityTeam = entity; + } + ComponentWrapper& entityTeamComponent = entityTeam["Team"]; + ComponentWrapper& localComponent = m_LocalPlayer["Team"]; + int entityTeamInt = entityTeamComponent["Team"]; + int localComponentInt = localComponent["Team"]; + int SpectatorInt = localComponent["Team"].Enum("Spectator"); + if (entityTeamInt != localComponentInt && localComponentInt != SpectatorInt) { + return false; + } + } return true; } From a006db9e63459f5a1ddbb83befa988e20944efca Mon Sep 17 00:00:00 2001 From: Jocke Date: Tue, 16 Feb 2016 16:06:17 +0100 Subject: [PATCH 279/355] WIP Fix dsync --- include/Game/Systems/PlayerMovementSystem.h | 2 +- src/Engine/Network/Client.cpp | 2 +- src/Engine/Network/Server.cpp | 4 ++-- src/Game/Systems/PlayerMovementSystem.cpp | 20 ++++++++++++-------- 4 files changed, 16 insertions(+), 12 deletions(-) diff --git a/include/Game/Systems/PlayerMovementSystem.h b/include/Game/Systems/PlayerMovementSystem.h index 2bcae866..d9006504 100644 --- a/include/Game/Systems/PlayerMovementSystem.h +++ b/include/Game/Systems/PlayerMovementSystem.h @@ -39,5 +39,5 @@ private: bool OnPlayerSpawned(Events::PlayerSpawned& e); void updateMovementControllers(double dt); - void updateVelocity(double dt); + void updateVelocity(EntityWrapper player, double dt); }; \ No newline at end of file diff --git a/src/Engine/Network/Client.cpp b/src/Engine/Network/Client.cpp index 62bc8e73..b25130f5 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -73,7 +73,7 @@ void Client::Update() m_TimeSinceSentInputs = std::clock(); } // HACK: Send absolute player positions for now to avoid desync until we have reliable messages - sendLocalPlayerTransform(); + //sendLocalPlayerTransform(); hasServerTimedOut(); } diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index 082849c7..d602d9ab 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -119,7 +119,7 @@ void Server::parseMessageType(Packet& packet) parseOnPlayerDamage(packet); break; case MessageType::PlayerTransform: - parsePlayerTransform(packet); +// parsePlayerTransform(packet); break; default: break; @@ -376,7 +376,7 @@ bool Server::OnInputCommand(const Events::InputCommand & e) isReadingData = !isReadingData; m_SaveDataTimer = std::clock(); } - if (e.Command == "KickPlayer" && e.Value > 0) { + else if (e.Command == "KickPlayer" && e.Value > 0) { kick(0); } diff --git a/src/Game/Systems/PlayerMovementSystem.cpp b/src/Game/Systems/PlayerMovementSystem.cpp index 71fb16ee..a144dd18 100644 --- a/src/Game/Systems/PlayerMovementSystem.cpp +++ b/src/Game/Systems/PlayerMovementSystem.cpp @@ -16,7 +16,15 @@ PlayerMovementSystem::~PlayerMovementSystem() void PlayerMovementSystem::Update(double dt) { updateMovementControllers(dt); - updateVelocity(dt); + if (IsServer) { + for (auto& kv : m_PlayerInputControllers) { + updateVelocity(kv.first, dt); + } + } else { + if (LocalPlayer.Valid()) { + updateVelocity(LocalPlayer, dt); + } + } } void PlayerMovementSystem::updateMovementControllers(double dt) @@ -221,15 +229,11 @@ void PlayerMovementSystem::updateMovementControllers(double dt) } -void PlayerMovementSystem::updateVelocity(double dt) +void PlayerMovementSystem::updateVelocity(EntityWrapper player, double dt) { // Only apply velocity to local player - if (!LocalPlayer.Valid()) { - return; - } - - ComponentWrapper& cTransform = LocalPlayer["Transform"]; - ComponentWrapper& cPhysics = LocalPlayer["Physics"]; + ComponentWrapper& cTransform = player["Transform"]; + ComponentWrapper& cPhysics = player["Physics"]; glm::vec3& velocity = cPhysics["Velocity"]; bool isOnGround = (bool)cPhysics["IsOnGround"]; From 8f84a5ddd673ba8fcd5fb94f20872aa8bbd7c24e Mon Sep 17 00:00:00 2001 From: Tleety Date: Tue, 16 Feb 2016 16:28:19 +0100 Subject: [PATCH 280/355] Buttons are now clickable --- include/Engine/Rendering/PickingPass.h | 2 +- include/Engine/Rendering/SpriteJob.h | 4 +- resources/Schema/Entities/Button.xml | 32 ++ .../Schema/Entities/QualityAssurance.xml | 373 ++++++++++++++++-- resources/Schema/Entities/TestMenu.xml | 299 ++++++++++++++ src/Engine/Rendering/DrawFinalPass.cpp | 3 - src/Engine/Rendering/PickingPass.cpp | 48 ++- 7 files changed, 722 insertions(+), 39 deletions(-) create mode 100644 resources/Schema/Entities/Button.xml create mode 100644 resources/Schema/Entities/TestMenu.xml diff --git a/include/Engine/Rendering/PickingPass.h b/include/Engine/Rendering/PickingPass.h index 2ce2e78d..d7a340f1 100644 --- a/include/Engine/Rendering/PickingPass.h +++ b/include/Engine/Rendering/PickingPass.h @@ -40,7 +40,7 @@ private: const IRenderer* m_Renderer; ShaderProgram* m_PickingProgram; - ShaderProgram* m_PickingSkinnedProgram; + ShaderProgram* m_PickingSkinnedProgram; Camera* m_Camera; struct PickingInfo diff --git a/include/Engine/Rendering/SpriteJob.h b/include/Engine/Rendering/SpriteJob.h index 3bb43a1c..4fe19dca 100644 --- a/include/Engine/Rendering/SpriteJob.h +++ b/include/Engine/Rendering/SpriteJob.h @@ -40,7 +40,8 @@ struct SpriteJob : RenderJob Depth = viewpos.z; } World = world; - + Pickable = world->HasComponent(cSprite.EntityID, "Button"); + FillColor = fillColor; FillPercentage = fillPercentage; }; @@ -60,6 +61,7 @@ struct SpriteJob : RenderJob unsigned int StartIndex = 0; unsigned int EndIndex = 0; World* World; + bool Pickable; glm::vec4 FillColor = glm::vec4(0); float FillPercentage = 0.0; diff --git a/resources/Schema/Entities/Button.xml b/resources/Schema/Entities/Button.xml new file mode 100644 index 00000000..21f64334 --- /dev/null +++ b/resources/Schema/Entities/Button.xml @@ -0,0 +1,32 @@ + + + + + + + Textures/Core/White.png + + + + + + + + + + + + Play + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + diff --git a/resources/Schema/Entities/QualityAssurance.xml b/resources/Schema/Entities/QualityAssurance.xml index 40951468..30fb915b 100644 --- a/resources/Schema/Entities/QualityAssurance.xml +++ b/resources/Schema/Entities/QualityAssurance.xml @@ -40,7 +40,7 @@ - + @@ -105,7 +105,7 @@ - + @@ -180,7 +180,7 @@ - + @@ -225,7 +225,7 @@ - + @@ -289,7 +289,7 @@ - + @@ -321,7 +321,7 @@ - + @@ -671,7 +671,7 @@ - + @@ -718,7 +718,7 @@ - + @@ -778,7 +778,7 @@ - + @@ -825,7 +825,7 @@ - + @@ -871,7 +871,7 @@ - + @@ -918,7 +918,7 @@ - + @@ -965,7 +965,7 @@ - + @@ -1027,7 +1027,7 @@ Models/Core/UnitCube.mesh - + true @@ -1077,7 +1077,7 @@ Models/Core/UnitCube.mesh - + true @@ -1167,7 +1167,7 @@ Models/Core/UnitCube.mesh - + true @@ -1217,7 +1217,7 @@ Models/Core/UnitCube.mesh - + true @@ -1379,7 +1379,7 @@ - + @@ -1388,7 +1388,7 @@ true - 0.75205058136495551 + 2.5166344949826396 3.7999999523162842 true @@ -1435,7 +1435,7 @@ - + @@ -1444,7 +1444,7 @@ - 1.2019563319790627 + 0.35000808291962926 Models/Characters/Assault/AssaultTPose.mesh @@ -1487,7 +1487,7 @@ - + @@ -1498,7 +1498,7 @@ true - 0.68540211563899389 + 0.35000808291962926 true @@ -1543,7 +1543,7 @@ - + @@ -1553,7 +1553,7 @@ true - 0.95150063648635763 + 9.4833086749886775 10 3 @@ -1601,7 +1601,7 @@ - + @@ -1611,7 +1611,7 @@ true - 1.3515288978624223 + 4.0667207575903603 true 5 true @@ -1678,10 +1678,10 @@ + Models/Core/UnitCube.mesh - @@ -1792,7 +1792,7 @@ true - 1.3682019578975679 + 2.5166344949826396 3.7999999523162842 true @@ -1836,12 +1836,12 @@ + Models/AssaultAnimated.mesh - @@ -2095,7 +2095,7 @@ Textures/Core/UnitHexagon.png - + @@ -2107,7 +2107,7 @@ 1 - + Textures/Core/UnitHexagon_Rotated.png @@ -2145,6 +2145,315 @@ + + + + + + + + + + + + Models/Widgets/Camera.mesh + false + + + + + + + + + + + + + + + + + + + + + Textures/Core/ErrorTexture.png + + + + + + + + + + + Textures/Core/White.png + + + + + + + + + + + Play + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + Textures/Core/White.png + + + + + + + + + + + Host + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + Textures/Core/White.png + + + + + + + + + + + Connect + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + Textures/Core/White.png + + + + + + + + + + + Settings + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + Textures/Core/White.png + + + + + + + + + + + Quit + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + + + + 1 + + + + + + + + + + Textures/Core/ErrorTexture.png + + + + + + + + + + + Textures/Core/White.png + + + + + + + + + + + Resolution + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + Textures/Core/White.png + + + + + + + + + + + Option2 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + Textures/Core/White.png + + + + + + + + + + + Butts + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + + + + + + Menu test area + Fonts/DroidSans.ttf,64 + + + + + + + + + + diff --git a/resources/Schema/Entities/TestMenu.xml b/resources/Schema/Entities/TestMenu.xml new file mode 100644 index 00000000..73678601 --- /dev/null +++ b/resources/Schema/Entities/TestMenu.xml @@ -0,0 +1,299 @@ + + + + + + + + + + + + + + + Models/Widgets/Camera.mesh + + + + + + + + + + + + + + + + + + + + + Textures/Core/ErrorTexture.png + + + + + + + + + + + Textures/Core/White.png + + + + + + + + + + + Play + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + Textures/Core/White.png + + + + + + + + + + + Host + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + Textures/Core/White.png + + + + + + + + + + + Connect + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + Textures/Core/White.png + + + + + + + + + + + Settings + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + Textures/Core/White.png + + + + + + + + + + + Quit + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + + + + 1 + + + + + + + + + + Textures/Core/ErrorTexture.png + + + + + + + + + + + Textures/Core/White.png + + + + + + + + + + + Resolution + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + Textures/Core/White.png + + + + + + + + + + + Option2 + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + Textures/Core/White.png + + + + + + + + + + + Butts + Fonts/DroidSans.ttf,64 + + + + + + + + + + + + + + + + + + + + diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index c98fb1f5..fd95ecee 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -689,9 +689,6 @@ void DrawFinalPass::DrawSprites(std::list>&jobs, Rend glDrawElements(GL_TRIANGLES, spriteJob->EndIndex - spriteJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(spriteJob->StartIndex*sizeof(unsigned int))); } } - - - // m_SpriteProgram->Unbind(); } diff --git a/src/Engine/Rendering/PickingPass.cpp b/src/Engine/Rendering/PickingPass.cpp index ecd0a4b8..a979eb0e 100644 --- a/src/Engine/Rendering/PickingPass.cpp +++ b/src/Engine/Rendering/PickingPass.cpp @@ -234,6 +234,52 @@ void PickingPass::Draw(RenderScene& scene) } } + for (auto& job : scene.Jobs.SpriteJob) { + auto spriteJob = std::dynamic_pointer_cast(job); + if (!spriteJob->Pickable) { + continue; + } + RenderState jobState; + + if (spriteJob) { + if (spriteJob->Depth == 0) { + jobState.Disable(GL_DEPTH_TEST); + } + int pickColor[2] = { m_ColorCounter[0], m_ColorCounter[1] }; + + PickingInfo pickInfo; + pickInfo.Entity = spriteJob->Entity; + pickInfo.World = spriteJob->World; + pickInfo.Camera = scene.Camera; + + auto color = m_EntityColors.find(std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)); + if (color != m_EntityColors.end()) { + pickColor[0] = color->second[0]; + pickColor[1] = color->second[1]; + } else { + m_EntityColors[std::make_tuple(pickInfo.Entity, pickInfo.World, pickInfo.Camera)] = glm::ivec2(pickColor[0], pickColor[1]); + if (m_ColorCounter[0] > 255) { + m_ColorCounter[0] = 0; + m_ColorCounter[1] += 1; + } else { + m_ColorCounter[0] += 1; + } + } + + m_PickingColorsToEntity[glm::ivec2(pickColor[0], pickColor[1])] = pickInfo; + + m_PickingProgram->Bind(); + glUniformMatrix4fv(glGetUniformLocation(shaderHandle, "M"), 1, GL_FALSE, glm::value_ptr(spriteJob->Matrix)); + 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())); + glUniform2fv(glGetUniformLocation(shaderHandle, "PickingColor"), 1, glm::value_ptr(glm::vec2(pickColor[0], pickColor[1]))); + + glBindVertexArray(spriteJob->Model->VAO); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, spriteJob->Model->ElementBuffer); + glDrawElements(GL_TRIANGLES, spriteJob->EndIndex - spriteJob->StartIndex + 1, GL_UNSIGNED_INT, (void*)(spriteJob->StartIndex * sizeof(unsigned int))); + } + } + /* for (auto &job : scene.Jobs.TransparentShieldedObjects) { auto modelJob = std::dynamic_pointer_cast(job); @@ -306,8 +352,6 @@ void PickingPass::Draw(RenderScene& scene) delete state; } - - void PickingPass::ClearPicking() { m_PickingColorsToEntity.clear(); From 4b8f1d95a355d54c570e70153d8c341542062c4b Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Tue, 16 Feb 2016 16:57:46 +0100 Subject: [PATCH 281/355] Added static class PerformanceTimer. Changed CMakeLists for engine to include boost timer. Added F2,F3 functions in editor. Added some timing, more to be added --- include/Engine/Core/PerformanceTimer.h | 36 +++++++++++ include/Engine/Core/SystemPipeline.h | 13 +++- include/Game/Game.h | 3 + resources/DefaultInput.ini | 4 +- src/Engine/CMakeLists.txt | 2 +- src/Engine/Core/PerformanceTimer.cpp | 87 ++++++++++++++++++++++++++ src/Engine/Editor/EditorSystem.cpp | 6 ++ src/Game/Game.cpp | 8 +++ 8 files changed, 154 insertions(+), 5 deletions(-) create mode 100644 include/Engine/Core/PerformanceTimer.h create mode 100644 src/Engine/Core/PerformanceTimer.cpp diff --git a/include/Engine/Core/PerformanceTimer.h b/include/Engine/Core/PerformanceTimer.h new file mode 100644 index 00000000..6fb5c4a5 --- /dev/null +++ b/include/Engine/Core/PerformanceTimer.h @@ -0,0 +1,36 @@ +#ifndef PerformanceTimer_h__ +#define PerformanceTimer_h__ + +#include +#include +#include "../Common.h" + +#include +using boost::timer::cpu_timer; + +class PerformanceTimer +{ +public: + static void StartTimer(std::string nameOfTimer); + static void StartTimerAndStopPrevious(std::string nameOfTimer); + static void StopTimer(std::string nameOfTimer); + static void SetFrameNumber(int frameNumber); + + static void ResetAllTimers(); + static void CreateExcelData(); + + //set timer/start + //get performance excel nånting + +private: + static std::map timers; + static double m_TimeElapsed; + static cpu_timer m_Timer; + static std::string currentTimerRunning; + static bool active; + //static map + + +}; + +#endif diff --git a/include/Engine/Core/SystemPipeline.h b/include/Engine/Core/SystemPipeline.h index 5f7aee0b..c4801fde 100644 --- a/include/Engine/Core/SystemPipeline.h +++ b/include/Engine/Core/SystemPipeline.h @@ -6,6 +6,7 @@ #include "System.h" #include "World.h" #include "EPause.h" +#include "PerformanceTimer.h" class SystemPipeline { @@ -72,7 +73,10 @@ public: // Update for (auto& system : group.ImpureSystems) { + auto className = (std::string)typeid(*system).name(); + PerformanceTimer::StartTimer(className); system->Update(dt); + PerformanceTimer::StopTimer(className); } for (auto& pair : group.PureSystems) { const std::string& componentName = pair.first; @@ -83,7 +87,10 @@ public: } for (auto& component : *pool) { for (auto& system : systems) { + auto className = (std::string)typeid(*system).name(); + PerformanceTimer::StartTimer(className); system->UpdateComponent(EntityWrapper(m_World, component.EntityID), component, dt); + PerformanceTimer::StopTimer(className); } } } @@ -106,9 +113,9 @@ private: std::vector m_OrderedSystemGroups; EventRelay m_EPause; - bool OnPause(const Events::Pause& e) { - if (e.World == m_World) { - m_Paused = true; + bool OnPause(const Events::Pause& e) { + if (e.World == m_World) { + m_Paused = true; } return true; } diff --git a/include/Game/Game.h b/include/Game/Game.h index baf15656..5a53c15c 100644 --- a/include/Game/Game.h +++ b/include/Game/Game.h @@ -35,6 +35,9 @@ #include "Sound/SoundManager.h" #include "Systems/SoundSystem.h" +//Performance +#include "Core/PerformanceTimer.h" + class Game { public: diff --git a/resources/DefaultInput.ini b/resources/DefaultInput.ini index d5489c3a..776cbecd 100644 --- a/resources/DefaultInput.ini +++ b/resources/DefaultInput.ini @@ -25,4 +25,6 @@ C=ConnectToServer N=SwitchToServer M=SwitchToClient P=SwitchToPlayer -K=TakeDamage,1500 \ No newline at end of file +K=TakeDamage,1500 +F2=PerformanceTimingResetAllTimers +F3=PerformanceTimingCreateExcelData \ No newline at end of file diff --git a/src/Engine/CMakeLists.txt b/src/Engine/CMakeLists.txt index 19763310..e74214cf 100644 --- a/src/Engine/CMakeLists.txt +++ b/src/Engine/CMakeLists.txt @@ -3,7 +3,7 @@ project(TacticalZ-Engine) find_package(OpenGL REQUIRED) find_package(GLEW REQUIRED) find_package(GLFW REQUIRED) -find_package(Boost REQUIRED COMPONENTS system filesystem thread chrono program_options) +find_package(Boost REQUIRED COMPONENTS system filesystem thread chrono timer program_options) find_package(assimp REQUIRED) find_package(ZLIB REQUIRED) find_package(PNG REQUIRED) diff --git a/src/Engine/Core/PerformanceTimer.cpp b/src/Engine/Core/PerformanceTimer.cpp new file mode 100644 index 00000000..a7a437c2 --- /dev/null +++ b/src/Engine/Core/PerformanceTimer.cpp @@ -0,0 +1,87 @@ +#include "Core/PerformanceTimer.h" +#include +#include +#include +#include + +cpu_timer PerformanceTimer::m_Timer; +double PerformanceTimer::m_TimeElapsed; +std::map PerformanceTimer::timers; +std::string PerformanceTimer::currentTimerRunning = ""; + +void PerformanceTimer::StartTimer(std::string nameOfTimer) +{ + timers[nameOfTimer].stop(); + timers[nameOfTimer].start(); + currentTimerRunning = nameOfTimer; +} + +void PerformanceTimer::StartTimerAndStopPrevious(std::string nameOfTimer) +{ + //stop the current timer and start some other - useful to not have to stop timers all the time + if (currentTimerRunning != "") { + timers[currentTimerRunning].stop(); + } + timers[nameOfTimer].stop(); + timers[nameOfTimer].start(); + currentTimerRunning = nameOfTimer; +} + + + +void PerformanceTimer::StopTimer(std::string nameOfTimer) +{ + timers[nameOfTimer].stop(); + currentTimerRunning = nameOfTimer; +} + + + +void PerformanceTimer::SetFrameNumber(int frameNumber) +{ +} + +void PerformanceTimer::ResetAllTimers() +{ + //stop all timers + for (auto aTimer : timers) + { + aTimer.second.stop(); + } + currentTimerRunning = ""; + timers.clear(); +} + +void PerformanceTimer::CreateExcelData() +{ + //wall = http://theboostcpplibraries.com/boost.timer + //http://www.boost.org/doc/libs/1_48_0/libs/timer/doc/cpu_timers.html + + //get path,time + char Dump_Path[MAX_PATH]; + GetModuleFileName(NULL, Dump_Path, sizeof(Dump_Path)); //path of current process + std::time_t t = std::time(NULL); + char tStr[16]; + std::strftime(tStr, 32, " %a %H-%M-%S", std::localtime(&t)); + std::string time(tStr); + std::string path(Dump_Path); + path = path.substr(0, path.length() - 4); + path += time + ".xls"; + std::ofstream someFileStream; + someFileStream.open(path, std::ofstream::out); + someFileStream << "classname" << ',' << "walltime" << ',' << "userTime" << ',' << "systemTime" << '\n'; + for (auto aTimer : timers) + { + //remove the "class" name in front of the string + auto className = aTimer.first; + if (className.find("class ") != std::string::npos) { + className.replace(0, 6, ""); + } + auto wallTime = (double)aTimer.second.elapsed().wall*1e-3; + auto userTime = (double)aTimer.second.elapsed().user*1e-3; + auto systemTime = (double)aTimer.second.elapsed().system*1e-3; + + someFileStream << className << "," << wallTime << ',' << userTime << ',' << systemTime << '\n'; + } + someFileStream.close(); +} diff --git a/src/Engine/Editor/EditorSystem.cpp b/src/Engine/Editor/EditorSystem.cpp index 4899519d..eedc7c22 100644 --- a/src/Engine/Editor/EditorSystem.cpp +++ b/src/Engine/Editor/EditorSystem.cpp @@ -223,6 +223,12 @@ bool EditorSystem::OnInputCommand(const Events::InputCommand& e) Enable(); } } + if (e.Command == "PerformanceTimingResetAllTimers" && e.Value > 0) { + PerformanceTimer::ResetAllTimers(); + } + if (e.Command == "PerformanceTimingCreateExcelData" && e.Value > 0) { + PerformanceTimer::CreateExcelData(); + } return true; } diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index 49b1a963..d2535518 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -187,16 +187,20 @@ void Game::Tick() // Handle input in a weird looking but responsive way m_EventBroker->Process(); m_EventBroker->Swap(); + PerformanceTimer::StartTimer("InputManager"); m_InputManager->Update(dt); m_EventBroker->Swap(); + PerformanceTimer::StartTimerAndStopPrevious("InputProxy"); m_InputProxy->Update(dt); m_EventBroker->Swap(); m_InputProxy->Process(); m_EventBroker->Swap(); + PerformanceTimer::StartTimerAndStopPrevious("SoundManager"); m_SoundManager->Update(dt); // Update network + PerformanceTimer::StartTimerAndStopPrevious("Network"); m_EventBroker->Process(); if (m_NetworkClient != nullptr) { m_NetworkClient->Update(); @@ -207,10 +211,14 @@ void Game::Tick() //m_SoundManager->Update(dt); // Iterate through systems and update world! + PerformanceTimer::StartTimerAndStopPrevious("SystemPipeline"); m_EventBroker->Process(); m_SystemPipeline->Update(dt); + PerformanceTimer::StartTimerAndStopPrevious("RendererUpdate"); m_Renderer->Update(dt); + PerformanceTimer::StartTimerAndStopPrevious("RendererDraw"); m_Renderer->Draw(*m_RenderFrame); + PerformanceTimer::StopTimer("RendererDraw"); m_RenderFrame->Clear(); m_EventBroker->Swap(); m_EventBroker->Clear(); From 42b49f9dba92e054a246c7c3d56814d82f4129d5 Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Tue, 16 Feb 2016 17:51:39 +0100 Subject: [PATCH 282/355] Added more timers to Rendering. --- include/Engine/Rendering/Renderer.h | 1 + resources/Schema/Entities/GameMap.xml | 8 +++++--- src/Engine/Rendering/Renderer.cpp | 19 ++++++++++++++++++- 3 files changed, 24 insertions(+), 4 deletions(-) diff --git a/include/Engine/Rendering/Renderer.h b/include/Engine/Rendering/Renderer.h index 04754514..936b0359 100644 --- a/include/Engine/Rendering/Renderer.h +++ b/include/Engine/Rendering/Renderer.h @@ -23,6 +23,7 @@ #include "imgui/imgui.h" #include "TextPass.h" #include "Util/CommonFunctions.h" +#include "Core/PerformanceTimer.h" class Renderer : public IRenderer { diff --git a/resources/Schema/Entities/GameMap.xml b/resources/Schema/Entities/GameMap.xml index 84a1e363..c3a16361 100644 --- a/resources/Schema/Entities/GameMap.xml +++ b/resources/Schema/Entities/GameMap.xml @@ -144,7 +144,7 @@ - + @@ -206,14 +206,16 @@ - + - + + + diff --git a/src/Engine/Rendering/Renderer.cpp b/src/Engine/Rendering/Renderer.cpp index be84160c..85687bf5 100644 --- a/src/Engine/Rendering/Renderer.cpp +++ b/src/Engine/Rendering/Renderer.cpp @@ -99,34 +99,48 @@ void Renderer::Draw(RenderFrame& frame) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //Clear other buffers + PerformanceTimer::StartTimer("Renderer-ClearBuffers"); m_PickingPass->ClearPicking(); m_DrawFinalPass->ClearBuffer(); m_DrawBloomPass->ClearBuffer(); + PerformanceTimer::StopTimer("Renderer-ClearBuffers"); for (auto scene : frame.RenderScenes){ + PerformanceTimer::StartTimer("Renderer-Depth"); SortRenderJobsByDepth(*scene); GLERROR("SortByDepth"); + PerformanceTimer::StartTimerAndStopPrevious("Renderer-Drawing PickingPass"); m_PickingPass->Draw(*scene); GLERROR("Drawing pickingpass"); + PerformanceTimer::StartTimerAndStopPrevious("Renderer-Generate Frustrums"); m_LightCullingPass->GenerateNewFrustum(*scene); GLERROR("Generate frustums"); + PerformanceTimer::StartTimerAndStopPrevious("Renderer-Filling Light List"); m_LightCullingPass->FillLightList(*scene); GLERROR("Filling light list"); + PerformanceTimer::StartTimerAndStopPrevious("Renderer-Light Culling"); m_LightCullingPass->CullLights(*scene); GLERROR("LightCulling"); + PerformanceTimer::StartTimerAndStopPrevious("Renderer-Draw Geometry+Light"); m_DrawFinalPass->Draw(*scene); GLERROR("Draw Geometry+Light"); //m_DrawScenePass->Draw(*scene); + PerformanceTimer::StartTimerAndStopPrevious("Renderer-Draw Text"); m_TextPass->Draw(*scene, *m_DrawFinalPass->FinalPassFrameBuffer()); GLERROR("Draw Text"); - + PerformanceTimer::StopTimer("Renderer-Draw Text"); } + PerformanceTimer::StartTimer("Renderer-Draw Bloom"); m_DrawBloomPass->Draw(m_DrawFinalPass->BloomTexture()); + PerformanceTimer::StopTimer("Renderer-Draw Bloom"); if (m_DebugTextureToDraw == 0) { + PerformanceTimer::StartTimer("Renderer-Color Correction Pass"); m_DrawColorCorrectionPass->Draw(m_DrawFinalPass->SceneTexture(), m_DrawBloomPass->GaussianTexture(), m_DrawFinalPass->SceneTextureLowRes(), m_DrawFinalPass->BloomTextureLowRes(), frame.Gamma, frame.Exposure); + PerformanceTimer::StopTimer("Renderer-Color Correction Pass"); } + PerformanceTimer::StartTimer("Renderer-Misc Debug Draws"); if (m_DebugTextureToDraw == 1) { m_DrawScreenQuadPass->Draw(m_DrawFinalPass->SceneTexture()); } @@ -145,10 +159,13 @@ void Renderer::Draw(RenderFrame& frame) if (m_DebugTextureToDraw == 6) { m_DrawScreenQuadPass->Draw(m_PickingPass->PickingTexture()); } + PerformanceTimer::StopTimer("Renderer-Misc Debug Draws"); + PerformanceTimer::StartTimer("Renderer-ImGuiRenderPass"); m_ImGuiRenderPass->Draw(); GLERROR("Imgui draw"); glfwSwapBuffers(m_Window); + PerformanceTimer::StopTimer("Renderer-ImGuiRenderPass"); } PickData Renderer::Pick(glm::vec2 screenCoord) From b2a437731ec8e5a85029b8f3132717bd0162f110 Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Tue, 16 Feb 2016 17:58:27 +0100 Subject: [PATCH 283/355] Small cleanup in the code --- include/Engine/Core/PerformanceTimer.h | 7 ------- src/Engine/Core/PerformanceTimer.cpp | 9 ++------- 2 files changed, 2 insertions(+), 14 deletions(-) diff --git a/include/Engine/Core/PerformanceTimer.h b/include/Engine/Core/PerformanceTimer.h index 6fb5c4a5..9f2c3d66 100644 --- a/include/Engine/Core/PerformanceTimer.h +++ b/include/Engine/Core/PerformanceTimer.h @@ -19,18 +19,11 @@ public: static void ResetAllTimers(); static void CreateExcelData(); - //set timer/start - //get performance excel nånting - private: static std::map timers; static double m_TimeElapsed; static cpu_timer m_Timer; static std::string currentTimerRunning; - static bool active; - //static map - - }; #endif diff --git a/src/Engine/Core/PerformanceTimer.cpp b/src/Engine/Core/PerformanceTimer.cpp index a7a437c2..05ac221a 100644 --- a/src/Engine/Core/PerformanceTimer.cpp +++ b/src/Engine/Core/PerformanceTimer.cpp @@ -27,16 +27,12 @@ void PerformanceTimer::StartTimerAndStopPrevious(std::string nameOfTimer) currentTimerRunning = nameOfTimer; } - - void PerformanceTimer::StopTimer(std::string nameOfTimer) { timers[nameOfTimer].stop(); currentTimerRunning = nameOfTimer; } - - void PerformanceTimer::SetFrameNumber(int frameNumber) { } @@ -54,9 +50,6 @@ void PerformanceTimer::ResetAllTimers() void PerformanceTimer::CreateExcelData() { - //wall = http://theboostcpplibraries.com/boost.timer - //http://www.boost.org/doc/libs/1_48_0/libs/timer/doc/cpu_timers.html - //get path,time char Dump_Path[MAX_PATH]; GetModuleFileName(NULL, Dump_Path, sizeof(Dump_Path)); //path of current process @@ -70,6 +63,8 @@ void PerformanceTimer::CreateExcelData() std::ofstream someFileStream; someFileStream.open(path, std::ofstream::out); someFileStream << "classname" << ',' << "walltime" << ',' << "userTime" << ',' << "systemTime" << '\n'; + + //write all timers to file for (auto aTimer : timers) { //remove the "class" name in front of the string From 443289143770aff128609b7d48e02da08b0f37dc Mon Sep 17 00:00:00 2001 From: Jocke Date: Wed, 17 Feb 2016 10:21:50 +0100 Subject: [PATCH 284/355] Fixed crash in Client::parsePlayerDamage. --- src/Engine/Network/Client.cpp | 5 +++-- src/Engine/Network/Server.cpp | 1 - 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Engine/Network/Client.cpp b/src/Engine/Network/Client.cpp index b25130f5..b595536d 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -437,11 +437,12 @@ void Client::parsePlayerDamage(Packet& packet) { Events::PlayerDamage e; PlayerID victimID = packet.ReadPrimitive(); - if(!serverClientMapsHasEntity(victimID)){ + PlayerID inflictorID = packet.ReadPrimitive(); + if(!serverClientMapsHasEntity(victimID) || !serverClientMapsHasEntity(inflictorID)){ return; } e.Inflictor = EntityWrapper(m_World, m_ServerIDToClientID.at(victimID)); - e.Victim = EntityWrapper(m_World, m_ServerIDToClientID.at(packet.ReadPrimitive())); + e.Victim = EntityWrapper(m_World, m_ServerIDToClientID.at(inflictorID)); e.Damage = packet.ReadPrimitive(); // Don't rebroadcast our own player damage events or we'll have an infinite loop! if (e.Inflictor != m_LocalPlayer) { diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index d602d9ab..3f59eb0c 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -84,7 +84,6 @@ void Server::Update() if (isReadingData) { Network::Update(); } - } void Server::parseMessageType(Packet& packet) From 0af9edc6e5392fabbd58390c12c17eedab0d7d9d Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Wed, 17 Feb 2016 10:53:20 +0100 Subject: [PATCH 285/355] Editor is properly disabled when disabled in config --- src/Engine/Editor/EditorSystem.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/Engine/Editor/EditorSystem.cpp b/src/Engine/Editor/EditorSystem.cpp index 4899519d..921df4dc 100644 --- a/src/Engine/Editor/EditorSystem.cpp +++ b/src/Engine/Editor/EditorSystem.cpp @@ -43,6 +43,8 @@ EditorSystem::EditorSystem(SystemParams params, IRenderer* renderer, RenderFrame m_Enabled = ResourceManager::Load("Config.ini")->Get("Debug.EditorEnabled", false); if (m_Enabled) { Enable(); + } else { + Disable(); } } From b13362360a928d7d18e9e03ce61748a4b51e298a Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Wed, 17 Feb 2016 11:22:42 +0100 Subject: [PATCH 286/355] Fixed RespawnModel of Pickups --- resources/Schema/Entities/AmmoPickup.xml | 3 ++- resources/Schema/Entities/HealthPickup.xml | 3 ++- resources/Schema/Entities/NewMap.xml | 20 ++++++++++---------- 3 files changed, 14 insertions(+), 12 deletions(-) diff --git a/resources/Schema/Entities/AmmoPickup.xml b/resources/Schema/Entities/AmmoPickup.xml index 534b76e2..d0bcfff6 100644 --- a/resources/Schema/Entities/AmmoPickup.xml +++ b/resources/Schema/Entities/AmmoPickup.xml @@ -5,10 +5,11 @@ - Models/Core/UnitSphere.mesh + Models/Props/PickUps/AmmoPickUp.mesh + diff --git a/resources/Schema/Entities/HealthPickup.xml b/resources/Schema/Entities/HealthPickup.xml index dfc6f938..868ca233 100644 --- a/resources/Schema/Entities/HealthPickup.xml +++ b/resources/Schema/Entities/HealthPickup.xml @@ -5,10 +5,11 @@ - Models/Core/UnitSphere.mesh + Models/Props/PickUps/HealthPickUp.mesh + diff --git a/resources/Schema/Entities/NewMap.xml b/resources/Schema/Entities/NewMap.xml index dcdb7bec..b564efd7 100644 --- a/resources/Schema/Entities/NewMap.xml +++ b/resources/Schema/Entities/NewMap.xml @@ -5019,7 +5019,7 @@ - + @@ -5089,7 +5089,7 @@ - + @@ -5165,7 +5165,7 @@ - + @@ -5184,7 +5184,7 @@ - + @@ -5203,7 +5203,7 @@ - + @@ -5222,7 +5222,7 @@ - + @@ -5241,7 +5241,7 @@ - + @@ -5260,7 +5260,7 @@ - + @@ -5279,7 +5279,7 @@ - + @@ -5298,7 +5298,7 @@ - + From 8f28c760dd8e45d45ff54f241be4a10c497ed782 Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Wed, 17 Feb 2016 11:47:10 +0100 Subject: [PATCH 287/355] You can now AssaultDash in the air --- .../Engine/Input/FirstPersonInputController.h | 4 ++-- resources/Schema/Entities/NewMap.xml | 20 +++++++++---------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/include/Engine/Input/FirstPersonInputController.h b/include/Engine/Input/FirstPersonInputController.h index 5529185a..7dc24a2c 100644 --- a/include/Engine/Input/FirstPersonInputController.h +++ b/include/Engine/Input/FirstPersonInputController.h @@ -202,7 +202,7 @@ void FirstPersonInputController::AssaultDashCheck(double dt, bool } //dashing with shift - if (m_ShiftDashing && m_AssaultDashCoolDownTimer <= 0.0f && !isJumping) { + if (m_ShiftDashing && m_AssaultDashCoolDownTimer <= 0.0f) { //player is dashing with shift //the wanted-direction is set in playermovement already so we dont need to check what direction we want to dash in! m_AssaultDashCoolDownTimer = assaultDashCoolDownMaxTimer; @@ -227,7 +227,7 @@ void FirstPersonInputController::AssaultDashCheck(double dt, bool } m_ValidDoubleTap = false; - if (!(m_AssaultDashCoolDownTimer <= 0.0f && !isJumping)) { + if (!(m_AssaultDashCoolDownTimer <= 0.0f)) { //if we cant dash at the moment, then just reset the tap-sensitivity-timer m_AssaultDashDoubleTapDeltaTime = 0.f; return; diff --git a/resources/Schema/Entities/NewMap.xml b/resources/Schema/Entities/NewMap.xml index dcdb7bec..00dc476f 100644 --- a/resources/Schema/Entities/NewMap.xml +++ b/resources/Schema/Entities/NewMap.xml @@ -5019,7 +5019,7 @@ - + @@ -5089,7 +5089,7 @@ - + @@ -5165,7 +5165,7 @@ - + @@ -5184,7 +5184,7 @@ - + @@ -5203,7 +5203,7 @@ - + @@ -5222,7 +5222,7 @@ - + @@ -5241,7 +5241,7 @@ - + @@ -5260,7 +5260,7 @@ - + @@ -5279,7 +5279,7 @@ - + @@ -5298,7 +5298,7 @@ - + From 657125b46913faa268ec020181ff17010168d511 Mon Sep 17 00:00:00 2001 From: Tleety Date: Wed, 17 Feb 2016 13:44:11 +0100 Subject: [PATCH 288/355] Moved menu code into GUI Button events are now sent when you click. --- include/Engine/GUI/Button.h | 165 ----------- include/Engine/GUI/ButtonSystem.h | 44 +++ include/Engine/GUI/EButtonClicked.h | 15 + include/Engine/GUI/EButtonEnter.h | 17 -- include/Engine/GUI/EButtonLeave.h | 17 -- include/Engine/GUI/EButtonPress.h | 20 -- include/Engine/GUI/EButtonPressed.h | 15 + include/Engine/GUI/EButtonRelease.h | 20 -- include/Engine/GUI/EButtonReleased.h | 13 + include/Engine/GUI/Frame.h | 261 ------------------ include/Engine/GUI/MainMenuSystem.h | 32 +++ include/Engine/GUI/TextureFrame.h | 112 -------- include/Game/Game.h | 2 - include/Game/Systems/HealthSystem.h | 5 +- resources/Schema/Components/Button.xsd | 1 + .../Schema/Entities/QualityAssurance.xml | 64 ++--- src/Engine/GUI/ButtonSystem.cpp | 78 ++++++ src/Engine/GUI/MainMenuSystem.cpp | 37 +++ src/Game/Game.cpp | 10 +- 19 files changed, 273 insertions(+), 655 deletions(-) delete mode 100644 include/Engine/GUI/Button.h create mode 100644 include/Engine/GUI/ButtonSystem.h create mode 100644 include/Engine/GUI/EButtonClicked.h delete mode 100644 include/Engine/GUI/EButtonEnter.h delete mode 100644 include/Engine/GUI/EButtonLeave.h delete mode 100644 include/Engine/GUI/EButtonPress.h create mode 100644 include/Engine/GUI/EButtonPressed.h delete mode 100644 include/Engine/GUI/EButtonRelease.h create mode 100644 include/Engine/GUI/EButtonReleased.h delete mode 100644 include/Engine/GUI/Frame.h create mode 100644 include/Engine/GUI/MainMenuSystem.h delete mode 100644 include/Engine/GUI/TextureFrame.h create mode 100644 src/Engine/GUI/ButtonSystem.cpp create mode 100644 src/Engine/GUI/MainMenuSystem.cpp diff --git a/include/Engine/GUI/Button.h b/include/Engine/GUI/Button.h deleted file mode 100644 index 80845cb7..00000000 --- a/include/Engine/GUI/Button.h +++ /dev/null @@ -1,165 +0,0 @@ -#ifndef GUI_BUTTON_H__ -#define GUI_BUTTON_H__ - -#include "GUI/TextureFrame.h" -#include "GUI/EButtonEnter.h" -#include "GUI/EButtonLeave.h" -#include "GUI/EButtonPress.h" -#include "GUI/EButtonRelease.h" -#include "Core/EMouseMove.h" -#include "Core/EMousePress.h" -#include "Core/EMouseRelease.h" - -namespace dd -{ -namespace GUI -{ - -class Button : public TextureFrame -{ -public: - Button(Frame* parent, std::string name) - : TextureFrame(parent, name) - { - EVENT_SUBSCRIBE_MEMBER(m_EMouseMove, &Button::OnMouseMove); - EVENT_SUBSCRIBE_MEMBER(m_EMousePress, &Button::OnMousePress); - EVENT_SUBSCRIBE_MEMBER(m_EMouseRelease, &Button::OnMouseRelease); - } - - void SetTextureHover(std::string resourceName) - { - m_TextureHover = resourceName; - } - void SetTextureReleased(std::string resourceName) - { - m_TextureReleased = resourceName; - SetTexture(resourceName); - } - void SetTexturePressed(std::string resourceName) - { - m_TexturePressed = resourceName; - } - - void Draw(RenderScene& rq) override - { - if (m_Texture == nullptr && !m_TextureReleased.empty()) { - SetTexture(m_TextureReleased); - } - - TextureFrame::Draw(rq); - } - - virtual void OnEnter() { } - virtual void OnLeave() { } - virtual void OnPress() { } - virtual void OnRelease() { } - -protected: - bool m_MouseIsOver = false; - bool m_IsDown = false; - - virtual bool OnMouseMove(const Events::MouseMove& event) - { - if (Hidden()) { - return false; - } - - bool isOver = Rectangle::Intersects(AbsoluteRectangle(), Rectangle(event.X, event.Y, 1, 1)); - if (isOver && !m_MouseIsOver) { // Enter - if (!m_IsDown) { - if (!m_TextureHover.empty()) { - SetTexture(m_TextureHover); - } - } - OnEnter(); - Events::ButtonEnter e; - e.FrameName = m_Name; - EventBroker->Publish(e); - Events::PlaySound soundEvent; - soundEvent.FilePath = "Sounds/GUI/hover-n.wav"; - EventBroker->Publish(soundEvent); - - } else if (!isOver && m_MouseIsOver) { // Leave - if (!m_IsDown) { - if (!m_TextureReleased.empty()) { - SetTexture(m_TextureReleased); - } - } - OnLeave(); - Events::ButtonLeave e; - e.FrameName = m_Name; - EventBroker->Publish(e); - } - m_MouseIsOver = isOver; - - return true; - } - virtual bool OnMousePress(const Events::MousePress& event) - { - if (Hidden()) { - //LOG_DEBUG("Pressed hidden button"); - return false; - } - - if (!Rectangle::Intersects(AbsoluteRectangle(), Rectangle(event.X, event.Y, 1, 1))) { - return false; - } - - if (!m_TexturePressed.empty()) { - SetTexture(m_TexturePressed); - } - - m_IsDown = true; - OnPress(); - Events::ButtonPress e; - e.FrameName = m_Name; - e.Button = this; - EventBroker->Publish(e); - - return true; - } - virtual bool OnMouseRelease(const Events::MouseRelease& event) - { - if (Hidden()) { - //LOG_DEBUG("Released hidden button"); - return false; - } - - bool isOver = Rectangle::Intersects(AbsoluteRectangle(), Rectangle(event.X, event.Y, 1, 1)); - if (!isOver && !m_IsDown) { - return false; - } - - if (m_MouseIsOver) { - if (!m_TextureHover.empty()) { - SetTexture(m_TextureHover); - } - } else { - if (!m_TextureReleased.empty()) { - SetTexture(m_TextureReleased); - } - } - - m_IsDown = false; - OnRelease(); - Events::ButtonRelease e; - e.FrameName = m_Name; - e.Button = this; - EventBroker->Publish(e); - - return true; - } - -private: - EventRelay m_EMouseMove; - EventRelay m_EMousePress; - EventRelay m_EMouseRelease; - - std::string m_TextureHover; - std::string m_TexturePressed; - std::string m_TextureReleased; -}; - -} -} -#endif diff --git a/include/Engine/GUI/ButtonSystem.h b/include/Engine/GUI/ButtonSystem.h new file mode 100644 index 00000000..7dfe6b48 --- /dev/null +++ b/include/Engine/GUI/ButtonSystem.h @@ -0,0 +1,44 @@ +#ifndef ButtonSystem_h__ +#define ButtonSystem_h__ + +#include "../Rendering/IRenderer.h" +#include "../Core/ConfigFile.h" +#include "../Rendering/PickingPass.h" +#include "../Core/ResourceManager.h" +#include "../Core/System.h" +#include "../Core/Event.h" +#include "../Core/EMousePress.h" +#include "../Core/EMouseRelease.h" +#include "../Core/ELockMouse.h" + +#include "EButtonPressed.h" +#include "EButtonReleased.h" +#include "EButtonClicked.h" + + +class ButtonSystem : public PureSystem +{ +public: + ButtonSystem(SystemParams params, IRenderer* renderer); + virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) override; +private: + IRenderer* m_Renderer; + bool m_MouseIsLocked = false; + + EntityWrapper m_PickEntity = EntityWrapper::Invalid; + PickData m_PickData; + + EventRelay m_EMouseLock; + bool OnMouseLock(const Events::LockMouse& e); + EventRelay m_EMouseUnlock; + bool OnMouseUnlock(const Events::UnlockMouse& e); + + EventRelay m_EMousePress; + bool OnMousePress(const Events::MousePress& e); + EventRelay m_EMouseRelease; + bool OnMouseRelease(const Events::MouseRelease& e); +}; + + + +#endif \ No newline at end of file diff --git a/include/Engine/GUI/EButtonClicked.h b/include/Engine/GUI/EButtonClicked.h new file mode 100644 index 00000000..f34d6b3d --- /dev/null +++ b/include/Engine/GUI/EButtonClicked.h @@ -0,0 +1,15 @@ +#ifndef Events_ButtonClicked_h__ +#define Events_ButtonClicked_h__ + +#include "Core/Event.h" + +namespace Events +{ + +struct ButtonClicked : public Event { + std::string EntityName = "DEFAULT STRING USED"; +}; + +} + +#endif \ No newline at end of file diff --git a/include/Engine/GUI/EButtonEnter.h b/include/Engine/GUI/EButtonEnter.h deleted file mode 100644 index 13a78383..00000000 --- a/include/Engine/GUI/EButtonEnter.h +++ /dev/null @@ -1,17 +0,0 @@ -#ifndef Events_ButtonEnter_h__ -#define Events_ButtonEnter_h__ - -#include "../Core/EventBroker.h" - -namespace Events -{ - -/** Thrown on GUI button hover. */ -struct ButtonEnter : Event -{ - std::string FrameName; -}; - -} - -#endif \ No newline at end of file diff --git a/include/Engine/GUI/EButtonLeave.h b/include/Engine/GUI/EButtonLeave.h deleted file mode 100644 index 789e5aec..00000000 --- a/include/Engine/GUI/EButtonLeave.h +++ /dev/null @@ -1,17 +0,0 @@ -#ifndef Events_ButtonLeave_h__ -#define Events_ButtonLeave_h__ - -#include "../Core/EventBroker.h" - -namespace Events -{ - -/** Thrown on GUI button hover. */ -struct ButtonLeave : Event -{ - std::string FrameName; -}; - -} - -#endif \ No newline at end of file diff --git a/include/Engine/GUI/EButtonPress.h b/include/Engine/GUI/EButtonPress.h deleted file mode 100644 index 6f925b2b..00000000 --- a/include/Engine/GUI/EButtonPress.h +++ /dev/null @@ -1,20 +0,0 @@ -#ifndef Events_ButtonPress_h__ -#define Events_ButtonPress_h__ - -#include "../Core/EventBroker.h" - -namespace GUI { class Button; } - -namespace Events -{ - -/** Thrown on GUI button press. */ -struct ButtonPress : Event -{ - std::string FrameName; - GUI::Button* Button; -}; - -} - -#endif \ No newline at end of file diff --git a/include/Engine/GUI/EButtonPressed.h b/include/Engine/GUI/EButtonPressed.h new file mode 100644 index 00000000..04d50978 --- /dev/null +++ b/include/Engine/GUI/EButtonPressed.h @@ -0,0 +1,15 @@ +#ifndef Events_ButtonPressed_h__ +#define Events_ButtonPressed_h__ + +#include "Core/Event.h" + +namespace Events +{ + +struct ButtonPressed : public Event { + std::string EntityName = "DEFAULT STRING USED"; +}; + +} + +#endif \ No newline at end of file diff --git a/include/Engine/GUI/EButtonRelease.h b/include/Engine/GUI/EButtonRelease.h deleted file mode 100644 index d13a8ad6..00000000 --- a/include/Engine/GUI/EButtonRelease.h +++ /dev/null @@ -1,20 +0,0 @@ -#ifndef Events_ButtonRelease_h__ -#define Events_ButtonRelease_h__ - -#include "../Core/EventBroker.h" - -namespace GUI { class Button; } - -namespace Events -{ - -/** Thrown on GUI button release. */ -struct ButtonRelease : Event -{ - std::string FrameName; - GUI::Button* Button; -}; - -} - -#endif \ No newline at end of file diff --git a/include/Engine/GUI/EButtonReleased.h b/include/Engine/GUI/EButtonReleased.h new file mode 100644 index 00000000..14736ca0 --- /dev/null +++ b/include/Engine/GUI/EButtonReleased.h @@ -0,0 +1,13 @@ +#ifndef Events_ButtonReleased_h__ +#define Events_ButtonReleased_h__ + +#include "Core/Event.h" + +namespace Events +{ + +struct ButtonReleased : public Event { }; + +} + +#endif \ No newline at end of file diff --git a/include/Engine/GUI/Frame.h b/include/Engine/GUI/Frame.h deleted file mode 100644 index 4c5f2eb9..00000000 --- a/include/Engine/GUI/Frame.h +++ /dev/null @@ -1,261 +0,0 @@ -#ifndef GUI_Frame_h__ -#define GUI_Frame_h__ - -#include "../Common.h" -#include "../Core/Util/Rectangle.h" -#include "../Core/EventBroker.h" -#include "../Core/EKeyDown.h" -#include "../Core/EKeyUp.h" -#include "../Core/ResourceManager.h" -#include "../Rendering/RenderQueue.h" -#include "../Rendering/Texture.h" -#include "../Input/EInputCommand.h" - -namespace GUI -{ - -class Frame : public Rectangle -{ -public: - enum class Anchor - { - Left, - Right, - Top, - Bottom - }; - - static const int BaseWidth = 1280; - static const int BaseHeight = 720; - - // Set up a base frame with an event broker - Frame(EventBroker* eventBroker) - : m_EventBroker(eventBroker) - , BaseFrame(this) - , m_Name("UIParent") - , Rectangle() { } - - // Create a frame as a child - Frame(Frame* parent, std::string name) - : m_Name(name) - { - SetParent(parent); - Width = parent->Width; - Height = parent->Height; - EVENT_SUBSCRIBE_MEMBER(m_EKeyDown, &Frame::OnKeyDown); - EVENT_SUBSCRIBE_MEMBER(m_EKeyUp, &Frame::OnKeyUp); - EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &Frame::OnCommand); - } - - ~Frame() - { - /*for (auto layer : m_Children) - { - for (auto child : layer.second) - { - delete child.second; - } - } - - if (m_Parent) - { - m_Parent->RemoveChild(this); - }*/ - } - - Frame* Parent() const { return m_Parent; } - - void SetParent(Frame* parent) - { - if (parent == nullptr) { - LOG_ERROR("Failed to parent frame \"%s\": Invalid parent", m_Name.c_str()); - return; - } - - m_Layer = parent->Layer() + 1; - parent->AddChild(this); - m_Parent = parent; - m_EventBroker = parent->m_EventBroker; - BaseFrame = parent->BaseFrame; - } - - void AddChild(Frame* child) - { - m_Children[child->m_Layer].insert(std::make_pair(child->Name(), child)); - if (m_Parent) { - m_Parent->AddChild(child); - } - } - - void RemoveChild(Frame* child) - { - auto it = m_Children.find(child->m_Layer); - if (it != m_Children.end()) { - m_Children.erase(it); - } - - if (m_Parent) { - m_Parent->RemoveChild(child); - } - } - - std::string Name() const { return m_Name; } - void SetName(std::string val) { m_Name = val; } - - int Layer() const { return m_Layer; } - - bool Hidden() const - { - if (m_Parent) - return m_Parent->Hidden() || m_Hidden; - else - return m_Hidden; - } - bool Visible() const - { - return !Hidden(); - } - - virtual void Hide() { m_Hidden = true; } - virtual void Show() { m_Hidden = false; } - - int Left() const override - { - if (m_Parent) - return m_Parent->Left() + X; - else - return X; - } - void SetLeft(int absLeft) override - { - if (m_Parent) { - X = absLeft - m_Parent->Left(); - } else { - X = absLeft; - } - } - int Right() const override - { - return Left() + Width; - } - void SetRight(int absRight) override - { - if (m_Parent) { - X = absRight - Width - m_Parent->Left(); - } else { - X = absRight - Width; - } - } - int Top() const override - { - if (m_Parent) - return m_Parent->Top() + Y; - else - return Y; - } - void SetTop(int absTop) override - { - if (m_Parent) { - Y = absTop - m_Parent->Top(); - } else { - Y = absTop; - } - } - int Bottom() const override - { - return Top() + Height; - } - void SetBottom(int absBottom) override - { - if (m_Parent) { - Y = absBottom - Height - m_Parent->Top(); - } else { - Y = absBottom - Height; - } - } - - glm::vec2 Scale() - { - if (m_Parent) - return m_Parent->Scale(); - else - return glm::vec2(Width, Height) / glm::vec2(BaseWidth, BaseHeight); - } - - Rectangle AbsoluteRectangle() - { - int left = Left(); - if (m_Parent) - left = std::max(left, m_Parent->Left()); - int top = Top(); - if (m_Parent) - top = std::max(top, m_Parent->Top()); - int width = Right() - left; - int height = Bottom() - top; - return Rectangle(left, top, width, height); - } - - void UpdateLayered(double dt) - { - // Update ourselves - this->Update(dt); - - // Update children - for (auto& pairLayer : m_Children) { - auto children = pairLayer.second; - for (auto& pairChild : children) { - auto child = pairChild.second; - child->Update(dt); - } - } - } - - virtual void Update(double dt) { } - - void DrawLayered(RenderScene& rq) - { - if (this->Hidden()) - return; - - // Draw ourselves - this->Draw(rq); - - // Draw children - for (auto& pairLayer : m_Children) { - auto children = pairLayer.second; - for (auto& pairChild : children) { - auto child = pairChild.second; - if (child->Hidden()) - continue; - child->Draw(rq); - } - } - } - - virtual void Draw(RenderScene& rq) { } - -protected: - ::EventBroker* m_EventBroker; - Frame* BaseFrame = nullptr; - - std::string m_Name = "Unnamed"; - int m_Layer = 0; - bool m_Hidden = false; - - Frame* m_Parent = nullptr; - typedef std::multimap Children_t; // name -> frame - std::map m_Children; // layer -> Children_t - - virtual bool OnKeyDown(const Events::KeyDown& event) { return false; } - virtual bool OnKeyUp(const Events::KeyUp& event) { return false; } - virtual bool OnCommand(const Events::InputCommand& event) { return false; } - -private: - EventRelay m_EKeyDown; - EventRelay m_EKeyUp; - EventRelay m_EInputCommand; -}; - -} - -#endif diff --git a/include/Engine/GUI/MainMenuSystem.h b/include/Engine/GUI/MainMenuSystem.h new file mode 100644 index 00000000..45400d1d --- /dev/null +++ b/include/Engine/GUI/MainMenuSystem.h @@ -0,0 +1,32 @@ +#ifndef MainMenuSystem_h__ +#define MainMenuSystem_h__ + +#include "../Core/System.h" +#include "../Rendering/IRenderer.h" +#include "../Core/ResourceManager.h" +#include "../Core/Event.h" + +#include "EButtonClicked.h" +#include "EButtonPressed.h" +#include "EButtonReleased.h" + + +class MainMenuSystem : public ImpureSystem +{ +public: + MainMenuSystem(SystemParams params, IRenderer* renderer); + virtual void Update(double dt) override; + +private: + IRenderer* m_Renderer; + + EventRelay m_EClicked; + bool OnButtonClick(const Events::ButtonClicked& e); + EventRelay m_EReleased; + bool OnButtonRelease(const Events::ButtonReleased& e); + EventRelay m_EPressed; + bool OnButtonPress(const Events::ButtonPressed& e); + +}; + +#endif \ No newline at end of file diff --git a/include/Engine/GUI/TextureFrame.h b/include/Engine/GUI/TextureFrame.h deleted file mode 100644 index 77967b4d..00000000 --- a/include/Engine/GUI/TextureFrame.h +++ /dev/null @@ -1,112 +0,0 @@ -#ifndef GUI_TextureFrame_h__ -#define GUI_TextureFrame_h__ - -#include "Frame.h" -#include "../Rendering/Texture.h" -#include "../Rendering/Util/CommonFunctions.h" - -namespace GUI -{ - -class TextureFrame : public Frame -{ -public: - TextureFrame(Frame* parent, std::string name) - : Frame(parent, name) { } - - void EnableScissor() { m_ScissorEnabled = true; } - void DisableScissor() { m_ScissorEnabled = false; } - - void Draw(RenderScene& rq) override - { - if (m_Texture == nullptr) - return; - - // Texture while fading - if (m_FadeTexture && m_CurrentFade < 1) { - FrameJob job; - job.Scissor = (m_ScissorEnabled) ? m_Parent->AbsoluteRectangle() : Rectangle(); - job.Viewport = Rectangle(Left(), Top(), Width, Height); - job.TextureID = m_FadeTexture->ResourceID; - job.DiffuseTexture = m_FadeTexture; - job.Color = glm::vec4(m_Color.r, m_Color.g, m_Color.b, m_Color.a); - job.Name = Name(); - rq.GUI.Add(job); - } - - // Main texture - { - FrameJob job; - job.Scissor = (m_ScissorEnabled) ? m_Parent->AbsoluteRectangle() : Rectangle(); - job.Viewport = Rectangle(Left(), Top(), Width, Height); - job.TextureID = m_Texture->ResourceID; - job.DiffuseTexture = m_Texture; - job.Color = glm::vec4(m_Color.r, m_Color.g, m_Color.b, m_Color.a * m_CurrentFade); - job.Name = Name(); - rq.GUI.Add(job); - } - } - - std::string Texture() const { return m_TextureName; } - - void SetTexture(std::string resourceName) - { - if (resourceName.empty()) { - m_Texture = nullptr; - return; - } - - m_Texture = CommonFunctions::LoadTexture(resourceName, false); - m_TextureName = resourceName; - if (m_Texture == nullptr) { - m_Texture = CommonFunctions::LoadTexture("Textures/Core/ErrorTexture.png", false); - } - - SizeToTexture(); - } - - void SizeToTexture() - { - if (m_Texture != nullptr) { - this->Width = m_Texture->Width; - this->Height = m_Texture->Height; - } - } - - void FadeToTexture(std::string resourceName, double duration) - { - m_FadeTexture = m_Texture; - SetTexture(resourceName); - m_FadeDuration = duration; - m_CurrentFade = 0.f; - } - - void Update(double dt) override - { - if (m_CurrentFade < 1) { - m_CurrentFade += dt / m_FadeDuration; - if (m_CurrentFade > 1) { - m_FadeTexture = nullptr; - m_CurrentFade = 1; - m_FadeDuration = 0; - } - } - } - - glm::vec4 Color() const { return m_Color; } - void SetColor(glm::vec4 val) { m_Color = val; } - -protected: - bool m_ScissorEnabled = true; - Texture* m_Texture = nullptr; - std::string m_TextureName; - Texture* m_FadeTexture = nullptr; - glm::vec4 m_Color = glm::vec4(1.f, 1.f, 1.f, 1.f); - float m_FadeDuration = 0.f; - float m_CurrentFade = 1.f; - -}; - -} - -#endif diff --git a/include/Game/Game.h b/include/Game/Game.h index baf15656..d13efec0 100644 --- a/include/Game/Game.h +++ b/include/Game/Game.h @@ -8,7 +8,6 @@ #include "Core/EventBroker.h" #include "Rendering/Renderer.h" #include "Core/InputManager.h" -#include "GUI/Frame.h" #include "Core/World.h" #include "Input/InputProxy.h" #include "Input/KeyboardInputHandler.h" @@ -53,7 +52,6 @@ private: IRenderer* m_Renderer; InputManager* m_InputManager; InputProxy* m_InputProxy; - GUI::Frame* m_FrameStack; World* m_World; Octree* m_OctreeCollision; Octree* m_OctreeTrigger; diff --git a/include/Game/Systems/HealthSystem.h b/include/Game/Systems/HealthSystem.h index 56f2f838..962e3737 100644 --- a/include/Game/Systems/HealthSystem.h +++ b/include/Game/Systems/HealthSystem.h @@ -27,17 +27,16 @@ public: private: bool m_NetworkEnabled; - //methods which will take care of specific events + // methods which will take care of specific events EventRelay m_EPlayerDamage; bool HealthSystem::OnPlayerDamaged(Events::PlayerDamage& e); EventRelay m_EPlayerHealthPickup; bool HealthSystem::OnPlayerHealthPickup(Events::PlayerHealthPickup& e); EventRelay m_InputCommand; bool HealthSystem::OnInputCommand(Events::InputCommand& e); - + //vector which will keep track of health changes std::vector> m_DeltaHealthVector; - }; #endif \ No newline at end of file diff --git a/resources/Schema/Components/Button.xsd b/resources/Schema/Components/Button.xsd index 07f2eafc..7d97fef1 100644 --- a/resources/Schema/Components/Button.xsd +++ b/resources/Schema/Components/Button.xsd @@ -1,6 +1,7 @@ + Makes sprites klickable. diff --git a/resources/Schema/Entities/QualityAssurance.xml b/resources/Schema/Entities/QualityAssurance.xml index 30fb915b..6bd8a25a 100644 --- a/resources/Schema/Entities/QualityAssurance.xml +++ b/resources/Schema/Entities/QualityAssurance.xml @@ -40,7 +40,7 @@ - + @@ -105,7 +105,7 @@ - + @@ -180,7 +180,7 @@ - + @@ -225,7 +225,7 @@ - + @@ -289,7 +289,7 @@ - + @@ -321,7 +321,7 @@ - + @@ -671,7 +671,7 @@ - + @@ -718,7 +718,7 @@ - + @@ -778,7 +778,7 @@ - + @@ -825,7 +825,7 @@ - + @@ -871,7 +871,7 @@ - + @@ -918,7 +918,7 @@ - + @@ -965,7 +965,7 @@ - + @@ -1379,7 +1379,7 @@ - + @@ -1388,7 +1388,7 @@ true - 2.5166344949826396 + 2.5333333077342104 3.7999999523162842 true @@ -1435,7 +1435,7 @@ - + @@ -1444,7 +1444,7 @@ - 0.35000808291962926 + 0.70455028055985736 Models/Characters/Assault/AssaultTPose.mesh @@ -1487,7 +1487,7 @@ - + @@ -1498,7 +1498,7 @@ true - 0.35000808291962926 + 0.70455028055985736 true @@ -1543,7 +1543,7 @@ - + @@ -1553,7 +1553,7 @@ true - 9.4833086749886775 + 9.1832418997049956 10 3 @@ -1601,7 +1601,7 @@ - + @@ -1611,7 +1611,7 @@ true - 4.0667207575903603 + 1.007708532606415 true 5 true @@ -1792,7 +1792,7 @@ true - 2.5166344949826396 + 2.5333333077342104 3.7999999523162842 true @@ -2185,7 +2185,7 @@ - + @@ -2213,7 +2213,7 @@ - + @@ -2241,7 +2241,7 @@ - + @@ -2269,7 +2269,7 @@ - + @@ -2297,7 +2297,7 @@ - + @@ -2349,7 +2349,7 @@ - + @@ -2377,7 +2377,7 @@ - + @@ -2405,7 +2405,7 @@ - + diff --git a/src/Engine/GUI/ButtonSystem.cpp b/src/Engine/GUI/ButtonSystem.cpp new file mode 100644 index 00000000..dbdc0e18 --- /dev/null +++ b/src/Engine/GUI/ButtonSystem.cpp @@ -0,0 +1,78 @@ +#include "GUI/ButtonSystem.h" + +ButtonSystem::ButtonSystem(SystemParams params, IRenderer* renderer) + : System(params) + , PureSystem("Button") + , m_Renderer(renderer) +{ + EVENT_SUBSCRIBE_MEMBER(m_EMousePress, &ButtonSystem::OnMousePress); + EVENT_SUBSCRIBE_MEMBER(m_EMouseRelease, &ButtonSystem::OnMouseRelease); + EVENT_SUBSCRIBE_MEMBER(m_EMouseLock, &ButtonSystem::OnMouseLock); + EVENT_SUBSCRIBE_MEMBER(m_EMouseUnlock, &ButtonSystem::OnMouseUnlock); +} + + +bool ButtonSystem::OnMouseLock(const Events::LockMouse& e) +{ + m_MouseIsLocked = true; + return true; +} + + +bool ButtonSystem::OnMouseUnlock(const Events::UnlockMouse& e) +{ + m_MouseIsLocked = false; + return true; +} + + +bool ButtonSystem::OnMousePress(const Events::MousePress& e) +{ + if (e.Button == GLFW_MOUSE_BUTTON_1 && !m_MouseIsLocked) { + m_PickData = m_Renderer->Pick(glm::vec2(e.X, e.Y)); + if (m_PickData.Entity != EntityID_Invalid && m_PickData.World == m_World) { + if(m_World->HasComponent(m_PickData.Entity, "Button")) { + //Entity is a button, save it and send pressed event. + + m_PickEntity = EntityWrapper(m_World, m_PickData.Entity); + + //You have clicked on a button entity, send pressed event. + Events::ButtonPressed ePressed; + ePressed.EntityName = m_PickEntity.Name(); + m_EventBroker->Publish(ePressed); + } + } + } + return true; +} + +bool ButtonSystem::OnMouseRelease(const Events::MouseRelease& e) +{ + if(!m_MouseIsLocked) { + //Mouse is not locked, send release event. + Events::ButtonReleased eReleased; + m_EventBroker->Publish(eReleased); + m_PickData = m_Renderer->Pick(glm::vec2(e.X, e.Y)); + if(m_PickData.Entity != EntityID_Invalid && m_PickData.World == m_World) { + if(m_World->HasComponent(m_PickData.Entity, "Button")) { + EntityWrapper ent = EntityWrapper(m_World, m_PickData.Entity); + if (ent == m_PickEntity) { + //The entity you released the mouse button on is the same as you pressed it on. "Clicked" + Events::ButtonClicked eClicked; + eClicked.EntityName = m_PickEntity.Name(); + m_EventBroker->Publish(eClicked); + } + } + } + } + return true; +} + +void ButtonSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& cHealth, double dt) +{ + +} + + + + \ No newline at end of file diff --git a/src/Engine/GUI/MainMenuSystem.cpp b/src/Engine/GUI/MainMenuSystem.cpp new file mode 100644 index 00000000..3d6b6ced --- /dev/null +++ b/src/Engine/GUI/MainMenuSystem.cpp @@ -0,0 +1,37 @@ +#include "GUI/MainMenuSystem.h" + +MainMenuSystem::MainMenuSystem(SystemParams params, IRenderer* renderer) + : System(params) + , ImpureSystem() + , m_Renderer(renderer) +{ + EVENT_SUBSCRIBE_MEMBER(m_EPressed, &MainMenuSystem::OnButtonPress); + EVENT_SUBSCRIBE_MEMBER(m_EReleased, &MainMenuSystem::OnButtonRelease); + EVENT_SUBSCRIBE_MEMBER(m_EClicked, &MainMenuSystem::OnButtonClick); +} + +void MainMenuSystem::Update(double dt) +{ + +} + +bool MainMenuSystem::OnButtonClick(const Events::ButtonClicked& e) +{ + printf("\nClicked: %s", e.EntityName); + return true; +} + +bool MainMenuSystem::OnButtonRelease(const Events::ButtonReleased& e) +{ + printf("\nReleased"); + + return true; +} + +bool MainMenuSystem::OnButtonPress(const Events::ButtonPressed& e) +{ + printf("\nPressed: %s", e.EntityName); + + return true; +} + diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index 49b1a963..45044937 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -26,6 +26,8 @@ #include "Network/MultiplayerSnapshotFilter.h" #include "Game/Systems/AmmunitionHUDSystem.h" #include "Game/Systems/KillFeedSystem.h" +#include "GUI/ButtonSystem.h" +#include "GUI/MainMenuSystem.h" Game::Game(int argc, char* argv[]) @@ -72,11 +74,6 @@ Game::Game(int argc, char* argv[]) m_InputProxy->AddHandler(); m_InputProxy->LoadBindings("Input.ini"); - // Create the root level GUI frame - m_FrameStack = new GUI::Frame(m_EventBroker); - m_FrameStack->Width = m_Renderer->Resolution().Width; - m_FrameStack->Height = m_Renderer->Resolution().Height; - // Create a world m_World = new World(m_EventBroker); std::string mapToLoad = m_Config->Get("Debug.LoadMap", ""); @@ -132,6 +129,8 @@ Game::Game(int argc, char* argv[]) m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); m_SystemPipeline->AddSystem(updateOrderLevel); + m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer); + m_SystemPipeline->AddSystem(updateOrderLevel, m_Renderer); // Populate Octree with collidables ++updateOrderLevel; m_SystemPipeline->AddSystem(updateOrderLevel, m_OctreeCollision, "Collidable"); @@ -168,7 +167,6 @@ Game::~Game() delete m_NetworkServer; } delete m_World; - delete m_FrameStack; delete m_InputProxy; delete m_InputManager; delete m_RenderFrame; From 833015f45e97ae173130abe67595c24f86bfa333 Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Wed, 17 Feb 2016 13:44:41 +0100 Subject: [PATCH 289/355] Small code cleanup for PerformanceTimer --- include/Engine/Core/PerformanceTimer.h | 4 ---- resources/Schema/Entities/NewMap.xml | 20 ++++++++++---------- src/Engine/Core/PerformanceTimer.cpp | 12 +++--------- 3 files changed, 13 insertions(+), 23 deletions(-) diff --git a/include/Engine/Core/PerformanceTimer.h b/include/Engine/Core/PerformanceTimer.h index 9f2c3d66..a3cdfa92 100644 --- a/include/Engine/Core/PerformanceTimer.h +++ b/include/Engine/Core/PerformanceTimer.h @@ -1,10 +1,7 @@ #ifndef PerformanceTimer_h__ #define PerformanceTimer_h__ -#include -#include #include "../Common.h" - #include using boost::timer::cpu_timer; @@ -21,7 +18,6 @@ public: private: static std::map timers; - static double m_TimeElapsed; static cpu_timer m_Timer; static std::string currentTimerRunning; }; diff --git a/resources/Schema/Entities/NewMap.xml b/resources/Schema/Entities/NewMap.xml index dcdb7bec..f5b975b8 100644 --- a/resources/Schema/Entities/NewMap.xml +++ b/resources/Schema/Entities/NewMap.xml @@ -5019,7 +5019,7 @@ - + @@ -5089,7 +5089,7 @@ - + @@ -5165,7 +5165,7 @@ - + @@ -5184,7 +5184,7 @@ - + @@ -5203,7 +5203,7 @@ - + @@ -5222,7 +5222,7 @@ - + @@ -5241,7 +5241,7 @@ - + @@ -5260,7 +5260,7 @@ - + @@ -5279,7 +5279,7 @@ - + @@ -5298,7 +5298,7 @@ - + diff --git a/src/Engine/Core/PerformanceTimer.cpp b/src/Engine/Core/PerformanceTimer.cpp index 05ac221a..50983e79 100644 --- a/src/Engine/Core/PerformanceTimer.cpp +++ b/src/Engine/Core/PerformanceTimer.cpp @@ -1,11 +1,8 @@ #include "Core/PerformanceTimer.h" -#include #include #include -#include cpu_timer PerformanceTimer::m_Timer; -double PerformanceTimer::m_TimeElapsed; std::map PerformanceTimer::timers; std::string PerformanceTimer::currentTimerRunning = ""; @@ -50,16 +47,13 @@ void PerformanceTimer::ResetAllTimers() void PerformanceTimer::CreateExcelData() { - //get path,time - char Dump_Path[MAX_PATH]; - GetModuleFileName(NULL, Dump_Path, sizeof(Dump_Path)); //path of current process + //get time std::time_t t = std::time(NULL); char tStr[16]; std::strftime(tStr, 32, " %a %H-%M-%S", std::localtime(&t)); std::string time(tStr); - std::string path(Dump_Path); - path = path.substr(0, path.length() - 4); - path += time + ".xls"; + std::string path("TacticalZ"); + path += time + ".csv"; std::ofstream someFileStream; someFileStream.open(path, std::ofstream::out); someFileStream << "classname" << ',' << "walltime" << ',' << "userTime" << ',' << "systemTime" << '\n'; From a6c30100afcb64335aebf75c7bb2060c3b5ff4d1 Mon Sep 17 00:00:00 2001 From: Tleety Date: Wed, 17 Feb 2016 14:16:17 +0100 Subject: [PATCH 290/355] FrameWork for menu buttons --- src/Engine/GUI/MainMenuSystem.cpp | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/Engine/GUI/MainMenuSystem.cpp b/src/Engine/GUI/MainMenuSystem.cpp index 3d6b6ced..36d4a173 100644 --- a/src/Engine/GUI/MainMenuSystem.cpp +++ b/src/Engine/GUI/MainMenuSystem.cpp @@ -17,20 +17,27 @@ void MainMenuSystem::Update(double dt) bool MainMenuSystem::OnButtonClick(const Events::ButtonClicked& e) { - printf("\nClicked: %s", e.EntityName); + if(e.EntityName == "Play") { + //Run play code + } else if(e.EntityName == "Connect") { + //Run connect code + } else if(e.EntityName == "Host") { + //Run host code + } else if(e.EntityName == "Quit") { + printf("No, you stay"); + } + return true; } bool MainMenuSystem::OnButtonRelease(const Events::ButtonReleased& e) { - printf("\nReleased"); return true; } bool MainMenuSystem::OnButtonPress(const Events::ButtonPressed& e) { - printf("\nPressed: %s", e.EntityName); return true; } From b8222c7b2ea3753be3c06703da9ca88b204e9c79 Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Wed, 17 Feb 2016 14:54:42 +0100 Subject: [PATCH 291/355] The rotation of the Pickups are now also included in the AmmoPickup.xml, HealthPickup.xml --- resources/Schema/Entities/AmmoPickup.xml | 4 ++++ resources/Schema/Entities/HealthPickup.xml | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/resources/Schema/Entities/AmmoPickup.xml b/resources/Schema/Entities/AmmoPickup.xml index d0bcfff6..1d1435f7 100644 --- a/resources/Schema/Entities/AmmoPickup.xml +++ b/resources/Schema/Entities/AmmoPickup.xml @@ -7,6 +7,10 @@ Models/Props/PickUps/AmmoPickUp.mesh + + 0.1 + + diff --git a/resources/Schema/Entities/HealthPickup.xml b/resources/Schema/Entities/HealthPickup.xml index 868ca233..c6fbc4f4 100644 --- a/resources/Schema/Entities/HealthPickup.xml +++ b/resources/Schema/Entities/HealthPickup.xml @@ -7,6 +7,10 @@ Models/Props/PickUps/HealthPickUp.mesh + + 0.1 + + From 23bb1a64057fc3f5f9c21b0206b2daf3e384217b Mon Sep 17 00:00:00 2001 From: William Moberg Date: Wed, 17 Feb 2016 14:54:59 +0100 Subject: [PATCH 292/355] Cannot respawn inside other players, unless all are blocked. --- include/Engine/Collision/Collision.h | 10 ++- include/Game/Systems/SpawnerSystem.h | 7 +- src/Engine/Collision/Collision.cpp | 53 +++++++++++++-- src/Game/Systems/PlayerSpawnSystem.cpp | 4 +- src/Game/Systems/SpawnerSystem.cpp | 93 +++++++++++++++++++++----- 5 files changed, 143 insertions(+), 24 deletions(-) diff --git a/include/Engine/Collision/Collision.h b/include/Engine/Collision/Collision.h index 546d03f5..9e1a81db 100644 --- a/include/Engine/Collision/Collision.h +++ b/include/Engine/Collision/Collision.h @@ -78,13 +78,21 @@ bool AABBvsTriangles(const AABB& box, bool& isOnGround, glm::vec3& outResolutionVector); +//Detects collision, but does not resolve. +bool AABBvsTriangles(const AABB& box, + const RawModel::Vertex* modelVertices, + const std::vector& modelIndices, + const glm::mat4& modelMatrix); + //Return true if the boxes are intersecting. bool AABBVsAABB(const AABB& a, const AABB& b); //Return true if the boxes are intersecting. //Also outputs the minimum translation that box [a] would need in order to resolve collision. bool AABBVsAABB(const AABB& a, const AABB& b, glm::vec3& minimumTranslation); -// Calculates an absolute AABB from an entity AABB component +// Calculates an absolute AABB from an entity AABB component or Model component. +// if takeModelBox is true, the AABB component will be ignored and box is calculated from Model. +// if takeModelBox is false, the AABB component will be prefered, if it exists. boost::optional EntityAbsoluteAABB(EntityWrapper& entity, bool takeModelBox = false); boost::optional AbsoluteAABBExplosionEffect(EntityWrapper& entity); //Returns the first entity hit by the input ray. entitiesPotentiallyHitSorted needs to be sorted diff --git a/include/Game/Systems/SpawnerSystem.h b/include/Game/Systems/SpawnerSystem.h index 9cb4bd06..e4a44738 100644 --- a/include/Game/Systems/SpawnerSystem.h +++ b/include/Game/Systems/SpawnerSystem.h @@ -15,11 +15,16 @@ class SpawnerSystem : public System public: SpawnerSystem(SystemParams params); - static EntityWrapper Spawn(EntityWrapper spawner, EntityWrapper parent = EntityWrapper::Invalid); + // If dontCollideComponent is set, to e.g. "Player", then all the spawner + // will try to pick a spawn location so that the spawned entity doesn't + // collide with anything that has that component and is collidable. + static EntityWrapper Spawn(EntityWrapper spawner, EntityWrapper parent = EntityWrapper::Invalid, const std::string& dontCollideComponent = ""); private: EventRelay m_OnSpawnerSpawn; bool OnSpawnerSpawn(Events::SpawnerSpawn& e); + static void transformEntityToSpawnPoint(EntityWrapper spawnedEntity, EntityWrapper spawnPoint); + static bool spawnedEntityIsColliding(EntityWrapper spawnedEntity, EntityWrapper spawnPoint, const std::string& dontCollideComponent); }; #endif \ No newline at end of file diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index ab2098b7..87d8bf26 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -366,7 +366,8 @@ bool AABBvsTriangle(const AABB& box, float verticalStepHeight, bool& isOnGround, glm::vec3& boxVelocity, - glm::vec3& outResolution) + glm::vec3& outResolution, + bool resolveCollision) { //Check so we don't have a zero area triangle when calculating the normal. //Also, don't check a triangle facing away from the player. @@ -426,7 +427,7 @@ bool AABBvsTriangle(const AABB& box, //if projections don't overlap, return false. if (!rectangleVsTriangle(boxMin, boxMax, t2D, resolutionVector, resolutionDist, pushedFromTriangleLine)) { return false; - } else { + } else if (resolveCollision) { //Overwrite the smallest resolution if this is smaller. if (resolutionDist < resolveShortest.DistanceSq) { resolveShortest.Vector = glm::vec3(0.f); @@ -463,6 +464,11 @@ bool AABBvsTriangle(const AABB& box, if (glm::abs(t) > 1) { return false; } + + if (!resolveCollision) { + return true; + } + glm::vec3 cornerResolution = (1+t) * diagonal; //Overwrite the smallest resolution if cornerResolution is smaller. float lenSq = glm::length2(cornerResolution); @@ -537,7 +543,8 @@ bool AABBvsTriangles(const AABB& box, glm::vec3& boxVelocity, float verticalStepHeight, bool& isOnGround, - glm::vec3& outResolutionVector) + glm::vec3& outResolutionVector, + bool resolveCollision) { bool hit = false; @@ -553,7 +560,7 @@ bool AABBvsTriangles(const AABB& box, }; glm::vec3 outVec; bool collideWithGround = isOnGround; - if (AABBvsTriangle(newBox, triVertices, originalBoxVelocity, verticalStepHeight, collideWithGround, boxVelocity, outVec)) { + if (AABBvsTriangle(newBox, triVertices, originalBoxVelocity, verticalStepHeight, collideWithGround, boxVelocity, outVec, resolveCollision)) { hit = true; outResolutionVector += outVec; newBox = AABB::FromOriginSize(newBox.Origin() + outVec, newBox.Size()); @@ -569,6 +576,44 @@ bool AABBvsTriangles(const AABB& box, return hit; } +bool AABBvsTriangles(const AABB& box, + const RawModel::Vertex* modelVertices, + const std::vector& modelIndices, + const glm::mat4& modelMatrix, + glm::vec3& boxVelocity, + float verticalStepHeight, + bool& isOnGround, + glm::vec3& outResolutionVector) +{ + return AABBvsTriangles(box, + modelVertices, + modelIndices, + modelMatrix, + boxVelocity, + verticalStepHeight, + isOnGround, + outResolutionVector, + true); +} + +bool AABBvsTriangles(const AABB& box, + const RawModel::Vertex* modelVertices, + const std::vector& modelIndices, + const glm::mat4& modelMatrix) +{ + glm::vec3 vel, outres; + bool g; + return AABBvsTriangles(box, + modelVertices, + modelIndices, + modelMatrix, + vel, + 0.f, + g, + outres, + false); +} + boost::optional EntityAbsoluteAABB(EntityWrapper& entity, bool takeModelBox) { AABB modelSpaceBox; diff --git a/src/Game/Systems/PlayerSpawnSystem.cpp b/src/Game/Systems/PlayerSpawnSystem.cpp index 5f53a1fc..6254c674 100644 --- a/src/Game/Systems/PlayerSpawnSystem.cpp +++ b/src/Game/Systems/PlayerSpawnSystem.cpp @@ -3,7 +3,7 @@ //This should be set by the config anyway. float PlayerSpawnSystem::m_RespawnTime = 15.0f; -PlayerSpawnSystem::PlayerSpawnSystem(SystemParams params) +PlayerSpawnSystem::PlayerSpawnSystem(SystemParams params) : System(params) , m_Timer(0.f) { @@ -49,7 +49,7 @@ void PlayerSpawnSystem::Update(double dt) } // Spawn the player! - EntityWrapper player = SpawnerSystem::Spawn(spawner); + EntityWrapper player = SpawnerSystem::Spawn(spawner, EntityWrapper::Invalid, "Player"); // Set the player team affiliation player["Team"]["Team"] = req.Team; diff --git a/src/Game/Systems/SpawnerSystem.cpp b/src/Game/Systems/SpawnerSystem.cpp index b3c556f1..90f677fe 100644 --- a/src/Game/Systems/SpawnerSystem.cpp +++ b/src/Game/Systems/SpawnerSystem.cpp @@ -1,12 +1,13 @@ #include "Systems/SpawnerSystem.h" +#include "Collision/Collision.h" -SpawnerSystem::SpawnerSystem(SystemParams params) +SpawnerSystem::SpawnerSystem(SystemParams params) : System(params) { EVENT_SUBSCRIBE_MEMBER(m_OnSpawnerSpawn, &SpawnerSystem::OnSpawnerSpawn); } -EntityWrapper SpawnerSystem::Spawn(EntityWrapper spawner, EntityWrapper parent /*= EntityWrapper::Invalid*/) +EntityWrapper SpawnerSystem::Spawn(EntityWrapper spawner, EntityWrapper parent /*= EntityWrapper::Invalid*/, const std::string& dontCollideComponent) { // Spawn the entity in the parent's world if it exists, otherwise in the spawner's world World* world = parent.World; @@ -14,17 +15,41 @@ EntityWrapper SpawnerSystem::Spawn(EntityWrapper spawner, EntityWrapper parent / world = spawner.World; } + // Load the entity file and parse it + const std::string& entityFilePath = spawner["Spawner"]["EntityFile"]; + auto entityFile = ResourceManager::Load(entityFilePath); + if (entityFile == nullptr) { + return EntityWrapper::Invalid; + } + EntityFileParser parser(entityFile); + EntityWrapper spawnedEntity(world, parser.MergeEntities(world, parent.ID)); + + //If the spawned entity is collideable, then we must not spawn it where it collides with something that + //has a dontCollideComponent attached. + bool spawnOnCollidable = dontCollideComponent.empty() || !spawnedEntity.HasComponent("Collidable"); + if (!spawnOnCollidable) { + boost::optional optBox = Collision::EntityAbsoluteAABB(spawnedEntity); + //If we can't calculate the box for some reason, then just spawn somewhere anyway. + if (!optBox) { + spawnOnCollidable = true; + } + } + // Find any SpawnPoints existing as children of spawner auto children = spawner.World->GetChildren(spawner.ID); std::vector spawnPoints; for (auto kv = children.first; kv != children.second; ++kv) { const EntityID& child = kv->second; if (spawner.World->HasComponent(child, "SpawnPoint")) { - spawnPoints.push_back(EntityWrapper(spawner.World, child)); + EntityWrapper spawnPoint = EntityWrapper(spawner.World, child); + if (spawnOnCollidable || !spawnedEntityIsColliding(spawnedEntity, spawnPoint, dontCollideComponent)) { + spawnPoints.push_back(spawnPoint); + } } } // Choose a random SpawnPoint + // If there are no children, or if they are all blocked, then the entity will be spawned at the spawner itself. EntityWrapper spawnPoint = spawner; if (!spawnPoints.empty()) { if (spawnPoints.size() > 1) { @@ -39,25 +64,61 @@ EntityWrapper SpawnerSystem::Spawn(EntityWrapper spawner, EntityWrapper parent / } } - // Load the entity file and parse it - const std::string& entityFilePath = spawner["Spawner"]["EntityFile"]; - auto entityFile = ResourceManager::Load(entityFilePath); - if (entityFile == nullptr) { - return EntityWrapper::Invalid; - } - EntityFileParser parser(entityFile); - EntityWrapper spawnedEntity(world, parser.MergeEntities(world, parent.ID)); - if (spawnPoint != parent) { - // Set its position and orientation to that of the SpawnPoint - spawnedEntity["Transform"]["Position"] = Transform::AbsolutePosition(spawnPoint.World, spawnPoint.ID); - // TODO: Quaternions, bitch - spawnedEntity["Transform"]["Orientation"] = glm::eulerAngles(Transform::AbsoluteOrientation(spawnPoint)); + transformEntityToSpawnPoint(spawnedEntity, spawnPoint); } return spawnedEntity; } +void SpawnerSystem::transformEntityToSpawnPoint(EntityWrapper spawnedEntity, EntityWrapper spawnPoint) +{ + // Set its position and orientation to that of the SpawnPoint + spawnedEntity["Transform"]["Position"] = Transform::AbsolutePosition(spawnPoint.World, spawnPoint.ID); + // TODO: Quaternions, bitch + spawnedEntity["Transform"]["Orientation"] = glm::eulerAngles(Transform::AbsoluteOrientation(spawnPoint)); +} + +bool SpawnerSystem::spawnedEntityIsColliding(EntityWrapper spawnedEntity, EntityWrapper spawnPoint, const std::string& dontCollideComponent) +{ + transformEntityToSpawnPoint(spawnedEntity, spawnPoint); + //Check if the spawned entity collides with anything, and if so, continue to the next spawnpoint. + EntityAABB spawnedBox = *Collision::EntityAbsoluteAABB(spawnedEntity); + const ComponentPool* otherSpawnedEntities = spawnPoint.World->GetComponents(dontCollideComponent); + for (const auto& obj : *otherSpawnedEntities) { + if (spawnedEntity.ID == obj.EntityID) { + continue; + } + EntityWrapper otherEntity = EntityWrapper(spawnPoint.World, obj.EntityID); + if (!otherEntity.HasComponent("Collidable")) { + continue; + } + auto otherBox = Collision::EntityAbsoluteAABB(otherEntity); + if (!otherBox) { + continue; + } + if (Collision::AABBVsAABB(spawnedBox, *otherBox)) { + if (!spawnedBox.Entity.HasComponent("Model")) { + return true; + } + RawModel* model = nullptr; + try { + model = ResourceManager::Load(otherEntity["Model"]["Resource"]); + } catch (const std::exception&) { + } + + if (model != nullptr && Collision::AABBvsTriangles( + spawnedBox, + model->Vertices(), + model->m_Indices, + Transform::ModelMatrix(otherEntity))) { + return true; + } + } + } + return false; +} + bool SpawnerSystem::OnSpawnerSpawn(Events::SpawnerSpawn& e) { EntityWrapper spawnedEntity = Spawn(e.Spawner, e.Parent); From fdc8f753cb9b843cae8ba6f32bcee04297fb3fc2 Mon Sep 17 00:00:00 2001 From: stiffly Date: Wed, 17 Feb 2016 15:51:26 +0100 Subject: [PATCH 293/355] Implemented primitive server "heartbeat" logic, which sends server info from server to client without being connected. --- include/Engine/Network/Client.h | 3 +++ include/Engine/Network/MessageType.h | 1 + include/Engine/Network/Server.h | 5 +++++ include/Engine/Network/UDPServer.h | 1 + src/Engine/Network/Client.cpp | 26 +++++++++++++++++++++++++- src/Engine/Network/Server.cpp | 20 ++++++++++++++++++-- src/Engine/Network/TCPServer.cpp | 2 +- src/Engine/Network/UDPServer.cpp | 7 +++++++ 8 files changed, 61 insertions(+), 4 deletions(-) diff --git a/include/Engine/Network/Client.h b/include/Engine/Network/Client.h index 978c9b65..70cc10d5 100644 --- a/include/Engine/Network/Client.h +++ b/include/Engine/Network/Client.h @@ -14,6 +14,7 @@ #include "Network/MessageType.h" #include "Network/PlayerDefinition.h" #include "Network/UDPClient.h" +#include "Network/UDPServer.h" //LOL #include "Network/TCPClient.h" #include "Network/SnapshotDefinitions.h" #include "Core/World.h" @@ -82,6 +83,7 @@ public: void parseTCPConnect(Packet& packet); void parsePlayerConnected(Packet& packet); void parsePing(); + void parseHeartbeat(Packet& packet); void parseKick(); void parsePlayersSpawned(Packet& packet); void parseEntityDeletion(Packet& packet); @@ -112,6 +114,7 @@ public: void parsePlayerDamage(Packet& packet); private: UDPClient m_Unreliable; + UDPServer m_Heartbeat; TCPClient m_Reliable; }; diff --git a/include/Engine/Network/MessageType.h b/include/Engine/Network/MessageType.h index a72f054e..2b3b02c0 100644 --- a/include/Engine/Network/MessageType.h +++ b/include/Engine/Network/MessageType.h @@ -19,6 +19,7 @@ enum class MessageType EntityDeleted, ComponentDeleted, PlayerTransform, + Heartbeat, Invalid }; diff --git a/include/Engine/Network/Server.h b/include/Engine/Network/Server.h index b37bffab..0a2cb029 100644 --- a/include/Engine/Network/Server.h +++ b/include/Engine/Network/Server.h @@ -8,6 +8,7 @@ #include "Network/TCPServer.h" #include "Network/UDPServer.h" +#include "Network/UDPClient.h" //LOL #include "Network/MessageType.h" #include "Network/PlayerDefinition.h" #include "Core/World.h" @@ -32,6 +33,7 @@ private: // Network channels TCPServer m_Reliable; UDPServer m_Unreliable; + UDPClient m_Heartbeat; // dont forget to set these in the childrens receive logic boost::asio::ip::address m_Address; int m_Port = 27666; @@ -44,11 +46,13 @@ private: // time for previouse message std::clock_t previousePingMessage = std::clock(); std::clock_t previousSnapshotMessage = std::clock(); + std::clock_t previousHeartbeat = std::clock(); std::clock_t timOutTimer = std::clock(); // How often we send messages (milliseconds) float pingIntervalMs; float snapshotInterval; + float heartbeatInterval = 5000; int checkTimeOutInterval = 100; int m_NextPlayerID = 0; std::vector m_InputCommandsToBroadcast; @@ -67,6 +71,7 @@ private: void addChildrenToPacket(Packet& packet, EntityID entityID); void addInputCommandsToPacket(Packet& packet); void sendPing(); + void sendHeartBeat(); void checkForTimeOuts(); void disconnect(PlayerID playerID); void parseMessageType(Packet& packet); diff --git a/include/Engine/Network/UDPServer.h b/include/Engine/Network/UDPServer.h index 246fb333..6ba7cd96 100644 --- a/include/Engine/Network/UDPServer.h +++ b/include/Engine/Network/UDPServer.h @@ -8,6 +8,7 @@ class UDPServer : public NetworkServer { public: UDPServer(); + UDPServer(int port); ~UDPServer(); void AcceptNewConnections(int& nextPlayerID, std::map& connectedPlayers); void Receive(Packet & packet, PlayerDefinition & playerDefinition); diff --git a/src/Engine/Network/Client.cpp b/src/Engine/Network/Client.cpp index b595536d..ddd884b0 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -3,6 +3,7 @@ using namespace boost::asio::ip; Client::Client(World* world, EventBroker* eventBroker) : Network(world, eventBroker) + , m_Heartbeat(13) { // Asumes root node is EntityID_Invalid insertIntoServerClientMaps(EntityID_Invalid, EntityID_Invalid); @@ -65,7 +66,15 @@ void Client::Update() } } - + while (m_Heartbeat.IsSocketAvailable()) { + Packet packet(MessageType::Invalid); + PlayerDefinition localArea; + localArea.Endpoint = boost::asio::ip::udp::endpoint(boost::asio::ip::address().from_string("127.0.0.1"), 13); + m_Heartbeat.Receive(packet, localArea); + if(packet.GetMessageType() == MessageType::Heartbeat) { + parseHeartbeat(packet); + } + } if (m_IsConnected) { // Don't send 1 input in 1 packet, bunch em up. if (m_SendInputIntervalMs < (1000 * (std::clock() - m_TimeSinceSentInputs) / (double)CLOCKS_PER_SEC)) { @@ -119,6 +128,9 @@ void Client::parseMessageType(Packet& packet) case MessageType::ComponentDeleted: parseComponentDeletion(packet); break; + case MessageType::Heartbeat: + parseHeartbeat(packet); + break; case MessageType::OnPlayerDamage: parsePlayerDamage(packet); break; @@ -173,6 +185,18 @@ void Client::parsePing() m_Reliable.Send(packet); } + +void Client::parseHeartbeat(Packet& packet) +{ + // Pop size, message type, and ID + packet.ReadPrimitive(); + packet.ReadPrimitive(); + packet.ReadPrimitive(); + std::string serverName = packet.ReadString(); + int playersConnected = packet.ReadPrimitive(); + LOG_INFO("Serverlist\nName\tPlayers\n%s\t%i\n", serverName.c_str(), playersConnected); +} + void Client::parseKick() { LOG_WARNING("You have been kicked from the server."); diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index 3f59eb0c..a32852b0 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -1,6 +1,6 @@ #include "Network/Server.h" -Server::Server(World* world, EventBroker* eventBroker, int port) +Server::Server(World* world, EventBroker* eventBroker, int port) : Network(world, eventBroker) { ConfigFile* config = ResourceManager::Load("Config.ini"); @@ -13,12 +13,13 @@ Server::Server(World* world, EventBroker* eventBroker, int port) EVENT_SUBSCRIBE_MEMBER(m_EComponentDeleted, &Server::OnComponentDeleted); EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &Server::OnPlayerDamage); - // Bind + // BindWW if (port == 0) { port = config->Get("Networking.Port", 27666); } m_Port = port; LOG_INFO("Server initialized and bound to port %i", port); + m_Heartbeat.Connect("Server", "127.0.0.1", 13); } Server::~Server() @@ -58,6 +59,7 @@ void Server::Update() parseMessageType(packet); } } + // Check if players have disconnected for (int i = 0; i < m_PlayersToDisconnect.size(); i++) { disconnect(m_PlayersToDisconnect.at(i)); @@ -75,6 +77,11 @@ void Server::Update() sendPing(); previousePingMessage = currentTime; } + // Server heartbeat (display server list on clients) + if (heartbeatInterval < (1000 * (currentTime - previousHeartbeat) / (double)CLOCKS_PER_SEC)) { + sendHeartBeat(); + previousHeartbeat = currentTime; + } // Time out logic if (checkTimeOutInterval < (1000 * (currentTime - timOutTimer) / (double)CLOCKS_PER_SEC)) { checkForTimeOuts(); @@ -230,6 +237,15 @@ void Server::sendPing() reliableBroadcast(packet); } + +void Server::sendHeartBeat() +{ + Packet packet(MessageType::Heartbeat); + packet.WriteString("This is a servername"); // server name + packet.WritePrimitive(m_ConnectedPlayers.size()); + m_Heartbeat.Send(packet); +} + void Server::checkForTimeOuts() { double startPing = 1000 * m_StartPingTime diff --git a/src/Engine/Network/TCPServer.cpp b/src/Engine/Network/TCPServer.cpp index a449e684..66f14053 100644 --- a/src/Engine/Network/TCPServer.cpp +++ b/src/Engine/Network/TCPServer.cpp @@ -1,7 +1,7 @@ #include "Network/TCPServer.h" using namespace boost::asio::ip; -TCPServer::TCPServer() +TCPServer::TCPServer() { acceptor = std::unique_ptr(new tcp::acceptor(m_IOService, tcp::endpoint(tcp::v4(), 27666))); } diff --git a/src/Engine/Network/UDPServer.cpp b/src/Engine/Network/UDPServer.cpp index 4b0a08ba..b4046003 100644 --- a/src/Engine/Network/UDPServer.cpp +++ b/src/Engine/Network/UDPServer.cpp @@ -5,6 +5,11 @@ UDPServer::UDPServer() m_Socket = std::unique_ptr(new boost::asio::ip::udp::socket(m_IOService, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), 27666))); } +UDPServer::UDPServer(int port) +{ + m_Socket = std::unique_ptr(new boost::asio::ip::udp::socket(m_IOService, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), port))); +} + UDPServer::~UDPServer() { } @@ -31,6 +36,8 @@ void UDPServer::Send(Packet & packet) 0); } + + void UDPServer::Receive(Packet & packet, PlayerDefinition & playerDefinition) { int bytesRead = readBuffer(m_ReadBuffer); From 72db672dbf55bf207df7aef8a7ccf3a41d2f50dd Mon Sep 17 00:00:00 2001 From: William Moberg Date: Wed, 17 Feb 2016 16:06:35 +0100 Subject: [PATCH 294/355] Ray will not hit objects in octree if they are transparent or invisible. --- src/Engine/Collision/Collision.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index 87d8bf26..99566404 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -693,8 +693,9 @@ boost::optional EntityFirstHitByRay(const Ray& ray, std::vector Date: Wed, 17 Feb 2016 16:50:24 +0100 Subject: [PATCH 295/355] Working billbording --- resources/Schema/Components/Indicator.xml | 4 + resources/Schema/Components/Indicator.xsd | 14 +- resources/Schema/Entities/JohansTestMap.xml | 90 +-- resources/Schema/Entities/Player.xml | 30 +- resources/Schema/Entities/PlayerRed.xml | 29 +- resources/Schema/Entities/TestPlayerIndicator | 590 ------------------ .../Schema/Entities/TestPlayerIndicator.xml | 590 ------------------ src/Engine/Rendering/RenderSystem.cpp | 53 +- 8 files changed, 121 insertions(+), 1279 deletions(-) delete mode 100644 resources/Schema/Entities/TestPlayerIndicator delete mode 100644 resources/Schema/Entities/TestPlayerIndicator.xml diff --git a/resources/Schema/Components/Indicator.xml b/resources/Schema/Components/Indicator.xml index cd4e3f46..3aab2d1b 100644 --- a/resources/Schema/Components/Indicator.xml +++ b/resources/Schema/Components/Indicator.xml @@ -1,3 +1,7 @@ + 10 + 10 + 1 + 1 \ No newline at end of file diff --git a/resources/Schema/Components/Indicator.xsd b/resources/Schema/Components/Indicator.xsd index 54a6bfe5..69e47821 100644 --- a/resources/Schema/Components/Indicator.xsd +++ b/resources/Schema/Components/Indicator.xsd @@ -5,7 +5,19 @@ - Billbord and makes a Model or Sprite too always appare on players screen + Billbord a Sprite around global Y axis + + + + After this distance between the camera and the sprite, the sprite will not get any smaller on the screen + + + Smaller distance between the camera and the sprite, the sprite will not get any bigger on the screen + + + + + \ No newline at end of file diff --git a/resources/Schema/Entities/JohansTestMap.xml b/resources/Schema/Entities/JohansTestMap.xml index 06e97bdc..c60ea350 100644 --- a/resources/Schema/Entities/JohansTestMap.xml +++ b/resources/Schema/Entities/JohansTestMap.xml @@ -4783,41 +4783,7 @@ - - - - - - - - - - - - - Textures/Test/aM4ME4GR.png - false - - - - - - - - - - - - Textures/Test/SmallDiff.png - false - - - - - - - - + @@ -4952,41 +4918,7 @@ - - - - - - - - - - - - - Textures/Test/aM4ME4GR.png - false - - - - - - - - - - Textures/Test/SmallDiff.png - false - - - - - - - - - - + @@ -5149,7 +5081,7 @@ - Schema/Entities/Player.xml + Schema/Entities/TestPlayerIndicator.xml @@ -5233,7 +5165,7 @@ - + @@ -5252,7 +5184,7 @@ - + @@ -5271,7 +5203,7 @@ - + @@ -5290,7 +5222,7 @@ - + @@ -5309,7 +5241,7 @@ - + @@ -5328,7 +5260,7 @@ - + @@ -5347,7 +5279,7 @@ - + @@ -5366,7 +5298,7 @@ - + diff --git a/resources/Schema/Entities/Player.xml b/resources/Schema/Entities/Player.xml index be6009ba..64ebbf54 100644 --- a/resources/Schema/Entities/Player.xml +++ b/resources/Schema/Entities/Player.xml @@ -349,7 +349,7 @@ Idle - 1.6050530664521858 + 0.30516549779527224 1 @@ -370,8 +370,8 @@ true - - + + @@ -477,7 +477,7 @@ Idle - 1.620305457513453 + 1.9204144556290004 1 @@ -501,8 +501,8 @@ Models/Weapons/Blue/AssaultWeaponBlue.mesh - - + + @@ -572,6 +572,24 @@ + + + + 30 + + + Textures/Icons/Arrow.png + false + + + + + + + + + + diff --git a/resources/Schema/Entities/PlayerRed.xml b/resources/Schema/Entities/PlayerRed.xml index d9839e9f..a6c6d077 100644 --- a/resources/Schema/Entities/PlayerRed.xml +++ b/resources/Schema/Entities/PlayerRed.xml @@ -349,7 +349,7 @@ Idle - 1.6050530664521858 + 0.73262309029003347 1 @@ -370,8 +370,8 @@ true - - + + @@ -477,7 +477,7 @@ Idle - 1.620305457513453 + 0.031207590802594609 1 @@ -501,8 +501,8 @@ Models/Weapons/Red/AssaultWeaponRed.mesh - - + + @@ -572,6 +572,23 @@ + + + + 30 + + + Textures/Icons/Arrow.png + + + + + + + + + + diff --git a/resources/Schema/Entities/TestPlayerIndicator b/resources/Schema/Entities/TestPlayerIndicator deleted file mode 100644 index 504fa0db..00000000 --- a/resources/Schema/Entities/TestPlayerIndicator +++ /dev/null @@ -1,590 +0,0 @@ - - - - - - - - - - 600 - - - - - - - - - 5 - - - - - - - - - - - - - - - - - - - - - - - - Models/Widgets/Camera.mesh - false - - - - - - - - - - - - - - - - - - - Textures/Weapons/Crosshair/SmallThickHoleDot.png - false - - - - - - - - - - - - Schema/Entities/HitMarker.xml - - - - - - - - - - - - - - 1 - - - - - 100/100 - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - 1 - - - - Textures/HealthHUD3.png - - - - - - - - - - - - - - - - - - - - - - - - - Textures/Core/UnitHexagon.png - - - - - - - - - - - 2 - - - - - - Textures/Core/UnitHexagon_Rotated.png - - - - - - - - - - - - - - - Textures/Core/UnitHexagon.png - - - - - - - - - - - 3 - - - - - - Textures/Core/UnitHexagon_Rotated.png - - - - - - - - - - - - - - - Textures/Core/UnitHexagon.png - - - - - - - - - - - 4 - - - - - - Textures/Core/UnitHexagon_Rotated.png - - - - - - - - - - - - - - - Textures/Core/UnitHexagon.png - - - - - - - - - - - 1 - - - 0.10332605343919568 - - - - Textures/Core/UnitHexagon_Rotated.png - - - - - - - - - - - - - - - Textures/Core/UnitHexagon.png - - - - - - - - - - - - - - - Textures/Core/UnitHexagon_Rotated.png - - - - - - - - - - - - - - - - - - - - - - - - - - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - - - - - Idle - 1.0214894690177836 - 1 - - - Models/Characters/Assault/FirstPerson.mesh - - true - - - - - - - - R_Arm_Weapon_Joint - - - Models/Weapons/Blue/AssaultWeaponBlue.mesh - true - - - - - - - - - - - Schema/Entities/RayBlue.xml - - - - - - - - - - - Schema/Entities/ReloadEffectView.xml - - - - - - - - - - - - - - - - - - Textures/Core/UnitHexagon.png - - - - - - - - - - - - - - - - - - 32 - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - 360 - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - - - - - - - - - - - Models/Widgets/Camera.mesh - false - - - - - - - - - - - - Idle - 0.33673680560517383 - 1 - - - AimRifle - - - - - Models/Characters/Assault/AssaultAnimations.mesh - - - - - - - - - R_Arm_Weapon_Joint - - - Models/Weapons/Blue/AssaultWeaponBlue.mesh - - - - - - - - - - - Schema/Entities/RayBlue.xml - - - - - - - - - - - Schema/Entities/ReloadEffectWorld.xml - - - - - - - - - - - - - Models/Core/UnitCube.mesh - - false - - - - - - - - - - - - Models/Core/UnitCube.mesh - - false - - - - - - - - - - - Insert name here - Fonts/DroidSans.ttf,100 - - - - - - - - - - - - - - Textures/Test/aM4ME4GR.png - - - - - - - - - - diff --git a/resources/Schema/Entities/TestPlayerIndicator.xml b/resources/Schema/Entities/TestPlayerIndicator.xml deleted file mode 100644 index 56390bcb..00000000 --- a/resources/Schema/Entities/TestPlayerIndicator.xml +++ /dev/null @@ -1,590 +0,0 @@ - - - - - - - - - - 600 - - - - - - - - - 5 - - - - - - - - - - - - - - - - - - - - - - - - Models/Widgets/Camera.mesh - false - - - - - - - - - - - - - - - - - - - Textures/Weapons/Crosshair/SmallThickHoleDot.png - false - - - - - - - - - - - - Schema/Entities/HitMarker.xml - - - - - - - - - - - - - - 1 - - - - - 100/100 - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - 1 - - - - Textures/HealthHUD3.png - - - - - - - - - - - - - - - - - - - - - - - - - Textures/Core/UnitHexagon.png - - - - - - - - - - - 2 - - - - - - Textures/Core/UnitHexagon_Rotated.png - - - - - - - - - - - - - - - Textures/Core/UnitHexagon.png - - - - - - - - - - - 3 - - - - - - Textures/Core/UnitHexagon_Rotated.png - - - - - - - - - - - - - - - Textures/Core/UnitHexagon.png - - - - - - - - - - - 4 - - - - - - Textures/Core/UnitHexagon_Rotated.png - - - - - - - - - - - - - - - Textures/Core/UnitHexagon.png - - - - - - - - - - - 1 - - - 0.10332605343919568 - - - - Textures/Core/UnitHexagon_Rotated.png - - - - - - - - - - - - - - - Textures/Core/UnitHexagon.png - - - - - - - - - - - - - - - Textures/Core/UnitHexagon_Rotated.png - - - - - - - - - - - - - - - - - - - - - - - - - - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - - - - - Idle - 0.71065405191594166 - 1 - - - Models/Characters/Assault/FirstPerson.mesh - - true - - - - - - - - R_Arm_Weapon_Joint - - - Models/Weapons/Blue/AssaultWeaponBlue.mesh - true - - - - - - - - - - - Schema/Entities/RayBlue.xml - - - - - - - - - - - Schema/Entities/ReloadEffectView.xml - - - - - - - - - - - - - - - - - - Textures/Core/UnitHexagon.png - - - - - - - - - - - - - - - - - - 32 - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - 360 - Fonts/DroidSans.ttf,64 - - - - - - - - - - - - - - - - - - - - - - - - Models/Widgets/Camera.mesh - false - - - - - - - - - - - - Idle - 1.0759003871452997 - 1 - - - AimRifle - - - - - Models/Characters/Assault/AssaultAnimations.mesh - - - - - - - - - R_Arm_Weapon_Joint - - - Models/Weapons/Blue/AssaultWeaponBlue.mesh - - - - - - - - - - - Schema/Entities/RayBlue.xml - - - - - - - - - - - Schema/Entities/ReloadEffectWorld.xml - - - - - - - - - - - - - Models/Core/UnitCube.mesh - - false - - - - - - - - - - - - Models/Core/UnitCube.mesh - - false - - - - - - - - - - - Insert name here - Fonts/DroidSans.ttf,100 - - - - - - - - - - - - - - Textures/Test/aM4ME4GR.png - - - - - - - - - - diff --git a/src/Engine/Rendering/RenderSystem.cpp b/src/Engine/Rendering/RenderSystem.cpp index cd604b8c..c05b3681 100644 --- a/src/Engine/Rendering/RenderSystem.cpp +++ b/src/Engine/Rendering/RenderSystem.cpp @@ -67,13 +67,53 @@ void RenderSystem::fillSprites(std::list>& jobs, Worl fillColor = (glm::vec4)fillComponent["Color"]; } - glm::mat4 modelMatrix = Transform::ModelMatrix(entity.ID, world); - + glm::mat4 modelMatrix = glm::mat4(1); + bool isIndicator = false; if (world->HasComponent(entity.ID, "Indicator") || entity.FirstParentWithComponent("Indicator").Valid()) { isIndicator = true; - modelMatrix = modelMatrix * m_Camera->BillboardMatrix(); + glm::vec3 pos = Transform::AbsolutePosition(entity); + + + // Code for shcneking if sprite is inside or outside of screen + //glm::vec4 projectedPos = m_Camera->ProjectionMatrix() * m_Camera->ViewMatrix() * glm::vec4(pos, 1.0f); + //projectedPos /= projectedPos.w; + //// Check if inside of outside of screen. + //if (projectedPos.x < -1.0f || projectedPos.x > 1.0f || projectedPos.y < -1.0f || projectedPos.y > 1.0f) { + // // is outside of screen + //} else { + // // is inside of screen + //} + + + glm::vec3 zAxis = glm::vec3(0.0f, 1.0f, 0.0f); + glm::vec3 normal = pos - m_Camera->Position(); + normal.y = 0; + normal = glm::normalize(normal); + glm::vec3 right = glm::cross(normal, zAxis); + glm::vec3 up = glm::cross(right, normal); + + modelMatrix[0][0] = right.x; + modelMatrix[0][1] = right.y; + modelMatrix[0][2] = right.z; + + modelMatrix[1][0] = zAxis.x; + modelMatrix[1][1] = zAxis.y; + modelMatrix[1][2] = zAxis.z; + + modelMatrix[2][0] = normal.x; + modelMatrix[2][1] = normal.y; + modelMatrix[2][2] = normal.z; + + modelMatrix[3][0] = pos.x; + modelMatrix[3][1] = pos.y; + modelMatrix[3][2] = pos.z; + + modelMatrix = modelMatrix * glm::scale(Transform::AbsoluteScale(entity)); + + } else { + modelMatrix = Transform::ModelMatrix(entity.ID, world); } std::shared_ptr spriteJob = std::shared_ptr(new SpriteJob(cSprite, m_Camera, modelMatrix, world, fillColor, fillPercentage, depthSorted, isIndicator)); @@ -101,8 +141,8 @@ bool RenderSystem::isEntityVisible(EntityWrapper& entity) // If a sprite is an Indicator, it's not local on player and object is in the same team, then dispaly it if ( - (entity.HasComponent("Indicator")) - && (entity != m_LocalPlayer || !entity.IsChildOf(m_LocalPlayer)) + entity.HasComponent("Indicator") + && !entity.IsChildOf(m_LocalPlayer) && (entity.HasComponent("Team") || entity.FirstParentWithComponent("Team").Valid()) && entity.HasComponent("Sprite") && m_LocalPlayer.World != nullptr @@ -110,8 +150,7 @@ bool RenderSystem::isEntityVisible(EntityWrapper& entity) EntityWrapper entityTeam; if (!entity.HasComponent("Team")) { entityTeam = entity.FirstParentWithComponent("Team"); - } - else { + } else { entityTeam = entity; } ComponentWrapper& entityTeamComponent = entityTeam["Team"]; From 46987beefbc413d95beba20a87965b2f18ede9e1 Mon Sep 17 00:00:00 2001 From: stiffly Date: Wed, 17 Feb 2016 17:05:10 +0100 Subject: [PATCH 296/355] Updated the serverlist, now prints adress and port of the server. --- include/Engine/Network/Client.h | 2 +- include/Engine/Network/TCPServer.h | 2 ++ src/Engine/Network/Client.cpp | 14 ++++++++------ src/Engine/Network/Server.cpp | 4 +++- src/Engine/Network/TCPServer.cpp | 9 +++++++++ 5 files changed, 23 insertions(+), 8 deletions(-) diff --git a/include/Engine/Network/Client.h b/include/Engine/Network/Client.h index 70cc10d5..01e18da8 100644 --- a/include/Engine/Network/Client.h +++ b/include/Engine/Network/Client.h @@ -83,7 +83,7 @@ public: void parseTCPConnect(Packet& packet); void parsePlayerConnected(Packet& packet); void parsePing(); - void parseHeartbeat(Packet& packet); + void parseHeartbeat(Packet& packet, PlayerDefinition); void parseKick(); void parsePlayersSpawned(Packet& packet); void parseEntityDeletion(Packet& packet); diff --git a/include/Engine/Network/TCPServer.h b/include/Engine/Network/TCPServer.h index 9cc7646a..424599c9 100644 --- a/include/Engine/Network/TCPServer.h +++ b/include/Engine/Network/TCPServer.h @@ -16,6 +16,8 @@ public: void Send(Packet & packet, PlayerDefinition & playerDefinition); void Send(Packet & packet); void Disconnect(); + int Port() { return acceptor->local_endpoint().port(); } + std::string Address(); private: // TCP logic boost::asio::io_service m_IOService; diff --git a/src/Engine/Network/Client.cpp b/src/Engine/Network/Client.cpp index ddd884b0..a9a67bae 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -72,7 +72,7 @@ void Client::Update() localArea.Endpoint = boost::asio::ip::udp::endpoint(boost::asio::ip::address().from_string("127.0.0.1"), 13); m_Heartbeat.Receive(packet, localArea); if(packet.GetMessageType() == MessageType::Heartbeat) { - parseHeartbeat(packet); + parseHeartbeat(packet, localArea); } } if (m_IsConnected) { @@ -128,9 +128,6 @@ void Client::parseMessageType(Packet& packet) case MessageType::ComponentDeleted: parseComponentDeletion(packet); break; - case MessageType::Heartbeat: - parseHeartbeat(packet); - break; case MessageType::OnPlayerDamage: parsePlayerDamage(packet); break; @@ -186,7 +183,7 @@ void Client::parsePing() } -void Client::parseHeartbeat(Packet& packet) +void Client::parseHeartbeat(Packet& packet, PlayerDefinition pd) { // Pop size, message type, and ID packet.ReadPrimitive(); @@ -194,7 +191,12 @@ void Client::parseHeartbeat(Packet& packet) packet.ReadPrimitive(); std::string serverName = packet.ReadString(); int playersConnected = packet.ReadPrimitive(); - LOG_INFO("Serverlist\nName\tPlayers\n%s\t%i\n", serverName.c_str(), playersConnected); + std::string address = packet.ReadString(); + int port = packet.ReadPrimitive(); + //TODO: save these to some kind of list which can be represented to the player + //TODO: This should not happen when a client is connected to a server + + LOG_INFO("Serverlist\nName\tPlayers\tIP\t\tPort\n%s\t%i\t%s\t%i\n", serverName.c_str(), playersConnected, address, port); } void Client::parseKick() diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index a32852b0..8dd398bd 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -241,8 +241,10 @@ void Server::sendPing() void Server::sendHeartBeat() { Packet packet(MessageType::Heartbeat); - packet.WriteString("This is a servername"); // server name + packet.WriteString("Bob"); // server name packet.WritePrimitive(m_ConnectedPlayers.size()); + packet.WriteString(m_Reliable.Address()); + packet.WritePrimitive(m_Reliable.Port()); m_Heartbeat.Send(packet); } diff --git a/src/Engine/Network/TCPServer.cpp b/src/Engine/Network/TCPServer.cpp index 66f14053..a55eee98 100644 --- a/src/Engine/Network/TCPServer.cpp +++ b/src/Engine/Network/TCPServer.cpp @@ -74,7 +74,16 @@ void TCPServer::Send(Packet & packet) void TCPServer::Disconnect() { +} + +std::string TCPServer::Address() +{ + boost::asio::ip::tcp::resolver resolver(m_IOService); + boost::asio::ip::tcp::resolver::query query(boost::asio::ip::tcp::v4(), boost::asio::ip::host_name(), ""); + boost::asio::ip::tcp::resolver::iterator it = resolver.resolve(query); + boost::asio::ip::tcp::endpoint endpoint = *it; + return endpoint.address().to_string().c_str(); } void TCPServer::Receive(Packet & packet, PlayerDefinition & playerDefinition) From 3e7936ef00263f43e7c9def9ff63a685efc463dc Mon Sep 17 00:00:00 2001 From: Tleety Date: Wed, 17 Feb 2016 17:44:33 +0100 Subject: [PATCH 297/355] You can now change resolution by pressing buttons. --- include/Engine/GUI/MainMenuSystem.h | 1 + .../Schema/Entities/QualityAssurance.xml | 84 +++++++++---------- src/Engine/GUI/MainMenuSystem.cpp | 11 +++ src/Engine/Rendering/Renderer.cpp | 2 +- 4 files changed, 55 insertions(+), 43 deletions(-) diff --git a/include/Engine/GUI/MainMenuSystem.h b/include/Engine/GUI/MainMenuSystem.h index 45400d1d..ba69ff0d 100644 --- a/include/Engine/GUI/MainMenuSystem.h +++ b/include/Engine/GUI/MainMenuSystem.h @@ -6,6 +6,7 @@ #include "../Core/ResourceManager.h" #include "../Core/Event.h" + #include "EButtonClicked.h" #include "EButtonPressed.h" #include "EButtonReleased.h" diff --git a/resources/Schema/Entities/QualityAssurance.xml b/resources/Schema/Entities/QualityAssurance.xml index 6bd8a25a..762da931 100644 --- a/resources/Schema/Entities/QualityAssurance.xml +++ b/resources/Schema/Entities/QualityAssurance.xml @@ -40,7 +40,7 @@ - + @@ -77,18 +77,6 @@ - - - - Sound Test - Fonts/DroidSans.ttf,64 - - - - - - - @@ -105,7 +93,7 @@ - + @@ -180,7 +168,7 @@ - + @@ -225,7 +213,7 @@ - + @@ -289,7 +277,7 @@ - + @@ -321,7 +309,7 @@ - + @@ -671,7 +659,7 @@ - + @@ -718,7 +706,7 @@ - + @@ -778,7 +766,7 @@ - + @@ -825,7 +813,7 @@ - + @@ -871,7 +859,7 @@ - + @@ -918,7 +906,7 @@ - + @@ -965,7 +953,7 @@ - + @@ -1379,7 +1367,7 @@ - + @@ -1388,7 +1376,7 @@ true - 2.5333333077342104 + 2.6831806538294813 3.7999999523162842 true @@ -1435,7 +1423,7 @@ - + @@ -1444,7 +1432,7 @@ - 0.70455028055985736 + 1.9833111709021125 Models/Characters/Assault/AssaultTPose.mesh @@ -1487,7 +1475,7 @@ - + @@ -1498,7 +1486,7 @@ true - 0.70455028055985736 + 1.9833111709021125 true @@ -1543,7 +1531,7 @@ - + @@ -1553,7 +1541,7 @@ true - 9.1832418997049956 + 1.05003269646582 10 3 @@ -1601,7 +1589,7 @@ - + @@ -1611,7 +1599,7 @@ true - 1.007708532606415 + 0.75001660742393028 true 5 true @@ -1792,7 +1780,7 @@ true - 2.5333333077342104 + 2.6831806538294813 3.7999999523162842 true @@ -2349,7 +2337,7 @@ - + @@ -2364,7 +2352,7 @@ - Resolution + 1920x1080 Fonts/DroidSans.ttf,64 @@ -2377,7 +2365,7 @@ - + @@ -2392,7 +2380,7 @@ - Option2 + 1280x720 Fonts/DroidSans.ttf,64 @@ -2405,7 +2393,7 @@ - + @@ -2420,7 +2408,7 @@ - Butts + 854x480 Fonts/DroidSans.ttf,64 @@ -2454,6 +2442,18 @@ + + + + Sound Test + Fonts/DroidSans.ttf,64 + + + + + + + diff --git a/src/Engine/GUI/MainMenuSystem.cpp b/src/Engine/GUI/MainMenuSystem.cpp index 36d4a173..68db7b60 100644 --- a/src/Engine/GUI/MainMenuSystem.cpp +++ b/src/Engine/GUI/MainMenuSystem.cpp @@ -25,6 +25,17 @@ bool MainMenuSystem::OnButtonClick(const Events::ButtonClicked& e) //Run host code } else if(e.EntityName == "Quit") { printf("No, you stay"); + } else if (e.EntityName == "Res1080") { + glfwSetWindowSize(m_Renderer->Window(), 1920, 1080); + printf("1080"); + } else if (e.EntityName == "Res720") { + glfwSetWindowSize(m_Renderer->Window(), 1280, 720); + glViewport(0, 0, 1280, 720); + printf("720"); + } else if (e.EntityName == "Res480") { + glfwSetWindowSize(m_Renderer->Window(), 854, 480); + glViewport(0, 0, 854, 480); + printf("480"); } return true; diff --git a/src/Engine/Rendering/Renderer.cpp b/src/Engine/Rendering/Renderer.cpp index be84160c..0ba25128 100644 --- a/src/Engine/Rendering/Renderer.cpp +++ b/src/Engine/Rendering/Renderer.cpp @@ -60,7 +60,7 @@ void Renderer::InitializeWindow() } int windowSize[2]; - glfwGetWindowSize(m_Window, &windowSize[0], &windowSize[1]); + glfwGetFramebufferSize(m_Window, &windowSize[0], &windowSize[1]); m_ViewportSize = Rectangle(windowSize[0], windowSize[1]); } From 5e3af7ac5d6eb1ca0883ff5bf891bdb9b0688aee Mon Sep 17 00:00:00 2001 From: Teejoon Date: Wed, 17 Feb 2016 17:58:01 +0100 Subject: [PATCH 298/355] Player Indicator now working OK. Scaling depending on how far away you are makes the Indicator to hide players head behind it. Shields are making indicators to disappear. --- resources/Schema/Components/Indicator.xml | 5 +-- resources/Schema/Components/Indicator.xsd | 7 ----- resources/Schema/Entities/Player.xml | 16 +++++----- resources/Schema/Entities/PlayerRed.xml | 16 +++++----- src/Engine/Rendering/RenderSystem.cpp | 38 ++++++++++++++++++++--- 5 files changed, 51 insertions(+), 31 deletions(-) diff --git a/resources/Schema/Components/Indicator.xml b/resources/Schema/Components/Indicator.xml index 3aab2d1b..1dfc0077 100644 --- a/resources/Schema/Components/Indicator.xml +++ b/resources/Schema/Components/Indicator.xml @@ -1,7 +1,4 @@ - 10 - 10 - 1 - 1 + 10 \ No newline at end of file diff --git a/resources/Schema/Components/Indicator.xsd b/resources/Schema/Components/Indicator.xsd index 69e47821..5015b13c 100644 --- a/resources/Schema/Components/Indicator.xsd +++ b/resources/Schema/Components/Indicator.xsd @@ -9,14 +9,7 @@ - - After this distance between the camera and the sprite, the sprite will not get any smaller on the screen - - - Smaller distance between the camera and the sprite, the sprite will not get any bigger on the screen - - diff --git a/resources/Schema/Entities/Player.xml b/resources/Schema/Entities/Player.xml index 64ebbf54..dfc8855c 100644 --- a/resources/Schema/Entities/Player.xml +++ b/resources/Schema/Entities/Player.xml @@ -349,7 +349,7 @@ Idle - 0.30516549779527224 + 1.9902125899398158 1 @@ -370,8 +370,8 @@ true - - + + @@ -477,7 +477,7 @@ Idle - 1.9204144556290004 + 1.7887947062665859 1 @@ -501,8 +501,8 @@ Models/Weapons/Blue/AssaultWeaponBlue.mesh - - + + @@ -575,7 +575,7 @@ - 30 + 80 Textures/Icons/Arrow.png @@ -585,7 +585,7 @@ - + diff --git a/resources/Schema/Entities/PlayerRed.xml b/resources/Schema/Entities/PlayerRed.xml index a6c6d077..fc8dea66 100644 --- a/resources/Schema/Entities/PlayerRed.xml +++ b/resources/Schema/Entities/PlayerRed.xml @@ -349,7 +349,7 @@ Idle - 0.73262309029003347 + 1.5972608217572741 1 @@ -370,8 +370,8 @@ true - - + + @@ -477,7 +477,7 @@ Idle - 0.031207590802594609 + 1.0291785284465931 1 @@ -501,8 +501,8 @@ Models/Weapons/Red/AssaultWeaponRed.mesh - - + + @@ -575,7 +575,7 @@ - 30 + 80 Textures/Icons/Arrow.png @@ -584,7 +584,7 @@ - + diff --git a/src/Engine/Rendering/RenderSystem.cpp b/src/Engine/Rendering/RenderSystem.cpp index c05b3681..a0534fed 100644 --- a/src/Engine/Rendering/RenderSystem.cpp +++ b/src/Engine/Rendering/RenderSystem.cpp @@ -67,16 +67,26 @@ void RenderSystem::fillSprites(std::list>& jobs, Worl fillColor = (glm::vec4)fillComponent["Color"]; } - glm::mat4 modelMatrix = glm::mat4(1); + glm::mat4 modelMatrix; bool isIndicator = false; if (world->HasComponent(entity.ID, "Indicator") || entity.FirstParentWithComponent("Indicator").Valid()) { + EntityWrapper EntityWithIndicator; + if (world->HasComponent(entity.ID, "Indicator")) { + EntityWithIndicator = entity; + } + else { + EntityWithIndicator = entity.FirstParentWithComponent("Indicator"); + } + auto indicator = EntityWithIndicator["Indicator"]; + + float minScale = (float)(double)indicator["MinScale"]; isIndicator = true; glm::vec3 pos = Transform::AbsolutePosition(entity); - // Code for shcneking if sprite is inside or outside of screen + // Code for check if sprite is inside or outside of screen //glm::vec4 projectedPos = m_Camera->ProjectionMatrix() * m_Camera->ViewMatrix() * glm::vec4(pos, 1.0f); //projectedPos /= projectedPos.w; //// Check if inside of outside of screen. @@ -89,6 +99,13 @@ void RenderSystem::fillSprites(std::list>& jobs, Worl glm::vec3 zAxis = glm::vec3(0.0f, 1.0f, 0.0f); glm::vec3 normal = pos - m_Camera->Position(); + + //float distance = glm::length(normal); + //if (distance < minDistance) { + // pos = pos - glm::normalize(normal) * (distance - minDistance); + //} else if (distance > maxDistance) { + // pos = pos - glm::normalize(normal) * (distance - maxDistance); + //} normal.y = 0; normal = glm::normalize(normal); glm::vec3 right = glm::cross(normal, zAxis); @@ -97,21 +114,34 @@ void RenderSystem::fillSprites(std::list>& jobs, Worl modelMatrix[0][0] = right.x; modelMatrix[0][1] = right.y; modelMatrix[0][2] = right.z; + modelMatrix[0][3] = 0.0f; modelMatrix[1][0] = zAxis.x; modelMatrix[1][1] = zAxis.y; modelMatrix[1][2] = zAxis.z; + modelMatrix[1][3] = 0.0f; modelMatrix[2][0] = normal.x; modelMatrix[2][1] = normal.y; modelMatrix[2][2] = normal.z; + modelMatrix[2][3] = 0.0f; modelMatrix[3][0] = pos.x; modelMatrix[3][1] = pos.y; modelMatrix[3][2] = pos.z; + modelMatrix[3][3] = 1.0f; - modelMatrix = modelMatrix * glm::scale(Transform::AbsoluteScale(entity)); - + glm::mat4 tranformationMatrix = modelMatrix * glm::scale(Transform::AbsoluteScale(entity)); + glm::vec4 tmp = tranformationMatrix * glm::vec4(glm::vec3(0.5, 0.5, 0), 1.0f); + glm::vec2 projectedTopRight = m_Camera->WorldToScreen(glm::vec3(tmp), m_Renderer->GetViewportSize()); + tmp = tranformationMatrix * glm::vec4(glm::vec3(-0.5, -0.5, 0), 1.0f); + glm::vec2 projectedBottomLeft = m_Camera->WorldToScreen(glm::vec3(tmp), m_Renderer->GetViewportSize()); + + float diag = glm::length(projectedBottomLeft - projectedTopRight); + if (diag < minScale) { + tranformationMatrix = tranformationMatrix * glm::scale(glm::vec3(minScale / diag, minScale / diag, minScale / diag)); + } + modelMatrix = tranformationMatrix; } else { modelMatrix = Transform::ModelMatrix(entity.ID, world); } From c4d3c515e4f77d1120b05c833f384cea7724e699 Mon Sep 17 00:00:00 2001 From: Teejoon Date: Wed, 17 Feb 2016 18:04:49 +0100 Subject: [PATCH 299/355] Marge with Master --- resources/Schema/Entities/JohansTestMap.xml | 5311 ------------------- resources/Schema/Entities/Player.xml | 2 +- resources/Schema/Entities/PlayerRed.xml | 2 +- 3 files changed, 2 insertions(+), 5313 deletions(-) delete mode 100644 resources/Schema/Entities/JohansTestMap.xml diff --git a/resources/Schema/Entities/JohansTestMap.xml b/resources/Schema/Entities/JohansTestMap.xml deleted file mode 100644 index c60ea350..00000000 --- a/resources/Schema/Entities/JohansTestMap.xml +++ /dev/null @@ -1,5311 +0,0 @@ - - - - - - - - - - - - - - - - - - Models/Props/Ground.mesh - - - - - - - - - Models/Props/Highground1.mesh - - - - - - - - - - Models/Props/Highground2.mesh - - - - - - - - - - Models/Props/Highground1.mesh - - - - - - - - - - - - Models/Props/Highground2.mesh - - - - - - - - - - - - Models/Props/Highground3.mesh - - - - - - - - - - Models/Props/Highground4.mesh - - - - - - - - - - Models/Props/Highground5.mesh - - - - - - - - - - - Models/Props/Highground6.mesh - - - - - - - - - - Models/Props/Walls/SciFiWallTop.mesh - - - - - - - - - Models/Props/Walls/SciFiWallBig.mesh - - - - - - - - - - Models/Props/Walls/SciFiWallMedium.mesh - - - - - - - - - - Models/Props/Walls/SciFiWallSmall1.mesh - - - - - - - - - - Models/Props/Walls/SciFiWallSmall2.mesh - - - - - - - - - - Models/Props/Walls/SciFiWallBig.mesh - - - - - - - - - - - - Models/Props/Walls/SciFiWallMedium.mesh - - - - - - - - - - - - Models/Props/Walls/SciFiWallSmall3.mesh - - - - - - - - - - Models/Props/Walls/SciFiWallSmall4.mesh - - - - - - - - - - - - - - - - - - - - Models/Props/Pillars/SciFiPillar1Blue.mesh - - - - - - - - - - - - - Models/Props/Pillars/SciFiPillar1Red.mesh - - - - - - - - - - - - - Models/Props/Pillars/StonePillar.mesh - - - - - - - - - - - - Models/Props/Pillars/StonePillar.mesh - - - - - - - - - - - - - Models/Props/Pillars/SciFiPillar2Red.mesh - - - - - - - - - - - - - Models/Props/Pillars/SciFiPillar3Blue.mesh - - - - - - - - - - - - - - Models/Props/Pillars/SciFiPillar1Blue.mesh - - - - - - - - - - - - - - Models/Props/Pillars/SciFiPillar1Red.mesh - - - - - - - - - - - - - - Models/Props/Pillars/SciFiPillar3Red.mesh - - - - - - - - - - - - - - Models/Props/Pillars/StonePillar.mesh - - - - - - - - - - - - Models/Props/Pillars/StonePillar.mesh - - - - - - - - - - - - - Models/Props/Pillars/StonePillar.mesh - - - - - - - - - - - - - Models/Props/Pillars/SciFiPillar2Blue.mesh - - - - - - - - - - - - - Models/Props/Pillars/SciFiPillar2Red.mesh - - - - - - - - - - - - - Models/Props/Pillars/StonePillar.mesh - - - - - - - - - - - Models/Props/Pillars/StonePillar.mesh - - - - - - - - - - - - - - - Models/Props/Pillars/SciFiPillar2Blue.mesh - - - - - - - - - - - - - - Models/Props/Pillars/SciFiPillar2Blue.mesh - - - - - - - - - - - - - - Models/Props/Pillars/SciFiPillar2Blue.mesh - - - - - - - - - - - - - - Models/Props/Pillars/SciFiPillar2Blue.mesh - - - - - - - - - - - - - Models/Props/Pillars/StonePillar.mesh - - - - - - - - - - - - - Models/Props/Pillars/SciFiPillar2Red.mesh - - - - - - - - - - - - - - Models/Props/Pillars/SciFiPillar2Red.mesh - - - - - - - - - - - - - Models/Props/Pillars/SciFiPillar2Red.mesh - - - - - - - - - - - - - - Models/Props/Pillars/StonePillar.mesh - - - - - - - - - - - - - Models/Props/Pillars/SciFiPillar2Red.mesh - - - - - - - - - - - - - - - - - - - - Models/Props/Walls/BigWallBlue.mesh - - - - - - - - - - - Models/Props/Walls/BigWallBlue.mesh - - - - - - - - - - - - - - - Models/Props/Walls/BigWallBlue.mesh - - - - - - - - - - - Models/Props/Walls/BigWallBlue.mesh - - - - - - - - - - - - - - Models/Props/Walls/BigWallRed.mesh - - - - - - - - - - - - Models/Props/Walls/BigWallRed.mesh - - - - - - - - - - - - - - - Models/Props/Walls/BigWallRed.mesh - - - - - - - - - - - - Models/Props/Walls/BigWallRed.mesh - - - - - - - - - - - - - - - Models/Props/Walls/BigWallRed.mesh - - - - - - - - - - - - Models/Props/Walls/BigWallRed.mesh - - - - - - - - - - - - - - Models/Props/Walls/BigWallRed.mesh - - - - - - - - - - - - - - - - Models/Props/Walls/BigWallBlue.mesh - - - - - - - - - - - - Models/Props/Walls/BigWallBlue.mesh - - - - - - - - - - - - - Models/Props/Walls/BigWallBlue.mesh - - - - - - - - - - - - - - - Models/Props/Walls/MediumWall3.mesh - - - - - - - - - - - - Models/Props/Walls/MediumWall3.mesh - - - - - - - - - - - - - - Models/Props/Walls/SmallWall3.mesh - - - - - - - - - - - - - Models/Props/Walls/SmallWall3.mesh - - - - - - - - - - - - Models/Props/Walls/SmallWall3.mesh - - - - - - - - - - - - - - Models/Props/Walls/SmallWall2.mesh - - - - - - - - - - - - - Models/Props/Walls/SmallWall4.mesh - - - - - - - - - - - - Models/Props/Walls/SmallWall3.mesh - - - - - - - - - - - - Models/Props/Walls/SmallWall2.mesh - - - - - - - - - - - - - Models/Props/Walls/SmallWall2.mesh - - - - - - - - - - - - - Models/Props/Walls/SmallWall2.mesh - - - - - - - - - - - - - Models/Props/Walls/MediumWall2.mesh - - - - - - - - - - - - Models/Props/Walls/MediumWall2.mesh - - - - - - - - - - - - - - Models/Props/Walls/MediumWall1.mesh - - - - - - - - - - - - Models/Props/Walls/MediumWall1.mesh - - - - - - - - - - - - - - Models/Props/Walls/MediumWall1.mesh - - - - - - - - - - - - Models/Props/Walls/MediumWall1.mesh - - - - - - - - - - - - Models/Props/Walls/MediumWall1.mesh - - - - - - - - - - - - - - Models/Props/Walls/BigWallRed.mesh - - - - - - - - - - - Models/Props/Walls/BigWallRed.mesh - - - - - - - - - - - - Models/Props/Walls/BigWallRed.mesh - - - - - - - - - - - Models/Props/Walls/BigWallRed.mesh - - - - - - - - - - - - - - - - Models/Props/Walls/BigWallRed.mesh - - - - - - - - - - - - - Models/Props/Walls/BigWallRed.mesh - - - - - - - - - - - - - - Models/Props/Walls/BigWallBlue.mesh - - - - - - - - - - - Models/Props/Walls/BigWallBlue.mesh - - - - - - - - - - - - Models/Props/Walls/BigWallBlue.mesh - - - - - - - - - - - - Models/Props/Walls/BigWallBlue.mesh - - - - - - - - - - - - - - Models/Props/Walls/BigWallBlue.mesh - - - - - - - - - - - - Models/Props/Walls/SmallWall3.mesh - - - - - - - - - - - - Models/Props/Walls/SmallWall3.mesh - - - - - - - - - - - - - Models/Props/Walls/SmallWall4.mesh - - - - - - - - - - - - - - Models/Props/Walls/SmallWall4.mesh - - - - - - - - - - - - Models/Props/Walls/SmallWall2.mesh - - - - - - - - - - - - - - Models/Props/Walls/SmallWall2.mesh - - - - - - - - - - - - - Models/Props/Walls/BigWallBlue.mesh - - - - - - - - - - - - Models/Props/Walls/BigWallBlue.mesh - - - - - - - - - - - Models/Props/Walls/BigWallBlue.mesh - - - - - - - - - - - - - - - Models/Props/Walls/SmallWall2.mesh - - - - - - - - - - - - - - Models/Props/Walls/SmallWall2.mesh - - - - - - - - - - - Models/Props/Walls/BigWallBlue.mesh - - - - - - - - - - - Models/Props/Walls/BigWallBlue.mesh - - - - - - - - - - - - - - - - Models/Props/Walls/BigWallBlue.mesh - - - - - - - - - - - Models/Props/Walls/BigWallBlue.mesh - - - - - - - - - - - - Models/Props/Walls/BigWallBlue.mesh - - - - - - - - - - - - Models/Props/Walls/BigWallBlue.mesh - - - - - - - - - - - - - - Models/Props/Walls/BigWallBlue.mesh - - - - - - - - - - - - Models/Props/Walls/BigWallBlue.mesh - - - - - - - - - - - - - - - Models/Props/Walls/MediumWall3.mesh - - - - - - - - - - - - - Models/Props/Walls/BigWallRed.mesh - - - - - - - - - - - Models/Props/Walls/BigWallRed.mesh - - - - - - - - - - - - Models/Props/Walls/BigWallRed.mesh - - - - - - - - - - - - - - Models/Props/Walls/BigWallRed.mesh - - - - - - - - - - - - Models/Props/Walls/BigWallRed.mesh - - - - - - - - - - - - - - Models/Props/Walls/BigWallRed.mesh - - - - - - - - - - - - Models/Props/Walls/BigWallRed.mesh - - - - - - - - - - - - Models/Props/Walls/SmallWall2.mesh - - - - - - - - - - - - Models/Props/Walls/BigWallRed.mesh - - - - - - - - - - - - - - Models/Props/Walls/SmallWall3.mesh - - - - - - - - - - - - Models/Props/Walls/SpecialWall1.mesh - - - - - - - - - - - - - - Models/Props/Flora/SpecialRoot.mesh - - - - - - - - - - - - - - Models/Props/Walls/MediumWall1.mesh - - - - - - - - - - - - - Models/Props/Walls/MediumWall1.mesh - - - - - - - - - - - - - Models/Props/Walls/MediumWall1.mesh - - - - - - - - - - - - Models/Props/Walls/MediumWall3.mesh - - - - - - - - - - - - - Models/Props/Walls/MediumWall1.mesh - - - - - - - - - - - - Models/Props/Walls/MediumWall1.mesh - - - - - - - - - - - - - - Models/Props/Walls/SmallWall2.mesh - - - - - - - - - - - - - Models/Props/Walls/SmallWall2.mesh - - - - - - - - - - - - Models/Props/Walls/SmallWall2.mesh - - - - - - - - - - - - Models/Props/Walls/MediumWall3.mesh - - - - - - - - - - - - Models/Props/Walls/MediumWall2.mesh - - - - - - - - - - - Models/Props/Walls/MediumWall2.mesh - - - - - - - - - - - - - Models/Props/Walls/SmallWall3.mesh - - - - - - - - - - - - Models/Props/Walls/SmallWall4.mesh - - - - - - - - - - - - - - - - Models/Props/Walls/MediumWall3.mesh - - - - - - - - - - - - - Models/Props/Walls/MediumWall2.mesh - - - - - - - - - - - - - Models/Props/Walls/SpecialWall1.mesh - - - - - - - - - - - - - - Models/Props/Walls/MediumWall1.mesh - - - - - - - - - - - - - Models/Props/Walls/SpecialWall1.mesh - - - - - - - - - - - - Models/Props/Walls/SpecialWall1.mesh - - - - - - - - - - - - - Models/Props/Walls/SpecialWall1.mesh - - - - - - - - - - - - - Models/Props/Walls/SpecialWall1.mesh - - - - - - - - - - - - - Models/Props/Walls/SpecialWall1.mesh - - - - - - - - - - - - - - Models/Props/Walls/SpecialWall1.mesh - - - - - - - - - - - - - - - - - - - - - Models/Props/Bridges/WoodenBridge.mesh - - - - - - - - - - - - - - Models/Props/Bridges/WoodenBridge.mesh - - - - - - - - - - - - - - Models/Props/Bridges/WoodenBridge.mesh - - - - - - - - - - - - - Models/Props/Bridges/SciFiBridge1Red.mesh - - - - - - - - - - - - - Models/Props/Bridges/SciFiBridgeDefense.mesh - - - - - - - - - - - - Models/Props/Bridges/SciFiBridgeDefense.mesh - - - - - - - - - - - Models/Props/Bridges/SciFiBridgeDefense.mesh - - - - - - - - - - - Models/Props/Bridges/SciFiBridgeDefense.mesh - - - - - - - - - - - - - - - - - - Models/Props/Bridges/SciFiBridgeDefense.mesh - - - - - - - - - - - - Models/Props/Bridges/SciFiBridgeDefense.mesh - - - - - - - - - - - Models/Props/Bridges/SciFiBridgeDefense.mesh - - - - - - - - - - - Models/Props/Bridges/SciFiBridgeDefense.mesh - - - - - - - - - - - - - - - - - - - - Models/Props/Bridges/SciFiBridge1Blue.mesh - - - - - - - - - - - - - Models/Props/Bridges/SciFiBridgeDefense.mesh - - - - - - - - - - - - Models/Props/Bridges/SciFiBridgeDefense.mesh - - - - - - - - - - - Models/Props/Bridges/SciFiBridgeDefense.mesh - - - - - - - - - - - - Models/Props/Bridges/SciFiBridgeDefense.mesh - - - - - - - - - - - - - - - - - - Models/Props/Bridges/SciFiBridgeDefense.mesh - - - - - - - - - - - - Models/Props/Bridges/SciFiBridgeDefense.mesh - - - - - - - - - - - Models/Props/Bridges/SciFiBridgeDefense.mesh - - - - - - - - - - - Models/Props/Bridges/SciFiBridgeDefense.mesh - - - - - - - - - - - - - - - - - - - - Models/Props/Pillars/SciFiBridgePillar1.mesh - - - - - - - - - - - - - - Models/Props/Bridges/SciFiBridge1Blue.mesh - - - - - - - - - - - - - Models/Props/Bridges/SciFiBridge1Blue.mesh - - - - - - - - - - - - - Models/Props/Pillars/SciFiBridgePillar1.mesh - - - - - - - - - - - - - - Models/Props/Bridges/SciFiBridge1Red.mesh - - - - - - - - - - - - - Models/Props/Bridges/SciFiBridge1Red.mesh - - - - - - - - - - - - - Models/Props/Bridges/WoodenBridge.mesh - - - - - - - - - - - - - - - - - - - - - Models/Props/Pillars/SciFiBridgePillar1.mesh - - - - - - - - - - - - - - Models/Props/Pillars/SciFiBridgePillar1.mesh - - - - - - - - - - - - - - Models/Props/Walls/MediumWall2.mesh - - - - - - - - - - - Models/Props/Walls/MediumWall2.mesh - - - - - - - - - - - - - - - Models/Props/Walls/MediumWall3.mesh - - - - - - - - - - - Models/Props/Walls/MediumWall3.mesh - - - - - - - - - - - - - - Models/Props/Pillars/SciFiBridgePillar1.mesh - - - - - - - - - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - - - Models/Props/Walls/MediumWall1.mesh - - - - - - - - - - - - Models/Props/Walls/MediumWall1.mesh - - - - - - - - - - - - Models/Props/Walls/MediumWall1.mesh - - - - - - - - - - - - - - Models/Props/Walls/MediumWall1.mesh - - - - - - - - - - - Models/Props/Walls/MediumWall1.mesh - - - - - - - - - - - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - - Models/Core/UnitPlane.mesh - - true - - - - - - - - - - - - - Models/Core/UnitPlane.mesh - - true - - - - - - - - - - - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - Models/Core/UnitCube.mesh - - - - - - - - - - - - - - - - Models/Props/Pillars/SciFiBridgePillar1.mesh - - - - - - - - - - - - - - Models/Props/Pillars/SciFiBridgePillar1.mesh - - - - - - - - - - - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - - - - - - Models/Props/Flora/TreeLog.mesh - - - - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - - - - - Models/Props/Flora/SpecialRoot.mesh - - - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - - - - - Models/Props/Flora/SpecialRoot.mesh - - - - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - - - - - Models/Props/Flora/AliveBush.mesh - true - - - - - - - - - - - - - - Models/Props/Flora/SpecialRoot.mesh - - - - - - - - - - - - - - - - - - - - - Models/Props/Stones/BigStone.mesh - - - - - - - - - - - - - Models/Props/Stones/MediumStone2.mesh - - - - - - - - - - - - - - Models/Props/Stones/BigStone.mesh - - - - - - - - - - - - - Models/Props/Stones/BigStone.mesh - - - - - - - - - - - - - - Models/Props/Stones/BigStone.mesh - - - - - - - - - - - - Models/Props/Stones/BigStone.mesh - - - - - - - - - - - - - Models/Props/Stones/BigStone.mesh - - - - - - - - - - - - - - - - Models/Props/Stones/BigStone.mesh - - - - - - - - - - - - - Models/Props/Stones/MediumStone1.mesh - - - - - - - - - - - - - - Models/Props/Stones/SmallStone1.mesh - - - - - - - - - - - - - - Models/Props/Stones/BigStone.mesh - - - - - - - - - - - - Models/Props/Stones/MediumStone1.mesh - - - - - - - - - - - - - Models/Props/Stones/MediumStone1.mesh - - - - - - - - - - - - - - - Models/Props/Stones/MediumStone1.mesh - - - - - - - - - - - - - - Models/Props/Stones/BigStone.mesh - - - - - - - - - - - - Models/Props/Stones/BigStone.mesh - - - - - - - - - - - - - Models/Props/Stones/BigStone.mesh - - - - - - - - - - - - - Models/Props/Stones/BigStone.mesh - - - - - - - - - - - - - Models/Props/Stones/MediumStone2.mesh - - - - - - - - - - - - - - Models/Props/Stones/BigStone.mesh - - - - - - - - - - - - Models/Props/Stones/BigStone.mesh - - - - - - - - - - - - - - - - - Models/Props/Stones/BigStone.mesh - - - - - - - - - - - Models/Props/Stones/BigStone.mesh - - - - - - - - - - - - - Models/Props/Stones/BigStone.mesh - - - - - - - - - - - - - Models/Props/Stones/BigStone.mesh - - - - - - - - - - - - - Models/Props/Stones/SmallStone1.mesh - - - - - - - - - - - - - - Models/Props/Stones/BigStone.mesh - - - - - - - - - - - - - - - Models/Props/Stones/BigStone.mesh - - - - - - - - - - - - Models/Props/Stones/BigStone.mesh - - - - - - - - - - - - - - - - Models/Props/Stones/BigStone.mesh - - - - - - - - - - - - - Models/Props/Stones/BigStone.mesh - - - - - - - - - - - - - Models/Props/Stones/BigStone.mesh - - - - - - - - - - - - - Models/Props/Stones/BigStone.mesh - - - - - - - - - - - - Models/Props/Stones/SmallStone2.mesh - - - - - - - - - - - - - - Models/Props/Stones/MediumStone2.mesh - - - - - - - - - - - - - Models/Props/Stones/ShinyStoneCrystalRed.mesh - - - - - - - - - - - - - - Models/Props/Stones/ShinyStoneCrystalRed.mesh - - - - - - - - - - - - - - Models/Props/Stones/ShinyStoneCrystalRed.mesh - - - - - - - - - - - - - - Models/Props/Walls/MediumWall1.mesh - - - - - - - - - - - - Models/Props/Stones/BigStone.mesh - - - - - - - - - - - - - Models/Props/Stones/SmallStone1.mesh - - - - - - - - - - - - - - Models/Props/Stones/MediumStone2.mesh - - - - - - - - - - - - - Models/Props/Stones/MediumStone2.mesh - - - - - - - - - - - - - Models/Props/Stones/SmallStone2.mesh - - - - - - - - - - - - - Models/Props/Stones/MediumStone2.mesh - - - - - - - - - - - - Models/Props/Stones/MediumStone2.mesh - - - - - - - - - - - - - - Models/Props/Stones/SmallStone1.mesh - - - - - - - - - - - - - - Models/Props/Stones/MediumStone2.mesh - - - - - - - - - - - - - - Models/Props/Stones/SmallStone1.mesh - - - - - - - - - - - - - Models/Props/Stones/SmallStone2.mesh - - - - - - - - - - - - - - Models/Props/Stones/SmallStone1.mesh - - - - - - - - - - - - - - Models/Props/Stones/MediumStone1.mesh - - - - - - - - - - - - - - - - - - - Models/Props/Stones/SmallStone1.mesh - - - - - - - - - - - - - Models/Props/Stones/SmallStone2.mesh - - - - - - - - - - - - - - Models/Props/Stones/MediumStone2.mesh - - - - - - - - - - - - - Models/Props/Stones/SmallStone1.mesh - - - - - - - - - - - - - - - Models/Props/Stones/SmallStone1.mesh - - - - - - - - - - - - - - Models/Props/Stones/SmallStone1.mesh - - - - - - - - - - - - - - - - Models/Props/Stones/SmallStone2.mesh - - - - - - - - - - - - - - Models/Props/Stones/SmallStone1.mesh - - - - - - - - - - - - - Models/Props/Stones/SmallStone2.mesh - - - - - - - - - - - - - - Models/Props/Stones/MediumStone2.mesh - - - - - - - - - - - - - - Models/Props/Stones/BigStone.mesh - - - - - - - - - - - - - Models/Props/Stones/MediumStone2.mesh - - - - - - - - - - - - Models/Props/Stones/MediumStone2.mesh - - - - - - - - - - - - - Models/Props/Stones/SmallStone1.mesh - - - - - - - - - - - - - - - - Models/Props/Stones/SmallStone2.mesh - - - - - - - - - - - - - - Models/Props/Stones/MediumStone2.mesh - - - - - - - - - - - - - - Models/Props/Stones/MediumStone1.mesh - - - - - - - - - - - - - - Models/Props/Stones/MediumStone2.mesh - - - - - - - - - - - - - Models/Props/Stones/BigStone.mesh - - - - - - - - - - - - - Models/Props/Stones/SmallStone2.mesh - - - - - - - - - - - - - - Models/Props/Stones/MediumStone2.mesh - - - - - - - - - - - - - - - - - - - - - Models/Props/PickUps/PickUpHolder.mesh - - - - - - - - - - - - - - Models/Props/PickUps/PickUpHolder.mesh - - - - - - - - - - - - - - Models/Props/PickUps/PickUpHolder.mesh - - - - - - - - - - - - - - Models/Props/PickUps/PickUpHolder.mesh - - - - - - - - - - - - - - - - - - - - - - Models/Props/PickUps/PickUpHolder.mesh - - - - - - - - - - - - - - Models/Props/PickUps/PickUpHolder.mesh - - - - - - - - - - - - - Models/Props/PickUps/PickUpHolder.mesh - - - - - - - - - - - - - - Models/Props/PickUps/PickUpHolder.mesh - - - - - - - - - - - - - - Models/Props/PickUps/PickUpHolder.mesh - - - - - - - - - - - - - - - - - - - - - Models/Props/Stones/AssaultHolder.mesh - - - - - - - - - - - - Models/Props/Stones/AssaultHolder.mesh - - - - - - - - - - - - - - - Models/Props/Stones/AssaultHolder.mesh - - - - - - - - - - - - Models/Props/Stones/AssaultHolder.mesh - - - - - - - - - - - - - - - Models/Props/Stones/AssaultHolder.mesh - - - - - - - - - - - - Models/Props/Stones/AssaultHolder.mesh - - - - - - - - - - - - Models/Props/Stones/AssaultHolder.mesh - - - - - - - - - - - - Models/Props/Stones/AssaultHolder.mesh - - - - - - - - - - - - - - - - - - - Models/Props/Stones/AssaultHolder.mesh - - - - - - - - - - - - - - Models/Props/Stones/AssaultHolder.mesh - - - - - - - - - - - - - - Models/Props/Stones/AssaultHolder.mesh - - - - - - - - - - - - - - Models/Props/Stones/AssaultHolder.mesh - - - - - - - - - - - - - - - - - - - - - Models/Props/SciFiHolder1.mesh - - - - - - - - - - - - - Models/Props/SciFiHolder1.mesh - - - - - - - - - - - - - Models/Props/SciFiHolder1.mesh - - - - - - - - - - - - - Models/Props/SciFiHolder1.mesh - - - - - - - - - - - - - Models/Props/SciFiHolder1.mesh - - - - - - - - - - - - - Models/Props/SciFiHolder1.mesh - - - - - - - - - - - - - Models/Props/SciFiHolder1.mesh - - - - - - - - - - - - - Models/Props/SciFiHolder1.mesh - - - - - - - - - - - - - - - - - - - - Models/Props/Stones/ShinyStoneCrystalRed.mesh - - - - - - - - - - - - - Models/Props/Stones/ShinyStoneCrystalRed.mesh - - - - - - - - - - - - - - Models/Props/Stones/ShinyStoneCrystalRed.mesh - - - - - - - - - - - - - Models/Props/Stones/ShinyStoneCrystalBlue.mesh - - - - - - - - - - - - - - Models/Props/Stones/ShinyStoneCrystalBlue.mesh - - - - - - - - - - - - - - Models/Props/Stones/ShinyStoneCrystalBlue.mesh - - - - - - - - - - - - - - Models/Props/Stones/ShinyStoneCrystalBlue.mesh - - - - - - - - - - - - - - Models/Props/Stones/ShinyStoneCrystalBlue.mesh - - - - - - - - - - - - - Models/Props/Stones/ShinyStoneCrystalRed.mesh - - - - - - - - - - - - - - Models/Props/Stones/ShinyStoneCrystalRed.mesh - - - - - - - - - - - - - - Models/Props/Stones/ShinyStoneCrystalBlue.mesh - - - - - - - - - - - - - - Models/Props/Stones/ShinyStoneCrystalBlue.mesh - - - - - - - - - - - - - - Models/Props/Stones/ShinyStoneCrystalRed.mesh - - - - - - - - - - - - - - Models/Props/Stones/ShinyStoneCrystalRed.mesh - - - - - - - - - - - - - Models/Props/Stones/ShinyStoneCrystalBlue.mesh - - - - - - - - - - - - - - Models/Props/Stones/ShinyStoneCrystalBlue.mesh - - - - - - - - - - - - - - Models/Props/Stones/ShinyStoneCrystalRed.mesh - - - - - - - - - - - - - - - - - - - - - - - Models/Props/CapturePoint/CapturePointBlue.mesh - - - - - - - - - - - - - 4 - - - Models/Core/UnitCylinder.mesh - - true - - - - - - - - - - - - - - - - - - - - - Models/Props/CapturePoint/CapturePointNeutral.mesh - - - - - - - - - - 3 - - - Models/Core/UnitCylinder.mesh - - true - - - - - - - - - - - - - - - - - Models/Props/CapturePoint/CapturePointNeutral.mesh - - - - - - - - - - 2 - - - Models/Core/UnitCylinder.mesh - - true - - - - - - - - - - - - - - - - - Models/Props/CapturePoint/CapturePointNeutral.mesh - - - - - - - - - - 1.5498908015879351 - 1 - - - Models/Core/UnitCylinder.mesh - - true - - - - - - - - - - - - - - - - - Models/Props/CapturePoint/CapturePointRed.mesh - - - - - - - - - - - - - - - Models/Core/UnitCylinder.mesh - - true - - - - - - - - - - - - - - - - - - - - - - - - - - - 1 - - - - - - - - - 10 - - - - - - - - - - 10 - - - - - - - - - - - - - 10 - - - - - - - - - - - 10 - - - - - - - - - - - 10 - - - - - - - - - - - 1 - - - - - - - - - - - - - - Schema/Entities/PlayerRed.xml - - - - - - - - - - - - - - - - Models/Characters/Assault/AssaultTPose.mesh - false - - - - - - - - - - - - Models/Characters/Assault/AssaultTPose.mesh - false - - - - - - - - - - - - Models/Characters/Assault/AssaultTPose.mesh - false - - - - - - - - - - - - Models/Characters/Assault/AssaultTPose.mesh - false - - - - - - - - - - - - - - Schema/Entities/TestPlayerIndicator.xml - - - - - - - - - - - - - - - - Models/Characters/Assault/AssaultTPose.mesh - false - - - - - - - - - - - - Models/Characters/Assault/AssaultTPose.mesh - false - - - - - - - - - - - - Models/Characters/Assault/AssaultTPose.mesh - false - - - - - - - - - - - - Models/Characters/Assault/AssaultTPose.mesh - false - - - - - - - - - - - - - - - - - - - Models/Props/PickUps/HealthPickUp.mesh - - - 0.10000000149011612 - - - - - - - - - - - - - - - - Models/Props/PickUps/AmmoPickUp.mesh - - - 0.10000000149011612 - - - - - - - - - - - - - - - - Models/Props/PickUps/HealthPickUp.mesh - - - 0.10000000149011612 - - - - - - - - - - - - - - - - Models/Props/PickUps/HealthPickUp.mesh - - - 0.10000000149011612 - - - - - - - - - - - - - - - - Models/Props/PickUps/AmmoPickUp.mesh - - - 0.10000000149011612 - - - - - - - - - - - - - - - - Models/Props/PickUps/HealthPickUp.mesh - - - 0.10000000149011612 - - - - - - - - - - - - - - - - Models/Props/PickUps/AmmoPickUp.mesh - - - 0.10000000149011612 - - - - - - - - - - - - - - - - Models/Props/PickUps/AmmoPickUp.mesh - - - 0.10000000149011612 - - - - - - - - - - - - - - - - diff --git a/resources/Schema/Entities/Player.xml b/resources/Schema/Entities/Player.xml index dfc8855c..4fd70af1 100644 --- a/resources/Schema/Entities/Player.xml +++ b/resources/Schema/Entities/Player.xml @@ -575,7 +575,7 @@ - 80 + 60 Textures/Icons/Arrow.png diff --git a/resources/Schema/Entities/PlayerRed.xml b/resources/Schema/Entities/PlayerRed.xml index fc8dea66..c9ac246d 100644 --- a/resources/Schema/Entities/PlayerRed.xml +++ b/resources/Schema/Entities/PlayerRed.xml @@ -575,7 +575,7 @@ - 80 + 60 Textures/Icons/Arrow.png From 64610e3c03b4ebe99b824b40b3f66ce51cef3f60 Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Thu, 18 Feb 2016 11:27:07 +0100 Subject: [PATCH 300/355] Fixed so some of the tests are working again. Also removed the test errors --- src/Tests/CapturePointTest.cpp | 2 +- src/Tests/CollisionTest.cpp | 18 +++++++++--------- src/Tests/HealthSystemTest.cpp | 2 +- src/Tests/PickupSpawnTest.cpp | 2 +- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/Tests/CapturePointTest.cpp b/src/Tests/CapturePointTest.cpp index 2c7bf430..8a9baf40 100644 --- a/src/Tests/CapturePointTest.cpp +++ b/src/Tests/CapturePointTest.cpp @@ -94,7 +94,7 @@ CapturePointTest::CapturePointTest(int runTestNumber) m_World = new World(); // Create system pipeline - m_SystemPipeline = new SystemPipeline(m_World,m_EventBroker); + m_SystemPipeline = new SystemPipeline(m_World,m_EventBroker, true, false); m_SystemPipeline->AddSystem(0); m_SystemPipeline->AddSystem(1); diff --git a/src/Tests/CollisionTest.cpp b/src/Tests/CollisionTest.cpp index 6cb6c88b..b5ba8245 100644 --- a/src/Tests/CollisionTest.cpp +++ b/src/Tests/CollisionTest.cpp @@ -33,10 +33,10 @@ void RayTest(std::string fileName) { ResourceManager::RegisterType("RawModel"); auto unitBox = ResourceManager::Load(fileName); BOOST_REQUIRE(unitBox != nullptr); - bool hit = Collision::RayVsModel(ray, unitBox->m_Vertices, unitBox->m_Indices); + bool hit = Collision::RayVsModel(ray, unitBox->Vertices(), unitBox->m_Indices, glm::mat4(1)); BOOST_CHECK(hit); ray.SetDirection(glm::vec3(-1, 0, 0)); - hit = Collision::RayVsModel(ray, unitBox->m_Vertices, unitBox->m_Indices); + hit = Collision::RayVsModel(ray, unitBox->Vertices(), unitBox->m_Indices, glm::mat4(1)); BOOST_CHECK(!hit); } @@ -146,12 +146,12 @@ BOOST_AUTO_TEST_CASE(rayVsModelTest2) z = Collision::RayVsAABB(ray, someAABB); if (z) { //hit - bool hit = Collision::RayVsModel(ray, unitBox->m_Vertices, unitBox->m_Indices); + bool hit = Collision::RayVsModel(ray, unitBox->Vertices(), unitBox->m_Indices,glm::mat4(1)); if (!hit) { //if rayvsaabb hit but rayvvmodel didnt hit, we get to here - glm::vec3 outtttttttt; - hit = Collision::RayVsModel(ray, unitBox->m_Vertices, unitBox->m_Indices, outtttttttt); - hit = Collision::RayVsModel(ray, unitBox->m_Vertices, unitBox->m_Indices); + glm::mat4 outtttttttt; + hit = Collision::RayVsModel(ray, unitBox->Vertices(), unitBox->m_Indices, glm::mat4(1)); + hit = Collision::RayVsModel(ray, unitBox->Vertices(), unitBox->m_Indices, glm::mat4(1)); } else { hit = hit; @@ -163,7 +163,7 @@ BOOST_AUTO_TEST_CASE(rayVsModelTest2) // z = z; //} // - bool hit = Collision::RayVsModel(ray, unitBox->m_Vertices, unitBox->m_Indices); + bool hit = Collision::RayVsModel(ray, unitBox->Vertices(), unitBox->m_Indices, glm::mat4(1)); ////breakpoint test //if (!hit) { // hit = hit; @@ -175,8 +175,8 @@ BOOST_AUTO_TEST_CASE(rayVsModelTest2) //if rayvsmodel hit but rayvsaabb didnt hit then we get to here z = Collision::RayVsAABB(ray, someAABB); glm::vec3 outtttttttt; - hit = Collision::RayVsModel(ray, unitBox->m_Vertices, unitBox->m_Indices, outtttttttt); - hit = Collision::RayVsModel(ray, unitBox->m_Vertices, unitBox->m_Indices); + hit = Collision::RayVsModel(ray, unitBox->Vertices(), unitBox->m_Indices, glm::mat4(1)); + hit = Collision::RayVsModel(ray, unitBox->Vertices(), unitBox->m_Indices, glm::mat4(1)); } else { z = z; diff --git a/src/Tests/HealthSystemTest.cpp b/src/Tests/HealthSystemTest.cpp index 8c084070..bf2650a3 100644 --- a/src/Tests/HealthSystemTest.cpp +++ b/src/Tests/HealthSystemTest.cpp @@ -48,7 +48,7 @@ GameHealthSystemTest::GameHealthSystemTest() fp.MergeEntities(m_World); // Create system pipeline - m_SystemPipeline = new SystemPipeline(m_World, m_EventBroker); + m_SystemPipeline = new SystemPipeline(m_World, m_EventBroker, false, false); m_SystemPipeline->AddSystem(0); //The Test diff --git a/src/Tests/PickupSpawnTest.cpp b/src/Tests/PickupSpawnTest.cpp index 7cbed85f..4acd897e 100644 --- a/src/Tests/PickupSpawnTest.cpp +++ b/src/Tests/PickupSpawnTest.cpp @@ -39,7 +39,7 @@ PickupSpawnTest::PickupSpawnTest(int runTestNumber) m_World = new World(); // Create system pipeline - m_SystemPipeline = new SystemPipeline(m_World, m_EventBroker); + m_SystemPipeline = new SystemPipeline(m_World, m_EventBroker, false, false); m_SystemPipeline->AddSystem(0); m_SystemPipeline->AddSystem(1); From 97499f1c28d04b01d510b3e30b3fbab88ad8a41e Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Thu, 18 Feb 2016 11:37:03 +0100 Subject: [PATCH 301/355] Made ComponentPool copyable by making sure string fields are handled properly --- include/Engine/Core/ComponentInfo.h | 1 + include/Engine/Core/ComponentPool.h | 4 +- include/Engine/Core/ComponentWrapper.h | 72 ++++++++++------------ include/Engine/Core/MemoryPool.h | 21 ++++++- src/Engine/Core/ComponentPool.cpp | 35 ++++++++++- src/Engine/Core/EntityFilePreprocessor.cpp | 3 + src/Engine/Core/World.cpp | 1 + 7 files changed, 89 insertions(+), 48 deletions(-) diff --git a/include/Engine/Core/ComponentInfo.h b/include/Engine/Core/ComponentInfo.h index d9799059..3383f297 100644 --- a/include/Engine/Core/ComponentInfo.h +++ b/include/Engine/Core/ComponentInfo.h @@ -27,6 +27,7 @@ struct ComponentInfo std::string Name; std::unordered_map Fields; std::vector FieldsInOrder; + std::vector StringFields; unsigned int Stride = 0; std::shared_ptr Defaults = nullptr; std::shared_ptr Meta = nullptr; diff --git a/include/Engine/Core/ComponentPool.h b/include/Engine/Core/ComponentPool.h index 957b8756..aedfd06b 100644 --- a/include/Engine/Core/ComponentPool.h +++ b/include/Engine/Core/ComponentPool.h @@ -1,6 +1,7 @@ #ifndef ComponentPool_h__ #define ComponentPool_h__ +#include #include "MemoryPool.h" #include "ComponentInfo.h" #include "ComponentWrapper.h" @@ -45,7 +46,8 @@ public: : m_ComponentInfo(ci) , m_Pool(ci.Meta->Allocation, sizeof(EntityID) + ci.Stride) { } - ComponentPool(const ComponentPool& other) = delete; + ~ComponentPool(); + ComponentPool(const ComponentPool& other); ComponentPool(const ComponentPool&& other) = delete; const ::ComponentInfo& ComponentInfo() const { return m_ComponentInfo; } diff --git a/include/Engine/Core/ComponentWrapper.h b/include/Engine/Core/ComponentWrapper.h index 0b9f7357..3ebad94a 100644 --- a/include/Engine/Core/ComponentWrapper.h +++ b/include/Engine/Core/ComponentWrapper.h @@ -7,6 +7,23 @@ #include "ComponentInfo.h" #include "Util/Any.h" +template +struct ComponentField { }; + +template +struct ComponentField::value>::type> +{ + static T& Get(const ComponentInfo::Field_t& info, char* data) { return *reinterpret_cast(data); } + static void Set(const ComponentInfo::Field_t& info, char* data, const T& value) { Get(data) = value; } +}; + +template <> +struct ComponentField +{ + static std::string& Get(const ComponentInfo::Field_t& info, char* data) { return **reinterpret_cast(data); } + static void Set(const ComponentInfo::Field_t& info, char* data, const std::string& value) { Get(info, data) = value; } +}; + struct ComponentWrapper { ComponentWrapper(const ComponentInfo& componentInfo, char* data) @@ -47,7 +64,20 @@ struct ComponentWrapper void Copy(ComponentWrapper& destination) { - memcpy(destination.Data, this->Data, Info.Stride); + // Copy trivial data + memcpy(destination.Data, Data, Info.Stride); + // Duplicate strings + SolidifyStrings(destination); + } + + // When component data has been copied, strings need to be reconstructed or they'll refer to the same data! + static void SolidifyStrings(ComponentWrapper& component) + { + for (auto& name : component.Info.StringFields) { + std::size_t offset = component.Info.Fields.at(name).Offset; + auto& value = *reinterpret_cast(component.Data + offset); + new (component.Data + offset) std::string(value); + } } struct SubscriptProxy @@ -94,44 +124,4 @@ private: boost::shared_array m_DataReference; }; -// TODO: Move this to Tests once entity importing is finished -class ComponentWrapperFactory -{ -public: - ComponentWrapperFactory() = default; - ComponentWrapperFactory(std::string componentTypeName, unsigned int allocation = 0) - { - m_ComponentInfo.Name = componentTypeName; - m_ComponentInfo.Meta->Allocation = allocation; - } - - template - void AddProperty(std::string fieldName, T defaultValue) - { - m_DefaultValues.push_back(defaultValue); - m_ComponentInfo.Fields[fieldName].Type = typeid(T).name(); - m_ComponentInfo.Fields[fieldName].Offset = m_ComponentInfo.Stride; - m_ComponentInfo.Fields[fieldName].Stride = sizeof(T); - m_ComponentInfo.Stride += sizeof(T); - } - - ComponentInfo& Finalize() - { - m_ComponentInfo.Defaults = std::shared_ptr(new char[m_ComponentInfo.Stride]); - std::size_t offset = 0; - for (auto& val : m_DefaultValues) { - memcpy(m_ComponentInfo.Defaults.get() + offset, val.Data.get(), val.Size); - offset += val.Size; - } - - return m_ComponentInfo; - } - - operator ComponentInfo&() { return Finalize(); } - -private: - ComponentInfo m_ComponentInfo; - std::vector m_DefaultValues; -}; - #endif diff --git a/include/Engine/Core/MemoryPool.h b/include/Engine/Core/MemoryPool.h index f4073294..0cf7b6bf 100644 --- a/include/Engine/Core/MemoryPool.h +++ b/include/Engine/Core/MemoryPool.h @@ -66,9 +66,24 @@ public: , m_LowestAllocatedSlot(m_NumSlots) { } - //We may get problems with memory being released - //prematurely, etc. if we allow copies. - MemoryPool(const MemoryPool& other) = delete; + MemoryPool(const MemoryPool& other) + : m_StartAddress(new char[other.m_NumSlots*other.m_Stride]) + , m_SlotIsAllocated(other.m_NumSlots, false) + , m_NumSlots(other.m_NumSlots) + , m_Stride(other.m_Stride) + , m_NumAllocatedSlots(0) + , m_CurrentAllocSlot(0) + , m_LowestAllocatedSlot(m_NumSlots) + { + // Copy statically allocated pool + memcpy(m_StartAddress, other.m_StartAddress, m_NumSlots*m_Stride); + // Copy dynamically allocated memory + for (char* otherAddr : other.m_ExtraMemory) { + char* addr = (char*)malloc(m_Stride); + memcpy(addr, otherAddr, m_Stride); + m_ExtraMemory.push_back(addr); + } + } MemoryPool(const MemoryPool&& other) = delete; //Free all memory that has been allocated. diff --git a/src/Engine/Core/ComponentPool.cpp b/src/Engine/Core/ComponentPool.cpp index 7b465fbc..bc4aab7e 100644 --- a/src/Engine/Core/ComponentPool.cpp +++ b/src/Engine/Core/ComponentPool.cpp @@ -1,7 +1,5 @@ #include "Core/ComponentPool.h" - - ComponentWrapper ComponentPoolForwardIterator::operator*() const { char* data = &(*m_MemoryPoolIterator); @@ -32,6 +30,28 @@ ComponentPoolForwardIterator& ComponentPoolForwardIterator::operator++() return *this; } +ComponentPool::ComponentPool(const ComponentPool& other) + : m_ComponentInfo(other.m_ComponentInfo) + , m_Pool(other.m_Pool) +{ + // Duplicate strings + for (auto& name : m_ComponentInfo.StringFields) { + for (auto& c : *this) { + ComponentWrapper::SolidifyStrings(c); + } + } +} + +ComponentPool::~ComponentPool() +{ + // Call std::string destructors + for (auto& name : m_ComponentInfo.StringFields) { + for (auto& c : *this) { + c.Field(name).~basic_string(); + } + } +} + //const ::ComponentInfo& ComponentPool::ComponentInfo() const //{ // return m_ComponentInfo; @@ -39,10 +59,19 @@ ComponentPoolForwardIterator& ComponentPoolForwardIterator::operator++() ComponentWrapper ComponentPool::Allocate(EntityID entity) { + // Allocate pool data char* data = m_Pool.Allocate(); + // Copy EntityID memcpy(data, &entity, sizeof(EntityID)); + m_EntityToComponent[entity] = data; - return ComponentWrapper(m_ComponentInfo, data); + ComponentWrapper component(m_ComponentInfo, data); + + // Copy defaults + memcpy(component.Data, m_ComponentInfo.Defaults.get(), m_ComponentInfo.Stride); + ComponentWrapper::SolidifyStrings(component); + + return component; } ComponentWrapper ComponentPool::GetByEntity(EntityID ent) diff --git a/src/Engine/Core/EntityFilePreprocessor.cpp b/src/Engine/Core/EntityFilePreprocessor.cpp index a1370dd2..c3a90c29 100644 --- a/src/Engine/Core/EntityFilePreprocessor.cpp +++ b/src/Engine/Core/EntityFilePreprocessor.cpp @@ -185,6 +185,9 @@ void EntityFilePreprocessor::parseComponentInfo() field.Offset = fieldOffset; field.Stride = stride; compInfo.FieldsInOrder.push_back(name); + if (field.Type == "string") { + compInfo.StringFields.push_back(name); + } fieldOffset += stride; } diff --git a/src/Engine/Core/World.cpp b/src/Engine/Core/World.cpp index 69c25f61..79f210ea 100644 --- a/src/Engine/Core/World.cpp +++ b/src/Engine/Core/World.cpp @@ -48,6 +48,7 @@ ComponentWrapper World::AttachComponent(EntityID entity, const std::string& comp ComponentWrapper c = pool->Allocate(entity); // Write default values memcpy(c.Data, ci.Defaults.get(), ci.Stride); + ComponentWrapper::SolidifyStrings(c); return c; } From ca907b912e69488023aa589dfe0f43c564a4b908 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Thu, 18 Feb 2016 13:54:32 +0100 Subject: [PATCH 302/355] Copy constructor for deep copy of World. --- include/Engine/Core/World.h | 1 + src/Engine/Core/World.cpp | 9 +++++++++ 2 files changed, 10 insertions(+) diff --git a/include/Engine/Core/World.h b/include/Engine/Core/World.h index 35394b9f..1604df37 100644 --- a/include/Engine/Core/World.h +++ b/include/Engine/Core/World.h @@ -15,6 +15,7 @@ public: : m_EventBroker(eventBroker) { } ~World(); + World(const World& other); // Create empty entity EntityID CreateEntity(EntityID parent = 0); diff --git a/src/Engine/Core/World.cpp b/src/Engine/Core/World.cpp index 79f210ea..a0223e02 100644 --- a/src/Engine/Core/World.cpp +++ b/src/Engine/Core/World.cpp @@ -9,6 +9,15 @@ World::~World() } } +World::World(const World& other) + : m_EventBroker(other.m_EventBroker) +{ + // Deep copy component pools + for (auto& kv : m_ComponentPools) { + m_ComponentPools[kv.first] = new ComponentPool(*kv.second); + } +} + EntityID World::CreateEntity(EntityID parent /*= 0*/) { EntityID newEntity = generateEntityID(); From e15a7b9485474d999769efe5a64d6b2abe052cf9 Mon Sep 17 00:00:00 2001 From: Tleety Date: Thu, 18 Feb 2016 18:00:26 +0100 Subject: [PATCH 303/355] You can now change resolution without any apparent bugs. --- include/Engine/Rendering/DrawFinalPass.h | 2 +- include/Engine/Rendering/LightCullingPass.h | 1 + include/Engine/Rendering/PickingPass.h | 2 + include/Engine/Rendering/Renderer.h | 7 ++ .../Schema/Entities/QualityAssurance.xml | 76 +++++++++++++------ src/Engine/GUI/MainMenuSystem.cpp | 8 +- src/Engine/Rendering/DrawFinalPass.cpp | 10 ++- src/Engine/Rendering/FrameBuffer.cpp | 4 +- src/Engine/Rendering/LightCullingPass.cpp | 7 ++ src/Engine/Rendering/PickingPass.cpp | 9 +++ src/Engine/Rendering/Renderer.cpp | 16 +++- 11 files changed, 108 insertions(+), 34 deletions(-) diff --git a/include/Engine/Rendering/DrawFinalPass.h b/include/Engine/Rendering/DrawFinalPass.h index bf8d4d76..1d91f6a2 100644 --- a/include/Engine/Rendering/DrawFinalPass.h +++ b/include/Engine/Rendering/DrawFinalPass.h @@ -20,6 +20,7 @@ public: void InitializeShaderPrograms(); void Draw(RenderScene& scene); void ClearBuffer(); + void OnWindowResize(); //Return the texture that is used in later stages to apply the bloom effect GLuint BloomTexture() const { return m_BloomTexture; } @@ -31,7 +32,6 @@ public: FrameBuffer* FinalPassFrameBuffer() { return &m_FinalPassFrameBuffer; } FrameBuffer* FinalPassFrameBufferLowRes() { return &m_FinalPassFrameBufferLowRes; } - private: void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const; void GenerateMipMapTexture(GLuint* texture, GLenum wrapping, glm::vec2 dimensions, GLint format, GLenum type, GLint numMipMaps) const; diff --git a/include/Engine/Rendering/LightCullingPass.h b/include/Engine/Rendering/LightCullingPass.h index d8852df0..914fb8bb 100644 --- a/include/Engine/Rendering/LightCullingPass.h +++ b/include/Engine/Rendering/LightCullingPass.h @@ -21,6 +21,7 @@ public: void SetSSBOSizes(); void CullLights(RenderScene& scene); void FillLightList(RenderScene& scene); + void OnWindowResize(); GLuint FrustumSSBO() const { return m_FrustumSSBO; } GLuint LightSSBO() const { return m_LightSSBO; } diff --git a/include/Engine/Rendering/PickingPass.h b/include/Engine/Rendering/PickingPass.h index d7a340f1..f6434781 100644 --- a/include/Engine/Rendering/PickingPass.h +++ b/include/Engine/Rendering/PickingPass.h @@ -22,6 +22,8 @@ public: void Draw(RenderScene& scene); void ClearPicking(); + void OnWindowResize(); + //Getters const ShaderProgram& PickingProgram() const { return *m_PickingProgram; } //const std::unordered_map& PickingColorsToEntity() const { return m_PickingColorsToEntity; } diff --git a/include/Engine/Rendering/Renderer.h b/include/Engine/Rendering/Renderer.h index 04754514..fc1b6939 100644 --- a/include/Engine/Rendering/Renderer.h +++ b/include/Engine/Rendering/Renderer.h @@ -26,6 +26,8 @@ class Renderer : public IRenderer { + static void glfwFrameBufferCallback(GLFWwindow* window, int width, int height); + public: Renderer(EventBroker* eventBroker) : m_EventBroker(eventBroker) @@ -37,8 +39,12 @@ public: virtual PickData Pick(glm::vec2 screenCoord) override; + private: //----------------------Variables----------------------// + + static std::unordered_map m_WindowToRenderer; + EventBroker* m_EventBroker; TextPass* m_TextPass; @@ -50,6 +56,7 @@ private: Model* m_UnitSphere; int m_DebugTextureToDraw = 0; + bool m_ResizeWindow = false; PickingPass* m_PickingPass; LightCullingPass* m_LightCullingPass; diff --git a/resources/Schema/Entities/QualityAssurance.xml b/resources/Schema/Entities/QualityAssurance.xml index 762da931..0aa2fbe7 100644 --- a/resources/Schema/Entities/QualityAssurance.xml +++ b/resources/Schema/Entities/QualityAssurance.xml @@ -40,7 +40,7 @@ - + @@ -93,7 +93,7 @@ - + @@ -168,7 +168,7 @@ - + @@ -213,7 +213,7 @@ - + @@ -277,7 +277,7 @@ - + @@ -309,7 +309,7 @@ - + @@ -659,7 +659,7 @@ - + @@ -706,7 +706,7 @@ - + @@ -766,7 +766,7 @@ - + @@ -813,7 +813,7 @@ - + @@ -859,7 +859,7 @@ - + @@ -906,7 +906,7 @@ - + @@ -953,7 +953,7 @@ - + @@ -1367,7 +1367,7 @@ - + @@ -1376,7 +1376,7 @@ true - 2.6831806538294813 + 0.8256214817261025 3.7999999523162842 true @@ -1423,7 +1423,7 @@ - + @@ -1432,7 +1432,7 @@ - 1.9833111709021125 + 1.8641349174045843 Models/Characters/Assault/AssaultTPose.mesh @@ -1475,7 +1475,7 @@ - + @@ -1486,7 +1486,7 @@ true - 1.9833111709021125 + 1.8641349174045843 true @@ -1531,7 +1531,7 @@ - + @@ -1541,7 +1541,7 @@ true - 1.05003269646582 + 1.2301962937648341 10 3 @@ -1589,7 +1589,7 @@ - + @@ -1599,7 +1599,7 @@ true - 0.75001660742393028 + 3.4214855659573402 true 5 true @@ -1780,7 +1780,7 @@ true - 2.6831806538294813 + 0.8256214817261025 3.7999999523162842 true @@ -2421,6 +2421,34 @@ + + + + + Textures/Core/White.png + + + + + + + + + + + FullScreen + Fonts/DroidSans.ttf,64 + + + + + + + + + + + diff --git a/src/Engine/GUI/MainMenuSystem.cpp b/src/Engine/GUI/MainMenuSystem.cpp index 68db7b60..f8bf032b 100644 --- a/src/Engine/GUI/MainMenuSystem.cpp +++ b/src/Engine/GUI/MainMenuSystem.cpp @@ -27,15 +27,17 @@ bool MainMenuSystem::OnButtonClick(const Events::ButtonClicked& e) printf("No, you stay"); } else if (e.EntityName == "Res1080") { glfwSetWindowSize(m_Renderer->Window(), 1920, 1080); - printf("1080"); + printf("\n1080"); } else if (e.EntityName == "Res720") { glfwSetWindowSize(m_Renderer->Window(), 1280, 720); glViewport(0, 0, 1280, 720); - printf("720"); + printf("\n720"); } else if (e.EntityName == "Res480") { glfwSetWindowSize(m_Renderer->Window(), 854, 480); glViewport(0, 0, 854, 480); - printf("480"); + printf("\n480"); + } else if (e.EntityName == "FullScreen") { + printf("No fullscreen for now"); } return true; diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index fd95ecee..e907c6de 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -274,6 +274,12 @@ void DrawFinalPass::ClearBuffer() m_FinalPassFrameBuffer.Unbind(); } + +void DrawFinalPass::OnWindowResize() +{ + InitializeFrameBuffers(); +} + void DrawFinalPass::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const { glGenTextures(1, texture); @@ -702,7 +708,7 @@ void DrawFinalPass::BindExplosionUniforms(GLuint shaderHandle, std::shared_ptrProjectionMatrix())); GLERROR("Bind 4 uniform"); - glUniform2f(glGetUniformLocation(shaderHandle, "ScreenDimensions"), m_Renderer->Resolution().Width, m_Renderer->Resolution().Height); + glUniform2f(glGetUniformLocation(shaderHandle, "ScreenDimensions"), m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); GLERROR("Bind 5 uniform"); glUniform3fv(glGetUniformLocation(shaderHandle, "ExplosionOrigin"), 1, glm::value_ptr(job->ExplosionOrigin)); @@ -754,7 +760,7 @@ void DrawFinalPass::BindModelUniforms(GLuint shaderHandle, std::shared_ptrResolution().Width, m_Renderer->Resolution().Height); + glUniform2f(Location_ScreenDimensions, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); GLERROR("Bind 5 uniform"); GLint Location_FillPercentage = glGetUniformLocation(shaderHandle, "FillPercentage"); diff --git a/src/Engine/Rendering/FrameBuffer.cpp b/src/Engine/Rendering/FrameBuffer.cpp index c0be4cb1..09ca6161 100644 --- a/src/Engine/Rendering/FrameBuffer.cpp +++ b/src/Engine/Rendering/FrameBuffer.cpp @@ -72,9 +72,7 @@ void FrameBuffer::Generate() GLenum* bufferTextures = &attachments[0]; glDrawBuffers(attachments.size(), bufferTextures); - if(GLERROR("4")) { - printf("hello"); - } + GLERROR("GLBufferAttachement error"); if (GLenum frameBufferStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { GLERROR("Framebuffer incomplete"); diff --git a/src/Engine/Rendering/LightCullingPass.cpp b/src/Engine/Rendering/LightCullingPass.cpp index 0ae359db..d7a577a4 100644 --- a/src/Engine/Rendering/LightCullingPass.cpp +++ b/src/Engine/Rendering/LightCullingPass.cpp @@ -110,6 +110,13 @@ void LightCullingPass::FillLightList(RenderScene& scene) } } + +void LightCullingPass::OnWindowResize() +{ + SetSSBOSizes(); + InitializeSSBOs(); +} + void LightCullingPass::InitializeSSBOs() { glGenBuffers(1, &m_FrustumSSBO); diff --git a/src/Engine/Rendering/PickingPass.cpp b/src/Engine/Rendering/PickingPass.cpp index a979eb0e..88b18ecb 100644 --- a/src/Engine/Rendering/PickingPass.cpp +++ b/src/Engine/Rendering/PickingPass.cpp @@ -15,6 +15,8 @@ PickingPass::~PickingPass() } + + void PickingPass::InitializeTextures() { GenerateTexture(&m_PickingTexture, GL_CLAMP_TO_BORDER, GL_LINEAR, @@ -365,6 +367,13 @@ void PickingPass::ClearPicking() m_PickingBuffer.Unbind(); } + +void PickingPass::OnWindowResize() +{ + InitializeTextures(); + InitializeFrameBuffers(); +} + PickData PickingPass::Pick(glm::vec2 screenCoord) { int fbWidth; diff --git a/src/Engine/Rendering/Renderer.cpp b/src/Engine/Rendering/Renderer.cpp index 0ba25128..8f9d37ec 100644 --- a/src/Engine/Rendering/Renderer.cpp +++ b/src/Engine/Rendering/Renderer.cpp @@ -1,5 +1,7 @@ #include "Rendering/Renderer.h" +std::unordered_map Renderer::m_WindowToRenderer; + void Renderer::Initialize() { InitializeWindow(); @@ -12,7 +14,6 @@ void Renderer::Initialize() m_TextPass = new TextPass(); m_TextPass->Initialize(); - /* m_ScreenQuad = ResourceManager::Load("Models/Core/ScreenQuad.obj"); m_UnitQuad = ResourceManager::Load("Models/Core/UnitQuad.obj"); m_UnitSphere = ResourceManager::Load("Models/Core/UnitSphere.obj");*/ @@ -20,6 +21,16 @@ void Renderer::Initialize() m_ImGuiRenderPass = new ImGuiRenderPass(this, m_EventBroker); } +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_DrawFinalPass->OnWindowResize(); + currentRenderer->m_LightCullingPass->OnWindowResize(); + currentRenderer->m_PickingPass->OnWindowResize(); +} + void Renderer::InitializeWindow() { // Initialize GLFW @@ -39,6 +50,7 @@ void Renderer::InitializeWindow() LOG_ERROR("GLFW: Failed to create window"); exit(EXIT_FAILURE); } + glfwSetFramebufferSizeCallback(m_Window, &glfwFrameBufferCallback); glfwMakeContextCurrent(m_Window); // GL version info @@ -59,6 +71,8 @@ void Renderer::InitializeWindow() exit(EXIT_FAILURE); } + m_WindowToRenderer[m_Window] = this; + int windowSize[2]; glfwGetFramebufferSize(m_Window, &windowSize[0], &windowSize[1]); m_ViewportSize = Rectangle(windowSize[0], windowSize[1]); From 8c9f4bb84b47ea075bbaa3e3ca83045d036df861 Mon Sep 17 00:00:00 2001 From: Tleety Date: Fri, 19 Feb 2016 11:42:52 +0100 Subject: [PATCH 304/355] Resize should now be working correctly. --- include/Engine/Rendering/DrawBloomPass.h | 2 ++ src/Engine/Rendering/DrawBloomPass.cpp | 9 +++++++++ src/Engine/Rendering/DrawFinalPass.cpp | 17 ++++++++++++++++- src/Engine/Rendering/FrameBuffer.cpp | 4 +++- src/Engine/Rendering/LightCullingPass.cpp | 23 ++++++++++++++++++++++- src/Engine/Rendering/PickingPass.cpp | 4 +++- src/Engine/Rendering/Renderer.cpp | 1 + 7 files changed, 56 insertions(+), 4 deletions(-) diff --git a/include/Engine/Rendering/DrawBloomPass.h b/include/Engine/Rendering/DrawBloomPass.h index 539d6957..a5d6b578 100644 --- a/include/Engine/Rendering/DrawBloomPass.h +++ b/include/Engine/Rendering/DrawBloomPass.h @@ -24,6 +24,8 @@ public: void Draw(GLuint texture); + void OnWindowRezise(); + //Getters //Return the blurred result of the texture that was sent into draw GLuint GaussianTexture() const { return m_GaussianTexture_vert; } diff --git a/src/Engine/Rendering/DrawBloomPass.cpp b/src/Engine/Rendering/DrawBloomPass.cpp index 46612d5e..23080a52 100644 --- a/src/Engine/Rendering/DrawBloomPass.cpp +++ b/src/Engine/Rendering/DrawBloomPass.cpp @@ -121,6 +121,15 @@ void DrawBloomPass::Draw(GLuint texture) GLERROR("DrawBloomPass::Draw: END"); } + +void DrawBloomPass::OnWindowRezise() +{ + 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(); + 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(); +} + void DrawBloomPass::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const { glGenTextures(1, texture); diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index e907c6de..4cb85deb 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -277,7 +277,22 @@ void DrawFinalPass::ClearBuffer() void DrawFinalPass::OnWindowResize() { - InitializeFrameBuffers(); + //InitializeFrameBuffers(); + glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBuffer); + glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); + + 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); + 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); + m_FinalPassFrameBuffer.Generate(); + + + glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBufferLowRes); + glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, (int)(m_Renderer->GetViewportSize().Width/m_ShieldPixelRate), (int)(m_Renderer->GetViewportSize().Height/m_ShieldPixelRate)); + + GenerateTexture(&m_SceneTextureLowRes, GL_CLAMP_TO_EDGE, GL_NEAREST, glm::vec2((int)(m_Renderer->GetViewportSize().Width/m_ShieldPixelRate), (int)(m_Renderer->GetViewportSize().Height/m_ShieldPixelRate)), GL_RGB16F, GL_RGB, GL_FLOAT); + GenerateTexture(&m_BloomTextureLowRes, GL_CLAMP_TO_EDGE, GL_NEAREST, glm::vec2((int)(m_Renderer->GetViewportSize().Width/m_ShieldPixelRate), (int)(m_Renderer->GetViewportSize().Height/m_ShieldPixelRate)), GL_RGB16F, GL_RGB, GL_FLOAT); + m_FinalPassFrameBufferLowRes.Generate(); + GLERROR("Error changing texture resolutions"); } void DrawFinalPass::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const diff --git a/src/Engine/Rendering/FrameBuffer.cpp b/src/Engine/Rendering/FrameBuffer.cpp index 09ca6161..794fb84e 100644 --- a/src/Engine/Rendering/FrameBuffer.cpp +++ b/src/Engine/Rendering/FrameBuffer.cpp @@ -72,7 +72,9 @@ void FrameBuffer::Generate() GLenum* bufferTextures = &attachments[0]; glDrawBuffers(attachments.size(), bufferTextures); - GLERROR("GLBufferAttachement error"); + if (GLERROR("GLBufferAttachement error")) { + printf(": AttachmentSize %i", attachments.size()); + } if (GLenum frameBufferStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { GLERROR("Framebuffer incomplete"); diff --git a/src/Engine/Rendering/LightCullingPass.cpp b/src/Engine/Rendering/LightCullingPass.cpp index d7a577a4..1ce1f88c 100644 --- a/src/Engine/Rendering/LightCullingPass.cpp +++ b/src/Engine/Rendering/LightCullingPass.cpp @@ -114,7 +114,28 @@ void LightCullingPass::FillLightList(RenderScene& scene) void LightCullingPass::OnWindowResize() { SetSSBOSizes(); - InitializeSSBOs(); + + glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_FrustumSSBO); + glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(Frustum)*m_NumberOfTiles, nullptr, GL_DYNAMIC_COPY); + GLERROR("m_FrustumSSBO"); + + glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_LightSSBO); + glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(LightSource) * 200, nullptr, GL_DYNAMIC_COPY); + GLERROR("m_LightSSBO"); + + glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_LightGridSSBO); + glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(LightGrid)*m_NumberOfTiles, nullptr, GL_DYNAMIC_COPY); + GLERROR("m_LightGridSSBO"); + + glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_LightOffsetSSBO); + glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(m_LightOffset), &m_LightOffset, GL_DYNAMIC_COPY); + GLERROR("m_LightOffsetSSBO"); + + glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_LightIndexSSBO); + glBufferData(GL_SHADER_STORAGE_BUFFER, sizeof(float)*m_NumberOfTiles*MAX_LIGHTS_PER_TILE, m_LightIndex, GL_DYNAMIC_COPY); + GLERROR("m_LightIndexSSBO"); + + glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0); } void LightCullingPass::InitializeSSBOs() diff --git a/src/Engine/Rendering/PickingPass.cpp b/src/Engine/Rendering/PickingPass.cpp index 88b18ecb..40509d0c 100644 --- a/src/Engine/Rendering/PickingPass.cpp +++ b/src/Engine/Rendering/PickingPass.cpp @@ -371,7 +371,9 @@ void PickingPass::ClearPicking() void PickingPass::OnWindowResize() { InitializeTextures(); - InitializeFrameBuffers(); + glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBuffer); + glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); + m_PickingBuffer.Generate(); } PickData PickingPass::Pick(glm::vec2 screenCoord) diff --git a/src/Engine/Rendering/Renderer.cpp b/src/Engine/Rendering/Renderer.cpp index 8f9d37ec..e4627f01 100644 --- a/src/Engine/Rendering/Renderer.cpp +++ b/src/Engine/Rendering/Renderer.cpp @@ -29,6 +29,7 @@ void Renderer::glfwFrameBufferCallback(GLFWwindow* window, int width, int height currentRenderer->m_DrawFinalPass->OnWindowResize(); currentRenderer->m_LightCullingPass->OnWindowResize(); currentRenderer->m_PickingPass->OnWindowResize(); + currentRenderer->m_DrawBloomPass->OnWindowRezise(); } void Renderer::InitializeWindow() From fc5d054cb2bc9a7a6a5f08fca25f2f50eca9a4ba Mon Sep 17 00:00:00 2001 From: Tleety Date: Fri, 19 Feb 2016 12:49:07 +0100 Subject: [PATCH 305/355] Entity is now sent with the click events. Fixed small things --- include/Engine/GUI/EButtonClicked.h | 3 ++- include/Engine/GUI/EButtonPressed.h | 3 ++- include/Engine/GUI/EButtonReleased.h | 4 +++- include/Engine/Rendering/ModelJob.h | 4 ++-- src/Engine/GUI/ButtonSystem.cpp | 11 ++++++++--- src/Engine/Rendering/DrawFinalPass.cpp | 4 ++-- 6 files changed, 19 insertions(+), 10 deletions(-) diff --git a/include/Engine/GUI/EButtonClicked.h b/include/Engine/GUI/EButtonClicked.h index f34d6b3d..e4fe7abe 100644 --- a/include/Engine/GUI/EButtonClicked.h +++ b/include/Engine/GUI/EButtonClicked.h @@ -7,7 +7,8 @@ namespace Events { struct ButtonClicked : public Event { - std::string EntityName = "DEFAULT STRING USED"; + std::string EntityName; + EntityWrapper Entity; }; } diff --git a/include/Engine/GUI/EButtonPressed.h b/include/Engine/GUI/EButtonPressed.h index 04d50978..3615ac8a 100644 --- a/include/Engine/GUI/EButtonPressed.h +++ b/include/Engine/GUI/EButtonPressed.h @@ -7,7 +7,8 @@ namespace Events { struct ButtonPressed : public Event { - std::string EntityName = "DEFAULT STRING USED"; + std::string EntityName; + EntityWrapper Entity; }; } diff --git a/include/Engine/GUI/EButtonReleased.h b/include/Engine/GUI/EButtonReleased.h index 14736ca0..90170518 100644 --- a/include/Engine/GUI/EButtonReleased.h +++ b/include/Engine/GUI/EButtonReleased.h @@ -6,7 +6,9 @@ namespace Events { -struct ButtonReleased : public Event { }; +struct ButtonReleased : public Event { + EntityWrapper Entity; +}; } diff --git a/include/Engine/Rendering/ModelJob.h b/include/Engine/Rendering/ModelJob.h index ccd0e093..8801d2eb 100644 --- a/include/Engine/Rendering/ModelJob.h +++ b/include/Engine/Rendering/ModelJob.h @@ -108,7 +108,7 @@ struct ModelJob : RenderJob EndIndex = matGroup->EndIndex; Matrix = matrix; Color = modelComponent["Color"]; - GlowIntencity = ((double)modelComponent["GlowIntensity"]); + GlowIntensity = ((double)modelComponent["GlowIntensity"]); Entity = modelComponent.EntityID; glm::vec3 abspos = Transform::AbsolutePosition(world, modelComponent.EntityID); glm::vec3 worldpos = glm::vec3(camera->ViewMatrix() * glm::vec4(abspos, 1)); @@ -171,7 +171,7 @@ struct ModelJob : RenderJob ::Skeleton::AnimationOffset AnimationOffset; - float GlowIntencity = 8.0; + float GlowIntensity = 8.0; glm::vec4 DiffuseColor; glm::vec4 SpecularColor; glm::vec4 IncandescenceColor; diff --git a/src/Engine/GUI/ButtonSystem.cpp b/src/Engine/GUI/ButtonSystem.cpp index dbdc0e18..7c66e456 100644 --- a/src/Engine/GUI/ButtonSystem.cpp +++ b/src/Engine/GUI/ButtonSystem.cpp @@ -38,6 +38,7 @@ bool ButtonSystem::OnMousePress(const Events::MousePress& e) //You have clicked on a button entity, send pressed event. Events::ButtonPressed ePressed; + ePressed.Entity = m_PickEntity; ePressed.EntityName = m_PickEntity.Name(); m_EventBroker->Publish(ePressed); } @@ -50,15 +51,19 @@ bool ButtonSystem::OnMouseRelease(const Events::MouseRelease& e) { if(!m_MouseIsLocked) { //Mouse is not locked, send release event. - Events::ButtonReleased eReleased; - m_EventBroker->Publish(eReleased); m_PickData = m_Renderer->Pick(glm::vec2(e.X, e.Y)); if(m_PickData.Entity != EntityID_Invalid && m_PickData.World == m_World) { + EntityWrapper ent = EntityWrapper(m_World, m_PickData.Entity); + + Events::ButtonReleased eReleased; + eReleased.Entity = ent; + m_EventBroker->Publish(eReleased); + if(m_World->HasComponent(m_PickData.Entity, "Button")) { - EntityWrapper ent = EntityWrapper(m_World, m_PickData.Entity); if (ent == m_PickEntity) { //The entity you released the mouse button on is the same as you pressed it on. "Clicked" Events::ButtonClicked eClicked; + eClicked.Entity = m_PickEntity; eClicked.EntityName = m_PickEntity.Name(); m_EventBroker->Publish(eClicked); } diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index fd95ecee..54a523be 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -736,7 +736,7 @@ void DrawFinalPass::BindExplosionUniforms(GLuint shaderHandle, std::shared_ptrGlowIntencity); + glUniform1f(glGetUniformLocation(shaderHandle, "GlowIntensity"), job->GlowIntensity); GLERROR("END"); } @@ -775,7 +775,7 @@ void DrawFinalPass::BindModelUniforms(GLuint shaderHandle, std::shared_ptrGlowIntencity); + glUniform1f(Location_GlowIntensity, job->GlowIntensity); GLERROR("END"); } From 6e5335a266afa82a4a2a64e8d2b8244b93dae200 Mon Sep 17 00:00:00 2001 From: Tleety Date: Fri, 19 Feb 2016 13:16:26 +0100 Subject: [PATCH 306/355] Release now return name and entity of the entity that was previously klicked. --- include/Engine/GUI/EButtonReleased.h | 1 + src/Engine/GUI/ButtonSystem.cpp | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/include/Engine/GUI/EButtonReleased.h b/include/Engine/GUI/EButtonReleased.h index 90170518..ecd8dde2 100644 --- a/include/Engine/GUI/EButtonReleased.h +++ b/include/Engine/GUI/EButtonReleased.h @@ -7,6 +7,7 @@ namespace Events { struct ButtonReleased : public Event { + std::string EntityName; EntityWrapper Entity; }; diff --git a/src/Engine/GUI/ButtonSystem.cpp b/src/Engine/GUI/ButtonSystem.cpp index 7c66e456..93ae1811 100644 --- a/src/Engine/GUI/ButtonSystem.cpp +++ b/src/Engine/GUI/ButtonSystem.cpp @@ -56,7 +56,8 @@ bool ButtonSystem::OnMouseRelease(const Events::MouseRelease& e) EntityWrapper ent = EntityWrapper(m_World, m_PickData.Entity); Events::ButtonReleased eReleased; - eReleased.Entity = ent; + eReleased.EntityName = m_PickEntity.Name(); + eReleased.Entity = m_PickEntity; m_EventBroker->Publish(eReleased); if(m_World->HasComponent(m_PickData.Entity, "Button")) { From 722b795d3717cdfd8d087b18f79f2abda2fb9702 Mon Sep 17 00:00:00 2001 From: Tleety Date: Fri, 19 Feb 2016 13:30:41 +0100 Subject: [PATCH 307/355] Fixed spelling --- include/Engine/Rendering/DrawBloomPass.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/Engine/Rendering/DrawBloomPass.h b/include/Engine/Rendering/DrawBloomPass.h index a5d6b578..07c90e23 100644 --- a/include/Engine/Rendering/DrawBloomPass.h +++ b/include/Engine/Rendering/DrawBloomPass.h @@ -24,7 +24,7 @@ public: void Draw(GLuint texture); - void OnWindowRezise(); + void OnWindowResize(); //Getters //Return the blurred result of the texture that was sent into draw From 949ee76f553cea745d575349d83fc2e3a39be950 Mon Sep 17 00:00:00 2001 From: Tleety Date: Fri, 19 Feb 2016 13:52:16 +0100 Subject: [PATCH 308/355] Fallow and name fix --- resources/Shaders/ForwardPlus.frag.glsl | 2 +- src/Engine/Rendering/DrawBloomPass.cpp | 2 +- src/Engine/Rendering/Renderer.cpp | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/resources/Shaders/ForwardPlus.frag.glsl b/resources/Shaders/ForwardPlus.frag.glsl index d757ff36..8e248aad 100644 --- a/resources/Shaders/ForwardPlus.frag.glsl +++ b/resources/Shaders/ForwardPlus.frag.glsl @@ -73,7 +73,7 @@ struct LightResult { }; float CalcAttenuation(float radius, float dist, float falloff) { - return 1.0 - smoothstep(radius * 0.3, radius, dist); + return 1.0 - smoothstep(radius * falloff, radius, dist); } vec4 CalcSpecular(vec4 lightColor, vec4 viewVec, vec4 lightVec, vec4 normal) { diff --git a/src/Engine/Rendering/DrawBloomPass.cpp b/src/Engine/Rendering/DrawBloomPass.cpp index 23080a52..1855a653 100644 --- a/src/Engine/Rendering/DrawBloomPass.cpp +++ b/src/Engine/Rendering/DrawBloomPass.cpp @@ -122,7 +122,7 @@ void DrawBloomPass::Draw(GLuint texture) } -void DrawBloomPass::OnWindowRezise() +void DrawBloomPass::OnWindowResize() { 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(); diff --git a/src/Engine/Rendering/Renderer.cpp b/src/Engine/Rendering/Renderer.cpp index d0c06ea0..b8665fce 100644 --- a/src/Engine/Rendering/Renderer.cpp +++ b/src/Engine/Rendering/Renderer.cpp @@ -29,7 +29,7 @@ void Renderer::glfwFrameBufferCallback(GLFWwindow* window, int width, int height currentRenderer->m_DrawFinalPass->OnWindowResize(); currentRenderer->m_LightCullingPass->OnWindowResize(); currentRenderer->m_PickingPass->OnWindowResize(); - currentRenderer->m_DrawBloomPass->OnWindowRezise(); + currentRenderer->m_DrawBloomPass->OnWindowResize(); } void Renderer::InitializeWindow() From d135ea2da6cf7ccc2ee62a9272b30e2e476f22f5 Mon Sep 17 00:00:00 2001 From: Tleety Date: Fri, 19 Feb 2016 13:53:43 +0100 Subject: [PATCH 309/355] Small fix --- src/Engine/Rendering/DrawBloomPass.cpp | 2 +- src/Engine/Rendering/Renderer.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Engine/Rendering/DrawBloomPass.cpp b/src/Engine/Rendering/DrawBloomPass.cpp index 23080a52..1855a653 100644 --- a/src/Engine/Rendering/DrawBloomPass.cpp +++ b/src/Engine/Rendering/DrawBloomPass.cpp @@ -122,7 +122,7 @@ void DrawBloomPass::Draw(GLuint texture) } -void DrawBloomPass::OnWindowRezise() +void DrawBloomPass::OnWindowResize() { 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(); diff --git a/src/Engine/Rendering/Renderer.cpp b/src/Engine/Rendering/Renderer.cpp index d0c06ea0..b8665fce 100644 --- a/src/Engine/Rendering/Renderer.cpp +++ b/src/Engine/Rendering/Renderer.cpp @@ -29,7 +29,7 @@ void Renderer::glfwFrameBufferCallback(GLFWwindow* window, int width, int height currentRenderer->m_DrawFinalPass->OnWindowResize(); currentRenderer->m_LightCullingPass->OnWindowResize(); currentRenderer->m_PickingPass->OnWindowResize(); - currentRenderer->m_DrawBloomPass->OnWindowRezise(); + currentRenderer->m_DrawBloomPass->OnWindowResize(); } void Renderer::InitializeWindow() From 22664848dc44ab481a3dbe601c70132202262edf Mon Sep 17 00:00:00 2001 From: William Moberg Date: Fri, 19 Feb 2016 14:16:22 +0100 Subject: [PATCH 310/355] You should not be able to fall through ground or dash thru walls. Very thin objects may still be possible to go through, e.g. the grid border walls in GameMap.xml. --- include/Engine/Collision/CollisionSystem.h | 4 +- resources/Schema/Components/Physics.xml | 1 + resources/Schema/Components/Physics.xsd | 1 + src/Engine/Collision/Collision.cpp | 2 +- src/Engine/Collision/CollisionSystem.cpp | 59 ++++++++++++++++++++-- 5 files changed, 59 insertions(+), 8 deletions(-) diff --git a/include/Engine/Collision/CollisionSystem.h b/include/Engine/Collision/CollisionSystem.h index c963e6b8..9cd2fe63 100644 --- a/include/Engine/Collision/CollisionSystem.h +++ b/include/Engine/Collision/CollisionSystem.h @@ -15,11 +15,11 @@ class CollisionSystem : public PureSystem public: CollisionSystem(SystemParams params, Octree* octree) : System(params) - , PureSystem("Collidable") + , PureSystem("Physics") , m_Octree(octree) { } - virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) override; + virtual void UpdateComponent(EntityWrapper& entity, ComponentWrapper& cPhysics, double dt) override; private: Octree* m_Octree; diff --git a/resources/Schema/Components/Physics.xml b/resources/Schema/Components/Physics.xml index 6cb73c75..84b6aba3 100644 --- a/resources/Schema/Components/Physics.xml +++ b/resources/Schema/Components/Physics.xml @@ -2,6 +2,7 @@ true + false 0.33 diff --git a/resources/Schema/Components/Physics.xsd b/resources/Schema/Components/Physics.xsd index 7fed1fb5..206e2a23 100644 --- a/resources/Schema/Components/Physics.xsd +++ b/resources/Schema/Components/Physics.xsd @@ -13,6 +13,7 @@ m/s^2 + The largest height of a "stair-step" that can be walked over diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index ab2098b7..3aadf9fe 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -207,7 +207,7 @@ bool RayVsModel(const Ray& ray, glm::vec3 v0 = Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix); glm::vec3 v1 = Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix); glm::vec3 v2 = Transform::TransformPoint(modelVertices[modelIndices[i++]].Position, modelMatrix); - float dist = INFINITY; + float dist = outDistance; float u; float v; if (RayVsTriangle(ray, v0, v1, v2, dist, u, v)) { diff --git a/src/Engine/Collision/CollisionSystem.cpp b/src/Engine/Collision/CollisionSystem.cpp index afd09022..fcc3665f 100644 --- a/src/Engine/Collision/CollisionSystem.cpp +++ b/src/Engine/Collision/CollisionSystem.cpp @@ -3,24 +3,71 @@ #include "Core/AABB.h" #include "Rendering/Model.h" -void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& component, double dt) +void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& cPhysics, double dt) { - if (!entity.HasComponent("Physics")) { + if (!entity.HasComponent("Collidable")) { return; } - ComponentWrapper& cPhysics = entity["Physics"]; - boost::optional boundingBox = Collision::EntityAbsoluteAABB(entity); if (!boundingBox) { return; } ComponentWrapper& cTransform = entity["Transform"]; EntityAABB& boxA = *boundingBox; + bool everHitTheGround = false; + + glm::vec3 size = boxA.Size(); + float diameter = std::min(size.x, size.z); + glm::vec3 prevOrigin = (glm::vec3)cPhysics["PrevOrigin"]; + glm::vec3 toCurrentPos = boxA.Origin() - prevOrigin; + float rayLength = glm::length(toCurrentPos) + 0.5f*diameter; + //If the entity has moved farther than the size of its box, we need to handle it specially. + bool traceCollision = rayLength > diameter; + //hack solution: If prevOrigin is less than -9000 in all dimensions, + //then it means it is not set, i.e. this is the first collision check for the entity. + if (traceCollision && glm::any(glm::greaterThan((glm::vec3)cPhysics["PrevOrigin"], glm::vec3(-9000.f)))) { + Ray ray(prevOrigin, toCurrentPos); + m_OctreeResult.clear(); + m_Octree->ObjectsPossiblyHitByRay(ray, m_OctreeResult); + for (auto& boxB : m_OctreeResult) { + if (boxA.Entity == boxB.Entity) { + continue; + } + bool hit; + float dist; + if (boxB.Entity.HasComponent("Model")) { + RawModel* model; + std::string res = (std::string)boxB.Entity["Model"]["Resource"]; + try { + model = ResourceManager::Load(res); + } catch (const std::exception&) { + continue; + } + float u, v; + hit = Collision::RayVsModel(ray, model->Vertices(), model->m_Indices, Transform::ModelMatrix(boxB.Entity), dist, u, v); + } else { + hit = Collision::RayVsAABB(ray, boxB, dist); + } + if (hit && dist < rayLength) { + //Set the entity to where it was colliding, minus the maximum box size. + //TODO: Perhaps this should be done slightly more properly. + glm::vec3 newOriginPos = ray.Origin() + (dist - 0.707107f*diameter) * ray.Direction(); + glm::vec3 resolve = newOriginPos - boxA.Origin(); + (glm::vec3&)cTransform["Position"] += resolve; + boxA = *Collision::EntityAbsoluteAABB(entity); + if (resolve.y > 0) { + everHitTheGround = true; + (bool)cPhysics["IsOnGround"] = true; + ((glm::vec3&)cPhysics["Velocity"]).y = 0.f; + } + break; + } + } + } // Collide against octree items m_OctreeResult.clear(); m_Octree->ObjectsInSameRegion(*boundingBox, m_OctreeResult); - bool everHitTheGround = false; for (auto& boxB : m_OctreeResult) { glm::vec3 resolutionVector; if (boxA.Entity == boxB.Entity) { @@ -64,4 +111,6 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c if (!everHitTheGround) { (bool)cPhysics["IsOnGround"] = false; } + + (glm::vec3&)cPhysics["PrevOrigin"] = boxA.Origin(); } From 97fcdb342d5fcd51758b3eea3c3ae99debfd2604 Mon Sep 17 00:00:00 2001 From: Tleety Date: Fri, 19 Feb 2016 14:23:40 +0100 Subject: [PATCH 311/355] Bloom should now show behind transparent objects. --- resources/Shaders/ForwardPlus.frag.glsl | 2 +- src/Engine/Rendering/DrawFinalPass.cpp | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/resources/Shaders/ForwardPlus.frag.glsl b/resources/Shaders/ForwardPlus.frag.glsl index 8e248aad..2db0295c 100644 --- a/resources/Shaders/ForwardPlus.frag.glsl +++ b/resources/Shaders/ForwardPlus.frag.glsl @@ -169,7 +169,7 @@ void main() sceneColor = vec4(color_result.xyz, clamp(color_result.a, 0, 1)); color_result += glowTexel*GlowIntensity; - bloomColor = vec4(clamp(color_result.xyz - 1.0, 0, 100), 1.0); + bloomColor = vec4(clamp(color_result.xyz - 1.0, 0, 100), clamp(color_result.a, 0, 1)); //Tiled Debug Code /* diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index d46f9591..1b99955a 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -191,8 +191,10 @@ void DrawFinalPass::Draw(RenderScene& scene) state->StencilMask(0x00); DrawModelRenderQueues(scene.Jobs.OpaqueObjects, scene); GLERROR("OpaqueObjects"); + state->BlendFunc(GL_ONE, GL_ONE); DrawModelRenderQueues(scene.Jobs.TransparentObjects, scene); GLERROR("TransparentObjects"); + state->BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); DrawSprites(scene.Jobs.SpriteJob, scene); GLERROR("SpriteJobs"); From 881ce7b02fc7ed0c67cd84544ea6069437c815d8 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Fri, 19 Feb 2016 14:37:14 +0100 Subject: [PATCH 312/355] Proper string handling without nasty memory leaks. PHEW. --- include/Engine/Core/ComponentInfo.h | 3 +- include/Engine/Core/ComponentWrapper.h | 66 +++++++++++++++++++++- include/Engine/Core/MemoryPool.h | 14 +++-- include/Engine/Core/Util/Any.h | 7 ++- src/Engine/Core/ComponentPool.cpp | 19 +++++-- src/Engine/Core/EntityFilePreprocessor.cpp | 2 +- src/Engine/Core/World.cpp | 13 +++-- src/Tests/WorldTest.cpp | 44 +++++++++++++++ 8 files changed, 144 insertions(+), 24 deletions(-) diff --git a/include/Engine/Core/ComponentInfo.h b/include/Engine/Core/ComponentInfo.h index 3383f297..137a44d8 100644 --- a/include/Engine/Core/ComponentInfo.h +++ b/include/Engine/Core/ComponentInfo.h @@ -2,6 +2,7 @@ #define ComponentInfo_h__ #include "../Common.h" +#include struct ComponentInfo { @@ -29,7 +30,7 @@ struct ComponentInfo std::vector FieldsInOrder; std::vector StringFields; unsigned int Stride = 0; - std::shared_ptr Defaults = nullptr; + boost::shared_array Defaults = nullptr; std::shared_ptr Meta = nullptr; }; diff --git a/include/Engine/Core/ComponentWrapper.h b/include/Engine/Core/ComponentWrapper.h index 3ebad94a..7897e874 100644 --- a/include/Engine/Core/ComponentWrapper.h +++ b/include/Engine/Core/ComponentWrapper.h @@ -2,6 +2,7 @@ #define ComponentWrapper_h__ #include +#include #include "../Common.h" #include "Entity.h" #include "ComponentInfo.h" @@ -75,10 +76,21 @@ struct ComponentWrapper { for (auto& name : component.Info.StringFields) { std::size_t offset = component.Info.Fields.at(name).Offset; - auto& value = *reinterpret_cast(component.Data + offset); + std::string value = *reinterpret_cast(component.Data + offset); new (component.Data + offset) std::string(value); } } + + // This needs to be called to properly free component data, because strings. + static void Destroy(ComponentInfo info, char* data) + { + // Call std::string destructors + for (auto& name : info.StringFields) { + std::size_t offset = info.Fields.at(name).Offset; + auto field = reinterpret_cast(data + offset); + field->~basic_string(); + } + } struct SubscriptProxy { @@ -124,4 +136,56 @@ private: boost::shared_array m_DataReference; }; +// TODO: Move this to Tests once entity importing is finished +class ComponentWrapperFactory +{ +public: + ComponentWrapperFactory() = default; + ComponentWrapperFactory(std::string componentTypeName, unsigned int allocation = 0) + { + m_ComponentInfo.Name = componentTypeName; + m_ComponentInfo.Meta = std::make_shared(); + m_ComponentInfo.Meta->Allocation = allocation; + } + + template + void AddProperty(std::string fieldName, T defaultValue) + { + auto& field = m_ComponentInfo.Fields[fieldName]; + field.Name = fieldName; + field.Type = typeid(T).name(); + field.Offset = m_ComponentInfo.Stride; + field.Stride = sizeof(T); + m_ComponentInfo.FieldsInOrder.push_back(field.Name); + if (field.Type == typeid(std::string).name()) { + field.Type = "string"; + m_ComponentInfo.StringFields.push_back(field.Name); + } + m_ComponentInfo.Stride += sizeof(T); + m_DefaultValues.push_back(std::make_pair(field, defaultValue)); + } + + ComponentInfo& Finalize() + { + m_ComponentInfo.Defaults = boost::shared_array(new char[m_ComponentInfo.Stride]); + std::size_t offset = 0; + for (auto& pair : m_DefaultValues) { + if (pair.first.Type == "string") { + new (m_ComponentInfo.Defaults.get() + offset) std::string(*reinterpret_cast(pair.second.Data.get())); + } else { + memcpy(m_ComponentInfo.Defaults.get() + offset, pair.second.Data.get(), pair.second.Size); + } + offset += pair.second.Size; + } + + return m_ComponentInfo; + } + + operator ComponentInfo&() { return Finalize(); } + +private: + ComponentInfo m_ComponentInfo; + std::vector> m_DefaultValues; +}; + #endif diff --git a/include/Engine/Core/MemoryPool.h b/include/Engine/Core/MemoryPool.h index 0cf7b6bf..053e75aa 100644 --- a/include/Engine/Core/MemoryPool.h +++ b/include/Engine/Core/MemoryPool.h @@ -68,12 +68,13 @@ public: MemoryPool(const MemoryPool& other) : m_StartAddress(new char[other.m_NumSlots*other.m_Stride]) - , m_SlotIsAllocated(other.m_NumSlots, false) + , m_SlotIsAllocated(other.m_SlotIsAllocated) + , m_ExtraMemory() , m_NumSlots(other.m_NumSlots) + , m_LowestAllocatedSlot(other.m_LowestAllocatedSlot) + , m_NumAllocatedSlots(other.m_NumAllocatedSlots) , m_Stride(other.m_Stride) - , m_NumAllocatedSlots(0) - , m_CurrentAllocSlot(0) - , m_LowestAllocatedSlot(m_NumSlots) + , m_CurrentAllocSlot(other.m_CurrentAllocSlot) { // Copy statically allocated pool memcpy(m_StartAddress, other.m_StartAddress, m_NumSlots*m_Stride); @@ -93,8 +94,9 @@ public: delete[] m_StartAddress; m_StartAddress = nullptr; } - for (char* addr : m_ExtraMemory) - free(addr); + for (char* addr : m_ExtraMemory) { + free(addr); + } m_ExtraMemory.clear(); } diff --git a/include/Engine/Core/Util/Any.h b/include/Engine/Core/Util/Any.h index f0f90737..e7b93dfb 100644 --- a/include/Engine/Core/Util/Any.h +++ b/include/Engine/Core/Util/Any.h @@ -2,6 +2,7 @@ #define Util_Any_h__ #include +#include struct Any { @@ -10,7 +11,7 @@ struct Any template Any(const T& value) { - Data = std::shared_ptr(new char[sizeof(T)]); + Data = boost::shared_array(new char[sizeof(T)]); Size = sizeof(T); memcpy(Data.get(), &value, Size); } @@ -18,7 +19,7 @@ struct Any template Any(T&& value) { - Data = std::shared_ptr(new char[sizeof(T)]); + Data = boost::shared_array(new char[sizeof(T)]); Size = sizeof(T); memcpy(Data.get(), &value, Size); } @@ -35,7 +36,7 @@ struct Any return Any(value); } - std::shared_ptr Data = nullptr; + boost::shared_array Data = nullptr; std::size_t Size = 0; }; diff --git a/src/Engine/Core/ComponentPool.cpp b/src/Engine/Core/ComponentPool.cpp index bc4aab7e..059b2e38 100644 --- a/src/Engine/Core/ComponentPool.cpp +++ b/src/Engine/Core/ComponentPool.cpp @@ -32,11 +32,19 @@ ComponentPoolForwardIterator& ComponentPoolForwardIterator::operator++() ComponentPool::ComponentPool(const ComponentPool& other) : m_ComponentInfo(other.m_ComponentInfo) - , m_Pool(other.m_Pool) + , m_Pool(other.m_Pool) + , m_EntityToComponent() { + // Update EntityToComponent pointers + for (char& ptr : m_Pool) { + EntityID entity = *reinterpret_cast(&ptr); + m_EntityToComponent[entity] = &ptr; + } + // Duplicate strings for (auto& name : m_ComponentInfo.StringFields) { for (auto& c : *this) { + std::string& val = c[name]; ComponentWrapper::SolidifyStrings(c); } } @@ -44,11 +52,9 @@ ComponentPool::ComponentPool(const ComponentPool& other) ComponentPool::~ComponentPool() { - // Call std::string destructors - for (auto& name : m_ComponentInfo.StringFields) { - for (auto& c : *this) { - c.Field(name).~basic_string(); - } + // Destroy component data + for (auto& c : *this) { + ComponentWrapper::Destroy(c.Info, c.Data); } } @@ -86,6 +92,7 @@ bool ComponentPool::KnowsEntity(EntityID ent) void ComponentPool::Delete(ComponentWrapper& wrapper) { + ComponentWrapper::Destroy(wrapper.Info, wrapper.Data); m_EntityToComponent.erase(wrapper.EntityID); m_Pool.Free(wrapper.Data - sizeof(EntityID)); } diff --git a/src/Engine/Core/EntityFilePreprocessor.cpp b/src/Engine/Core/EntityFilePreprocessor.cpp index c3a90c29..592daedb 100644 --- a/src/Engine/Core/EntityFilePreprocessor.cpp +++ b/src/Engine/Core/EntityFilePreprocessor.cpp @@ -204,7 +204,7 @@ void EntityFilePreprocessor::parseDefaults() for (auto& ci : m_ComponentInfo) { // Allocate memory for default values - ci.second.Defaults = std::shared_ptr(new char[ci.second.Stride]); + ci.second.Defaults = boost::shared_array(new char[ci.second.Stride], std::bind(&ComponentWrapper::Destroy, ci.second, std::placeholders::_1)); memset(ci.second.Defaults.get(), 0, ci.second.Stride); std::string componentName = ci.first; diff --git a/src/Engine/Core/World.cpp b/src/Engine/Core/World.cpp index a0223e02..8788a92e 100644 --- a/src/Engine/Core/World.cpp +++ b/src/Engine/Core/World.cpp @@ -11,14 +11,18 @@ World::~World() World::World(const World& other) : m_EventBroker(other.m_EventBroker) + , m_CurrentEntityID(other.m_CurrentEntityID) + , m_EntityParents(other.m_EntityParents) + , m_EntityChildren(other.m_EntityChildren) + , m_EntityNames(other.m_EntityNames) { // Deep copy component pools - for (auto& kv : m_ComponentPools) { + for (auto& kv : other.m_ComponentPools) { m_ComponentPools[kv.first] = new ComponentPool(*kv.second); } } -EntityID World::CreateEntity(EntityID parent /*= 0*/) +EntityID World::CreateEntity(EntityID parent /*= EntityID_Invalid*/) { EntityID newEntity = generateEntityID(); if (newEntity == parent) { @@ -53,11 +57,8 @@ ComponentWrapper World::AttachComponent(EntityID entity, const std::string& comp ComponentPool* pool = m_ComponentPools.at(componentType); const ComponentInfo& ci = pool->ComponentInfo(); - // Allocate space for the component + // Allocate component with default values ComponentWrapper c = pool->Allocate(entity); - // Write default values - memcpy(c.Data, ci.Defaults.get(), ci.Stride); - ComponentWrapper::SolidifyStrings(c); return c; } diff --git a/src/Tests/WorldTest.cpp b/src/Tests/WorldTest.cpp index 03008562..633e617a 100644 --- a/src/Tests/WorldTest.cpp +++ b/src/Tests/WorldTest.cpp @@ -69,3 +69,47 @@ BOOST_AUTO_TEST_CASE(WorldTestMultipleAllocations, * utf::tolerance(0.00001)) i++; } } + +BOOST_AUTO_TEST_CASE(WorldCopy, *utf::tolerance(0.00001)) +{ + World w1; + + // Create a test component + auto testComponent = ComponentWrapperFactory("Test", 2); + testComponent.AddProperty("TestInteger", 1337); + testComponent.AddProperty("TestDouble", 13.37); + testComponent.AddProperty("TestString", std::string("DefaultString")); + testComponent.AddProperty("TestVec3", glm::vec3(1.f, 2.f, 3.f)); + w1.RegisterComponent(testComponent); + + // Create a test entity + EntityID w1_e1 = w1.CreateEntity(); + auto w1_c1 = w1.AttachComponent(w1_e1, "Test"); + + // Create a child + EntityID w1_e2 = w1.CreateEntity(w1_e1); + auto w1_c2 = w1.AttachComponent(w1_e2, "Test"); + w1_c2["TestString"] = "NonDefaultString"; + + // Copy the world! + World w2 = w1; + + // Fetch the components + auto w2_c1 = w2.GetComponent(w1_e1, "Test"); + auto w2_c2 = w2.GetComponent(w1_e2, "Test"); + + // Check that built-in types are copied but don't reside in the same memory + BOOST_CHECK((int)w1_c1["TestInteger"] == (int)w2_c1["TestInteger"]); + BOOST_CHECK(&(int&)w1_c1["TestInteger"] != &(int&)w2_c1["TestInteger"]); + BOOST_CHECK((double)w1_c1["TestDouble"] == (double)w2_c1["TestDouble"]); + BOOST_CHECK(&(int&)w1_c1["TestDouble"] != &(int&)w2_c1["TestDouble"]); + BOOST_CHECK((int)w1_c2["TestInteger"] == (int)w2_c2["TestInteger"]); + BOOST_CHECK(&(int&)w1_c2["TestInteger"] != &(int&)w2_c2["TestInteger"]); + BOOST_CHECK((double)w1_c2["TestDouble"] == (double)w2_c2["TestDouble"]); + BOOST_CHECK(&(int&)w1_c2["TestDouble"] != &(int&)w2_c2["TestDouble"]); + // Check that specially handled strings are fine + BOOST_CHECK((std::string)w1_c1["TestString"] == (std::string)w2_c1["TestString"]); + BOOST_CHECK(&(std::string&)w1_c1["TestString"] != &(std::string&)w2_c1["TestString"]); + BOOST_CHECK((std::string)w1_c2["TestString"] == (std::string)w2_c2["TestString"]); + BOOST_CHECK(&(std::string&)w1_c2["TestString"] != &(std::string&)w2_c2["TestString"]); +} From 2f259c37732ce618de453a050c793c3ebdb21458 Mon Sep 17 00:00:00 2001 From: stiffly Date: Fri, 19 Feb 2016 15:38:09 +0100 Subject: [PATCH 313/355] Added an event to search for servers. Client now broadcasts a serverlistrequest. An active server will then answer the request and send info about the server. The client saves this data to a list and presents it to the user. --- include/Engine/Network/Client.h | 27 ++++++-- include/Engine/Network/ESearchForServers.h | 12 ++++ include/Engine/Network/MessageType.h | 2 +- include/Engine/Network/Server.h | 6 +- include/Engine/Network/TCPServer.h | 9 ++- include/Engine/Network/UDPClient.h | 1 + include/Engine/Network/UDPServer.h | 4 +- src/Engine/Network/Client.cpp | 74 ++++++++++++++++------ src/Engine/Network/Server.cpp | 49 +++++++++----- src/Engine/Network/TCPServer.cpp | 8 ++- src/Engine/Network/UDPClient.cpp | 15 ++++- src/Engine/Network/UDPServer.cpp | 22 +++++++ 12 files changed, 178 insertions(+), 51 deletions(-) create mode 100644 include/Engine/Network/ESearchForServers.h diff --git a/include/Engine/Network/Client.h b/include/Engine/Network/Client.h index 01e18da8..7d23670a 100644 --- a/include/Engine/Network/Client.h +++ b/include/Engine/Network/Client.h @@ -14,7 +14,6 @@ #include "Network/MessageType.h" #include "Network/PlayerDefinition.h" #include "Network/UDPClient.h" -#include "Network/UDPServer.h" //LOL #include "Network/TCPClient.h" #include "Network/SnapshotDefinitions.h" #include "Core/World.h" @@ -25,6 +24,19 @@ #include "Network/EInterpolate.h" #include "Network/SnapshotFilter.h" #include "Core/EPlayerSpawned.h" +#include "Network/ESearchForServers.h" + +struct ServerInfo +{ + ServerInfo(std::string a, int b, std::string c, int d) + { + Address = a; Port = b; Name = c; PlayersConnected = d; + } + std::string Address = ""; + int Port = 0; + std::string Name = ""; + int PlayersConnected = 0; +}; class Client : public Network { @@ -83,10 +95,11 @@ public: void parseTCPConnect(Packet& packet); void parsePlayerConnected(Packet& packet); void parsePing(); - void parseHeartbeat(Packet& packet, PlayerDefinition); + void parseServerlist(Packet& packet); void parseKick(); void parsePlayersSpawned(Packet& packet); void parseEntityDeletion(Packet& packet); + void parsePlayerDamage(Packet& packet); void parseComponentDeletion(Packet& packet); void InterpolateFields(Packet & packet, const ComponentInfo & componentInfo, const EntityID & entityID, const std::string & componentType); void parseSnapshot(Packet& packet); @@ -96,6 +109,7 @@ public: void sendInputCommands(); void sendLocalPlayerTransform(); void becomePlayer(); + void displayServerlist(); // Mapping Logic // Returns if local EntityID exist in map bool clientServerMapsHasEntity(EntityID clientEntityID); @@ -111,11 +125,16 @@ public: bool OnPlayerDamage(const Events::PlayerDamage& e); EventRelay m_EPlayerSpawned; bool OnPlayerSpawned(const Events::PlayerSpawned& e); - void parsePlayerDamage(Packet& packet); + EventRelay< Client, Events::SearchForServers> m_ESearchForServers; + bool OnSearchForServers(const Events::SearchForServers& e); private: UDPClient m_Unreliable; - UDPServer m_Heartbeat; + UDPClient m_ServerlistRequest; TCPClient m_Reliable; + std::vector m_Serverlist; + bool m_SearchingForServers = false; + std::clock_t m_StartSearchTime; + double m_SearchingTime = 2000; // Config I guess }; #endif diff --git a/include/Engine/Network/ESearchForServers.h b/include/Engine/Network/ESearchForServers.h new file mode 100644 index 00000000..1b08a8f3 --- /dev/null +++ b/include/Engine/Network/ESearchForServers.h @@ -0,0 +1,12 @@ +#ifndef Events_SearchForServers_h__ +#define Events_SearchForServers_h__ + +#include "Core/Event.h" + +namespace Events +{ + +struct SearchForServers : public Event { }; + +} +#endif diff --git a/include/Engine/Network/MessageType.h b/include/Engine/Network/MessageType.h index 2b3b02c0..93695063 100644 --- a/include/Engine/Network/MessageType.h +++ b/include/Engine/Network/MessageType.h @@ -19,7 +19,7 @@ enum class MessageType EntityDeleted, ComponentDeleted, PlayerTransform, - Heartbeat, + ServerlistRequest, Invalid }; diff --git a/include/Engine/Network/Server.h b/include/Engine/Network/Server.h index 0a2cb029..982df3b1 100644 --- a/include/Engine/Network/Server.h +++ b/include/Engine/Network/Server.h @@ -33,7 +33,7 @@ private: // Network channels TCPServer m_Reliable; UDPServer m_Unreliable; - UDPClient m_Heartbeat; + UDPServer m_ServerlistRequest; // dont forget to set these in the childrens receive logic boost::asio::ip::address m_Address; int m_Port = 27666; @@ -46,13 +46,11 @@ private: // time for previouse message std::clock_t previousePingMessage = std::clock(); std::clock_t previousSnapshotMessage = std::clock(); - std::clock_t previousHeartbeat = std::clock(); std::clock_t timOutTimer = std::clock(); // How often we send messages (milliseconds) float pingIntervalMs; float snapshotInterval; - float heartbeatInterval = 5000; int checkTimeOutInterval = 100; int m_NextPlayerID = 0; std::vector m_InputCommandsToBroadcast; @@ -71,7 +69,6 @@ private: void addChildrenToPacket(Packet& packet, EntityID entityID); void addInputCommandsToPacket(Packet& packet); void sendPing(); - void sendHeartBeat(); void checkForTimeOuts(); void disconnect(PlayerID playerID); void parseMessageType(Packet& packet); @@ -86,6 +83,7 @@ private: void parseUDPConnect(Packet & packet); void parseTCPConnect(Packet & packet); void parseDisconnect(); + void parseServerlistRequest(boost::asio::ip::udp::endpoint endpoint); bool shouldSendToClient(EntityWrapper childEntity); // Debug event diff --git a/include/Engine/Network/TCPServer.h b/include/Engine/Network/TCPServer.h index 424599c9..1140579a 100644 --- a/include/Engine/Network/TCPServer.h +++ b/include/Engine/Network/TCPServer.h @@ -16,8 +16,9 @@ public: void Send(Packet & packet, PlayerDefinition & playerDefinition); void Send(Packet & packet); void Disconnect(); - int Port() { return acceptor->local_endpoint().port(); } - std::string Address(); + int Port() { return m_Port; } + std::string Address() { return m_Address; } + private: // TCP logic boost::asio::io_service m_IOService; @@ -28,6 +29,10 @@ private: int& nextPlayerID, std::map& connectedPlayers, const boost::system::error_code& error); int readBuffer(char* data, PlayerDefinition& playerDefinition); + int GetPort(); + std::string GetAddress(); + int m_Port = 0; + std::string m_Address = ""; }; #endif \ No newline at end of file diff --git a/include/Engine/Network/UDPClient.h b/include/Engine/Network/UDPClient.h index 3a458d3e..f986dd08 100644 --- a/include/Engine/Network/UDPClient.h +++ b/include/Engine/Network/UDPClient.h @@ -14,6 +14,7 @@ public: void Disconnect(); void Receive(Packet& packet); void Send(Packet & packet); + void Broadcast(Packet& packet, int port); bool IsSocketAvailable(); private: // Assio UDP logic diff --git a/include/Engine/Network/UDPServer.h b/include/Engine/Network/UDPServer.h index 6ba7cd96..15dd977c 100644 --- a/include/Engine/Network/UDPServer.h +++ b/include/Engine/Network/UDPServer.h @@ -13,7 +13,9 @@ public: void AcceptNewConnections(int& nextPlayerID, std::map& connectedPlayers); void Receive(Packet & packet, PlayerDefinition & playerDefinition); void Send(Packet & packet, PlayerDefinition & playerDefinition); - void Send(Packet & packet); + void Send(Packet & packet); + void Send(Packet & packet, boost::asio::ip::udp::endpoint endpoint); + void Broadcast(Packet & packet, int port); bool IsSocketAvailable(); private: // UDP logic diff --git a/src/Engine/Network/Client.cpp b/src/Engine/Network/Client.cpp index a9a67bae..5207eaac 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -1,9 +1,8 @@ #include "Network/Client.h" using namespace boost::asio::ip; -Client::Client(World* world, EventBroker* eventBroker) +Client::Client(World* world, EventBroker* eventBroker) : Network(world, eventBroker) - , m_Heartbeat(13) { // Asumes root node is EntityID_Invalid insertIntoServerClientMaps(EntityID_Invalid, EntityID_Invalid); @@ -14,6 +13,8 @@ Client::Client(World* world, EventBroker* eventBroker) m_PlayerName = config->Get("Networking.Name", "Raptorcopter"); m_SendInputIntervalMs = config->Get("Networking.SendInputIntervalMs", 33); LOG_INFO("Client initialized"); + + m_ServerlistRequest.Connect(m_PlayerName, "192.168.1.51", 32554); } Client::Client(World* world, EventBroker* eventBroker, std::unique_ptr snapshotFilter) @@ -31,6 +32,7 @@ void Client::Connect(std::string address, int port) EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &Client::OnInputCommand); EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &Client::OnPlayerDamage); EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &Client::OnPlayerSpawned); + EVENT_SUBSCRIBE_MEMBER(m_ESearchForServers, &Client::OnSearchForServers); auto config = ResourceManager::Load("Config.ini"); m_Address = address; if (address.empty()) { @@ -66,15 +68,22 @@ void Client::Update() } } - while (m_Heartbeat.IsSocketAvailable()) { + + while (m_ServerlistRequest.IsSocketAvailable()) { Packet packet(MessageType::Invalid); - PlayerDefinition localArea; - localArea.Endpoint = boost::asio::ip::udp::endpoint(boost::asio::ip::address().from_string("127.0.0.1"), 13); - m_Heartbeat.Receive(packet, localArea); - if(packet.GetMessageType() == MessageType::Heartbeat) { - parseHeartbeat(packet, localArea); + m_ServerlistRequest.Receive(packet); + if (packet.GetMessageType() == MessageType::ServerlistRequest) { + parseServerlist(packet); } } + + if (m_SearchingForServers) { + if (m_SearchingTime < (1000* (std::clock() - m_StartSearchTime) / (double)CLOCKS_PER_SEC)) { + m_SearchingForServers = false; + displayServerlist(); + } + } + if (m_IsConnected) { // Don't send 1 input in 1 packet, bunch em up. if (m_SendInputIntervalMs < (1000 * (std::clock() - m_TimeSinceSentInputs) / (double)CLOCKS_PER_SEC)) { @@ -183,20 +192,18 @@ void Client::parsePing() } -void Client::parseHeartbeat(Packet& packet, PlayerDefinition pd) +void Client::parseServerlist(Packet& packet) { // Pop size, message type, and ID packet.ReadPrimitive(); packet.ReadPrimitive(); packet.ReadPrimitive(); - std::string serverName = packet.ReadString(); - int playersConnected = packet.ReadPrimitive(); std::string address = packet.ReadString(); int port = packet.ReadPrimitive(); - //TODO: save these to some kind of list which can be represented to the player + std::string serverName = packet.ReadString(); + int playersConnected = packet.ReadPrimitive(); //TODO: This should not happen when a client is connected to a server - - LOG_INFO("Serverlist\nName\tPlayers\tIP\t\tPort\n%s\t%i\t%s\t%i\n", serverName.c_str(), playersConnected, address, port); + m_Serverlist.push_back({ address, port, serverName, playersConnected }); } void Client::parseKick() @@ -216,12 +223,12 @@ void Client::parseSpawnEvents() } e.Player = EntityWrapper(m_World, m_ServerIDToClientID.at(m_PlayerSpawnEvents.at(i).Player.ID)); //e.Spawner = EntityWrapper(m_World, m_ServerIDToClientID.at(m_PlayerSpawnEvents.at(i).Spawner.ID)); - e.PlayerID = -1; + e.PlayerID = -1; e.PlayerName = m_PlayerSpawnEvents.at(i).PlayerName; m_EventBroker->Publish(e); } m_PlayerSpawnEvents = tempSpawn; - // m_PlayerSpawnEvents.clear(); + // m_PlayerSpawnEvents.clear(); } void Client::parsePlayersSpawned(Packet& packet) @@ -338,7 +345,7 @@ void Client::parseSnapshot(Packet& packet) if (serverClientMapsHasEntity(serverEntityID)) { EntityID localEntityID = m_ServerIDToClientID.at(serverEntityID); EntityWrapper localEntity(m_World, localEntityID); - + // Update entity if (m_World->HasComponent(localEntityID, componentType)) { SharedComponentWrapper newComponent = createSharedComponent(packet, localEntityID, componentInfo); @@ -397,6 +404,12 @@ void Client::disconnect() bool Client::OnInputCommand(const Events::InputCommand & e) { + // TEMP + if (e.Command == "SearchForServers" && e.Value > 0) { + Events::SearchForServers e; + m_EventBroker->Publish(e); + } + if (e.PlayerID != -1) { return false; } @@ -459,12 +472,23 @@ bool Client::OnPlayerSpawned(const Events::PlayerSpawned& e) return true; } +bool Client::OnSearchForServers(const Events::SearchForServers& e) +{ + m_SearchingForServers = true; + m_StartSearchTime = std::clock(); + m_Serverlist.clear(); + LOG_INFO("Searching for LAN servers...\n"); + Packet packet(MessageType::ServerlistRequest); + m_ServerlistRequest.Broadcast(packet, 13); // TODO: Config + return true; +} + void Client::parsePlayerDamage(Packet& packet) { Events::PlayerDamage e; PlayerID victimID = packet.ReadPrimitive(); PlayerID inflictorID = packet.ReadPrimitive(); - if(!serverClientMapsHasEntity(victimID) || !serverClientMapsHasEntity(inflictorID)){ + if (!serverClientMapsHasEntity(victimID) || !serverClientMapsHasEntity(inflictorID)) { return; } e.Inflictor = EntityWrapper(m_World, m_ServerIDToClientID.at(victimID)); @@ -493,7 +517,7 @@ void Client::sendLocalPlayerTransform() packet.WritePrimitive(orientation.x); packet.WritePrimitive(orientation.y); packet.WritePrimitive(orientation.z); - + bool hasAssaultWeapon = m_LocalPlayer.HasComponent("AssaultWeapon"); packet.WritePrimitive(hasAssaultWeapon); if (hasAssaultWeapon) { @@ -501,7 +525,7 @@ void Client::sendLocalPlayerTransform() packet.WritePrimitive((int)cAssaultWeapon["MagazineAmmo"]); packet.WritePrimitive((int)cAssaultWeapon["Ammo"]); } - + m_Unreliable.Send(packet); } @@ -554,6 +578,16 @@ void Client::becomePlayer() m_Reliable.Send(packet); } + +void Client::displayServerlist() +{ + LOG_INFO("This is a serverlist:\n"); + for (int i = 0; i < m_Serverlist.size(); i++) { + ServerInfo si = m_Serverlist[i]; + LOG_INFO("%s:%i\t%s\t%i\n", si.Address, si.Port, si.Name, si.PlayersConnected); + } +} + bool Client::clientServerMapsHasEntity(EntityID clientEntityID) { if (m_ClientIDToServerID.find(clientEntityID) != m_ClientIDToServerID.end()) { diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index 8dd398bd..0bed0b62 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -2,6 +2,7 @@ Server::Server(World* world, EventBroker* eventBroker, int port) : Network(world, eventBroker) + , m_ServerlistRequest(13) { ConfigFile* config = ResourceManager::Load("Config.ini"); snapshotInterval = 1000 * config->Get("Networking.SnapshotInterval", 0.05f); @@ -19,7 +20,6 @@ Server::Server(World* world, EventBroker* eventBroker, int port) } m_Port = port; LOG_INFO("Server initialized and bound to port %i", port); - m_Heartbeat.Connect("Server", "127.0.0.1", 13); } Server::~Server() @@ -60,8 +60,23 @@ void Server::Update() } } + while (m_ServerlistRequest.IsSocketAvailable()) { + Packet packet(MessageType::Invalid); + PlayerDefinition localArea; + localArea.Endpoint = boost::asio::ip::udp::endpoint(); + m_ServerlistRequest.Receive(packet, localArea); + if(packet.GetMessageType() == MessageType::ServerlistRequest) { + packet.ReadPrimitive(); // Pop size + packet.ReadPrimitive(); // Pop MsgType + packet.ReadPrimitive(); // Pop packet ID + int port = packet.ReadPrimitive(); + std::string address = localArea.Endpoint.address().to_string(); + parseServerlistRequest(boost::asio::ip::udp::endpoint(boost::asio::ip::address().from_string(address), port)); + } + } + // Check if players have disconnected - for (int i = 0; i < m_PlayersToDisconnect.size(); i++) { + for (int i = 0; i < m_PlayersToDisconnect.size(); i++) { disconnect(m_PlayersToDisconnect.at(i)); } m_PlayersToDisconnect.clear(); @@ -77,11 +92,7 @@ void Server::Update() sendPing(); previousePingMessage = currentTime; } - // Server heartbeat (display server list on clients) - if (heartbeatInterval < (1000 * (currentTime - previousHeartbeat) / (double)CLOCKS_PER_SEC)) { - sendHeartBeat(); - previousHeartbeat = currentTime; - } + // Time out logic if (checkTimeOutInterval < (1000 * (currentTime - timOutTimer) / (double)CLOCKS_PER_SEC)) { checkForTimeOuts(); @@ -238,15 +249,6 @@ void Server::sendPing() } -void Server::sendHeartBeat() -{ - Packet packet(MessageType::Heartbeat); - packet.WriteString("Bob"); // server name - packet.WritePrimitive(m_ConnectedPlayers.size()); - packet.WriteString(m_Reliable.Address()); - packet.WritePrimitive(m_Reliable.Port()); - m_Heartbeat.Send(packet); -} void Server::checkForTimeOuts() { @@ -340,6 +342,20 @@ void Server::parseDisconnect() } } + +void Server::parseServerlistRequest(boost::asio::ip::udp::endpoint endpoint) +{ + Packet packet(MessageType::ServerlistRequest); + packet.WriteString(m_Reliable.Address()); + packet.WritePrimitive(m_Reliable.Port()); + packet.WriteString("SERVERNAME"); + packet.WritePrimitive(m_ConnectedPlayers.size()); + //PlayerDefinition pDef; + //pDef.Endpoint = boost::asio::ip::udp::endpoint(endpoint.address(), 13); + + m_ServerlistRequest.Send(packet/*, endpoint*/); +} + void Server::disconnect(PlayerID playerID) { //broadcast("A player disconnected"); @@ -364,6 +380,7 @@ void Server::parseOnPlayerDamage(Packet & packet) e.Victim = EntityWrapper(m_World, packet.ReadPrimitive()); e.Damage = packet.ReadPrimitive(); m_EventBroker->Publish(e); + //LOG_DEBUG("Server::parseOnPlayerDamage: Command is %s. Value is %f. PlayerID is %i.", e.DamageAmount, e.PlayerDamagedID, e.TypeOfDamage.c_str()); } diff --git a/src/Engine/Network/TCPServer.cpp b/src/Engine/Network/TCPServer.cpp index a55eee98..452efa62 100644 --- a/src/Engine/Network/TCPServer.cpp +++ b/src/Engine/Network/TCPServer.cpp @@ -4,6 +4,8 @@ using namespace boost::asio::ip; TCPServer::TCPServer() { acceptor = std::unique_ptr(new tcp::acceptor(m_IOService, tcp::endpoint(tcp::v4(), 27666))); + m_Port = GetPort(); + m_Address = GetAddress(); } TCPServer::~TCPServer() @@ -76,8 +78,12 @@ void TCPServer::Disconnect() { } +int TCPServer::GetPort() +{ + return acceptor->local_endpoint().port(); +} -std::string TCPServer::Address() +std::string TCPServer::GetAddress() { boost::asio::ip::tcp::resolver resolver(m_IOService); boost::asio::ip::tcp::resolver::query query(boost::asio::ip::tcp::v4(), boost::asio::ip::host_name(), ""); diff --git a/src/Engine/Network/UDPClient.cpp b/src/Engine/Network/UDPClient.cpp index c76de084..68aebb03 100644 --- a/src/Engine/Network/UDPClient.cpp +++ b/src/Engine/Network/UDPClient.cpp @@ -15,9 +15,9 @@ void UDPClient::Connect(std::string playerName, std::string address, int port) if (m_Socket) { return; } - m_ReceiverEndpoint = udp::endpoint(boost::asio::ip::address::from_string(address), port); + m_ReceiverEndpoint = udp::endpoint(boost::asio::ip::address().from_string(address), port); m_Socket = boost::shared_ptr(new boost::asio::ip::udp::socket(m_IOService)); - m_Socket->connect(m_ReceiverEndpoint); + m_Socket->open(boost::asio::ip::udp::v4()); } void UDPClient::Disconnect() @@ -55,6 +55,17 @@ void UDPClient::Send(Packet& packet) packet.Data(), packet.Size()), m_ReceiverEndpoint, 0); +} + +void UDPClient::Broadcast(Packet& packet, int port) +{ + m_Socket->set_option(boost::asio::socket_base::broadcast(true)); + m_Socket->send_to(boost::asio::buffer( + packet.Data(), + packet.Size()), + udp::endpoint(boost::asio::ip::address_v4().broadcast(), port) + , 0); + m_Socket->set_option(boost::asio::socket_base::broadcast(false)); } bool UDPClient::IsSocketAvailable() diff --git a/src/Engine/Network/UDPServer.cpp b/src/Engine/Network/UDPServer.cpp index b4046003..f751d369 100644 --- a/src/Engine/Network/UDPServer.cpp +++ b/src/Engine/Network/UDPServer.cpp @@ -36,7 +36,29 @@ void UDPServer::Send(Packet & packet) 0); } +// Broadcasting respond specific logic +void UDPServer::Send(Packet & packet, boost::asio::ip::udp::endpoint endpoint) +{ + m_Socket->send_to( + boost::asio::buffer( + packet.Data(), + packet.Size()), + endpoint, + 0); +} +// Broadcasting +void UDPServer::Broadcast(Packet & packet, int port) +{ + m_Socket->set_option(boost::asio::socket_base::broadcast(true)); + m_Socket->send_to( + boost::asio::buffer( + packet.Data(), + packet.Size()), + boost::asio::ip::udp::endpoint(boost::asio::ip::address_v4().broadcast(),port), + 0); + m_Socket->set_option(boost::asio::socket_base::broadcast(false)); +} void UDPServer::Receive(Packet & packet, PlayerDefinition & playerDefinition) { From 2263fd2ad66d546874e3ac1faf3045974162d4ec Mon Sep 17 00:00:00 2001 From: Jocke Date: Fri, 19 Feb 2016 16:18:16 +0100 Subject: [PATCH 314/355] Fixed crash in Client::parsePlayerDamage. --- src/Engine/Network/Client.cpp | 5 +++-- src/Engine/Network/Server.cpp | 1 - 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Engine/Network/Client.cpp b/src/Engine/Network/Client.cpp index 3406535a..a2f52adb 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -437,11 +437,12 @@ void Client::parsePlayerDamage(Packet& packet) { Events::PlayerDamage e; PlayerID victimID = packet.ReadPrimitive(); - if(serverClientMapsHasEntity(victimID)){ + PlayerID inflictorID = packet.ReadPrimitive(); + if(!serverClientMapsHasEntity(victimID) || !serverClientMapsHasEntity(inflictorID)){ return; } e.Inflictor = EntityWrapper(m_World, m_ServerIDToClientID.at(victimID)); - e.Victim = EntityWrapper(m_World, m_ServerIDToClientID.at(packet.ReadPrimitive())); + e.Victim = EntityWrapper(m_World, m_ServerIDToClientID.at(inflictorID)); e.Damage = packet.ReadPrimitive(); // Don't rebroadcast our own player damage events or we'll have an infinite loop! if (e.Inflictor != m_LocalPlayer) { diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index 082849c7..aa66433b 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -84,7 +84,6 @@ void Server::Update() if (isReadingData) { Network::Update(); } - } void Server::parseMessageType(Packet& packet) From 68f2d5327d10338fac0a957e806853dc6ea05570 Mon Sep 17 00:00:00 2001 From: Jocke Date: Fri, 19 Feb 2016 16:37:26 +0100 Subject: [PATCH 315/355] added extra check in HealthSystem --- src/Game/Systems/HealthSystem.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Game/Systems/HealthSystem.cpp b/src/Game/Systems/HealthSystem.cpp index 7f5089c4..94f23c67 100644 --- a/src/Game/Systems/HealthSystem.cpp +++ b/src/Game/Systems/HealthSystem.cpp @@ -24,7 +24,7 @@ void HealthSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& cHea bool HealthSystem::OnPlayerDamaged(Events::PlayerDamage& e) { - if (!IsServer && m_NetworkEnabled) { + if (!IsServer && m_NetworkEnabled || !e.Victim.Valid()) { return false; } From 201480b17f6d72b0ee082916e577cea34defa9f2 Mon Sep 17 00:00:00 2001 From: Teejoon Date: Fri, 19 Feb 2016 16:50:04 +0100 Subject: [PATCH 316/355] SSAO is working, but is kinda crappy. You can change shade variables in the debug window. --- .../Rendering/DrawColorCorrectionPass.h | 2 +- include/Engine/Rendering/DrawFinalPass.h | 4 + include/Engine/Rendering/Renderer.h | 5 + include/Engine/Rendering/SSAOPass.h | 58 ++++++++ include/Engine/Rendering/SSAOPassState.h | 15 ++ .../Shaders/DrawColorCorrection.frag.glsl | 7 +- resources/Shaders/SSAO.frag.glsl | 106 ++++++++++++++ resources/Shaders/SSAO.vert.glsl | 8 ++ resources/Shaders/SSAOViewSpaceZ.frag.glsl | 14 ++ src/Engine/Rendering/DrawBloomPass.cpp | 34 +++-- .../Rendering/DrawColorCorrectionPass.cpp | 4 +- src/Engine/Rendering/DrawFinalPass.cpp | 56 +++++--- src/Engine/Rendering/Renderer.cpp | 15 +- src/Engine/Rendering/SSAOPass.cpp | 135 ++++++++++++++++++ src/Engine/Rendering/SSAOPassState.cpp | 16 +++ src/Engine/Rendering/ShaderProgram.cpp | 3 +- 16 files changed, 444 insertions(+), 38 deletions(-) create mode 100644 include/Engine/Rendering/SSAOPass.h create mode 100644 include/Engine/Rendering/SSAOPassState.h create mode 100644 resources/Shaders/SSAO.frag.glsl create mode 100644 resources/Shaders/SSAO.vert.glsl create mode 100644 resources/Shaders/SSAOViewSpaceZ.frag.glsl create mode 100644 src/Engine/Rendering/SSAOPass.cpp create mode 100644 src/Engine/Rendering/SSAOPassState.cpp diff --git a/include/Engine/Rendering/DrawColorCorrectionPass.h b/include/Engine/Rendering/DrawColorCorrectionPass.h index 231e2d33..db16cf98 100644 --- a/include/Engine/Rendering/DrawColorCorrectionPass.h +++ b/include/Engine/Rendering/DrawColorCorrectionPass.h @@ -17,7 +17,7 @@ public: void InitializeFrameBuffers(); void InitializeShaderPrograms(); - void Draw(GLuint sceneTexture, GLuint bloomTexture, GLuint sceneTextureLowRes, GLuint bloomTextureLowRes, GLfloat gamma, GLfloat exposure); + void Draw(GLuint sceneTexture, GLuint bloomTexture, GLuint sceneTextureLowRes, GLuint bloomTextureLowRes, GLuint SSAOTexture, GLfloat gamma, GLfloat exposure); private: const IRenderer* m_Renderer; diff --git a/include/Engine/Rendering/DrawFinalPass.h b/include/Engine/Rendering/DrawFinalPass.h index bf8d4d76..f1cf66c8 100644 --- a/include/Engine/Rendering/DrawFinalPass.h +++ b/include/Engine/Rendering/DrawFinalPass.h @@ -21,6 +21,9 @@ public: void Draw(RenderScene& scene); void ClearBuffer(); + //Return the texture that is used in later stages to apply the bloom effect + GLuint DepthBuffer() const { return m_DepthBuffer; } + Camera* DepthBufferCamera() const { return RenderCamera; } //Return the texture that is used in later stages to apply the bloom effect GLuint BloomTexture() const { return m_BloomTexture; } GLuint BloomTextureLowRes() const { return m_BloomTextureLowRes; } @@ -62,6 +65,7 @@ private: GLuint m_SceneTextureLowRes; GLuint m_DepthBuffer; GLuint m_DepthBufferLowRes; + Camera* RenderCamera; //maqke this component based i guess? GLuint m_ShieldPixelRate = 16; diff --git a/include/Engine/Rendering/Renderer.h b/include/Engine/Rendering/Renderer.h index 04754514..b613ba4f 100644 --- a/include/Engine/Rendering/Renderer.h +++ b/include/Engine/Rendering/Renderer.h @@ -16,6 +16,7 @@ #include "DrawScreenQuadPass.h" #include "DrawBloomPass.h" #include "DrawColorCorrectionPass.h" +#include "SSAOPass.h" #include "../Core/EventBroker.h" #include "ImGuiRenderPass.h" #include "Camera.h" @@ -50,6 +51,9 @@ private: Model* m_UnitSphere; int m_DebugTextureToDraw = 0; + float m_SSAO_Radius = 0.2f; + float m_SSAO_Bias = 0.012f; + float m_SSAO_Intensity = 1.0f; PickingPass* m_PickingPass; LightCullingPass* m_LightCullingPass; @@ -58,6 +62,7 @@ private: DrawScreenQuadPass* m_DrawScreenQuadPass; DrawBloomPass* m_DrawBloomPass; DrawColorCorrectionPass* m_DrawColorCorrectionPass; + SSAOPass* m_SSAOPass; //----------------------Functions----------------------// void InitializeWindow(); diff --git a/include/Engine/Rendering/SSAOPass.h b/include/Engine/Rendering/SSAOPass.h new file mode 100644 index 00000000..22f53ded --- /dev/null +++ b/include/Engine/Rendering/SSAOPass.h @@ -0,0 +1,58 @@ +#ifndef SSAOPass_h__ +#define SSAOPass_h__ + +#include "IRenderer.h" +#include "SSAOPassState.h" +//#include "LightCullingPass.h" Finalpass om den skall skickas in +#include "FrameBuffer.h" +#include "ShaderProgram.h" +#include "DrawBloomPass.h" +//#include "Util/UnorderedMapVec2.h" +#include "Texture.h" + +class SSAOPass +{ +public: + SSAOPass(IRenderer* rendere); + ~SSAOPass() { }; + + void Draw(GLuint depthBuffer, Camera* camera); + void Setting(float radius, float bias, float intensity); + void ClearBuffer(); + + //Return the SSAO of the texture sent to Draw + GLuint SSAOTexture() const { return m_DrawBloomPass->GaussianTexture(); } + +private: + void InitializeTexture(); + void InitializeFrameBuffer(); + void InitializeShaderProgram(); + void InitializeBuffer(); + + void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const; + + void ComputeAO(GLuint depthBuffer, Camera* camera); + //void blurHorizontal(GLuint depthBuffer); + //void blurVertical(GLuint depthBuffer); + + Model* m_ScreenQuad; + + const IRenderer* m_Renderer; + + float m_Radius; + float m_Bias; + float m_Intensity; + + GLuint m_SSAOTexture; + FrameBuffer m_SSAOFramBuffer; + + GLuint m_SSAOViewSpaceZTexture; + FrameBuffer m_SSAOViewSpaceZFramBuffer; + + ShaderProgram* m_SSAOProgram; + ShaderProgram* m_SSAOViewSpaceZProgram; + + DrawBloomPass* m_DrawBloomPass; +}; + +#endif \ No newline at end of file diff --git a/include/Engine/Rendering/SSAOPassState.h b/include/Engine/Rendering/SSAOPassState.h new file mode 100644 index 00000000..115fdcf7 --- /dev/null +++ b/include/Engine/Rendering/SSAOPassState.h @@ -0,0 +1,15 @@ +#ifndef SSAOPassState_h__ +#define SSAOPassState_h__ + +#include "Rendering/RenderState.h" + +class SSAOPassState : public RenderState +{ +public: + SSAOPassState(); + ~SSAOPassState(); +private: + +}; + +#endif \ No newline at end of file diff --git a/resources/Shaders/DrawColorCorrection.frag.glsl b/resources/Shaders/DrawColorCorrection.frag.glsl index 76db3e82..838a78f6 100644 --- a/resources/Shaders/DrawColorCorrection.frag.glsl +++ b/resources/Shaders/DrawColorCorrection.frag.glsl @@ -4,6 +4,7 @@ layout (binding = 0) uniform sampler2D SceneTexture; layout (binding = 1) uniform sampler2D BloomTexture; layout (binding = 2) uniform sampler2D SceneTextureLowRes; layout (binding = 3) uniform sampler2D BloomTextureLowRes; +layout (binding = 4) uniform sampler2D SSAOTexture; uniform float Exposure; uniform float Gamma; @@ -19,6 +20,10 @@ void main() vec4 bloomColor = texture(BloomTexture, Input.TextureCoordinate); vec4 hdrColorLowRes = texture(SceneTextureLowRes, Input.TextureCoordinate); vec4 bloomColorLowRes = texture(BloomTextureLowRes, Input.TextureCoordinate); + vec4 SSAO = texture(SSAOTexture, Input.TextureCoordinate); + + //hdrColor = hdrColor * SSAO; + SSAO = clamp(SSAO, 0.1f, 1.0f); hdrColor += bloomColor; hdrColorLowRes; @@ -33,7 +38,7 @@ void main() //gamme correction result = pow(result, vec3(1.0 / Gamma)); - + result = result * SSAO.rgb; fragmentColor = vec4(result, 1.0); //fragmentColor = hdrColor; //fragmentColor = bloomColor; diff --git a/resources/Shaders/SSAO.frag.glsl b/resources/Shaders/SSAO.frag.glsl new file mode 100644 index 00000000..b9ba58ce --- /dev/null +++ b/resources/Shaders/SSAO.frag.glsl @@ -0,0 +1,106 @@ +#version 430 + +//Number of samples per pixel +#define NUM_SAMPLES (24) + +//Number of turns around the cirle +#define NUM_TURNS (7) + +uniform sampler2D ViewSpaceZ; + +uniform vec4 ProjInfo; + +uniform float ProjScale; +//#define ProjScale 500 + +uniform float Radius; +//#define Radius 1.0f + +uniform float Bias; +//#define Bias 0.012f + +uniform float IntensityDivR6; +//#define IntensityDivR6 1 + +out vec4 fragmentColor; + +vec3 reconstructVSPosition(vec2 ScreenSpaceCoord, float z){ + return vec3((ScreenSpaceCoord * ProjInfo.xy + ProjInfo.zw) * z, z); +} + +vec3 getPosition(ivec2 ScreenSpaceCoord) { + vec3 P; + P.z = texelFetch(ViewSpaceZ, ScreenSpaceCoord, 0).r; + //Get the xy view space coordinates and add the z value from ViewSpaceZ buffer. + return reconstructVSPosition(vec2(ScreenSpaceCoord) + vec2(0.5), P.z); +} + +vec3 getVSFaceNormal(vec3 ViewSpacePosition) { + // Get tangets vector for the plane and ViewSpacePositin... don't ask how this functions works. It's pure magic. + // They do this and it just works... I would guess that they approximate the function of a plane from pixels close to the pixel were on now. + return normalize(cross(dFdx(ViewSpacePosition), dFdy(ViewSpacePosition))); +} + + +vec3 getSampleViewSpacePos(ivec2 ScreenSpaceCoord, int SampleIndex, float RotationAngle, float ScreenSpaceSampleRadius){ + // Pure Magic... + float alpha = float(SampleIndex + 0.5) * (1.0 / NUM_SAMPLES); + + // Angle to where to sample + float angle = alpha * (NUM_TURNS * 6.28) + RotationAngle; + + //Lenght to were to sample + ScreenSpaceSampleRadius = ScreenSpaceSampleRadius * alpha; + + vec2 screenSpaceSampleOffsetVecor = vec2(cos(angle), sin(angle)); + + // Get texel coordinate on where to sample by going screenSpaceSampleOffsetVecor direction in ScreenSpaceSampleRadius units from ScreenSpaceCoord (the point being shaded); + ivec2 screenSpaceSampleTexel = ivec2(ScreenSpaceSampleRadius * screenSpaceSampleOffsetVecor) + ScreenSpaceCoord; + + return getPosition(screenSpaceSampleTexel); +} + +float Radius2 = Radius * Radius; + +float sampleAO(ivec2 ScreenSpaceCoord, vec3 ShadedViewSpacePosition, vec3 ViewSpaceNormal, float ScreenSpaceSampleRadius, int SampleIndex, float RotationAngle) { + vec3 sampleViewSpacePosition = getSampleViewSpacePos(ScreenSpaceCoord, SampleIndex, RotationAngle, ScreenSpaceSampleRadius); + + vec3 sampleVector = ShadedViewSpacePosition - sampleViewSpacePosition; + + // vv = sampleVectorLenght ^ 2 + float vv = dot(sampleVector, sampleVector); + // vn = angle between sampleVector and Normal + float vn = dot(sampleVector, ViewSpaceNormal); + + const float epsilon = 0.01f; + + // vv < radius2 if the vector is shorter then the radius; + // vn - bias, offset the angle to reduse self occlusion. + // epsilon is here to make divison by 0 impossible. + return float(vv < Radius2) * max((vn - Bias) / (epsilon + vv), 0.0); + //float f = max(Radius2 - vv, 0.0); + //return f * f * f * max((vn - Bias) / (epsilon + vv), 0.0); +} + + +void main() { + ivec2 originScreenCoord = ivec2(gl_FragCoord.xy); + + vec3 origin = getPosition(originScreenCoord); + + vec3 viewSpaceNormal = getVSFaceNormal(origin); + + float screenSpaceSampleRadius = ProjScale * Radius / origin.z; + + //Offset on what angle to start on so that not evry pixel start sampling in the same direction, AlchemyAO + float rotationAngleOffset = (3 * originScreenCoord.x ^ originScreenCoord.y + originScreenCoord.x * originScreenCoord.y) * 10; + + float sum = 0.0; + for (int i = 0; i < NUM_SAMPLES; i++) { + sum += sampleAO(originScreenCoord, origin, viewSpaceNormal, screenSpaceSampleRadius, i, rotationAngleOffset); + } + + float A = max(0.0, 1.0 - sum * (2.0f / NUM_SAMPLES)); + //fragmentColor= vec4(viewSpaceNormal, 1.0f); + fragmentColor = vec4(A, A, A, 1.0f); +} diff --git a/resources/Shaders/SSAO.vert.glsl b/resources/Shaders/SSAO.vert.glsl new file mode 100644 index 00000000..a019c5ef --- /dev/null +++ b/resources/Shaders/SSAO.vert.glsl @@ -0,0 +1,8 @@ +#version 430 + +layout (location = 0) in vec3 Position; + +void main() +{ + gl_Position = vec4(Position, 1.0); +} \ No newline at end of file diff --git a/resources/Shaders/SSAOViewSpaceZ.frag.glsl b/resources/Shaders/SSAOViewSpaceZ.frag.glsl new file mode 100644 index 00000000..e4ec491b --- /dev/null +++ b/resources/Shaders/SSAOViewSpaceZ.frag.glsl @@ -0,0 +1,14 @@ +#version 430 + +uniform sampler2D DepthBuffer; +uniform vec3 ClipInfo; + +//out float depthLinear; +//Just for Debug, should be depthLinear +out vec4 fragmentColor; +void main() { + float depthSample = texelFetch(DepthBuffer, ivec2(gl_FragCoord.xy), 0).r; + float depthLinear = ClipInfo[0] / (ClipInfo[1] * depthSample + ClipInfo[2]); + //float depthLinear = (NearClip) / ( -depthSample + 1.0f); + fragmentColor = vec4(depthLinear, depthLinear, depthLinear, 1.0f); +} \ No newline at end of file diff --git a/src/Engine/Rendering/DrawBloomPass.cpp b/src/Engine/Rendering/DrawBloomPass.cpp index 46612d5e..e12ebd91 100644 --- a/src/Engine/Rendering/DrawBloomPass.cpp +++ b/src/Engine/Rendering/DrawBloomPass.cpp @@ -19,16 +19,20 @@ void DrawBloomPass::InitializeTextures() void DrawBloomPass::InitializeShaderPrograms() { m_GaussianProgram_horiz = ResourceManager::Load("##GaussianProgramHoriz"); - m_GaussianProgram_horiz->AddShader(std::shared_ptr(new VertexShader("Shaders/Gaussian_horiz.vert.glsl"))); - m_GaussianProgram_horiz->AddShader(std::shared_ptr(new FragmentShader("Shaders/Gaussian_horiz.frag.glsl"))); - m_GaussianProgram_horiz->Compile(); - m_GaussianProgram_horiz->Link(); + if (m_GaussianProgram_horiz->GetHandle() == 0) { + m_GaussianProgram_horiz->AddShader(std::shared_ptr(new VertexShader("Shaders/Gaussian_horiz.vert.glsl"))); + m_GaussianProgram_horiz->AddShader(std::shared_ptr(new FragmentShader("Shaders/Gaussian_horiz.frag.glsl"))); + m_GaussianProgram_horiz->Compile(); + m_GaussianProgram_horiz->Link(); + } - m_GaussianProgram_vert = ResourceManager::Load("##GaussianProgramVert"); - m_GaussianProgram_vert->AddShader(std::shared_ptr(new VertexShader("Shaders/Gaussian_vert.vert.glsl"))); - m_GaussianProgram_vert->AddShader(std::shared_ptr(new FragmentShader("Shaders/Gaussian_vert.frag.glsl"))); - m_GaussianProgram_vert->Compile(); - m_GaussianProgram_vert->Link(); + m_GaussianProgram_vert = ResourceManager::Load("##GaussianProgramVert"); + if (m_GaussianProgram_vert->GetHandle() == 0) { + m_GaussianProgram_vert->AddShader(std::shared_ptr(new VertexShader("Shaders/Gaussian_vert.vert.glsl"))); + m_GaussianProgram_vert->AddShader(std::shared_ptr(new FragmentShader("Shaders/Gaussian_vert.frag.glsl"))); + m_GaussianProgram_vert->Compile(); + m_GaussianProgram_vert->Link(); + } } @@ -70,16 +74,18 @@ void DrawBloomPass::Draw(GLuint texture) //Horizontal pass, first use the given texture then save it to the horizontal framebuffer. m_GaussianFrameBuffer_horiz.Bind(); + GLERROR("m_GaussianFrameBuffer_horiz.Bind()"); m_GaussianProgram_horiz->Bind(); - + GLERROR("m_GaussianProgram_horiz->Bind()"); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture); - + GLERROR("glBindTexture"); glBindVertexArray(m_ScreenQuad->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); + GLERROR("GL_ELEMENT_ARRAY_BUFFER"); 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("HEJ"); //Iterate some times to make it more gaussian. for (int i = 1; i < m_iterations; i++) { //Vertical pass @@ -92,7 +98,7 @@ void DrawBloomPass::Draw(GLuint texture) 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("HEJ LOOP"); //horizontal pass m_GaussianFrameBuffer_horiz.Bind(); @@ -112,7 +118,7 @@ void DrawBloomPass::Draw(GLuint texture) m_GaussianProgram_vert->Bind(); glBindTexture(GL_TEXTURE_2D, m_GaussianTexture_horiz); - + GLERROR("GL_TEXTURE_2D"); 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 diff --git a/src/Engine/Rendering/DrawColorCorrectionPass.cpp b/src/Engine/Rendering/DrawColorCorrectionPass.cpp index c82d614f..620bd896 100644 --- a/src/Engine/Rendering/DrawColorCorrectionPass.cpp +++ b/src/Engine/Rendering/DrawColorCorrectionPass.cpp @@ -18,7 +18,7 @@ void DrawColorCorrectionPass::InitializeShaderPrograms() m_ColorCorrectionProgram->Link(); } -void DrawColorCorrectionPass::Draw(GLuint sceneTexture, GLuint bloomTexture, GLuint sceneTextureLowRes, GLuint bloomTextureLowRes, GLfloat gamma, GLfloat exposure) +void DrawColorCorrectionPass::Draw(GLuint sceneTexture, GLuint bloomTexture, GLuint sceneTextureLowRes, GLuint bloomTextureLowRes, GLuint SSAOTexture, GLfloat gamma, GLfloat exposure) { //glBindFramebuffer(GL_FRAMEBUFFER, 0); GLERROR("DrawScreenQuadPass::Draw: Pre"); @@ -37,6 +37,8 @@ void DrawColorCorrectionPass::Draw(GLuint sceneTexture, GLuint bloomTexture, GLu glBindTexture(GL_TEXTURE_2D, sceneTextureLowRes); glActiveTexture(GL_TEXTURE3); glBindTexture(GL_TEXTURE_2D, bloomTextureLowRes); + glActiveTexture(GL_TEXTURE4); + glBindTexture(GL_TEXTURE_2D, SSAOTexture); glBindVertexArray(m_ScreenQuad->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index 11db71f0..a2681c65 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -22,10 +22,21 @@ void DrawFinalPass::InitializeTextures() void DrawFinalPass::InitializeFrameBuffers() { - glGenRenderbuffers(1, &m_DepthBuffer); + + glGenTextures(1, &m_DepthBuffer); + + glBindTexture(GL_TEXTURE_2D, m_DepthBuffer); + glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH24_STENCIL8, (int)(m_Renderer->GetViewportSize().Width), (int)(m_Renderer->GetViewportSize().Height), 0, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, nullptr); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); + + /*glGenRenderbuffers(1, &m_DepthBuffer); glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBuffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); - GLERROR("RenderBuffer generation"); + GLERROR("RenderBuffer generation");*/ + 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); //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); @@ -33,7 +44,7 @@ void DrawFinalPass::InitializeFrameBuffers() //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); - m_FinalPassFrameBuffer.AddResource(std::shared_ptr(new RenderBuffer(&m_DepthBuffer, GL_DEPTH_STENCIL_ATTACHMENT))); + m_FinalPassFrameBuffer.AddResource(std::shared_ptr(new Texture2D(&m_DepthBuffer, GL_DEPTH_STENCIL_ATTACHMENT))); //m_FinalPassFrameBuffer.AddResource(std::shared_ptr(new Texture2D(&m_StencilTexture, GL_STENCIL_ATTACHMENT))); m_FinalPassFrameBuffer.AddResource(std::shared_ptr(new Texture2D(&m_SceneTexture, GL_COLOR_ATTACHMENT0))); m_FinalPassFrameBuffer.AddResource(std::shared_ptr(new Texture2D(&m_BloomTexture, GL_COLOR_ATTACHMENT1))); @@ -176,10 +187,12 @@ void DrawFinalPass::InitializeShaderPrograms() void DrawFinalPass::Draw(RenderScene& scene) { GLERROR("Pre"); - + RenderCamera = scene.Camera; DrawFinalPassState* state = new DrawFinalPassState(m_FinalPassFrameBuffer.GetHandle()); if (scene.ClearDepth) { - glClear(GL_DEPTH_BUFFER_BIT); + //glClear(GL_DEPTH_BUFFER_BIT); + state->Disable(GL_DEPTH_TEST); + state->DepthMask(GL_FALSE); } //TODO: Do we need check for this or will it be per scene always? glClearStencil(0x00); @@ -241,7 +254,7 @@ void DrawFinalPass::Draw(RenderScene& scene) DrawShieldToStencilBuffer(scene.Jobs.ShieldObjects, scene); GLERROR("StencilPass"); - glClear(GL_DEPTH_BUFFER_BIT); + //glClear(GL_DEPTH_BUFFER_BIT); stateLowRes->Enable(GL_DEPTH_TEST); stateLowRes->StencilFunc(GL_LEQUAL, 1, 0xFF); @@ -743,17 +756,26 @@ void DrawFinalPass::BindExplosionUniforms(GLuint shaderHandle, std::shared_ptr& job, RenderScene& scene) { - GLERROR("Bind 1 uniform"); - GLint Location_M = glGetUniformLocation(shaderHandle, "M"); - glUniformMatrix4fv(Location_M, 1, GL_FALSE, glm::value_ptr(job->Matrix)); - GLERROR("Bind 2 uniform"); - GLint Location_V = glGetUniformLocation(shaderHandle, "V"); - glUniformMatrix4fv(Location_V, 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix())); - GLERROR("Bind 3 uniform"); - GLint Location_P = glGetUniformLocation(shaderHandle, "P"); - glUniformMatrix4fv(Location_P, 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix())); - GLERROR("Bind 4 uniform"); - + if (1/*job->Model->IsSkinned()*/) { + GLERROR("Bind 1 uniform"); + GLint Location_M = glGetUniformLocation(shaderHandle, "M"); + glUniformMatrix4fv(Location_M, 1, GL_FALSE, glm::value_ptr(job->Matrix)); + GLERROR("Bind 2 uniform"); + GLint Location_V = glGetUniformLocation(shaderHandle, "V"); + glUniformMatrix4fv(Location_V, 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix())); + GLERROR("Bind 3 uniform"); + GLint Location_P = glGetUniformLocation(shaderHandle, "P"); + glUniformMatrix4fv(Location_P, 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix())); + GLERROR("Bind 4 uniform"); + } else { + GLERROR("Bind 1 uniform"); + GLint Location_M = glGetUniformLocation(shaderHandle, "M"); + glUniformMatrix4fv(Location_M, 1, GL_FALSE, glm::value_ptr(job->Matrix)); + GLERROR("Bind 2 uniform"); + GLint Location_V = glGetUniformLocation(shaderHandle, "PV"); + glUniformMatrix4fv(Location_V, 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix() * scene.Camera->ViewMatrix())); + GLERROR("Bind 3 uniform"); + } GLint Location_ScreenDimensions = glGetUniformLocation(shaderHandle, "ScreenDimensions"); glUniform2f(Location_ScreenDimensions, m_Renderer->Resolution().Width, m_Renderer->Resolution().Height); GLERROR("Bind 5 uniform"); diff --git a/src/Engine/Rendering/Renderer.cpp b/src/Engine/Rendering/Renderer.cpp index be84160c..79c935a5 100644 --- a/src/Engine/Rendering/Renderer.cpp +++ b/src/Engine/Rendering/Renderer.cpp @@ -93,7 +93,12 @@ void Renderer::Update(double dt) void Renderer::Draw(RenderFrame& frame) { - ImGui::Combo("Draw textures", &m_DebugTextureToDraw, "Final\0Scene\0Bloom\0SceneLowRes\0BloomLowRes\0Gaussian\0Picking"); + ImGui::Combo("Draw textures", &m_DebugTextureToDraw, "Final\0Scene\0Bloom\0SceneLowRes\0BloomLowRes\0Gaussian\0Picking\0SSAO"); + + ImGui::SliderFloat("SSAO sample radius", &m_SSAO_Radius, 0.0001f, 1.0f); + ImGui::SliderFloat("SSAO bias", &m_SSAO_Bias, 0.0f, 1.0f); + ImGui::SliderFloat("SSAO intensity", &m_SSAO_Intensity, 0.0f, 1.0f); + m_SSAOPass->Setting(m_SSAO_Radius, m_SSAO_Bias, m_SSAO_Intensity); //clear buffer 0 glClearColor(0.f, 0.f, 0.f, 0.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); @@ -124,8 +129,10 @@ void Renderer::Draw(RenderFrame& frame) } m_DrawBloomPass->Draw(m_DrawFinalPass->BloomTexture()); + m_SSAOPass->Draw(m_DrawFinalPass->DepthBuffer(), m_DrawFinalPass->DepthBufferCamera()); + if (m_DebugTextureToDraw == 0) { - m_DrawColorCorrectionPass->Draw(m_DrawFinalPass->SceneTexture(), m_DrawBloomPass->GaussianTexture(), m_DrawFinalPass->SceneTextureLowRes(), m_DrawFinalPass->BloomTextureLowRes(), frame.Gamma, frame.Exposure); + m_DrawColorCorrectionPass->Draw(m_DrawFinalPass->SceneTexture(), m_DrawBloomPass->GaussianTexture(), m_DrawFinalPass->SceneTextureLowRes(), m_DrawFinalPass->BloomTextureLowRes(), m_SSAOPass->SSAOTexture(), frame.Gamma, frame.Exposure); } if (m_DebugTextureToDraw == 1) { m_DrawScreenQuadPass->Draw(m_DrawFinalPass->SceneTexture()); @@ -145,6 +152,9 @@ void Renderer::Draw(RenderFrame& frame) if (m_DebugTextureToDraw == 6) { m_DrawScreenQuadPass->Draw(m_PickingPass->PickingTexture()); } + if (m_DebugTextureToDraw == 7) { + m_DrawScreenQuadPass->Draw(m_SSAOPass->SSAOTexture()); + } m_ImGuiRenderPass->Draw(); GLERROR("Imgui draw"); @@ -191,4 +201,5 @@ void Renderer::InitializeRenderPasses() m_DrawScreenQuadPass = new DrawScreenQuadPass(this); m_DrawBloomPass = new DrawBloomPass(this); m_DrawColorCorrectionPass = new DrawColorCorrectionPass(this); + m_SSAOPass = new SSAOPass(this); } diff --git a/src/Engine/Rendering/SSAOPass.cpp b/src/Engine/Rendering/SSAOPass.cpp new file mode 100644 index 00000000..67b5cf33 --- /dev/null +++ b/src/Engine/Rendering/SSAOPass.cpp @@ -0,0 +1,135 @@ +#include "Rendering/SSAOPass.h" + +SSAOPass::SSAOPass(IRenderer* renderer) +{ + m_Renderer = renderer; + + m_ScreenQuad = ResourceManager::Load("Models/Core/ScreenQuad.mesh"); + + InitializeBuffer(); + InitializeShaderProgram(); + Setting(0.1f, 0.012f, 1.0f); + + m_DrawBloomPass = new DrawBloomPass(renderer); +} + +void SSAOPass::InitializeShaderProgram() +{ + m_SSAOProgram = ResourceManager::Load("##SSAOProgram"); + m_SSAOProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/SSAO.vert.glsl"))); + m_SSAOProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/SSAO.frag.glsl"))); + m_SSAOProgram->Compile(); + m_SSAOProgram->Link(); + + m_SSAOViewSpaceZProgram = ResourceManager::Load("##SSAOViewSpaceZProgram"); + m_SSAOViewSpaceZProgram->AddShader(std::shared_ptr(new VertexShader("Shaders/SSAO.vert.glsl"))); + m_SSAOViewSpaceZProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/SSAOViewSpaceZ.frag.glsl"))); + m_SSAOViewSpaceZProgram->Compile(); + m_SSAOViewSpaceZProgram->Link(); +} + + +void SSAOPass::InitializeBuffer() +{ + GenerateTexture(&m_SSAOTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); + + m_SSAOFramBuffer.AddResource(std::shared_ptr(new Texture2D(&m_SSAOTexture, GL_COLOR_ATTACHMENT0))); + m_SSAOFramBuffer.Generate(); + + GenerateTexture(&m_SSAOViewSpaceZTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB32F, GL_RGB, GL_FLOAT); + + m_SSAOViewSpaceZFramBuffer.AddResource(std::shared_ptr(new Texture2D(&m_SSAOViewSpaceZTexture, GL_COLOR_ATTACHMENT0))); + m_SSAOViewSpaceZFramBuffer.Generate(); +} + +void SSAOPass::ClearBuffer() +{ + m_SSAOFramBuffer.Bind(); + glClearColor(0.f, 0.f, 0.f, 0.f); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + m_SSAOFramBuffer.Unbind(); + + m_SSAOViewSpaceZFramBuffer.Bind(); + glClearColor(0.f, 0.f, 0.f, 0.f); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + m_SSAOViewSpaceZFramBuffer.Unbind(); +} + +void SSAOPass::Setting(float radius, float bias, float intensity) { + m_Radius = radius; + m_Bias = bias; + m_Intensity = intensity; +} + +void SSAOPass::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const +{ + glGenTextures(1, texture); + glBindTexture(GL_TEXTURE_2D, *texture); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapping); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapping); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filtering); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filtering); + glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, dimensions.x, dimensions.y, 0, format, type, nullptr); + GLERROR("Texture initialization failed"); +} + +void SSAOPass::Draw(GLuint depthBuffer, Camera* camera) +{ + SSAOPassState state; + GLuint viewSpaceZPShaderHandle = m_SSAOViewSpaceZProgram->GetHandle(); + GLuint SSAOShaderHandle = m_SSAOProgram->GetHandle(); + + m_SSAOViewSpaceZFramBuffer.Bind(); + m_SSAOViewSpaceZProgram->Bind(); + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, depthBuffer); + glm::vec3 clipInfo = glm::vec3( + (camera->NearClip() * camera->FarClip()), + (camera->NearClip() - camera->FarClip()), + (camera->FarClip()) + ); + /*glm::vec3 clipInfo = glm::vec3( + (camera->NearClip()), + (-1.0f), + (+1.0f) + );*/ + glUniform3fv(glGetUniformLocation(viewSpaceZPShaderHandle, "ClipInfo"), 1, glm::value_ptr(clipInfo)); + + 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); + + glm::vec4 projInfo = glm::vec4( + (-2.0f / (m_Renderer->GetViewportSize().Width * camera->ProjectionMatrix()[0][0])), + (-2.0f / (m_Renderer->GetViewportSize().Height * camera->ProjectionMatrix()[1][1])), + ((1.0f - camera->ProjectionMatrix()[0][2]) / camera->ProjectionMatrix()[0][0]), + ((1.0f - camera->ProjectionMatrix()[1][2]) / camera->ProjectionMatrix()[1][1]) + ); + + + m_SSAOFramBuffer.Bind(); + m_SSAOProgram->Bind(); + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, m_SSAOViewSpaceZTexture); + + // How many pixel there are in a 1m long object 1m away from the camera + glUniform1f(glGetUniformLocation(SSAOShaderHandle, "ProjScale"), m_Renderer->GetViewportSize().Height / (-2.0f * glm::tan(camera->FOV() * 0.5f))); + + glUniform1f(glGetUniformLocation(SSAOShaderHandle, "Radius"), m_Radius); + glUniform1f(glGetUniformLocation(SSAOShaderHandle, "Bias"), m_Bias); + glUniform1f(glGetUniformLocation(SSAOShaderHandle, "IntensityDivR6"), m_Intensity / glm::pow(m_Radius, 6)); + + glUniform4fv(glGetUniformLocation(SSAOShaderHandle, "ProjInfo"), 1, glm::value_ptr(projInfo)); + 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_DrawBloomPass->ClearBuffer(); + m_DrawBloomPass->Draw(m_SSAOTexture); +} + +void ComputeAO(GLuint depthBuffer, Camera* camera) { + +} \ No newline at end of file diff --git a/src/Engine/Rendering/SSAOPassState.cpp b/src/Engine/Rendering/SSAOPassState.cpp new file mode 100644 index 00000000..7dd49841 --- /dev/null +++ b/src/Engine/Rendering/SSAOPassState.cpp @@ -0,0 +1,16 @@ +#include "Rendering/SSAOPassState.h" + + +SSAOPassState::SSAOPassState() +{ + //BindFramebuffer(0); + Disable(GL_BLEND); + Disable(GL_DEPTH_TEST); + Disable(GL_CULL_FACE); +} + +SSAOPassState::~SSAOPassState() +{ + +} + diff --git a/src/Engine/Rendering/ShaderProgram.cpp b/src/Engine/Rendering/ShaderProgram.cpp index 9c26c15c..ae536bc0 100644 --- a/src/Engine/Rendering/ShaderProgram.cpp +++ b/src/Engine/Rendering/ShaderProgram.cpp @@ -98,8 +98,7 @@ void ShaderProgram::AddShader(std::shared_ptr shader) void ShaderProgram::Compile() { - if (m_ShaderProgramHandle == 0) - { + if (m_ShaderProgramHandle == 0) { m_ShaderProgramHandle = glCreateProgram(); } From 993d804cef57dc77a405301f9c572cb4f33db6cc Mon Sep 17 00:00:00 2001 From: stiffly Date: Fri, 19 Feb 2016 15:38:09 +0100 Subject: [PATCH 317/355] Added an event to search for servers. Client now broadcasts a serverlistrequest. An active server will then answer the request and send info about the server. The client saves this data to a list and presents it to the user. --- include/Engine/Network/Client.h | 27 ++++++-- include/Engine/Network/ESearchForServers.h | 12 ++++ include/Engine/Network/MessageType.h | 2 +- include/Engine/Network/Server.h | 6 +- include/Engine/Network/TCPServer.h | 9 ++- include/Engine/Network/UDPClient.h | 1 + include/Engine/Network/UDPServer.h | 4 +- src/Engine/Network/Client.cpp | 74 ++++++++++++++++------ src/Engine/Network/Server.cpp | 49 +++++++++----- src/Engine/Network/TCPServer.cpp | 8 ++- src/Engine/Network/UDPClient.cpp | 15 ++++- src/Engine/Network/UDPServer.cpp | 22 +++++++ 12 files changed, 178 insertions(+), 51 deletions(-) create mode 100644 include/Engine/Network/ESearchForServers.h diff --git a/include/Engine/Network/Client.h b/include/Engine/Network/Client.h index 01e18da8..7d23670a 100644 --- a/include/Engine/Network/Client.h +++ b/include/Engine/Network/Client.h @@ -14,7 +14,6 @@ #include "Network/MessageType.h" #include "Network/PlayerDefinition.h" #include "Network/UDPClient.h" -#include "Network/UDPServer.h" //LOL #include "Network/TCPClient.h" #include "Network/SnapshotDefinitions.h" #include "Core/World.h" @@ -25,6 +24,19 @@ #include "Network/EInterpolate.h" #include "Network/SnapshotFilter.h" #include "Core/EPlayerSpawned.h" +#include "Network/ESearchForServers.h" + +struct ServerInfo +{ + ServerInfo(std::string a, int b, std::string c, int d) + { + Address = a; Port = b; Name = c; PlayersConnected = d; + } + std::string Address = ""; + int Port = 0; + std::string Name = ""; + int PlayersConnected = 0; +}; class Client : public Network { @@ -83,10 +95,11 @@ public: void parseTCPConnect(Packet& packet); void parsePlayerConnected(Packet& packet); void parsePing(); - void parseHeartbeat(Packet& packet, PlayerDefinition); + void parseServerlist(Packet& packet); void parseKick(); void parsePlayersSpawned(Packet& packet); void parseEntityDeletion(Packet& packet); + void parsePlayerDamage(Packet& packet); void parseComponentDeletion(Packet& packet); void InterpolateFields(Packet & packet, const ComponentInfo & componentInfo, const EntityID & entityID, const std::string & componentType); void parseSnapshot(Packet& packet); @@ -96,6 +109,7 @@ public: void sendInputCommands(); void sendLocalPlayerTransform(); void becomePlayer(); + void displayServerlist(); // Mapping Logic // Returns if local EntityID exist in map bool clientServerMapsHasEntity(EntityID clientEntityID); @@ -111,11 +125,16 @@ public: bool OnPlayerDamage(const Events::PlayerDamage& e); EventRelay m_EPlayerSpawned; bool OnPlayerSpawned(const Events::PlayerSpawned& e); - void parsePlayerDamage(Packet& packet); + EventRelay< Client, Events::SearchForServers> m_ESearchForServers; + bool OnSearchForServers(const Events::SearchForServers& e); private: UDPClient m_Unreliable; - UDPServer m_Heartbeat; + UDPClient m_ServerlistRequest; TCPClient m_Reliable; + std::vector m_Serverlist; + bool m_SearchingForServers = false; + std::clock_t m_StartSearchTime; + double m_SearchingTime = 2000; // Config I guess }; #endif diff --git a/include/Engine/Network/ESearchForServers.h b/include/Engine/Network/ESearchForServers.h new file mode 100644 index 00000000..1b08a8f3 --- /dev/null +++ b/include/Engine/Network/ESearchForServers.h @@ -0,0 +1,12 @@ +#ifndef Events_SearchForServers_h__ +#define Events_SearchForServers_h__ + +#include "Core/Event.h" + +namespace Events +{ + +struct SearchForServers : public Event { }; + +} +#endif diff --git a/include/Engine/Network/MessageType.h b/include/Engine/Network/MessageType.h index 2b3b02c0..93695063 100644 --- a/include/Engine/Network/MessageType.h +++ b/include/Engine/Network/MessageType.h @@ -19,7 +19,7 @@ enum class MessageType EntityDeleted, ComponentDeleted, PlayerTransform, - Heartbeat, + ServerlistRequest, Invalid }; diff --git a/include/Engine/Network/Server.h b/include/Engine/Network/Server.h index 0a2cb029..982df3b1 100644 --- a/include/Engine/Network/Server.h +++ b/include/Engine/Network/Server.h @@ -33,7 +33,7 @@ private: // Network channels TCPServer m_Reliable; UDPServer m_Unreliable; - UDPClient m_Heartbeat; + UDPServer m_ServerlistRequest; // dont forget to set these in the childrens receive logic boost::asio::ip::address m_Address; int m_Port = 27666; @@ -46,13 +46,11 @@ private: // time for previouse message std::clock_t previousePingMessage = std::clock(); std::clock_t previousSnapshotMessage = std::clock(); - std::clock_t previousHeartbeat = std::clock(); std::clock_t timOutTimer = std::clock(); // How often we send messages (milliseconds) float pingIntervalMs; float snapshotInterval; - float heartbeatInterval = 5000; int checkTimeOutInterval = 100; int m_NextPlayerID = 0; std::vector m_InputCommandsToBroadcast; @@ -71,7 +69,6 @@ private: void addChildrenToPacket(Packet& packet, EntityID entityID); void addInputCommandsToPacket(Packet& packet); void sendPing(); - void sendHeartBeat(); void checkForTimeOuts(); void disconnect(PlayerID playerID); void parseMessageType(Packet& packet); @@ -86,6 +83,7 @@ private: void parseUDPConnect(Packet & packet); void parseTCPConnect(Packet & packet); void parseDisconnect(); + void parseServerlistRequest(boost::asio::ip::udp::endpoint endpoint); bool shouldSendToClient(EntityWrapper childEntity); // Debug event diff --git a/include/Engine/Network/TCPServer.h b/include/Engine/Network/TCPServer.h index 424599c9..1140579a 100644 --- a/include/Engine/Network/TCPServer.h +++ b/include/Engine/Network/TCPServer.h @@ -16,8 +16,9 @@ public: void Send(Packet & packet, PlayerDefinition & playerDefinition); void Send(Packet & packet); void Disconnect(); - int Port() { return acceptor->local_endpoint().port(); } - std::string Address(); + int Port() { return m_Port; } + std::string Address() { return m_Address; } + private: // TCP logic boost::asio::io_service m_IOService; @@ -28,6 +29,10 @@ private: int& nextPlayerID, std::map& connectedPlayers, const boost::system::error_code& error); int readBuffer(char* data, PlayerDefinition& playerDefinition); + int GetPort(); + std::string GetAddress(); + int m_Port = 0; + std::string m_Address = ""; }; #endif \ No newline at end of file diff --git a/include/Engine/Network/UDPClient.h b/include/Engine/Network/UDPClient.h index 3a458d3e..f986dd08 100644 --- a/include/Engine/Network/UDPClient.h +++ b/include/Engine/Network/UDPClient.h @@ -14,6 +14,7 @@ public: void Disconnect(); void Receive(Packet& packet); void Send(Packet & packet); + void Broadcast(Packet& packet, int port); bool IsSocketAvailable(); private: // Assio UDP logic diff --git a/include/Engine/Network/UDPServer.h b/include/Engine/Network/UDPServer.h index 6ba7cd96..15dd977c 100644 --- a/include/Engine/Network/UDPServer.h +++ b/include/Engine/Network/UDPServer.h @@ -13,7 +13,9 @@ public: void AcceptNewConnections(int& nextPlayerID, std::map& connectedPlayers); void Receive(Packet & packet, PlayerDefinition & playerDefinition); void Send(Packet & packet, PlayerDefinition & playerDefinition); - void Send(Packet & packet); + void Send(Packet & packet); + void Send(Packet & packet, boost::asio::ip::udp::endpoint endpoint); + void Broadcast(Packet & packet, int port); bool IsSocketAvailable(); private: // UDP logic diff --git a/src/Engine/Network/Client.cpp b/src/Engine/Network/Client.cpp index a9a67bae..8d0f40ae 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -1,9 +1,8 @@ #include "Network/Client.h" using namespace boost::asio::ip; -Client::Client(World* world, EventBroker* eventBroker) +Client::Client(World* world, EventBroker* eventBroker) : Network(world, eventBroker) - , m_Heartbeat(13) { // Asumes root node is EntityID_Invalid insertIntoServerClientMaps(EntityID_Invalid, EntityID_Invalid); @@ -14,6 +13,8 @@ Client::Client(World* world, EventBroker* eventBroker) m_PlayerName = config->Get("Networking.Name", "Raptorcopter"); m_SendInputIntervalMs = config->Get("Networking.SendInputIntervalMs", 33); LOG_INFO("Client initialized"); + + m_ServerlistRequest.Connect(m_PlayerName, "192.168.1.255", 32554); } Client::Client(World* world, EventBroker* eventBroker, std::unique_ptr snapshotFilter) @@ -31,6 +32,7 @@ void Client::Connect(std::string address, int port) EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &Client::OnInputCommand); EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &Client::OnPlayerDamage); EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &Client::OnPlayerSpawned); + EVENT_SUBSCRIBE_MEMBER(m_ESearchForServers, &Client::OnSearchForServers); auto config = ResourceManager::Load("Config.ini"); m_Address = address; if (address.empty()) { @@ -66,15 +68,22 @@ void Client::Update() } } - while (m_Heartbeat.IsSocketAvailable()) { + + while (m_ServerlistRequest.IsSocketAvailable()) { Packet packet(MessageType::Invalid); - PlayerDefinition localArea; - localArea.Endpoint = boost::asio::ip::udp::endpoint(boost::asio::ip::address().from_string("127.0.0.1"), 13); - m_Heartbeat.Receive(packet, localArea); - if(packet.GetMessageType() == MessageType::Heartbeat) { - parseHeartbeat(packet, localArea); + m_ServerlistRequest.Receive(packet); + if (packet.GetMessageType() == MessageType::ServerlistRequest) { + parseServerlist(packet); } } + + if (m_SearchingForServers) { + if (m_SearchingTime < (1000* (std::clock() - m_StartSearchTime) / (double)CLOCKS_PER_SEC)) { + m_SearchingForServers = false; + displayServerlist(); + } + } + if (m_IsConnected) { // Don't send 1 input in 1 packet, bunch em up. if (m_SendInputIntervalMs < (1000 * (std::clock() - m_TimeSinceSentInputs) / (double)CLOCKS_PER_SEC)) { @@ -183,20 +192,18 @@ void Client::parsePing() } -void Client::parseHeartbeat(Packet& packet, PlayerDefinition pd) +void Client::parseServerlist(Packet& packet) { // Pop size, message type, and ID packet.ReadPrimitive(); packet.ReadPrimitive(); packet.ReadPrimitive(); - std::string serverName = packet.ReadString(); - int playersConnected = packet.ReadPrimitive(); std::string address = packet.ReadString(); int port = packet.ReadPrimitive(); - //TODO: save these to some kind of list which can be represented to the player + std::string serverName = packet.ReadString(); + int playersConnected = packet.ReadPrimitive(); //TODO: This should not happen when a client is connected to a server - - LOG_INFO("Serverlist\nName\tPlayers\tIP\t\tPort\n%s\t%i\t%s\t%i\n", serverName.c_str(), playersConnected, address, port); + m_Serverlist.push_back({ address, port, serverName, playersConnected }); } void Client::parseKick() @@ -216,12 +223,12 @@ void Client::parseSpawnEvents() } e.Player = EntityWrapper(m_World, m_ServerIDToClientID.at(m_PlayerSpawnEvents.at(i).Player.ID)); //e.Spawner = EntityWrapper(m_World, m_ServerIDToClientID.at(m_PlayerSpawnEvents.at(i).Spawner.ID)); - e.PlayerID = -1; + e.PlayerID = -1; e.PlayerName = m_PlayerSpawnEvents.at(i).PlayerName; m_EventBroker->Publish(e); } m_PlayerSpawnEvents = tempSpawn; - // m_PlayerSpawnEvents.clear(); + // m_PlayerSpawnEvents.clear(); } void Client::parsePlayersSpawned(Packet& packet) @@ -338,7 +345,7 @@ void Client::parseSnapshot(Packet& packet) if (serverClientMapsHasEntity(serverEntityID)) { EntityID localEntityID = m_ServerIDToClientID.at(serverEntityID); EntityWrapper localEntity(m_World, localEntityID); - + // Update entity if (m_World->HasComponent(localEntityID, componentType)) { SharedComponentWrapper newComponent = createSharedComponent(packet, localEntityID, componentInfo); @@ -397,6 +404,12 @@ void Client::disconnect() bool Client::OnInputCommand(const Events::InputCommand & e) { + // TEMP + if (e.Command == "SearchForServers" && e.Value > 0) { + Events::SearchForServers e; + m_EventBroker->Publish(e); + } + if (e.PlayerID != -1) { return false; } @@ -459,12 +472,23 @@ bool Client::OnPlayerSpawned(const Events::PlayerSpawned& e) return true; } +bool Client::OnSearchForServers(const Events::SearchForServers& e) +{ + m_SearchingForServers = true; + m_StartSearchTime = std::clock(); + m_Serverlist.clear(); + LOG_INFO("Searching for LAN servers...\n"); + Packet packet(MessageType::ServerlistRequest); + m_ServerlistRequest.Broadcast(packet, 13); // TODO: Config + return true; +} + void Client::parsePlayerDamage(Packet& packet) { Events::PlayerDamage e; PlayerID victimID = packet.ReadPrimitive(); PlayerID inflictorID = packet.ReadPrimitive(); - if(!serverClientMapsHasEntity(victimID) || !serverClientMapsHasEntity(inflictorID)){ + if (!serverClientMapsHasEntity(victimID) || !serverClientMapsHasEntity(inflictorID)) { return; } e.Inflictor = EntityWrapper(m_World, m_ServerIDToClientID.at(victimID)); @@ -493,7 +517,7 @@ void Client::sendLocalPlayerTransform() packet.WritePrimitive(orientation.x); packet.WritePrimitive(orientation.y); packet.WritePrimitive(orientation.z); - + bool hasAssaultWeapon = m_LocalPlayer.HasComponent("AssaultWeapon"); packet.WritePrimitive(hasAssaultWeapon); if (hasAssaultWeapon) { @@ -501,7 +525,7 @@ void Client::sendLocalPlayerTransform() packet.WritePrimitive((int)cAssaultWeapon["MagazineAmmo"]); packet.WritePrimitive((int)cAssaultWeapon["Ammo"]); } - + m_Unreliable.Send(packet); } @@ -554,6 +578,16 @@ void Client::becomePlayer() m_Reliable.Send(packet); } + +void Client::displayServerlist() +{ + LOG_INFO("This is a serverlist:\n"); + for (int i = 0; i < m_Serverlist.size(); i++) { + ServerInfo si = m_Serverlist[i]; + LOG_INFO("%s:%i\t%s\t%i\n", si.Address, si.Port, si.Name, si.PlayersConnected); + } +} + bool Client::clientServerMapsHasEntity(EntityID clientEntityID) { if (m_ClientIDToServerID.find(clientEntityID) != m_ClientIDToServerID.end()) { diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index 8dd398bd..0bed0b62 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -2,6 +2,7 @@ Server::Server(World* world, EventBroker* eventBroker, int port) : Network(world, eventBroker) + , m_ServerlistRequest(13) { ConfigFile* config = ResourceManager::Load("Config.ini"); snapshotInterval = 1000 * config->Get("Networking.SnapshotInterval", 0.05f); @@ -19,7 +20,6 @@ Server::Server(World* world, EventBroker* eventBroker, int port) } m_Port = port; LOG_INFO("Server initialized and bound to port %i", port); - m_Heartbeat.Connect("Server", "127.0.0.1", 13); } Server::~Server() @@ -60,8 +60,23 @@ void Server::Update() } } + while (m_ServerlistRequest.IsSocketAvailable()) { + Packet packet(MessageType::Invalid); + PlayerDefinition localArea; + localArea.Endpoint = boost::asio::ip::udp::endpoint(); + m_ServerlistRequest.Receive(packet, localArea); + if(packet.GetMessageType() == MessageType::ServerlistRequest) { + packet.ReadPrimitive(); // Pop size + packet.ReadPrimitive(); // Pop MsgType + packet.ReadPrimitive(); // Pop packet ID + int port = packet.ReadPrimitive(); + std::string address = localArea.Endpoint.address().to_string(); + parseServerlistRequest(boost::asio::ip::udp::endpoint(boost::asio::ip::address().from_string(address), port)); + } + } + // Check if players have disconnected - for (int i = 0; i < m_PlayersToDisconnect.size(); i++) { + for (int i = 0; i < m_PlayersToDisconnect.size(); i++) { disconnect(m_PlayersToDisconnect.at(i)); } m_PlayersToDisconnect.clear(); @@ -77,11 +92,7 @@ void Server::Update() sendPing(); previousePingMessage = currentTime; } - // Server heartbeat (display server list on clients) - if (heartbeatInterval < (1000 * (currentTime - previousHeartbeat) / (double)CLOCKS_PER_SEC)) { - sendHeartBeat(); - previousHeartbeat = currentTime; - } + // Time out logic if (checkTimeOutInterval < (1000 * (currentTime - timOutTimer) / (double)CLOCKS_PER_SEC)) { checkForTimeOuts(); @@ -238,15 +249,6 @@ void Server::sendPing() } -void Server::sendHeartBeat() -{ - Packet packet(MessageType::Heartbeat); - packet.WriteString("Bob"); // server name - packet.WritePrimitive(m_ConnectedPlayers.size()); - packet.WriteString(m_Reliable.Address()); - packet.WritePrimitive(m_Reliable.Port()); - m_Heartbeat.Send(packet); -} void Server::checkForTimeOuts() { @@ -340,6 +342,20 @@ void Server::parseDisconnect() } } + +void Server::parseServerlistRequest(boost::asio::ip::udp::endpoint endpoint) +{ + Packet packet(MessageType::ServerlistRequest); + packet.WriteString(m_Reliable.Address()); + packet.WritePrimitive(m_Reliable.Port()); + packet.WriteString("SERVERNAME"); + packet.WritePrimitive(m_ConnectedPlayers.size()); + //PlayerDefinition pDef; + //pDef.Endpoint = boost::asio::ip::udp::endpoint(endpoint.address(), 13); + + m_ServerlistRequest.Send(packet/*, endpoint*/); +} + void Server::disconnect(PlayerID playerID) { //broadcast("A player disconnected"); @@ -364,6 +380,7 @@ void Server::parseOnPlayerDamage(Packet & packet) e.Victim = EntityWrapper(m_World, packet.ReadPrimitive()); e.Damage = packet.ReadPrimitive(); m_EventBroker->Publish(e); + //LOG_DEBUG("Server::parseOnPlayerDamage: Command is %s. Value is %f. PlayerID is %i.", e.DamageAmount, e.PlayerDamagedID, e.TypeOfDamage.c_str()); } diff --git a/src/Engine/Network/TCPServer.cpp b/src/Engine/Network/TCPServer.cpp index a55eee98..452efa62 100644 --- a/src/Engine/Network/TCPServer.cpp +++ b/src/Engine/Network/TCPServer.cpp @@ -4,6 +4,8 @@ using namespace boost::asio::ip; TCPServer::TCPServer() { acceptor = std::unique_ptr(new tcp::acceptor(m_IOService, tcp::endpoint(tcp::v4(), 27666))); + m_Port = GetPort(); + m_Address = GetAddress(); } TCPServer::~TCPServer() @@ -76,8 +78,12 @@ void TCPServer::Disconnect() { } +int TCPServer::GetPort() +{ + return acceptor->local_endpoint().port(); +} -std::string TCPServer::Address() +std::string TCPServer::GetAddress() { boost::asio::ip::tcp::resolver resolver(m_IOService); boost::asio::ip::tcp::resolver::query query(boost::asio::ip::tcp::v4(), boost::asio::ip::host_name(), ""); diff --git a/src/Engine/Network/UDPClient.cpp b/src/Engine/Network/UDPClient.cpp index c76de084..68aebb03 100644 --- a/src/Engine/Network/UDPClient.cpp +++ b/src/Engine/Network/UDPClient.cpp @@ -15,9 +15,9 @@ void UDPClient::Connect(std::string playerName, std::string address, int port) if (m_Socket) { return; } - m_ReceiverEndpoint = udp::endpoint(boost::asio::ip::address::from_string(address), port); + m_ReceiverEndpoint = udp::endpoint(boost::asio::ip::address().from_string(address), port); m_Socket = boost::shared_ptr(new boost::asio::ip::udp::socket(m_IOService)); - m_Socket->connect(m_ReceiverEndpoint); + m_Socket->open(boost::asio::ip::udp::v4()); } void UDPClient::Disconnect() @@ -55,6 +55,17 @@ void UDPClient::Send(Packet& packet) packet.Data(), packet.Size()), m_ReceiverEndpoint, 0); +} + +void UDPClient::Broadcast(Packet& packet, int port) +{ + m_Socket->set_option(boost::asio::socket_base::broadcast(true)); + m_Socket->send_to(boost::asio::buffer( + packet.Data(), + packet.Size()), + udp::endpoint(boost::asio::ip::address_v4().broadcast(), port) + , 0); + m_Socket->set_option(boost::asio::socket_base::broadcast(false)); } bool UDPClient::IsSocketAvailable() diff --git a/src/Engine/Network/UDPServer.cpp b/src/Engine/Network/UDPServer.cpp index b4046003..f751d369 100644 --- a/src/Engine/Network/UDPServer.cpp +++ b/src/Engine/Network/UDPServer.cpp @@ -36,7 +36,29 @@ void UDPServer::Send(Packet & packet) 0); } +// Broadcasting respond specific logic +void UDPServer::Send(Packet & packet, boost::asio::ip::udp::endpoint endpoint) +{ + m_Socket->send_to( + boost::asio::buffer( + packet.Data(), + packet.Size()), + endpoint, + 0); +} +// Broadcasting +void UDPServer::Broadcast(Packet & packet, int port) +{ + m_Socket->set_option(boost::asio::socket_base::broadcast(true)); + m_Socket->send_to( + boost::asio::buffer( + packet.Data(), + packet.Size()), + boost::asio::ip::udp::endpoint(boost::asio::ip::address_v4().broadcast(),port), + 0); + m_Socket->set_option(boost::asio::socket_base::broadcast(false)); +} void UDPServer::Receive(Packet & packet, PlayerDefinition & playerDefinition) { From 23dc8e07b28fdcf9247d2376d05489d86973f58e Mon Sep 17 00:00:00 2001 From: stiffly Date: Mon, 22 Feb 2016 10:41:37 +0100 Subject: [PATCH 318/355] Will this do the trick? Now tells the server to send HUD entities too. --- src/Engine/Network/Server.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index 0bed0b62..d05a4bb4 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -189,6 +189,7 @@ void Server::addChildrenToPacket(Packet & packet, EntityID entityID) for (auto it = itPair.first; it != itPair.second; it++) { EntityID childEntityID = it->second; // HACK: Only sync players for now, since the map turned out to be TOO LARGE to send in one snapshot and Simon's computer shits itself + // HACK: Also checked CapturePointHUD for now. (this would get out of sync); EntityWrapper childEntity(m_World, childEntityID); if (!shouldSendToClient(childEntity)) { continue; @@ -547,7 +548,8 @@ void Server::parsePlayerTransform(Packet& packet) bool Server::shouldSendToClient(EntityWrapper childEntity) { - return childEntity.HasComponent("Player") || childEntity.FirstParentWithComponent("Player").Valid(); + return childEntity.HasComponent("Player") || childEntity.FirstParentWithComponent("Player").Valid() + || childEntity.HasComponent("CapturePointHUD"); } PlayerID Server::GetPlayerIDFromEndpoint() From 4c1a2846364ed301e99a38e067d0b511caf1f2ff Mon Sep 17 00:00:00 2001 From: stiffly Date: Mon, 22 Feb 2016 11:30:31 +0100 Subject: [PATCH 319/355] Server now does Capture point logic too. --- src/Engine/Network/Server.cpp | 5 +++-- src/Game/Systems/CapturePointSystem.cpp | 10 +++++----- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index d05a4bb4..76c04ad7 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -136,7 +136,7 @@ void Server::parseMessageType(Packet& packet) parseOnPlayerDamage(packet); break; case MessageType::PlayerTransform: -// parsePlayerTransform(packet); + parsePlayerTransform(packet); break; default: break; @@ -549,7 +549,8 @@ void Server::parsePlayerTransform(Packet& packet) bool Server::shouldSendToClient(EntityWrapper childEntity) { return childEntity.HasComponent("Player") || childEntity.FirstParentWithComponent("Player").Valid() - || childEntity.HasComponent("CapturePointHUD"); + || childEntity.HasComponent("CapturePointHUD") || childEntity.FirstParentWithComponent("CapturePointHUD").Valid(); + } PlayerID Server::GetPlayerIDFromEndpoint() diff --git a/src/Game/Systems/CapturePointSystem.cpp b/src/Game/Systems/CapturePointSystem.cpp index 5fdd74cd..526b77da 100644 --- a/src/Game/Systems/CapturePointSystem.cpp +++ b/src/Game/Systems/CapturePointSystem.cpp @@ -6,20 +6,20 @@ CapturePointSystem::CapturePointSystem(SystemParams params) , PureSystem("CapturePoint") { //subscribe/listenTo playerdamage,healthpickup events (using the eventBroker) - if (IsClient) { + //if (IsClient) { EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &CapturePointSystem::OnTriggerTouch); EVENT_SUBSCRIBE_MEMBER(m_ETriggerLeave, &CapturePointSystem::OnTriggerLeave); EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &CapturePointSystem::OnCaptured); - } + //} } //here all capturepoints will update their component //NOTE: needs to run each frame, since we're possibly modifying the captureTimer for the capturePoints by dt void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, ComponentWrapper& cCapturePoint, double dt) { - if (!IsClient) { - return; - } + //if (!IsClient) { + // return; + //} if (m_WinnerWasFound) { return; From adceccf4029f23fcf3be52983766583dcc6fb58c Mon Sep 17 00:00:00 2001 From: Teejoon Date: Mon, 22 Feb 2016 14:48:20 +0100 Subject: [PATCH 320/355] SSAO now working. Changed in DrawFinalePass so that th AOTexture is on texture position 0 and only get binded once. Changed so that the picking pass get drawn once in the beginning so that the AO shatde could calculate AO from the depthbuffer generated during pthe pickingpass. In the ImGUI debugg window there is now sliders to change the behavior of the AO shader. Only the minimum ambient lightning is HardCoded in to the frowardPlus fragmentshaders with a define in the begining. --- .../Rendering/DrawColorCorrectionPass.h | 2 +- include/Engine/Rendering/DrawFinalPass.h | 4 +- include/Engine/Rendering/Renderer.h | 9 +- include/Engine/Rendering/SSAOPass.h | 7 +- resources/Schema/Entities/Player.xml | 14 ++-- resources/Schema/Entities/PlayerRed.xml | 14 ++-- .../Shaders/DrawColorCorrection.frag.glsl | 4 - resources/Shaders/ForwardPlus.frag.glsl | 19 +++-- .../Shaders/ForwardPlusSplatMapRGB.frag.glsl | 38 +++++---- resources/Shaders/SSAO.frag.glsl | 82 ++++++++++--------- resources/Shaders/SSAOViewSpaceZ.frag.glsl | 10 +-- resources/Shaders/Sprite.frag.glsl | 4 +- src/Engine/Rendering/DrawBloomPass.cpp | 7 -- .../Rendering/DrawColorCorrectionPass.cpp | 4 +- src/Engine/Rendering/DrawFinalPass.cpp | 64 +++++++-------- src/Engine/Rendering/PickingPass.cpp | 19 ++++- src/Engine/Rendering/Renderer.cpp | 27 +++--- src/Engine/Rendering/SSAOPass.cpp | 34 ++++---- 18 files changed, 192 insertions(+), 170 deletions(-) diff --git a/include/Engine/Rendering/DrawColorCorrectionPass.h b/include/Engine/Rendering/DrawColorCorrectionPass.h index db16cf98..231e2d33 100644 --- a/include/Engine/Rendering/DrawColorCorrectionPass.h +++ b/include/Engine/Rendering/DrawColorCorrectionPass.h @@ -17,7 +17,7 @@ public: void InitializeFrameBuffers(); void InitializeShaderPrograms(); - void Draw(GLuint sceneTexture, GLuint bloomTexture, GLuint sceneTextureLowRes, GLuint bloomTextureLowRes, GLuint SSAOTexture, GLfloat gamma, GLfloat exposure); + void Draw(GLuint sceneTexture, GLuint bloomTexture, GLuint sceneTextureLowRes, GLuint bloomTextureLowRes, GLfloat gamma, GLfloat exposure); private: const IRenderer* m_Renderer; diff --git a/include/Engine/Rendering/DrawFinalPass.h b/include/Engine/Rendering/DrawFinalPass.h index f1cf66c8..54f9407f 100644 --- a/include/Engine/Rendering/DrawFinalPass.h +++ b/include/Engine/Rendering/DrawFinalPass.h @@ -18,7 +18,7 @@ public: void InitializeTextures(); void InitializeFrameBuffers(); void InitializeShaderPrograms(); - void Draw(RenderScene& scene); + void Draw(RenderScene& scene, GLuint SSAOTexture); void ClearBuffer(); //Return the texture that is used in later stages to apply the bloom effect @@ -40,7 +40,7 @@ private: void GenerateMipMapTexture(GLuint* texture, GLenum wrapping, glm::vec2 dimensions, GLint format, GLenum type, GLint numMipMaps) const; void DrawSprites(std::list>&jobs, RenderScene& scene); - void DrawModelRenderQueues(std::list>& jobs, RenderScene& scene); + void DrawModelRenderQueues(std::list>& jobs, RenderScene& scene, GLuint SSAOTexture); void DrawShieldToStencilBuffer(std::list>& jobs, RenderScene& scene); void DrawShieldedModelRenderQueue(std::list>& jobs, RenderScene& scene); void DrawToDepthBuffer(std::list>& jobs, RenderScene& scene); diff --git a/include/Engine/Rendering/Renderer.h b/include/Engine/Rendering/Renderer.h index b613ba4f..d8c60cd8 100644 --- a/include/Engine/Rendering/Renderer.h +++ b/include/Engine/Rendering/Renderer.h @@ -51,9 +51,12 @@ private: Model* m_UnitSphere; int m_DebugTextureToDraw = 0; - float m_SSAO_Radius = 0.2f; - float m_SSAO_Bias = 0.012f; - float m_SSAO_Intensity = 1.0f; + float m_SSAO_Radius = 1.0f; + float m_SSAO_Bias = 0.05f; + float m_SSAO_Contrast = 1.5f; + float m_SSAO_IntensityScale = 1.0f; + int m_SSAO_NumOfSamples = 24; + int m_SSAO_NumOfTurns = 7; PickingPass* m_PickingPass; LightCullingPass* m_LightCullingPass; diff --git a/include/Engine/Rendering/SSAOPass.h b/include/Engine/Rendering/SSAOPass.h index 22f53ded..f15e20d3 100644 --- a/include/Engine/Rendering/SSAOPass.h +++ b/include/Engine/Rendering/SSAOPass.h @@ -17,7 +17,7 @@ public: ~SSAOPass() { }; void Draw(GLuint depthBuffer, Camera* camera); - void Setting(float radius, float bias, float intensity); + void Setting(float radius, float bias, float contrast, float intensityScale, int numOfSamples, int NumOfTurns); void ClearBuffer(); //Return the SSAO of the texture sent to Draw @@ -41,7 +41,10 @@ private: float m_Radius; float m_Bias; - float m_Intensity; + float m_Contrast; + float m_IntensityScale; + int m_NumOfSamples; + int m_NumOfTurns; GLuint m_SSAOTexture; FrameBuffer m_SSAOFramBuffer; diff --git a/resources/Schema/Entities/Player.xml b/resources/Schema/Entities/Player.xml index be6009ba..d4485112 100644 --- a/resources/Schema/Entities/Player.xml +++ b/resources/Schema/Entities/Player.xml @@ -349,13 +349,12 @@ Idle - 1.6050530664521858 + 1.8314163732853146 1 Models/Characters/Assault/FirstPerson.mesh - true @@ -367,11 +366,10 @@ Models/Weapons/Blue/AssaultWeaponBlue.mesh - true - - + + @@ -477,7 +475,7 @@ Idle - 1.620305457513453 + 0.16333512901638159 1 @@ -501,8 +499,8 @@ Models/Weapons/Blue/AssaultWeaponBlue.mesh - - + + diff --git a/resources/Schema/Entities/PlayerRed.xml b/resources/Schema/Entities/PlayerRed.xml index d9839e9f..4be8fc26 100644 --- a/resources/Schema/Entities/PlayerRed.xml +++ b/resources/Schema/Entities/PlayerRed.xml @@ -349,13 +349,12 @@ Idle - 1.6050530664521858 + 0.018170670865885086 1 Models/Characters/Assault/FirstPerson.mesh - true @@ -367,11 +366,10 @@ Models/Weapons/Red/AssaultWeaponRed.mesh - true - - + + @@ -477,7 +475,7 @@ Idle - 1.620305457513453 + 0.11675631578762591 1 @@ -501,8 +499,8 @@ Models/Weapons/Red/AssaultWeaponRed.mesh - - + + diff --git a/resources/Shaders/DrawColorCorrection.frag.glsl b/resources/Shaders/DrawColorCorrection.frag.glsl index 838a78f6..bae50887 100644 --- a/resources/Shaders/DrawColorCorrection.frag.glsl +++ b/resources/Shaders/DrawColorCorrection.frag.glsl @@ -4,7 +4,6 @@ layout (binding = 0) uniform sampler2D SceneTexture; layout (binding = 1) uniform sampler2D BloomTexture; layout (binding = 2) uniform sampler2D SceneTextureLowRes; layout (binding = 3) uniform sampler2D BloomTextureLowRes; -layout (binding = 4) uniform sampler2D SSAOTexture; uniform float Exposure; uniform float Gamma; @@ -20,10 +19,8 @@ void main() vec4 bloomColor = texture(BloomTexture, Input.TextureCoordinate); vec4 hdrColorLowRes = texture(SceneTextureLowRes, Input.TextureCoordinate); vec4 bloomColorLowRes = texture(BloomTextureLowRes, Input.TextureCoordinate); - vec4 SSAO = texture(SSAOTexture, Input.TextureCoordinate); //hdrColor = hdrColor * SSAO; - SSAO = clamp(SSAO, 0.1f, 1.0f); hdrColor += bloomColor; hdrColorLowRes; @@ -38,7 +35,6 @@ void main() //gamme correction result = pow(result, vec3(1.0 / Gamma)); - result = result * SSAO.rgb; fragmentColor = vec4(result, 1.0); //fragmentColor = hdrColor; //fragmentColor = bloomColor; diff --git a/resources/Shaders/ForwardPlus.frag.glsl b/resources/Shaders/ForwardPlus.frag.glsl index 471ee20b..b4e0022b 100644 --- a/resources/Shaders/ForwardPlus.frag.glsl +++ b/resources/Shaders/ForwardPlus.frag.glsl @@ -1,5 +1,7 @@ #version 430 +#define MIN_AMBIENT_LIGHT 0.3 + uniform mat4 M; uniform mat4 V; uniform mat4 P; @@ -14,10 +16,11 @@ uniform vec2 DiffuseUVRepeat; uniform vec2 NormalUVRepeat; uniform vec2 SpecularUVRepeat; uniform vec2 GlowUVRepeat; -layout (binding = 0) uniform sampler2D DiffuseTexture; -layout (binding = 1) uniform sampler2D NormalMapTexture; -layout (binding = 2) uniform sampler2D SpecularMapTexture; -layout (binding = 3) uniform sampler2D GlowMapTexture; +layout (binding = 0) uniform sampler2D AOTexture; +layout (binding = 1) uniform sampler2D DiffuseTexture; +layout (binding = 2) uniform sampler2D NormalMapTexture; +layout (binding = 3) uniform sampler2D SpecularMapTexture; +layout (binding = 4) uniform sampler2D GlowMapTexture; #define TILE_SIZE 16 @@ -119,6 +122,8 @@ vec4 CalcNormalMappedValue(vec3 normal, vec3 tangent, vec3 bitangent, vec2 textu void main() { + float ao = texelFetch(AOTexture, ivec2(gl_FragCoord.xy), 0).r; + ao = (clamp(1.0 - (1.0 - ao), 0.0, 1.0) + MIN_AMBIENT_LIGHT) / (1.0 + MIN_AMBIENT_LIGHT); vec4 diffuseTexel = texture2D(DiffuseTexture, Input.TextureCoordinate * DiffuseUVRepeat); vec4 glowTexel = texture2D(GlowMapTexture, Input.TextureCoordinate * GlowUVRepeat); vec4 specularTexel = texture2D(SpecularMapTexture, Input.TextureCoordinate * SpecularUVRepeat); @@ -133,7 +138,7 @@ void main() tilePos.y = int(gl_FragCoord.y/TILE_SIZE); LightResult totalLighting; - totalLighting.Diffuse = vec4(AmbientColor.rgb, 1.0); + totalLighting.Diffuse = vec4(AmbientColor.rgb * ao, 1.0); int currentTile = int(floor(gl_FragCoord.x/TILE_SIZE) + (floor(gl_FragCoord.y/TILE_SIZE) * int(ScreenDimensions.x/TILE_SIZE))); int start = int(LightGrids.Data[currentTile].Start); @@ -151,8 +156,8 @@ void main() } else if (light.Type == 2) { //Directional light_result = CalcDirectionalLightSource(V * light.Direction, light.Color, light.Intensity, viewVec, normal); } - totalLighting.Diffuse += light_result.Diffuse; - totalLighting.Specular += light_result.Specular; + totalLighting.Diffuse += vec4(light_result.Diffuse.rgb * ao, light_result.Diffuse.a); + totalLighting.Specular += vec4(light_result.Specular.rgb * ao, light_result.Specular.a); } vec4 color_result = mix((Color * diffuseTexel * DiffuseColor), Input.ExplosionColor, Input.ExplosionPercentageElapsed); diff --git a/resources/Shaders/ForwardPlusSplatMapRGB.frag.glsl b/resources/Shaders/ForwardPlusSplatMapRGB.frag.glsl index e862d926..cf358b96 100644 --- a/resources/Shaders/ForwardPlusSplatMapRGB.frag.glsl +++ b/resources/Shaders/ForwardPlusSplatMapRGB.frag.glsl @@ -1,5 +1,7 @@ #version 430 +#define MIN_AMBIENT_LIGHT 0.3 + uniform mat4 M; uniform mat4 V; uniform mat4 P; @@ -23,19 +25,20 @@ uniform vec2 SpecularUVRepeat3; uniform vec2 GlowUVRepeat1; uniform vec2 GlowUVRepeat2; uniform vec2 GlowUVRepeat3; -layout (binding = 0) uniform sampler2D SplatMapTexture; -layout (binding = 1) uniform sampler2D DiffuseTexture1; -layout (binding = 2) uniform sampler2D DiffuseTexture2; -layout (binding = 3) uniform sampler2D DiffuseTexture3; -layout (binding = 4) uniform sampler2D NormalMapTexture1; -layout (binding = 5) uniform sampler2D NormalMapTexture2; -layout (binding = 6) uniform sampler2D NormalMapTexture3; -layout (binding = 7) uniform sampler2D SpecularMapTexture1; -layout (binding = 8) uniform sampler2D SpecularMapTexture2; -layout (binding = 9) uniform sampler2D SpecularMapTexture3; -layout (binding = 10) uniform sampler2D GlowMapTexture1; -layout (binding = 11) uniform sampler2D GlowMapTexture2; -layout (binding = 12) uniform sampler2D GlowMapTexture3; +layout (binding = 0) uniform sampler2D AOTexture; +layout (binding = 1) uniform sampler2D SplatMapTexture; +layout (binding = 2) uniform sampler2D DiffuseTexture1; +layout (binding = 3) uniform sampler2D DiffuseTexture2; +layout (binding = 4) uniform sampler2D DiffuseTexture3; +layout (binding = 5) uniform sampler2D NormalMapTexture1; +layout (binding = 6) uniform sampler2D NormalMapTexture2; +layout (binding = 7) uniform sampler2D NormalMapTexture3; +layout (binding = 8) uniform sampler2D SpecularMapTexture1; +layout (binding = 9) uniform sampler2D SpecularMapTexture2; +layout (binding = 10) uniform sampler2D SpecularMapTexture3; +layout (binding = 11) uniform sampler2D GlowMapTexture1; +layout (binding = 12) uniform sampler2D GlowMapTexture2; +layout (binding = 13) uniform sampler2D GlowMapTexture3; #define TILE_SIZE 16 @@ -174,6 +177,9 @@ vec4 CalcBlendedNormal(vec4 blendValue, sampler2D R, sampler2D G, sampler2D B, void main() { + float ao = texelFetch(AOTexture, ivec2(gl_FragCoord.xy), 0).r; + ao = (clamp(1.0 - (1.0 - ao), 0.0, 1.0) + MIN_AMBIENT_LIGHT) / (1.0 + MIN_AMBIENT_LIGHT); + vec4 splatTexel = texture2D(SplatMapTexture, Input.TextureCoordinate); vec4 diffuseTexel = CalcBlendedTexel(splatTexel, DiffuseTexture1, DiffuseTexture2, DiffuseTexture3, @@ -195,7 +201,7 @@ void main() tilePos.y = int(gl_FragCoord.y/TILE_SIZE); LightResult totalLighting; - totalLighting.Diffuse = vec4(AmbientColor.rgb, 1.0); + totalLighting.Diffuse = vec4(AmbientColor.rgb * ao, 1.0); int currentTile = int(floor(gl_FragCoord.x/TILE_SIZE) + (floor(gl_FragCoord.y/TILE_SIZE) * int(ScreenDimensions.x/TILE_SIZE))); int start = int(LightGrids.Data[currentTile].Start); @@ -213,8 +219,8 @@ void main() } else if (light.Type == 2) { //Directional light_result = CalcDirectionalLightSource(V * light.Direction, light.Color, light.Intensity, viewVec, normal); } - totalLighting.Diffuse += light_result.Diffuse; - totalLighting.Specular += light_result.Specular; + totalLighting.Diffuse += vec4(light_result.Diffuse.rgb * ao, light_result.Diffuse.a); + totalLighting.Specular += vec4(light_result.Specular.rgb * ao, light_result.Specular.a); } vec4 color_result = mix((Color * diffuseTexel * DiffuseColor), Input.ExplosionColor, Input.ExplosionPercentageElapsed); diff --git a/resources/Shaders/SSAO.frag.glsl b/resources/Shaders/SSAO.frag.glsl index b9ba58ce..68c830f8 100644 --- a/resources/Shaders/SSAO.frag.glsl +++ b/resources/Shaders/SSAO.frag.glsl @@ -1,38 +1,37 @@ #version 430 //Number of samples per pixel -#define NUM_SAMPLES (24) +uniform int uNumOfSamples; +//#define NUM_SAMPLES (11) //Number of turns around the cirle -#define NUM_TURNS (7) +uniform int uNumOfTurns; +//#define NUM_TURNS (7) -uniform sampler2D ViewSpaceZ; +layout (binding = 0) uniform sampler2D ViewSpaceZ; -uniform vec4 ProjInfo; +uniform vec4 uProjInfo; -uniform float ProjScale; +uniform float uProjScale; //#define ProjScale 500 -uniform float Radius; +uniform float uRadius; //#define Radius 1.0f -uniform float Bias; +uniform float uBias; //#define Bias 0.012f -uniform float IntensityDivR6; +uniform float uContrast; //#define IntensityDivR6 1 -out vec4 fragmentColor; +uniform float uIntensityScale; -vec3 reconstructVSPosition(vec2 ScreenSpaceCoord, float z){ - return vec3((ScreenSpaceCoord * ProjInfo.xy + ProjInfo.zw) * z, z); -} +out float AO; -vec3 getPosition(ivec2 ScreenSpaceCoord) { - vec3 P; - P.z = texelFetch(ViewSpaceZ, ScreenSpaceCoord, 0).r; +vec3 getVSPosition(ivec2 ScreenSpaceCoord) { + float z = texelFetch(ViewSpaceZ, ScreenSpaceCoord, 0).r; //Get the xy view space coordinates and add the z value from ViewSpaceZ buffer. - return reconstructVSPosition(vec2(ScreenSpaceCoord) + vec2(0.5), P.z); + return vec3((uProjInfo[0] + (ScreenSpaceCoord.x * uProjInfo[1])) * z, (uProjInfo[2] + (ScreenSpaceCoord.y * uProjInfo[3])) * z, z); } vec3 getVSFaceNormal(vec3 ViewSpacePosition) { @@ -44,10 +43,10 @@ vec3 getVSFaceNormal(vec3 ViewSpacePosition) { vec3 getSampleViewSpacePos(ivec2 ScreenSpaceCoord, int SampleIndex, float RotationAngle, float ScreenSpaceSampleRadius){ // Pure Magic... - float alpha = float(SampleIndex + 0.5) * (1.0 / NUM_SAMPLES); + float alpha = float(SampleIndex) * (1.0 / uNumOfSamples); // Angle to where to sample - float angle = alpha * (NUM_TURNS * 6.28) + RotationAngle; + float angle = alpha * (uNumOfTurns * 6.28) + RotationAngle; //Lenght to were to sample ScreenSpaceSampleRadius = ScreenSpaceSampleRadius * alpha; @@ -57,50 +56,59 @@ vec3 getSampleViewSpacePos(ivec2 ScreenSpaceCoord, int SampleIndex, float Rotati // Get texel coordinate on where to sample by going screenSpaceSampleOffsetVecor direction in ScreenSpaceSampleRadius units from ScreenSpaceCoord (the point being shaded); ivec2 screenSpaceSampleTexel = ivec2(ScreenSpaceSampleRadius * screenSpaceSampleOffsetVecor) + ScreenSpaceCoord; - return getPosition(screenSpaceSampleTexel); + return getVSPosition(screenSpaceSampleTexel); } -float Radius2 = Radius * Radius; -float sampleAO(ivec2 ScreenSpaceCoord, vec3 ShadedViewSpacePosition, vec3 ViewSpaceNormal, float ScreenSpaceSampleRadius, int SampleIndex, float RotationAngle) { + +float sampleAO(ivec2 ScreenSpaceCoord, vec3 Origin, vec3 OriginNormal, float ScreenSpaceSampleRadius, int SampleIndex, float RotationAngle, float Radius) { + float radius2 = Radius * Radius; vec3 sampleViewSpacePosition = getSampleViewSpacePos(ScreenSpaceCoord, SampleIndex, RotationAngle, ScreenSpaceSampleRadius); - vec3 sampleVector = ShadedViewSpacePosition - sampleViewSpacePosition; + vec3 sampleVector = Origin - sampleViewSpacePosition; // vv = sampleVectorLenght ^ 2 float vv = dot(sampleVector, sampleVector); // vn = angle between sampleVector and Normal - float vn = dot(sampleVector, ViewSpaceNormal); + float vn = dot(sampleVector, OriginNormal); - const float epsilon = 0.01f; + const float epsilon = 0.0001f; // vv < radius2 if the vector is shorter then the radius; // vn - bias, offset the angle to reduse self occlusion. // epsilon is here to make divison by 0 impossible. - return float(vv < Radius2) * max((vn - Bias) / (epsilon + vv), 0.0); - //float f = max(Radius2 - vv, 0.0); - //return f * f * f * max((vn - Bias) / (epsilon + vv), 0.0); + return float(vv < radius2) * max((vn - uBias) / (epsilon + vv), 0.0); + //float f = max(radius2 - vv, 0.0); + //return f * f * f * max((vn - uBias) / (epsilon + vv), 0.0); } void main() { ivec2 originScreenCoord = ivec2(gl_FragCoord.xy); - vec3 origin = getPosition(originScreenCoord); + vec3 origin = getVSPosition(originScreenCoord); - vec3 viewSpaceNormal = getVSFaceNormal(origin); + float radius; + if(origin.z < uRadius){ + radius = origin.z; + } else { + radius = uRadius; + } - float screenSpaceSampleRadius = ProjScale * Radius / origin.z; - //Offset on what angle to start on so that not evry pixel start sampling in the same direction, AlchemyAO - float rotationAngleOffset = (3 * originScreenCoord.x ^ originScreenCoord.y + originScreenCoord.x * originScreenCoord.y) * 10; + vec3 originNormal = getVSFaceNormal(origin); + + float screenSpaceSampleRadius = -uProjScale * radius / origin.z; + + float rotationAngleOffset = 30 * originScreenCoord.x ^ originScreenCoord.y + 10 * originScreenCoord.x * originScreenCoord.y; float sum = 0.0; - for (int i = 0; i < NUM_SAMPLES; i++) { - sum += sampleAO(originScreenCoord, origin, viewSpaceNormal, screenSpaceSampleRadius, i, rotationAngleOffset); + for (int i = 0; i < uNumOfSamples; i++) { + sum += sampleAO(originScreenCoord, origin, originNormal, screenSpaceSampleRadius, i, rotationAngleOffset, radius); } - float A = max(0.0, 1.0 - sum * (2.0f / NUM_SAMPLES)); - //fragmentColor= vec4(viewSpaceNormal, 1.0f); - fragmentColor = vec4(A, A, A, 1.0f); + //float A = max(0.0, 1.0 - sum * (2.0f / uNumOfSamples)); + float A = 1.0 - sum * (2.0f * uIntensityScale / float(uNumOfSamples)); + AO = clamp(pow(A, uContrast), 0.0f, 1.0f); + //AO = vec4(originNormal, 1.0f); } diff --git a/resources/Shaders/SSAOViewSpaceZ.frag.glsl b/resources/Shaders/SSAOViewSpaceZ.frag.glsl index e4ec491b..dbcfd899 100644 --- a/resources/Shaders/SSAOViewSpaceZ.frag.glsl +++ b/resources/Shaders/SSAOViewSpaceZ.frag.glsl @@ -1,14 +1,14 @@ #version 430 -uniform sampler2D DepthBuffer; +layout (binding = 0) uniform sampler2D DepthBuffer; uniform vec3 ClipInfo; -//out float depthLinear; +out float depthLinear; //Just for Debug, should be depthLinear -out vec4 fragmentColor; +//out vec4 fragmentColor; void main() { float depthSample = texelFetch(DepthBuffer, ivec2(gl_FragCoord.xy), 0).r; - float depthLinear = ClipInfo[0] / (ClipInfo[1] * depthSample + ClipInfo[2]); + depthLinear = ClipInfo[0] / (ClipInfo[1] * depthSample + ClipInfo[2]); //float depthLinear = (NearClip) / ( -depthSample + 1.0f); - fragmentColor = vec4(depthLinear, depthLinear, depthLinear, 1.0f); + //fragmentColor = vec4(depthLinear, depthLinear, depthLinear, 1.0f); } \ No newline at end of file diff --git a/resources/Shaders/Sprite.frag.glsl b/resources/Shaders/Sprite.frag.glsl index 9ce2bbdf..754be6ac 100644 --- a/resources/Shaders/Sprite.frag.glsl +++ b/resources/Shaders/Sprite.frag.glsl @@ -7,8 +7,8 @@ uniform mat4 M; uniform mat4 V; uniform mat4 P; -layout (binding = 0) uniform sampler2D DiffuseTexture; -layout (binding = 1) uniform sampler2D GlowMapTexture; +layout (binding = 1) uniform sampler2D DiffuseTexture; +layout (binding = 2) uniform sampler2D GlowMapTexture; in VertexData{ diff --git a/src/Engine/Rendering/DrawBloomPass.cpp b/src/Engine/Rendering/DrawBloomPass.cpp index e12ebd91..7479962e 100644 --- a/src/Engine/Rendering/DrawBloomPass.cpp +++ b/src/Engine/Rendering/DrawBloomPass.cpp @@ -74,18 +74,13 @@ void DrawBloomPass::Draw(GLuint texture) //Horizontal pass, first use the given texture then save it to the horizontal framebuffer. m_GaussianFrameBuffer_horiz.Bind(); - GLERROR("m_GaussianFrameBuffer_horiz.Bind()"); m_GaussianProgram_horiz->Bind(); - GLERROR("m_GaussianProgram_horiz->Bind()"); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture); - GLERROR("glBindTexture"); glBindVertexArray(m_ScreenQuad->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); - GLERROR("GL_ELEMENT_ARRAY_BUFFER"); 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("HEJ"); //Iterate some times to make it more gaussian. for (int i = 1; i < m_iterations; i++) { //Vertical pass @@ -98,7 +93,6 @@ void DrawBloomPass::Draw(GLuint texture) 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("HEJ LOOP"); //horizontal pass m_GaussianFrameBuffer_horiz.Bind(); @@ -118,7 +112,6 @@ void DrawBloomPass::Draw(GLuint texture) m_GaussianProgram_vert->Bind(); glBindTexture(GL_TEXTURE_2D, m_GaussianTexture_horiz); - GLERROR("GL_TEXTURE_2D"); 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 diff --git a/src/Engine/Rendering/DrawColorCorrectionPass.cpp b/src/Engine/Rendering/DrawColorCorrectionPass.cpp index 620bd896..c82d614f 100644 --- a/src/Engine/Rendering/DrawColorCorrectionPass.cpp +++ b/src/Engine/Rendering/DrawColorCorrectionPass.cpp @@ -18,7 +18,7 @@ void DrawColorCorrectionPass::InitializeShaderPrograms() m_ColorCorrectionProgram->Link(); } -void DrawColorCorrectionPass::Draw(GLuint sceneTexture, GLuint bloomTexture, GLuint sceneTextureLowRes, GLuint bloomTextureLowRes, GLuint SSAOTexture, GLfloat gamma, GLfloat exposure) +void DrawColorCorrectionPass::Draw(GLuint sceneTexture, GLuint bloomTexture, GLuint sceneTextureLowRes, GLuint bloomTextureLowRes, GLfloat gamma, GLfloat exposure) { //glBindFramebuffer(GL_FRAMEBUFFER, 0); GLERROR("DrawScreenQuadPass::Draw: Pre"); @@ -37,8 +37,6 @@ void DrawColorCorrectionPass::Draw(GLuint sceneTexture, GLuint bloomTexture, GLu glBindTexture(GL_TEXTURE_2D, sceneTextureLowRes); glActiveTexture(GL_TEXTURE3); glBindTexture(GL_TEXTURE_2D, bloomTextureLowRes); - glActiveTexture(GL_TEXTURE4); - glBindTexture(GL_TEXTURE_2D, SSAOTexture); glBindVertexArray(m_ScreenQuad->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index a2681c65..9f2113d7 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -22,20 +22,10 @@ void DrawFinalPass::InitializeTextures() void DrawFinalPass::InitializeFrameBuffers() { - - glGenTextures(1, &m_DepthBuffer); - - glBindTexture(GL_TEXTURE_2D, m_DepthBuffer); - glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH24_STENCIL8, (int)(m_Renderer->GetViewportSize().Width), (int)(m_Renderer->GetViewportSize().Height), 0, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, nullptr); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); - - /*glGenRenderbuffers(1, &m_DepthBuffer); + glGenRenderbuffers(1, &m_DepthBuffer); glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBuffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); - GLERROR("RenderBuffer generation");*/ + GLERROR("RenderBuffer generation"); 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); @@ -44,7 +34,7 @@ void DrawFinalPass::InitializeFrameBuffers() //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); - m_FinalPassFrameBuffer.AddResource(std::shared_ptr(new Texture2D(&m_DepthBuffer, GL_DEPTH_STENCIL_ATTACHMENT))); + m_FinalPassFrameBuffer.AddResource(std::shared_ptr(new RenderBuffer(&m_DepthBuffer, GL_DEPTH_STENCIL_ATTACHMENT))); //m_FinalPassFrameBuffer.AddResource(std::shared_ptr(new Texture2D(&m_StencilTexture, GL_STENCIL_ATTACHMENT))); m_FinalPassFrameBuffer.AddResource(std::shared_ptr(new Texture2D(&m_SceneTexture, GL_COLOR_ATTACHMENT0))); m_FinalPassFrameBuffer.AddResource(std::shared_ptr(new Texture2D(&m_BloomTexture, GL_COLOR_ATTACHMENT1))); @@ -184,7 +174,7 @@ void DrawFinalPass::InitializeShaderPrograms() GLERROR("Creating DepthFill program"); } -void DrawFinalPass::Draw(RenderScene& scene) +void DrawFinalPass::Draw(RenderScene& scene, GLuint SSAOTexture) { GLERROR("Pre"); RenderCamera = scene.Camera; @@ -199,12 +189,11 @@ void DrawFinalPass::Draw(RenderScene& scene) glClear(GL_STENCIL_BUFFER_BIT); //Fill depth buffer - - + state->StencilMask(0x00); - DrawModelRenderQueues(scene.Jobs.OpaqueObjects, scene); + DrawModelRenderQueues(scene.Jobs.OpaqueObjects, scene, SSAOTexture); GLERROR("OpaqueObjects"); - DrawModelRenderQueues(scene.Jobs.TransparentObjects, scene); + DrawModelRenderQueues(scene.Jobs.TransparentObjects, scene, SSAOTexture); GLERROR("TransparentObjects"); DrawSprites(scene.Jobs.SpriteJob, scene); GLERROR("SpriteJobs"); @@ -219,11 +208,11 @@ void DrawFinalPass::Draw(RenderScene& scene) //Draw Opaque shielded objects state->StencilFunc(GL_NOTEQUAL, 1, 0xFF); state->StencilMask(0x00); - DrawModelRenderQueues(scene.Jobs.OpaqueShieldedObjects, scene); //might need changing + DrawModelRenderQueues(scene.Jobs.OpaqueShieldedObjects, scene, SSAOTexture); //might need changing GLERROR("Shielded Opaque object"); //Draw Transparen Shielded objects - DrawModelRenderQueues(scene.Jobs.TransparentShieldedObjects, scene); //might need changing + DrawModelRenderQueues(scene.Jobs.TransparentShieldedObjects, scene, SSAOTexture); //might need changing GLERROR("Shielded Transparent objects"); GLERROR("END"); @@ -259,9 +248,9 @@ void DrawFinalPass::Draw(RenderScene& scene) stateLowRes->Enable(GL_DEPTH_TEST); stateLowRes->StencilFunc(GL_LEQUAL, 1, 0xFF); stateLowRes->StencilMask(0x00); - DrawModelRenderQueues(scene.Jobs.OpaqueObjects, scene); + DrawModelRenderQueues(scene.Jobs.OpaqueObjects, scene, SSAOTexture); GLERROR("OpaqueObjects"); - DrawModelRenderQueues(scene.Jobs.TransparentObjects, scene); + DrawModelRenderQueues(scene.Jobs.TransparentObjects, scene, SSAOTexture); GLERROR("TransparentObjects"); glViewport(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); glScissor(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); @@ -313,7 +302,7 @@ void DrawFinalPass::GenerateMipMapTexture(GLuint* texture, GLenum wrapping, glm: GLERROR("MipMap Texture initialization failed"); } -void DrawFinalPass::DrawModelRenderQueues(std::list>& jobs, RenderScene& scene) +void DrawFinalPass::DrawModelRenderQueues(std::list>& jobs, RenderScene& scene, GLuint SSAOTexture) { GLuint forwardHandle = m_ForwardPlusProgram->GetHandle(); GLERROR("forwardHandle"); @@ -336,6 +325,9 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, m_LightCullingPass->LightGridSSBO()); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 4, m_LightCullingPass->LightIndexSSBO()); + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, SSAOTexture); + for (auto &job : jobs) { auto explosionEffectJob = std::dynamic_pointer_cast(job); if (explosionEffectJob) { @@ -682,14 +674,14 @@ void DrawFinalPass::DrawSprites(std::list>&jobs, Rend glUniform4fv(glGetUniformLocation(shaderHandle, "FillColor"), 1, glm::value_ptr(spriteJob->FillColor)); glUniform1f(glGetUniformLocation(shaderHandle, "FillPercentage"), spriteJob->FillPercentage); - glActiveTexture(GL_TEXTURE0); + glActiveTexture(GL_TEXTURE1); if (spriteJob->DiffuseTexture != nullptr) { glBindTexture(GL_TEXTURE_2D, spriteJob->DiffuseTexture->m_Texture); } else { glBindTexture(GL_TEXTURE_2D, m_ErrorTexture->m_Texture); } - glActiveTexture(GL_TEXTURE1); + glActiveTexture(GL_TEXTURE2); if (spriteJob->IncandescenceTexture != nullptr) { glBindTexture(GL_TEXTURE_2D, spriteJob->IncandescenceTexture->m_Texture); } else { @@ -804,7 +796,7 @@ void DrawFinalPass::BindExplosionTextures(GLuint shaderHandle, std::shared_ptrDiffuseTexture.size() > 0 && job->DiffuseTexture[0]->Texture != nullptr) { glBindTexture(GL_TEXTURE_2D, job->DiffuseTexture[0]->Texture->m_Texture); glUniform2fv(glGetUniformLocation(shaderHandle, "DiffuseUVRepeat"), 1, glm::value_ptr(job->DiffuseTexture[0]->UVRepeat)); @@ -814,7 +806,7 @@ void DrawFinalPass::BindExplosionTextures(GLuint shaderHandle, std::shared_ptrNormalTexture.size() > 0 && job->NormalTexture[0]->Texture != nullptr) { glBindTexture(GL_TEXTURE_2D, job->NormalTexture[0]->Texture->m_Texture); glUniform2fv(glGetUniformLocation(shaderHandle, "NormalUVRepeat"), 1, glm::value_ptr(job->NormalTexture[0]->UVRepeat)); @@ -824,7 +816,7 @@ void DrawFinalPass::BindExplosionTextures(GLuint shaderHandle, std::shared_ptrSpecularTexture.size() > 0 && job->SpecularTexture[0]->Texture != nullptr) { glBindTexture(GL_TEXTURE_2D, job->SpecularTexture[0]->Texture->m_Texture); glUniform2fv(glGetUniformLocation(shaderHandle, "SpecularUVRepeat"), 1, glm::value_ptr(job->SpecularTexture[0]->UVRepeat)); @@ -834,7 +826,7 @@ void DrawFinalPass::BindExplosionTextures(GLuint shaderHandle, std::shared_ptrIncandescenceTexture.size() > 0 && job->IncandescenceTexture[0]->Texture != nullptr) { glBindTexture(GL_TEXTURE_2D, job->IncandescenceTexture[0]->Texture->m_Texture); glUniform2fv(glGetUniformLocation(shaderHandle, "GlowUVRepeat"), 1, glm::value_ptr(job->IncandescenceTexture[0]->UVRepeat)); @@ -847,7 +839,7 @@ void DrawFinalPass::BindExplosionTextures(GLuint shaderHandle, std::shared_ptrSplatMap->Texture->m_Texture); int texturePosition = GL_TEXTURE1; @@ -922,7 +914,7 @@ void DrawFinalPass::BindModelTextures(GLuint shaderHandle, std::shared_ptrDiffuseTexture.size() > 0 && job->DiffuseTexture[0]->Texture != nullptr) { glBindTexture(GL_TEXTURE_2D, job->DiffuseTexture[0]->Texture->m_Texture); glUniform2fv(glGetUniformLocation(shaderHandle, "DiffuseUVRepeat"), 1, glm::value_ptr(job->DiffuseTexture[0]->UVRepeat)); @@ -932,7 +924,7 @@ void DrawFinalPass::BindModelTextures(GLuint shaderHandle, std::shared_ptrNormalTexture.size() > 0 && job->NormalTexture[0]->Texture != nullptr) { glBindTexture(GL_TEXTURE_2D, job->NormalTexture[0]->Texture->m_Texture); glUniform2fv(glGetUniformLocation(shaderHandle, "NormalUVRepeat"), 1, glm::value_ptr(job->NormalTexture[0]->UVRepeat)); @@ -942,7 +934,7 @@ void DrawFinalPass::BindModelTextures(GLuint shaderHandle, std::shared_ptrSpecularTexture.size() > 0 && job->SpecularTexture[0]->Texture != nullptr) { glBindTexture(GL_TEXTURE_2D, job->SpecularTexture[0]->Texture->m_Texture); glUniform2fv(glGetUniformLocation(shaderHandle, "SpecularUVRepeat"), 1, glm::value_ptr(job->SpecularTexture[0]->UVRepeat)); @@ -952,7 +944,7 @@ void DrawFinalPass::BindModelTextures(GLuint shaderHandle, std::shared_ptrIncandescenceTexture.size() > 0 && job->IncandescenceTexture[0]->Texture != nullptr) { glBindTexture(GL_TEXTURE_2D, job->IncandescenceTexture[0]->Texture->m_Texture); glUniform2fv(glGetUniformLocation(shaderHandle, "GlowUVRepeat"), 1, glm::value_ptr(job->IncandescenceTexture[0]->UVRepeat)); @@ -965,10 +957,10 @@ void DrawFinalPass::BindModelTextures(GLuint shaderHandle, std::shared_ptrSplatMap->Texture->m_Texture); - int texturePosition = GL_TEXTURE1; + int texturePosition = GL_TEXTURE2; //Bind 5 diffuse textures std::string UniformName = "DiffuseUVRepeat"; diff --git a/src/Engine/Rendering/PickingPass.cpp b/src/Engine/Rendering/PickingPass.cpp index ecd0a4b8..73679a68 100644 --- a/src/Engine/Rendering/PickingPass.cpp +++ b/src/Engine/Rendering/PickingPass.cpp @@ -23,11 +23,20 @@ void PickingPass::InitializeTextures() void PickingPass::InitializeFrameBuffers() { - glGenRenderbuffers(1, &m_DepthBuffer); + /* glGenRenderbuffers(1, &m_DepthBuffer); glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBuffer); - glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); + glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height);*/ - m_PickingBuffer.AddResource(std::shared_ptr(new RenderBuffer(&m_DepthBuffer, GL_DEPTH_ATTACHMENT))); + glGenTextures(1, &m_DepthBuffer); + + glBindTexture(GL_TEXTURE_2D, m_DepthBuffer); + glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH24_STENCIL8, (int)(m_Renderer->GetViewportSize().Width), (int)(m_Renderer->GetViewportSize().Height), 0, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, nullptr); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); + + m_PickingBuffer.AddResource(std::shared_ptr(new Texture2D(&m_DepthBuffer, GL_DEPTH_ATTACHMENT))); m_PickingBuffer.AddResource(std::shared_ptr(new Texture2D(&m_PickingTexture, GL_COLOR_ATTACHMENT0))); m_PickingBuffer.Generate(); } @@ -61,7 +70,9 @@ void PickingPass::Draw(RenderScene& scene) m_PickingProgram->Bind(); if (scene.ClearDepth) { - glClear(GL_DEPTH_BUFFER_BIT); + //glClear(GL_DEPTH_BUFFER_BIT); + state->Disable(GL_DEPTH_TEST); + state->DepthMask(GL_FALSE); } m_Camera = scene.Camera; diff --git a/src/Engine/Rendering/Renderer.cpp b/src/Engine/Rendering/Renderer.cpp index 79c935a5..2336ff99 100644 --- a/src/Engine/Rendering/Renderer.cpp +++ b/src/Engine/Rendering/Renderer.cpp @@ -93,12 +93,15 @@ void Renderer::Update(double dt) void Renderer::Draw(RenderFrame& frame) { - ImGui::Combo("Draw textures", &m_DebugTextureToDraw, "Final\0Scene\0Bloom\0SceneLowRes\0BloomLowRes\0Gaussian\0Picking\0SSAO"); + ImGui::Combo("Draw textures", &m_DebugTextureToDraw, "Final\0Scene\0Bloom\0SceneLowRes\0BloomLowRes\0Gaussian\0Picking\0Ambient Occlusion"); - ImGui::SliderFloat("SSAO sample radius", &m_SSAO_Radius, 0.0001f, 1.0f); - ImGui::SliderFloat("SSAO bias", &m_SSAO_Bias, 0.0f, 1.0f); - ImGui::SliderFloat("SSAO intensity", &m_SSAO_Intensity, 0.0f, 1.0f); - m_SSAOPass->Setting(m_SSAO_Radius, m_SSAO_Bias, m_SSAO_Intensity); + ImGui::SliderFloat("SSAO sample radius", &m_SSAO_Radius, 0.01f, 5.0f); + ImGui::SliderFloat("SSAO bias", &m_SSAO_Bias, 0.0f, 0.1f); + ImGui::SliderFloat("SSAO contrast", &m_SSAO_Contrast, 0.0f, 10.0f); + ImGui::SliderFloat("SSAO IntensityScale", &m_SSAO_IntensityScale, 0.0f, 10.0f); + ImGui::SliderInt("SSAO Number of Samples", &m_SSAO_NumOfSamples, 2, 100); + ImGui::SliderInt("SSAO Number of Turns", &m_SSAO_NumOfTurns, 0, 50); + m_SSAOPass->Setting(m_SSAO_Radius, m_SSAO_Bias, m_SSAO_Contrast, m_SSAO_IntensityScale, m_SSAO_NumOfSamples, m_SSAO_NumOfTurns); //clear buffer 0 glClearColor(0.f, 0.f, 0.f, 0.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); @@ -107,20 +110,23 @@ void Renderer::Draw(RenderFrame& frame) m_PickingPass->ClearPicking(); m_DrawFinalPass->ClearBuffer(); m_DrawBloomPass->ClearBuffer(); - + for (auto scene : frame.RenderScenes) { + m_PickingPass->Draw(*scene); + GLERROR("Drawing pickingpass"); + } + m_SSAOPass->Draw(m_PickingPass->DepthBuffer(), frame.RenderScenes.front()->Camera); + GLuint ao = m_SSAOPass->SSAOTexture(); for (auto scene : frame.RenderScenes){ SortRenderJobsByDepth(*scene); GLERROR("SortByDepth"); - m_PickingPass->Draw(*scene); - GLERROR("Drawing pickingpass"); m_LightCullingPass->GenerateNewFrustum(*scene); GLERROR("Generate frustums"); m_LightCullingPass->FillLightList(*scene); GLERROR("Filling light list"); m_LightCullingPass->CullLights(*scene); GLERROR("LightCulling"); - m_DrawFinalPass->Draw(*scene); + m_DrawFinalPass->Draw(*scene, ao); GLERROR("Draw Geometry+Light"); //m_DrawScenePass->Draw(*scene); @@ -129,10 +135,9 @@ void Renderer::Draw(RenderFrame& frame) } m_DrawBloomPass->Draw(m_DrawFinalPass->BloomTexture()); - m_SSAOPass->Draw(m_DrawFinalPass->DepthBuffer(), m_DrawFinalPass->DepthBufferCamera()); if (m_DebugTextureToDraw == 0) { - m_DrawColorCorrectionPass->Draw(m_DrawFinalPass->SceneTexture(), m_DrawBloomPass->GaussianTexture(), m_DrawFinalPass->SceneTextureLowRes(), m_DrawFinalPass->BloomTextureLowRes(), m_SSAOPass->SSAOTexture(), frame.Gamma, frame.Exposure); + m_DrawColorCorrectionPass->Draw(m_DrawFinalPass->SceneTexture(), m_DrawBloomPass->GaussianTexture(), m_DrawFinalPass->SceneTextureLowRes(), m_DrawFinalPass->BloomTextureLowRes(), frame.Gamma, frame.Exposure); } if (m_DebugTextureToDraw == 1) { m_DrawScreenQuadPass->Draw(m_DrawFinalPass->SceneTexture()); diff --git a/src/Engine/Rendering/SSAOPass.cpp b/src/Engine/Rendering/SSAOPass.cpp index 67b5cf33..331e040f 100644 --- a/src/Engine/Rendering/SSAOPass.cpp +++ b/src/Engine/Rendering/SSAOPass.cpp @@ -8,7 +8,7 @@ SSAOPass::SSAOPass(IRenderer* renderer) InitializeBuffer(); InitializeShaderProgram(); - Setting(0.1f, 0.012f, 1.0f); + Setting(0.1f, 0.012f, 1.0f, 1.0f, 13, 7); m_DrawBloomPass = new DrawBloomPass(renderer); } @@ -31,12 +31,12 @@ void SSAOPass::InitializeShaderProgram() void SSAOPass::InitializeBuffer() { - GenerateTexture(&m_SSAOTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB16F, GL_RGB, GL_FLOAT); + GenerateTexture(&m_SSAOTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_R8, GL_RED, GL_FLOAT); m_SSAOFramBuffer.AddResource(std::shared_ptr(new Texture2D(&m_SSAOTexture, GL_COLOR_ATTACHMENT0))); m_SSAOFramBuffer.Generate(); - GenerateTexture(&m_SSAOViewSpaceZTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RGB32F, GL_RGB, GL_FLOAT); + GenerateTexture(&m_SSAOViewSpaceZTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_R32F, GL_RED, GL_FLOAT); m_SSAOViewSpaceZFramBuffer.AddResource(std::shared_ptr(new Texture2D(&m_SSAOViewSpaceZTexture, GL_COLOR_ATTACHMENT0))); m_SSAOViewSpaceZFramBuffer.Generate(); @@ -55,10 +55,13 @@ void SSAOPass::ClearBuffer() m_SSAOViewSpaceZFramBuffer.Unbind(); } -void SSAOPass::Setting(float radius, float bias, float intensity) { +void SSAOPass::Setting(float radius, float bias, float contrast, float intensityScale, int numOfSamples, int NumOfTurns) { m_Radius = radius; m_Bias = bias; - m_Intensity = intensity; + m_Contrast = contrast; + m_IntensityScale = intensityScale; + m_NumOfSamples = numOfSamples; + m_NumOfTurns = NumOfTurns; } void SSAOPass::GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const @@ -102,10 +105,10 @@ void SSAOPass::Draw(GLuint depthBuffer, Camera* camera) , GL_UNSIGNED_INT, 0, m_ScreenQuad->MaterialGroups()[0].material->StartIndex); glm::vec4 projInfo = glm::vec4( - (-2.0f / (m_Renderer->GetViewportSize().Width * camera->ProjectionMatrix()[0][0])), - (-2.0f / (m_Renderer->GetViewportSize().Height * camera->ProjectionMatrix()[1][1])), - ((1.0f - camera->ProjectionMatrix()[0][2]) / camera->ProjectionMatrix()[0][0]), - ((1.0f - camera->ProjectionMatrix()[1][2]) / camera->ProjectionMatrix()[1][1]) + ((1.0 - camera->ProjectionMatrix()[0][2]) / camera->ProjectionMatrix()[0][0]), + (-2.0 / (m_Renderer->GetViewportSize().Width * camera->ProjectionMatrix()[0][0])), + ((1.0 + camera->ProjectionMatrix()[1][2]) / camera->ProjectionMatrix()[1][1]), + (-2.0 / (m_Renderer->GetViewportSize().Height * camera->ProjectionMatrix()[1][1])) ); @@ -116,13 +119,16 @@ void SSAOPass::Draw(GLuint depthBuffer, Camera* camera) glBindTexture(GL_TEXTURE_2D, m_SSAOViewSpaceZTexture); // How many pixel there are in a 1m long object 1m away from the camera - glUniform1f(glGetUniformLocation(SSAOShaderHandle, "ProjScale"), m_Renderer->GetViewportSize().Height / (-2.0f * glm::tan(camera->FOV() * 0.5f))); + glUniform1f(glGetUniformLocation(SSAOShaderHandle, "uProjScale"), m_Renderer->GetViewportSize().Height / (-2.0f * glm::tan(camera->FOV() * 0.5f))); - glUniform1f(glGetUniformLocation(SSAOShaderHandle, "Radius"), m_Radius); - glUniform1f(glGetUniformLocation(SSAOShaderHandle, "Bias"), m_Bias); - glUniform1f(glGetUniformLocation(SSAOShaderHandle, "IntensityDivR6"), m_Intensity / glm::pow(m_Radius, 6)); + glUniform1f(glGetUniformLocation(SSAOShaderHandle, "uRadius"), m_Radius); + glUniform1f(glGetUniformLocation(SSAOShaderHandle, "uBias"), m_Bias); + glUniform1f(glGetUniformLocation(SSAOShaderHandle, "uContrast"), m_Contrast); + glUniform1f(glGetUniformLocation(SSAOShaderHandle, "uIntensityScale"), m_IntensityScale); + glUniform1i(glGetUniformLocation(SSAOShaderHandle, "uNumOfSamples"), m_NumOfSamples); + glUniform1i(glGetUniformLocation(SSAOShaderHandle, "uNumOfTurns"), m_NumOfTurns);; - glUniform4fv(glGetUniformLocation(SSAOShaderHandle, "ProjInfo"), 1, glm::value_ptr(projInfo)); + glUniform4fv(glGetUniformLocation(SSAOShaderHandle, "uProjInfo"), 1, glm::value_ptr(projInfo)); 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); From 4cf8c3d8d7dacbb6d5ab9fd74deb1377e367a038 Mon Sep 17 00:00:00 2001 From: Teejoon Date: Mon, 22 Feb 2016 15:02:20 +0100 Subject: [PATCH 321/355] Fixed PerformanceTimer start and stop in Renderer.cpp since I have changed a little code there --- src/Engine/Rendering/Renderer.cpp | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/Engine/Rendering/Renderer.cpp b/src/Engine/Rendering/Renderer.cpp index 3ab05514..0c668cad 100644 --- a/src/Engine/Rendering/Renderer.cpp +++ b/src/Engine/Rendering/Renderer.cpp @@ -128,17 +128,20 @@ void Renderer::Draw(RenderFrame& frame) m_DrawBloomPass->ClearBuffer(); PerformanceTimer::StopTimer("Renderer-ClearBuffers"); for (auto scene : frame.RenderScenes) { + PerformanceTimer::StartTimer("Renderer-Depth"); m_PickingPass->Draw(*scene); GLERROR("Drawing pickingpass"); + PerformanceTimer::StopTimer("Renderer-Depth"); } + PerformanceTimer::StartTimer("AO generation"); m_SSAOPass->Draw(m_PickingPass->DepthBuffer(), frame.RenderScenes.front()->Camera); GLuint ao = m_SSAOPass->SSAOTexture(); + PerformanceTimer::StopTimer("AO generation"); for (auto scene : frame.RenderScenes){ - PerformanceTimer::StartTimer("Renderer-Depth"); + PerformanceTimer::StartTimer("Renderer-Drawing PickingPass"); SortRenderJobsByDepth(*scene); GLERROR("SortByDepth"); - PerformanceTimer::StartTimerAndStopPrevious("Renderer-Drawing PickingPass"); PerformanceTimer::StartTimerAndStopPrevious("Renderer-Generate Frustrums"); m_LightCullingPass->GenerateNewFrustum(*scene); GLERROR("Generate frustums"); @@ -158,14 +161,17 @@ void Renderer::Draw(RenderFrame& frame) GLERROR("Draw Text"); PerformanceTimer::StopTimer("Renderer-Draw Text"); } + PerformanceTimer::StartTimer("Renderer-Draw Bloom"); m_DrawBloomPass->Draw(m_DrawFinalPass->BloomTexture()); PerformanceTimer::StopTimer("Renderer-Draw Bloom"); + if (m_DebugTextureToDraw == 0) { PerformanceTimer::StartTimer("Renderer-Color Correction Pass"); m_DrawColorCorrectionPass->Draw(m_DrawFinalPass->SceneTexture(), m_DrawBloomPass->GaussianTexture(), m_DrawFinalPass->SceneTextureLowRes(), m_DrawFinalPass->BloomTextureLowRes(), frame.Gamma, frame.Exposure); PerformanceTimer::StopTimer("Renderer-Color Correction Pass"); } + PerformanceTimer::StartTimer("Renderer-Misc Debug Draws"); if (m_DebugTextureToDraw == 1) { m_DrawScreenQuadPass->Draw(m_DrawFinalPass->SceneTexture()); @@ -185,10 +191,10 @@ void Renderer::Draw(RenderFrame& frame) if (m_DebugTextureToDraw == 6) { m_DrawScreenQuadPass->Draw(m_PickingPass->PickingTexture()); } - PerformanceTimer::StopTimer("Renderer-Misc Debug Draws"); if (m_DebugTextureToDraw == 7) { m_DrawScreenQuadPass->Draw(m_SSAOPass->SSAOTexture()); } + PerformanceTimer::StopTimer("Renderer-Misc Debug Draws"); PerformanceTimer::StartTimer("Renderer-ImGuiRenderPass"); m_ImGuiRenderPass->Draw(); From ed9149fe63d049522e8a0adccb7bca2b507471b2 Mon Sep 17 00:00:00 2001 From: Jocke Date: Mon, 22 Feb 2016 16:01:26 +0100 Subject: [PATCH 322/355] Network buffer should now dynamically increase when needed. --- include/Engine/Network/NetworkClient.h | 5 +- include/Engine/Network/NetworkServer.cpp | 9 ++++ include/Engine/Network/NetworkServer.h | 5 +- include/Engine/Network/TCPClient.h | 2 +- include/Engine/Network/TCPServer.h | 2 +- include/Engine/Network/UDPClient.h | 2 +- include/Engine/Network/UDPServer.h | 2 +- src/Engine/Network/NetworkClient.cpp | 9 ++++ src/Engine/Network/Server.cpp | 4 +- src/Engine/Network/TCPClient.cpp | 47 ++++++++++++---- src/Engine/Network/TCPServer.cpp | 68 +++++++++++++++++++----- src/Engine/Network/UDPClient.cpp | 44 ++++++++++++--- src/Engine/Network/UDPServer.cpp | 52 ++++++++++++++---- 13 files changed, 206 insertions(+), 45 deletions(-) create mode 100644 include/Engine/Network/NetworkServer.cpp diff --git a/include/Engine/Network/NetworkClient.h b/include/Engine/Network/NetworkClient.h index d0339d84..4adc68f5 100644 --- a/include/Engine/Network/NetworkClient.h +++ b/include/Engine/Network/NetworkClient.h @@ -9,13 +9,16 @@ typedef unsigned int PacketID; class NetworkClient { public: + NetworkClient(); + virtual ~NetworkClient(); virtual void Connect(std::string playerName, std::string address, int port) = 0; virtual void Disconnect() = 0; virtual void Receive(Packet& packet) = 0; virtual void Send(Packet & packet) = 0; virtual bool IsSocketAvailable() = 0; protected: - char m_ReadBuffer[BUFFERSIZE] = { 0 }; + char* m_ReadBuffer; + unsigned int m_BufferSize = BUFFERSIZE; }; #endif \ No newline at end of file diff --git a/include/Engine/Network/NetworkServer.cpp b/include/Engine/Network/NetworkServer.cpp new file mode 100644 index 00000000..5a61fc61 --- /dev/null +++ b/include/Engine/Network/NetworkServer.cpp @@ -0,0 +1,9 @@ +#include "NetworkServer.h" + +NetworkServer::NetworkServer() +{ + m_ReadBuffer = new char[m_BufferSize]; +} + +NetworkServer::~NetworkServer() +{ } diff --git a/include/Engine/Network/NetworkServer.h b/include/Engine/Network/NetworkServer.h index ccec82cc..296c8762 100644 --- a/include/Engine/Network/NetworkServer.h +++ b/include/Engine/Network/NetworkServer.h @@ -10,12 +10,15 @@ typedef unsigned int PacketID; class NetworkServer { public: + NetworkServer(); + virtual ~NetworkServer(); virtual void AcceptNewConnections(int& nextPlayerID, std::map& connectedPlayers) = 0; virtual void Receive(Packet & packet, PlayerDefinition & playerDefinition) = 0; virtual void Send(Packet & packet, PlayerDefinition & playerDefinition) = 0; virtual void Send(Packet & packet) = 0; protected: - char m_ReadBuffer[BUFFERSIZE] = { 0 }; + char* m_ReadBuffer; + unsigned int m_BufferSize = BUFFERSIZE; }; #endif \ No newline at end of file diff --git a/include/Engine/Network/TCPClient.h b/include/Engine/Network/TCPClient.h index a666cbbe..2108fa3d 100644 --- a/include/Engine/Network/TCPClient.h +++ b/include/Engine/Network/TCPClient.h @@ -20,7 +20,7 @@ private: boost::asio::ip::tcp::endpoint m_Endpoint; boost::asio::io_service m_IOService; std::unique_ptr m_Socket; - size_t readBuffer(char* data); + size_t readBuffer(); PacketID m_SendPacketID = 0; bool m_IsConnected = false; }; diff --git a/include/Engine/Network/TCPServer.h b/include/Engine/Network/TCPServer.h index 9cc7646a..9294f5e8 100644 --- a/include/Engine/Network/TCPServer.h +++ b/include/Engine/Network/TCPServer.h @@ -25,7 +25,7 @@ private: void handle_accept(boost::shared_ptr socket, int& nextPlayerID, std::map& connectedPlayers, const boost::system::error_code& error); - int readBuffer(char* data, PlayerDefinition& playerDefinition); + int readBuffer(PlayerDefinition& playerDefinition); }; #endif \ No newline at end of file diff --git a/include/Engine/Network/UDPClient.h b/include/Engine/Network/UDPClient.h index 3a458d3e..f77a2382 100644 --- a/include/Engine/Network/UDPClient.h +++ b/include/Engine/Network/UDPClient.h @@ -20,7 +20,7 @@ private: boost::asio::io_service m_IOService; boost::asio::ip::udp::endpoint m_ReceiverEndpoint; boost::shared_ptr m_Socket; - int readBuffer(char* data); + int readBuffer(); PacketID m_SendPacketID = 0; }; diff --git a/include/Engine/Network/UDPServer.h b/include/Engine/Network/UDPServer.h index 246fb333..73279ef3 100644 --- a/include/Engine/Network/UDPServer.h +++ b/include/Engine/Network/UDPServer.h @@ -19,7 +19,7 @@ private: boost::asio::io_service m_IOService; boost::asio::ip::udp::endpoint m_ReceiverEndpoint; std::unique_ptr m_Socket; - int readBuffer(char* data); + int readBuffer(); }; #endif \ No newline at end of file diff --git a/src/Engine/Network/NetworkClient.cpp b/src/Engine/Network/NetworkClient.cpp index e69de29b..eba8e2a1 100644 --- a/src/Engine/Network/NetworkClient.cpp +++ b/src/Engine/Network/NetworkClient.cpp @@ -0,0 +1,9 @@ +#include "..\..\..\include\Engine\Network\NetworkClient.h" + +NetworkClient::NetworkClient() +{ + m_ReadBuffer = new char[m_BufferSize]; +} + +NetworkClient::~NetworkClient() +{ } diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index aa66433b..556834dc 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -446,7 +446,9 @@ void Server::parsePing() { for (auto& kv : m_ConnectedPlayers) { if (kv.second.TCPAddress == m_Address && - kv.second.TCPPort == m_Port) { + kv.second.TCPPort == m_Port + || (kv.second.Endpoint.address() == m_Address + && kv.second.Endpoint.port() == m_Port)) { kv.second.StopTime = std::clock(); break; } diff --git a/src/Engine/Network/TCPClient.cpp b/src/Engine/Network/TCPClient.cpp index df4f3826..e752161c 100644 --- a/src/Engine/Network/TCPClient.cpp +++ b/src/Engine/Network/TCPClient.cpp @@ -56,32 +56,61 @@ void TCPClient::Disconnect() void TCPClient::Receive(Packet& packet) { - size_t bytesRead = readBuffer(m_ReadBuffer); + size_t bytesRead = readBuffer(); if (bytesRead > 0) { packet.ReconstructFromData(m_ReadBuffer, bytesRead); } } -size_t TCPClient::readBuffer(char* data) +size_t TCPClient::readBuffer() { + //if (!m_Socket) { + // return 0; + //} + //boost::system::error_code error; + //// Read size of packet + //size_t bytesReceived = m_Socket->read_some(boost + // ::asio::buffer((void*)data, sizeof(int)), + // error); + //int sizeOfPacket = 0; + //memcpy(&sizeOfPacket, data, sizeof(int)); + + //// Read the rest of the message + //bytesReceived += m_Socket->read_some(boost + // ::asio::buffer((void*)(data + bytesReceived), sizeOfPacket - bytesReceived), + // error); + //if (error) { + // //LOG_ERROR("receive: %s", error.message().c_str()); + //} + //return bytesReceived; + if (!m_Socket) { return 0; } boost::system::error_code error; // Read size of packet - size_t bytesReceived = m_Socket->read_some(boost - ::asio::buffer((void*)data, sizeof(int)), - error); - int sizeOfPacket = 0; - memcpy(&sizeOfPacket, data, sizeof(int)); + m_Socket->receive(boost + ::asio::buffer((void*)m_ReadBuffer, sizeof(int)), + boost::asio::ip::tcp::socket::message_peek, error); + unsigned int sizeOfPacket = 0; + memcpy(&sizeOfPacket, m_ReadBuffer, sizeof(int)); + // if the buffer is to small increase the size of it + if (sizeOfPacket > m_BufferSize) { + delete[] m_ReadBuffer; + m_ReadBuffer = new char[sizeOfPacket]; + m_BufferSize = sizeOfPacket; + } // Read the rest of the message - bytesReceived += m_Socket->read_some(boost - ::asio::buffer((void*)(data + bytesReceived), sizeOfPacket - bytesReceived), + size_t bytesReceived = m_Socket->read_some(boost + ::asio::buffer((void*)(m_ReadBuffer), sizeOfPacket), error); if (error) { //LOG_ERROR("receive: %s", error.message().c_str()); } + if (sizeOfPacket > 1000000) + LOG_WARNING("The packets received are bigger than 1MB"); + return bytesReceived; } diff --git a/src/Engine/Network/TCPServer.cpp b/src/Engine/Network/TCPServer.cpp index a449e684..7080bd6d 100644 --- a/src/Engine/Network/TCPServer.cpp +++ b/src/Engine/Network/TCPServer.cpp @@ -7,8 +7,7 @@ TCPServer::TCPServer() } TCPServer::~TCPServer() -{ -} +{ } void TCPServer::AcceptNewConnections(int& nextPlayerID, std::map& connectedPlayers) { @@ -31,7 +30,7 @@ PlayerID GetPlayerIDFromEndpoint(const std::map& con return -1; } -void TCPServer::handle_accept(boost::shared_ptr socket, +void TCPServer::handle_accept(boost::shared_ptr socket, int& nextPlayerID, std::map& connectedPlayers, const boost::system::error_code& error) { @@ -51,6 +50,8 @@ void TCPServer::handle_accept(boost::shared_ptr socket, void TCPServer::Send(Packet & packet, PlayerDefinition & playerDefinition) { + if (!playerDefinition.TCPSocket) + return; try { packet.UpdateSize(); int bytesSent = playerDefinition.TCPSocket->send( @@ -73,38 +74,79 @@ void TCPServer::Send(Packet & packet) } void TCPServer::Disconnect() -{ +{ } +//void TCPServer::Receive(Packet & packet, PlayerDefinition & playerDefinition) +//{ +// int bytesRead = readBuffer(m_ReadBuffer, playerDefinition); +// if (bytesRead > 0) { +// packet.ReconstructFromData(m_ReadBuffer, bytesRead); +// } +// lastReceivedSocket = playerDefinition.TCPSocket; +//} +// +//int TCPServer::readBuffer(char* data, PlayerDefinition & playerDefinition) +//{ +// if (!playerDefinition.TCPSocket) { +// return 0; +// } +// boost::system::error_code error; +// // Read size of packet +// size_t bytesReceived = playerDefinition.TCPSocket->read_some(boost +// ::asio::buffer((void*)data, sizeof(int)), +// error); +// int sizeOfPacket = 0; +// memcpy(&sizeOfPacket, data, sizeof(int)); +// +// // Read the rest of the message +// bytesReceived += playerDefinition.TCPSocket->read_some(boost +// ::asio::buffer((void*)(data + bytesReceived), sizeOfPacket - bytesReceived), +// error); +// if (error) { +// //LOG_ERROR("receive: %s", error.message().c_str()); +// } +// return bytesReceived; +//} + void TCPServer::Receive(Packet & packet, PlayerDefinition & playerDefinition) { - int bytesRead = readBuffer(m_ReadBuffer, playerDefinition); + int bytesRead = readBuffer(playerDefinition); if (bytesRead > 0) { packet.ReconstructFromData(m_ReadBuffer, bytesRead); } lastReceivedSocket = playerDefinition.TCPSocket; } -int TCPServer::readBuffer(char* data, PlayerDefinition & playerDefinition) +int TCPServer::readBuffer(PlayerDefinition & playerDefinition) { if (!playerDefinition.TCPSocket) { return 0; } boost::system::error_code error; // Read size of packet - size_t bytesReceived = playerDefinition.TCPSocket->read_some(boost - ::asio::buffer((void*)data, sizeof(int)), - error); - int sizeOfPacket = 0; - memcpy(&sizeOfPacket, data, sizeof(int)); + playerDefinition.TCPSocket->receive(boost + ::asio::buffer((void*)m_ReadBuffer, sizeof(int)), + boost::asio::ip::tcp::socket::message_peek, error); + unsigned int sizeOfPacket = 0; + memcpy(&sizeOfPacket, m_ReadBuffer, sizeof(int)); + // if the buffer is to small increase the size of it + if (sizeOfPacket > m_BufferSize) { + delete[] m_ReadBuffer; + m_ReadBuffer = new char[sizeOfPacket]; + m_BufferSize = sizeOfPacket; + } // Read the rest of the message - bytesReceived += playerDefinition.TCPSocket->read_some(boost - ::asio::buffer((void*)(data + bytesReceived), sizeOfPacket - bytesReceived), + size_t bytesReceived = playerDefinition.TCPSocket->read_some(boost + ::asio::buffer((void*)(m_ReadBuffer), sizeOfPacket), error); if (error) { //LOG_ERROR("receive: %s", error.message().c_str()); } + if (sizeOfPacket > 1000000) + LOG_WARNING("The packets received are bigger than 1MB"); + return bytesReceived; } \ No newline at end of file diff --git a/src/Engine/Network/UDPClient.cpp b/src/Engine/Network/UDPClient.cpp index c76de084..d4e7bb19 100644 --- a/src/Engine/Network/UDPClient.cpp +++ b/src/Engine/Network/UDPClient.cpp @@ -27,30 +27,62 @@ void UDPClient::Disconnect() void UDPClient::Receive(Packet& packet) { - int bytesRead = readBuffer(m_ReadBuffer); + int bytesRead = readBuffer(); if (bytesRead > 0) { packet.ReconstructFromData(m_ReadBuffer, bytesRead); } } -int UDPClient::readBuffer(char* data) +int UDPClient::readBuffer() { + //if (!m_Socket) { + // return 0; + //} + //boost::system::error_code error; + //int bytesReceived = m_Socket->receive_from(boost + // ::asio::buffer((void*)data, BUFFERSIZE), + // m_ReceiverEndpoint, + // 0, error); + //if (error) { + // //LOG_ERROR("receive: %s", error.message().c_str()); + //} + //return bytesReceived; if (!m_Socket) { return 0; } boost::system::error_code error; - int bytesReceived = m_Socket->receive_from(boost - ::asio::buffer((void*)data, BUFFERSIZE), - m_ReceiverEndpoint, - 0, error); + // Read size of packet + m_Socket->receive(boost + ::asio::buffer((void*)m_ReadBuffer, sizeof(int)), + boost::asio::ip::udp::socket::message_peek, error); + int sizeOfPacket = 0; + memcpy(&sizeOfPacket, m_ReadBuffer, sizeof(int)); + + // if the buffer is to small increase the size of it + if (sizeOfPacket > m_BufferSize) { + delete[] m_ReadBuffer; + m_ReadBuffer = new char[sizeOfPacket]; + m_BufferSize = sizeOfPacket; + } + + size_t availableData = m_Socket->available(); + // Read the rest of the message + size_t bytesReceived = m_Socket->receive_from(boost + ::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"); + return bytesReceived; } void UDPClient::Send(Packet& packet) { + packet.UpdateSize(); m_Socket->send_to(boost::asio::buffer( packet.Data(), packet.Size()), diff --git a/src/Engine/Network/UDPServer.cpp b/src/Engine/Network/UDPServer.cpp index 4b0a08ba..163b959f 100644 --- a/src/Engine/Network/UDPServer.cpp +++ b/src/Engine/Network/UDPServer.cpp @@ -10,6 +10,7 @@ UDPServer::~UDPServer() void UDPServer::Send(Packet& packet, PlayerDefinition & playerDefinition) { + packet.UpdateSize(); try { int bytesSent = m_Socket->send_to( boost::asio::buffer(packet.Data(), packet.Size()), @@ -23,6 +24,7 @@ void UDPServer::Send(Packet& packet, PlayerDefinition & playerDefinition) // Send back to endpoint of received packet void UDPServer::Send(Packet & packet) { + packet.UpdateSize(); m_Socket->send_to( boost::asio::buffer( packet.Data(), @@ -33,7 +35,7 @@ void UDPServer::Send(Packet & packet) void UDPServer::Receive(Packet & packet, PlayerDefinition & playerDefinition) { - int bytesRead = readBuffer(m_ReadBuffer); + int bytesRead = readBuffer(); if (bytesRead > 0) { packet.ReconstructFromData(m_ReadBuffer, bytesRead); } @@ -45,17 +47,47 @@ bool UDPServer::IsSocketAvailable() return m_Socket->available(); } -int UDPServer::readBuffer(char* data) +int UDPServer::readBuffer() { - boost::system::error_code error = boost::asio::error::host_not_found; - unsigned int length = m_Socket->receive_from( - boost::asio::buffer((void*)data - , BUFFERSIZE) - , m_ReceiverEndpoint, 0, error); - if (error) { - LOG_WARNING(error.message().c_str()); + //boost::system::error_code error = boost::asio::error::host_not_found; + //unsigned int length = m_Socket->receive_from( + // boost::asio::buffer((void*)data + // , BUFFERSIZE) + // , m_ReceiverEndpoint, 0, error); + //if (error) { + // LOG_WARNING(error.message().c_str()); + //} + //return length; + if (!m_Socket) { + return 0; } - return length; + boost::system::error_code error; + // Read size of packet + 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; + memcpy(&sizeOfPacket, m_ReadBuffer, sizeof(int)); + + // if the buffer is to small increase the size of it + if (sizeOfPacket > m_BufferSize) { + delete[] m_ReadBuffer; + m_ReadBuffer = new char[sizeOfPacket]; + m_BufferSize = sizeOfPacket; + } + + // Read the rest of the message + size_t bytesReceived = m_Socket->receive_from(boost + ::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"); + + return bytesReceived; } void UDPServer::AcceptNewConnections(int& nextPlayerID, std::map& connectedPlayers) From 09aec08d0e210ee045e72821d73aeec60b79e9dd Mon Sep 17 00:00:00 2001 From: Teejoon Date: Mon, 22 Feb 2016 16:38:20 +0100 Subject: [PATCH 323/355] Pull request fixes --- include/Engine/Rendering/DrawFinalPass.h | 4 --- src/Engine/Rendering/DrawFinalPass.cpp | 32 ++++++++---------------- 2 files changed, 11 insertions(+), 25 deletions(-) diff --git a/include/Engine/Rendering/DrawFinalPass.h b/include/Engine/Rendering/DrawFinalPass.h index 0be65caf..e3389471 100644 --- a/include/Engine/Rendering/DrawFinalPass.h +++ b/include/Engine/Rendering/DrawFinalPass.h @@ -22,9 +22,6 @@ public: void ClearBuffer(); void OnWindowResize(); - //Return the texture that is used in later stages to apply the bloom effect - GLuint DepthBuffer() const { return m_DepthBuffer; } - Camera* DepthBufferCamera() const { return RenderCamera; } //Return the texture that is used in later stages to apply the bloom effect GLuint BloomTexture() const { return m_BloomTexture; } GLuint BloomTextureLowRes() const { return m_BloomTextureLowRes; } @@ -65,7 +62,6 @@ private: GLuint m_SceneTextureLowRes; GLuint m_DepthBuffer; GLuint m_DepthBufferLowRes; - Camera* RenderCamera; //maqke this component based i guess? GLuint m_ShieldPixelRate = 16; diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index 97482b3b..a12c52b1 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -177,7 +177,6 @@ void DrawFinalPass::InitializeShaderPrograms() void DrawFinalPass::Draw(RenderScene& scene, GLuint SSAOTexture) { GLERROR("Pre"); - RenderCamera = scene.Camera; DrawFinalPassState* state = new DrawFinalPassState(m_FinalPassFrameBuffer.GetHandle()); if (scene.ClearDepth) { //glClear(GL_DEPTH_BUFFER_BIT); @@ -768,26 +767,17 @@ void DrawFinalPass::BindExplosionUniforms(GLuint shaderHandle, std::shared_ptr& job, RenderScene& scene) { - if (1/*job->Model->IsSkinned()*/) { - GLERROR("Bind 1 uniform"); - GLint Location_M = glGetUniformLocation(shaderHandle, "M"); - glUniformMatrix4fv(Location_M, 1, GL_FALSE, glm::value_ptr(job->Matrix)); - GLERROR("Bind 2 uniform"); - GLint Location_V = glGetUniformLocation(shaderHandle, "V"); - glUniformMatrix4fv(Location_V, 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix())); - GLERROR("Bind 3 uniform"); - GLint Location_P = glGetUniformLocation(shaderHandle, "P"); - glUniformMatrix4fv(Location_P, 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix())); - GLERROR("Bind 4 uniform"); - } else { - GLERROR("Bind 1 uniform"); - GLint Location_M = glGetUniformLocation(shaderHandle, "M"); - glUniformMatrix4fv(Location_M, 1, GL_FALSE, glm::value_ptr(job->Matrix)); - GLERROR("Bind 2 uniform"); - GLint Location_V = glGetUniformLocation(shaderHandle, "PV"); - glUniformMatrix4fv(Location_V, 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix() * scene.Camera->ViewMatrix())); - GLERROR("Bind 3 uniform"); - } + GLERROR("Bind 1 uniform"); + GLint Location_M = glGetUniformLocation(shaderHandle, "M"); + glUniformMatrix4fv(Location_M, 1, GL_FALSE, glm::value_ptr(job->Matrix)); + GLERROR("Bind 2 uniform"); + GLint Location_V = glGetUniformLocation(shaderHandle, "V"); + glUniformMatrix4fv(Location_V, 1, GL_FALSE, glm::value_ptr(scene.Camera->ViewMatrix())); + GLERROR("Bind 3 uniform"); + GLint Location_P = glGetUniformLocation(shaderHandle, "P"); + glUniformMatrix4fv(Location_P, 1, GL_FALSE, glm::value_ptr(scene.Camera->ProjectionMatrix())); + GLERROR("Bind 4 uniform"); + GLint Location_ScreenDimensions = glGetUniformLocation(shaderHandle, "ScreenDimensions"); glUniform2f(Location_ScreenDimensions, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); GLERROR("Bind 5 uniform"); From b2d8cddfb745feb8482fa1320bccf38ddd0d307e Mon Sep 17 00:00:00 2001 From: Jocke Date: Mon, 22 Feb 2016 16:46:31 +0100 Subject: [PATCH 324/355] WE now send the map on connect after that only player information. --- include/Engine/Network/NetworkServer.cpp | 4 +- include/Engine/Network/Server.h | 5 ++- src/Engine/Network/NetworkClient.cpp | 4 +- src/Engine/Network/Server.cpp | 52 +++++++++++++++++++++++- src/Engine/Network/TCPClient.cpp | 1 + src/Engine/Network/TCPServer.cpp | 4 +- 6 files changed, 61 insertions(+), 9 deletions(-) diff --git a/include/Engine/Network/NetworkServer.cpp b/include/Engine/Network/NetworkServer.cpp index 5a61fc61..d553ef3d 100644 --- a/include/Engine/Network/NetworkServer.cpp +++ b/include/Engine/Network/NetworkServer.cpp @@ -6,4 +6,6 @@ NetworkServer::NetworkServer() } NetworkServer::~NetworkServer() -{ } +{ + delete[] m_ReadBuffer; +} diff --git a/include/Engine/Network/Server.h b/include/Engine/Network/Server.h index b37bffab..94705beb 100644 --- a/include/Engine/Network/Server.h +++ b/include/Engine/Network/Server.h @@ -54,7 +54,7 @@ private: std::vector m_InputCommandsToBroadcast; //Timers std::clock_t m_StartPingTime; - + // Packet loss logic PacketID m_PacketID = 0; PacketID m_PreviousPacketID = 0; @@ -64,6 +64,7 @@ private: void reliableBroadcast(Packet& packet); void unreliableBroadcast(Packet& packet); void sendSnapshot(); + void addPlayersToPacket(Packet& packet, EntityID entityID); void addChildrenToPacket(Packet& packet, EntityID entityID); void addInputCommandsToPacket(Packet& packet); void sendPing(); @@ -77,7 +78,7 @@ private: void parsePlayerTransform(Packet& packet); void parseOnInputCommand(Packet& packet); void parseClientPing(); - void parsePing(); + void parsePing(); void parseUDPConnect(Packet & packet); void parseTCPConnect(Packet & packet); void parseDisconnect(); diff --git a/src/Engine/Network/NetworkClient.cpp b/src/Engine/Network/NetworkClient.cpp index eba8e2a1..cc046176 100644 --- a/src/Engine/Network/NetworkClient.cpp +++ b/src/Engine/Network/NetworkClient.cpp @@ -6,4 +6,6 @@ NetworkClient::NetworkClient() } NetworkClient::~NetworkClient() -{ } +{ + delete[] m_ReadBuffer; +} diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index 556834dc..37692e60 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -146,7 +146,7 @@ void Server::sendSnapshot() { Packet packet(MessageType::Snapshot); addInputCommandsToPacket(packet); - addChildrenToPacket(packet, EntityID_Invalid); + addPlayersToPacket(packet, EntityID_Invalid); unreliableBroadcast(packet); } @@ -163,7 +163,7 @@ void Server::addInputCommandsToPacket(Packet& packet) m_InputCommandsToBroadcast.clear(); } -void Server::addChildrenToPacket(Packet & packet, EntityID entityID) +void Server::addPlayersToPacket(Packet & packet, EntityID entityID) { auto itPair = m_World->GetChildren(entityID); std::unordered_map worldComponentPools = m_World->GetComponentPools(); @@ -212,6 +212,49 @@ void Server::addChildrenToPacket(Packet & packet, EntityID entityID) } } +void Server::addChildrenToPacket(Packet & packet, EntityID entityID) +{ + auto itPair = m_World->GetChildren(entityID); + std::unordered_map worldComponentPools = m_World->GetComponentPools(); + // Loop through every child + for (auto it = itPair.first; it != itPair.second; it++) { + EntityID childEntityID = it->second; + // Write EntityID and parentsID and Entity name + packet.WritePrimitive(childEntityID); + packet.WritePrimitive(entityID); + packet.WriteString(m_World->GetName(childEntityID)); + // Write components to child + int numberOfComponents = 0; + for (auto& i : worldComponentPools) { + if (i.second->KnowsEntity(childEntityID)) { + numberOfComponents++; + } + } + // Write how many components should be read + packet.WritePrimitive(numberOfComponents); + for (auto& i : worldComponentPools) { + // If the entity exist in the pool + if (i.second->KnowsEntity(childEntityID)) { + ComponentWrapper componentWrapper = i.second->GetByEntity(childEntityID); + // ComponentType + packet.WriteString(componentWrapper.Info.Name); + // Loop through fields + for (auto& componentField : componentWrapper.Info.FieldsInOrder) { + ComponentInfo::Field_t fieldInfo = componentWrapper.Info.Fields.at(componentField); + if (fieldInfo.Type == "string") { + std::string& value = componentWrapper[componentField]; + packet.WriteString(value); + } else { + packet.WriteData(componentWrapper.Data + fieldInfo.Offset, fieldInfo.Stride); + } + } + } + } + // Go to to your children + addChildrenToPacket(packet, childEntityID); + } +} + void Server::sendPing() { // Prints connected players ping @@ -304,6 +347,11 @@ void Server::parseTCPConnect(Packet & packet) connnectPacket.WritePrimitive(playerID); m_Reliable.Send(connnectPacket); + Packet firstSnapshot(MessageType::Snapshot); + addInputCommandsToPacket(firstSnapshot); + addChildrenToPacket(firstSnapshot, EntityID_Invalid); + m_Reliable.Send(firstSnapshot); + // Send notification that a player has connected //Packet notificationPacket(MessageType::PlayerConnected); //broadcast(notificationPacket); diff --git a/src/Engine/Network/TCPClient.cpp b/src/Engine/Network/TCPClient.cpp index e752161c..f2920ae5 100644 --- a/src/Engine/Network/TCPClient.cpp +++ b/src/Engine/Network/TCPClient.cpp @@ -96,6 +96,7 @@ size_t TCPClient::readBuffer() memcpy(&sizeOfPacket, m_ReadBuffer, sizeof(int)); // if the buffer is to small increase the size of it + // TODO if message is huge 1 time the buffer will not decrease. if (sizeOfPacket > m_BufferSize) { delete[] m_ReadBuffer; m_ReadBuffer = new char[sizeOfPacket]; diff --git a/src/Engine/Network/TCPServer.cpp b/src/Engine/Network/TCPServer.cpp index 7080bd6d..425a9a4a 100644 --- a/src/Engine/Network/TCPServer.cpp +++ b/src/Engine/Network/TCPServer.cpp @@ -50,10 +50,8 @@ void TCPServer::handle_accept(boost::shared_ptr socket, void TCPServer::Send(Packet & packet, PlayerDefinition & playerDefinition) { - if (!playerDefinition.TCPSocket) - return; + packet.UpdateSize(); try { - packet.UpdateSize(); int bytesSent = playerDefinition.TCPSocket->send( boost::asio::buffer(packet.Data(), packet.Size()), 0); From 833006744a6dcce40c3d9f162f992dd22198c8fa Mon Sep 17 00:00:00 2001 From: stiffly Date: Mon, 22 Feb 2016 17:00:25 +0100 Subject: [PATCH 325/355] WIP --- include/Engine/Network/Client.h | 1 + resources/Schema/Entities/Player.xml | 3 +-- src/Engine/Network/Client.cpp | 20 +++++++++++--- src/Engine/Network/Server.cpp | 5 ++-- src/Game/Systems/CapturePointSystem.cpp | 36 +++++++++---------------- 5 files changed, 34 insertions(+), 31 deletions(-) diff --git a/include/Engine/Network/Client.h b/include/Engine/Network/Client.h index 7d23670a..d08b863a 100644 --- a/include/Engine/Network/Client.h +++ b/include/Engine/Network/Client.h @@ -103,6 +103,7 @@ public: void parseComponentDeletion(Packet& packet); void InterpolateFields(Packet & packet, const ComponentInfo & componentInfo, const EntityID & entityID, const std::string & componentType); void parseSnapshot(Packet& packet); + void UpdateLocalCapturePointHUD(EntityWrapper capturePointHUD); void identifyPacketLoss(); void hasServerTimedOut(); EntityID createPlayer(); diff --git a/resources/Schema/Entities/Player.xml b/resources/Schema/Entities/Player.xml index be6009ba..22fa3bd8 100644 --- a/resources/Schema/Entities/Player.xml +++ b/resources/Schema/Entities/Player.xml @@ -291,8 +291,7 @@ - - + diff --git a/src/Engine/Network/Client.cpp b/src/Engine/Network/Client.cpp index 16bd007d..ccca0d67 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -91,7 +91,7 @@ void Client::Update() m_TimeSinceSentInputs = std::clock(); } // HACK: Send absolute player positions for now to avoid desync until we have reliable messages - //sendLocalPlayerTransform(); + sendLocalPlayerTransform(); hasServerTimedOut(); } @@ -345,16 +345,18 @@ void Client::parseSnapshot(Packet& packet) if (serverClientMapsHasEntity(serverEntityID)) { EntityID localEntityID = m_ServerIDToClientID.at(serverEntityID); EntityWrapper localEntity(m_World, localEntityID); - // Update entity if (m_World->HasComponent(localEntityID, componentType)) { + if (localEntity.Name() == "CapturePointHUD") { + UpdateLocalCapturePointHUD(localEntity); + } SharedComponentWrapper newComponent = createSharedComponent(packet, localEntityID, componentInfo); bool shouldApply = true; // Apply potential filter function if (m_SnapshotFilter != nullptr) { shouldApply = m_SnapshotFilter->FilterComponent(localEntity, newComponent); } - if (shouldApply) { + if (shouldApply) { ComponentWrapper currentComponent = m_World->GetComponent(localEntityID, componentType); memcpy(currentComponent.Data, newComponent.Data, componentInfo.Stride); } @@ -392,6 +394,18 @@ void Client::parseSnapshot(Packet& packet) parseSpawnEvents(); } + +void Client::UpdateLocalCapturePointHUD(EntityWrapper capturePointHUD) +{ + //auto children = m_World->GetChildren(capturePointHUD.ID); + //for (auto it = children.first; it != children.second; it++) { + // it->first + //} + // + //EntityWrapper& localHUD = m_LocalPlayer.FirstChildByName("HUD").FirstChildByName("CapturePointHUD"); + //m_World->GetComponentPools() +} + void Client::disconnect() { m_IsConnected = false; diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index 76c04ad7..e309acf3 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -548,9 +548,8 @@ void Server::parsePlayerTransform(Packet& packet) bool Server::shouldSendToClient(EntityWrapper childEntity) { - return childEntity.HasComponent("Player") || childEntity.FirstParentWithComponent("Player").Valid() - || childEntity.HasComponent("CapturePointHUD") || childEntity.FirstParentWithComponent("CapturePointHUD").Valid(); - + return childEntity.HasComponent("Player") || childEntity.FirstParentWithComponent("Player").Valid() + || childEntity.HasComponent("CapturePoint") || childEntity.FirstParentWithComponent("CapturePoint").Valid(); } PlayerID Server::GetPlayerIDFromEndpoint() diff --git a/src/Game/Systems/CapturePointSystem.cpp b/src/Game/Systems/CapturePointSystem.cpp index 526b77da..598a1a8e 100644 --- a/src/Game/Systems/CapturePointSystem.cpp +++ b/src/Game/Systems/CapturePointSystem.cpp @@ -1,16 +1,15 @@ #include "Systems/CapturePointSystem.h" #include -CapturePointSystem::CapturePointSystem(SystemParams params) +CapturePointSystem::CapturePointSystem(SystemParams params) : System(params) , PureSystem("CapturePoint") { //subscribe/listenTo playerdamage,healthpickup events (using the eventBroker) - //if (IsClient) { - EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &CapturePointSystem::OnTriggerTouch); - EVENT_SUBSCRIBE_MEMBER(m_ETriggerLeave, &CapturePointSystem::OnTriggerLeave); - EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &CapturePointSystem::OnCaptured); - //} + EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &CapturePointSystem::OnTriggerTouch); + EVENT_SUBSCRIBE_MEMBER(m_ETriggerLeave, &CapturePointSystem::OnTriggerLeave); + EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &CapturePointSystem::OnCaptured); + } //here all capturepoints will update their component @@ -20,7 +19,6 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp //if (!IsClient) { // return; //} - if (m_WinnerWasFound) { return; } @@ -71,8 +69,7 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp std::map nextPossibleCapturePoint; nextPossibleCapturePoint["Red"] = -1; nextPossibleCapturePoint["Blue"] = -1; - for (int i = 0; i < m_NumberOfCapturePoints; i++) - { + for (int i = 0; i < m_NumberOfCapturePoints; i++) { if (!m_CapturePointNumberToEntityMap[i].HasComponent("Team")) { continue; } @@ -84,8 +81,7 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp nextPossibleCapturePoint["Blue"] = i + 1; } } - for (int i = m_NumberOfCapturePoints - 1; i >= 0; i--) - { + for (int i = m_NumberOfCapturePoints - 1; i >= 0; i--) { if (!m_CapturePointNumberToEntityMap[i].HasComponent("Team")) { continue; } @@ -100,8 +96,7 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp //reset timers and reset the bool that triggers this if (m_ResetTimers) { - for (int i = 0; i < m_NumberOfCapturePoints; i++) - { + for (int i = 0; i < m_NumberOfCapturePoints; i++) { ComponentWrapper& capturePoint = m_CapturePointNumberToEntityMap[i]["CapturePoint"]; if ((int)capturePoint["CapturePointNumber"] != nextPossibleCapturePoint["Red"] && (int)capturePoint["CapturePointNumber"] != nextPossibleCapturePoint["Blue"]) { @@ -116,8 +111,7 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp } //check how many players are standing inside and are healthy - for (size_t i = m_ETriggerTouchVector.size(); i > 0; i--) - { + for (size_t i = m_ETriggerTouchVector.size(); i > 0; i--) { auto triggerTouched = m_ETriggerTouchVector[i - 1]; if (std::get<1>(triggerTouched) == capturePointEntity) { //some player has touched this - lets figure out: what team, health @@ -195,17 +189,14 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp //check for possible winCondition = check if the homebase is owned by the other team bool checkForWinner = false; - if (capturePointNumber == m_RedTeamHomeCapturePoint && ownedBy != redTeam) - { + if (capturePointNumber == m_RedTeamHomeCapturePoint && ownedBy != redTeam) { checkForWinner = true; } - if (capturePointNumber == m_BlueTeamHomeCapturePoint && ownedBy != blueTeam) - { + if (capturePointNumber == m_BlueTeamHomeCapturePoint && ownedBy != blueTeam) { checkForWinner = true; } - if (checkForWinner && !m_WinnerWasFound) - { + if (checkForWinner && !m_WinnerWasFound) { //publish Win event Events::Win e; e.TeamThatWon = ownedBy; @@ -224,8 +215,7 @@ bool CapturePointSystem::OnTriggerTouch(const Events::TriggerTouch& e) bool CapturePointSystem::OnTriggerLeave(const Events::TriggerLeave& e) { - for (size_t i = 0; i < m_ETriggerTouchVector.size(); i++) - { + for (size_t i = 0; i < m_ETriggerTouchVector.size(); i++) { auto triggerTouched = m_ETriggerTouchVector[i]; if (std::get<0>(triggerTouched) == e.Entity && std::get<1>(triggerTouched) == e.Trigger) { m_ETriggerTouchVector.erase(m_ETriggerTouchVector.begin() + i); From 34a71b0767810b455bb1f001b2eaf87c0f5d9d33 Mon Sep 17 00:00:00 2001 From: Jocke Date: Mon, 22 Feb 2016 17:24:35 +0100 Subject: [PATCH 326/355] Fixed linking issue. --- src/Engine/Network/NetworkClient.cpp | 2 +- {include => src}/Engine/Network/NetworkServer.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename {include => src}/Engine/Network/NetworkServer.cpp (80%) diff --git a/src/Engine/Network/NetworkClient.cpp b/src/Engine/Network/NetworkClient.cpp index cc046176..7a61d5f3 100644 --- a/src/Engine/Network/NetworkClient.cpp +++ b/src/Engine/Network/NetworkClient.cpp @@ -1,4 +1,4 @@ -#include "..\..\..\include\Engine\Network\NetworkClient.h" +#include "Network/NetworkClient.h" NetworkClient::NetworkClient() { diff --git a/include/Engine/Network/NetworkServer.cpp b/src/Engine/Network/NetworkServer.cpp similarity index 80% rename from include/Engine/Network/NetworkServer.cpp rename to src/Engine/Network/NetworkServer.cpp index d553ef3d..1412621d 100644 --- a/include/Engine/Network/NetworkServer.cpp +++ b/src/Engine/Network/NetworkServer.cpp @@ -1,4 +1,4 @@ -#include "NetworkServer.h" +#include "Network/NetworkServer.h" NetworkServer::NetworkServer() { From e5ff88d3c9fd7fd21ca3729569e3bb5efe4185f8 Mon Sep 17 00:00:00 2001 From: stiffly Date: Mon, 22 Feb 2016 17:39:59 +0100 Subject: [PATCH 327/355] SoundSystem bug fix --- src/Game/Systems/SoundSystem.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/Game/Systems/SoundSystem.cpp b/src/Game/Systems/SoundSystem.cpp index 7101311d..56c1f018 100644 --- a/src/Game/Systems/SoundSystem.cpp +++ b/src/Game/Systems/SoundSystem.cpp @@ -90,6 +90,9 @@ bool SoundSystem::drumTimer(double dt) bool SoundSystem::OnCaptured(const Events::Captured & e) { + if (!LocalPlayer.Valid()) { + return false; + } int homeTeam = (int)m_World->GetComponent(e.CapturePointID, "Team")["Team"]; int team = (int)m_World->GetComponent(LocalPlayer.ID, "Team")["Team"]; Events::PlaySoundOnEntity ev; From fa4f007604745c8cdf9722d25b7486e4835e0007 Mon Sep 17 00:00:00 2001 From: Teejoon Date: Mon, 22 Feb 2016 18:35:00 +0100 Subject: [PATCH 328/355] Changed name from Indicator to SpriteIndicator. Can now be an indicator for a single team or every one --- resources/Schema/Components.xsd | 2 +- resources/Schema/Components/Indicator.xml | 4 - .../Schema/Components/SpriteIndicator.xml | 5 + .../{Indicator.xsd => SpriteIndicator.xsd} | 5 +- resources/Schema/Entities/Player.xml | 52 +++++++++-- resources/Schema/Entities/PlayerRed.xml | 59 ++++++++++-- src/Engine/Rendering/RenderSystem.cpp | 92 +++++++++---------- 7 files changed, 151 insertions(+), 68 deletions(-) delete mode 100644 resources/Schema/Components/Indicator.xml create mode 100644 resources/Schema/Components/SpriteIndicator.xml rename resources/Schema/Components/{Indicator.xsd => SpriteIndicator.xsd} (59%) diff --git a/resources/Schema/Components.xsd b/resources/Schema/Components.xsd index c97f2a06..42abed82 100644 --- a/resources/Schema/Components.xsd +++ b/resources/Schema/Components.xsd @@ -44,6 +44,6 @@ - + \ No newline at end of file diff --git a/resources/Schema/Components/Indicator.xml b/resources/Schema/Components/Indicator.xml deleted file mode 100644 index 1dfc0077..00000000 --- a/resources/Schema/Components/Indicator.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - 10 - \ No newline at end of file diff --git a/resources/Schema/Components/SpriteIndicator.xml b/resources/Schema/Components/SpriteIndicator.xml new file mode 100644 index 00000000..cbed22f0 --- /dev/null +++ b/resources/Schema/Components/SpriteIndicator.xml @@ -0,0 +1,5 @@ + + + 10 + false + \ No newline at end of file diff --git a/resources/Schema/Components/Indicator.xsd b/resources/Schema/Components/SpriteIndicator.xsd similarity index 59% rename from resources/Schema/Components/Indicator.xsd rename to resources/Schema/Components/SpriteIndicator.xsd index 5015b13c..bd8c1038 100644 --- a/resources/Schema/Components/Indicator.xsd +++ b/resources/Schema/Components/SpriteIndicator.xsd @@ -3,13 +3,16 @@ - + Billbord a Sprite around global Y axis + + Add a Team component to this Entity or Parent to make it visible only for that team + diff --git a/resources/Schema/Entities/Player.xml b/resources/Schema/Entities/Player.xml index d4485112..e68c0dd8 100644 --- a/resources/Schema/Entities/Player.xml +++ b/resources/Schema/Entities/Player.xml @@ -13,6 +13,7 @@ + @@ -60,6 +61,7 @@ Textures/Weapons/Crosshair/SmallThickHoleDot.png false + @@ -110,6 +112,7 @@ Textures/HealthHUD3.png + @@ -135,6 +138,7 @@ Textures/Core/UnitHexagon.png + @@ -152,6 +156,7 @@ Textures/Core/UnitHexagon_Rotated.png + @@ -167,6 +172,7 @@ Textures/Core/UnitHexagon.png + @@ -185,6 +191,7 @@ Textures/Core/UnitHexagon_Rotated.png + @@ -200,6 +207,7 @@ Textures/Core/UnitHexagon.png + @@ -217,6 +225,7 @@ Textures/Core/UnitHexagon_Rotated.png + @@ -232,6 +241,7 @@ Textures/Core/UnitHexagon.png + @@ -249,6 +259,7 @@ Textures/Core/UnitHexagon_Rotated.png + @@ -264,6 +275,7 @@ Textures/Core/UnitHexagon.png + @@ -279,6 +291,7 @@ Textures/Core/UnitHexagon_Rotated.png + @@ -304,6 +317,7 @@ + Fonts/DroidSans.ttf,64 @@ -316,6 +330,7 @@ + Fonts/DroidSans.ttf,64 @@ -330,6 +345,7 @@ + Fonts/DroidSans.ttf,64 @@ -349,8 +365,10 @@ Idle - 1.8314163732853146 + 1.1964538350402378 1 + + Models/Characters/Assault/FirstPerson.mesh @@ -368,8 +386,8 @@ Models/Weapons/Blue/AssaultWeaponBlue.mesh - - + + @@ -406,6 +424,7 @@ Textures/Core/UnitHexagon.png + @@ -475,8 +494,10 @@ Idle - 0.16333512901638159 + 0.59503633283673452 1 + + AimRifle @@ -499,8 +520,8 @@ Models/Weapons/Blue/AssaultWeaponBlue.mesh - - + + @@ -570,6 +591,25 @@ + + + + Textures/Icons/Arrow.png + false + + + + + + 30 + true + + + + + + + diff --git a/resources/Schema/Entities/PlayerRed.xml b/resources/Schema/Entities/PlayerRed.xml index 4be8fc26..c45f9280 100644 --- a/resources/Schema/Entities/PlayerRed.xml +++ b/resources/Schema/Entities/PlayerRed.xml @@ -13,6 +13,7 @@ + @@ -60,6 +61,7 @@ Textures/Weapons/Crosshair/SmallThickHoleDot.png false + @@ -110,6 +112,7 @@ Textures/HealthHUD3.png + @@ -135,6 +138,7 @@ Textures/Core/UnitHexagon.png + @@ -152,6 +156,7 @@ Textures/Core/UnitHexagon_Rotated.png + @@ -167,6 +172,7 @@ Textures/Core/UnitHexagon.png + @@ -185,6 +191,7 @@ Textures/Core/UnitHexagon_Rotated.png + @@ -200,6 +207,7 @@ Textures/Core/UnitHexagon.png + @@ -217,6 +225,7 @@ Textures/Core/UnitHexagon_Rotated.png + @@ -232,6 +241,7 @@ Textures/Core/UnitHexagon.png + @@ -249,6 +259,7 @@ Textures/Core/UnitHexagon_Rotated.png + @@ -264,6 +275,7 @@ Textures/Core/UnitHexagon.png + @@ -279,6 +291,7 @@ Textures/Core/UnitHexagon_Rotated.png + @@ -304,6 +317,7 @@ + Fonts/DroidSans.ttf,64 @@ -316,6 +330,7 @@ + Fonts/DroidSans.ttf,64 @@ -330,6 +345,7 @@ + Fonts/DroidSans.ttf,64 @@ -349,8 +365,10 @@ Idle - 0.018170670865885086 + 1.9065361003781902 1 + + Models/Characters/Assault/FirstPerson.mesh @@ -368,8 +386,8 @@ Models/Weapons/Red/AssaultWeaponRed.mesh - - + + @@ -406,6 +424,7 @@ Textures/Core/UnitHexagon.png + @@ -475,8 +494,10 @@ Idle - 0.11675631578762591 + 0.62178782386743592 1 + + AimRifle @@ -499,8 +520,8 @@ Models/Weapons/Red/AssaultWeaponRed.mesh - - + + @@ -570,6 +591,32 @@ + + + + + + + + + + + Textures/Icons/Arrow.png + false + + + + + + 30 + true + + + + + + + diff --git a/src/Engine/Rendering/RenderSystem.cpp b/src/Engine/Rendering/RenderSystem.cpp index a0534fed..7b0ea84f 100644 --- a/src/Engine/Rendering/RenderSystem.cpp +++ b/src/Engine/Rendering/RenderSystem.cpp @@ -52,40 +52,39 @@ void RenderSystem::fillSprites(std::list>& jobs, Worl continue; } - std::string diffuseResource = cSprite["DiffuseTexture"]; - std::string glowResource = cSprite["GlowMap"]; - bool depthSorted = cSprite["DepthSort"]; - if (diffuseResource.empty() && glowResource.empty()) { - continue; - } - - float fillPercentage = 0.f; - glm::vec4 fillColor = glm::vec4(0); - if (world->HasComponent(entity.ID, "Fill")) { - auto fillComponent = world->GetComponent(entity.ID, "Fill"); - fillPercentage = (float)(double)fillComponent["Percentage"]; - fillColor = (glm::vec4)fillComponent["Color"]; - } - glm::mat4 modelMatrix; - + + // See a sprite is an SpriteIndicator bool isIndicator = false; - if (world->HasComponent(entity.ID, "Indicator") || entity.FirstParentWithComponent("Indicator").Valid()) + if (world->HasComponent(entity.ID, "SpriteIndicator")) { - EntityWrapper EntityWithIndicator; - if (world->HasComponent(entity.ID, "Indicator")) { - EntityWithIndicator = entity; - } - else { - EntityWithIndicator = entity.FirstParentWithComponent("Indicator"); - } - auto indicator = EntityWithIndicator["Indicator"]; + auto indicator = entity["SpriteIndicator"]; float minScale = (float)(double)indicator["MinScale"]; + bool hasTeam = indicator["VisibleForSingleTeamOnly"]; isIndicator = true; glm::vec3 pos = Transform::AbsolutePosition(entity); + EntityWrapper entityTeam; + if (hasTeam && (entity.HasComponent("Team") || entity.FirstParentWithComponent("Team").Valid()) && m_LocalPlayer.World != nullptr) { + if (!entity.HasComponent("Team")) { + entityTeam = entity.FirstParentWithComponent("Team"); + } + else { + entityTeam = entity; + } + + ComponentWrapper& entityTeamComponent = entityTeam["Team"]; + ComponentWrapper& localComponent = m_LocalPlayer["Team"]; + int entityTeamInt = entityTeamComponent["Team"]; + int localComponentInt = localComponent["Team"]; + int SpectatorInt = localComponent["Team"].Enum("Spectator"); + if (entityTeamInt != localComponentInt && localComponentInt != SpectatorInt) { + continue; + } + } + // Code for check if sprite is inside or outside of screen //glm::vec4 projectedPos = m_Camera->ProjectionMatrix() * m_Camera->ViewMatrix() * glm::vec4(pos, 1.0f); //projectedPos /= projectedPos.w; @@ -142,10 +141,27 @@ void RenderSystem::fillSprites(std::list>& jobs, Worl tranformationMatrix = tranformationMatrix * glm::scale(glm::vec3(minScale / diag, minScale / diag, minScale / diag)); } modelMatrix = tranformationMatrix; - } else { + } + else { modelMatrix = Transform::ModelMatrix(entity.ID, world); } + + std::string diffuseResource = cSprite["DiffuseTexture"]; + std::string glowResource = cSprite["GlowMap"]; + bool depthSorted = cSprite["DepthSort"]; + if (diffuseResource.empty() && glowResource.empty()) { + continue; + } + + float fillPercentage = 0.f; + glm::vec4 fillColor = glm::vec4(0); + if (world->HasComponent(entity.ID, "Fill")) { + auto fillComponent = world->GetComponent(entity.ID, "Fill"); + fillPercentage = (float)(double)fillComponent["Percentage"]; + fillColor = (glm::vec4)fillComponent["Color"]; + } + std::shared_ptr spriteJob = std::shared_ptr(new SpriteJob(cSprite, m_Camera, modelMatrix, world, fillColor, fillPercentage, depthSorted, isIndicator)); jobs.push_back(spriteJob); @@ -168,30 +184,6 @@ bool RenderSystem::isEntityVisible(EntityWrapper& entity) ) { return false; } - - // If a sprite is an Indicator, it's not local on player and object is in the same team, then dispaly it - if ( - entity.HasComponent("Indicator") - && !entity.IsChildOf(m_LocalPlayer) - && (entity.HasComponent("Team") || entity.FirstParentWithComponent("Team").Valid()) - && entity.HasComponent("Sprite") - && m_LocalPlayer.World != nullptr - ) { - EntityWrapper entityTeam; - if (!entity.HasComponent("Team")) { - entityTeam = entity.FirstParentWithComponent("Team"); - } else { - entityTeam = entity; - } - ComponentWrapper& entityTeamComponent = entityTeam["Team"]; - ComponentWrapper& localComponent = m_LocalPlayer["Team"]; - int entityTeamInt = entityTeamComponent["Team"]; - int localComponentInt = localComponent["Team"]; - int SpectatorInt = localComponent["Team"].Enum("Spectator"); - if (entityTeamInt != localComponentInt && localComponentInt != SpectatorInt) { - return false; - } - } return true; } From fe3e0bac5bf86d54a374c3622b520d063e634a0b Mon Sep 17 00:00:00 2001 From: Teejoon Date: Mon, 22 Feb 2016 18:45:02 +0100 Subject: [PATCH 329/355] Changed SpritIndicator values on player --- resources/Schema/Entities/Player.xml | 15 ++++---- resources/Schema/Entities/PlayerRed.xml | 46 +++++++++++-------------- 2 files changed, 28 insertions(+), 33 deletions(-) diff --git a/resources/Schema/Entities/Player.xml b/resources/Schema/Entities/Player.xml index e68c0dd8..48adffac 100644 --- a/resources/Schema/Entities/Player.xml +++ b/resources/Schema/Entities/Player.xml @@ -365,7 +365,7 @@ Idle - 1.1964538350402378 + 0.97725610639912475 1 @@ -386,8 +386,8 @@ Models/Weapons/Blue/AssaultWeaponBlue.mesh - - + + @@ -494,7 +494,7 @@ Idle - 0.59503633283673452 + 0.87583812735846323 1 @@ -520,8 +520,8 @@ Models/Weapons/Blue/AssaultWeaponBlue.mesh - - + + @@ -601,11 +601,12 @@ - 30 + 50 true + diff --git a/resources/Schema/Entities/PlayerRed.xml b/resources/Schema/Entities/PlayerRed.xml index c45f9280..cd01632e 100644 --- a/resources/Schema/Entities/PlayerRed.xml +++ b/resources/Schema/Entities/PlayerRed.xml @@ -365,7 +365,7 @@ Idle - 1.9065361003781902 + 1.2667383999985162 1 @@ -386,8 +386,8 @@ Models/Weapons/Red/AssaultWeaponRed.mesh - - + + @@ -494,7 +494,7 @@ Idle - 0.62178782386743592 + 0.26532318661337229 1 @@ -520,8 +520,8 @@ Models/Weapons/Red/AssaultWeaponRed.mesh - - + + @@ -591,31 +591,25 @@ - + + + Textures/Icons/Arrow.png + false + + + + + + 50 + true + + - - - - - Textures/Icons/Arrow.png - false - - - - - - 30 - true - - - - - - + From fe9dbf0b0f34306a1842a96f9374be7c7711bbaf Mon Sep 17 00:00:00 2001 From: stiffly Date: Tue, 23 Feb 2016 10:33:20 +0100 Subject: [PATCH 330/355] Serverlist fix. --- src/Engine/Network/Client.cpp | 2 ++ src/Engine/Network/Server.cpp | 2 +- src/Engine/Network/UDPClient.cpp | 1 + src/Engine/Network/UDPServer.cpp | 4 ++++ 4 files changed, 8 insertions(+), 1 deletion(-) diff --git a/src/Engine/Network/Client.cpp b/src/Engine/Network/Client.cpp index ccca0d67..fc5b68e1 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -203,6 +203,8 @@ void Client::parseServerlist(Packet& packet) std::string serverName = packet.ReadString(); int playersConnected = packet.ReadPrimitive(); //TODO: This should not happen when a client is connected to a server + LOG_INFO("Parsing a server list!"); + m_Serverlist.push_back({ address, port, serverName, playersConnected }); } diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index 4b83967e..157f74dd 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -401,7 +401,7 @@ void Server::parseServerlistRequest(boost::asio::ip::udp::endpoint endpoint) packet.WritePrimitive(m_ConnectedPlayers.size()); //PlayerDefinition pDef; //pDef.Endpoint = boost::asio::ip::udp::endpoint(endpoint.address(), 13); - + LOG_INFO("Parsing a server list request!"); m_ServerlistRequest.Send(packet/*, endpoint*/); } diff --git a/src/Engine/Network/UDPClient.cpp b/src/Engine/Network/UDPClient.cpp index f31d5a17..37b9b1a0 100644 --- a/src/Engine/Network/UDPClient.cpp +++ b/src/Engine/Network/UDPClient.cpp @@ -91,6 +91,7 @@ void UDPClient::Send(Packet& packet) void UDPClient::Broadcast(Packet& packet, int port) { + packet.UpdateSize(); m_Socket->set_option(boost::asio::socket_base::broadcast(true)); m_Socket->send_to(boost::asio::buffer( packet.Data(), diff --git a/src/Engine/Network/UDPServer.cpp b/src/Engine/Network/UDPServer.cpp index fcf26aec..2f941b04 100644 --- a/src/Engine/Network/UDPServer.cpp +++ b/src/Engine/Network/UDPServer.cpp @@ -41,6 +41,7 @@ void UDPServer::Send(Packet & packet) // Broadcasting respond specific logic void UDPServer::Send(Packet & packet, boost::asio::ip::udp::endpoint endpoint) { + packet.UpdateSize(); m_Socket->send_to( boost::asio::buffer( packet.Data(), @@ -52,6 +53,7 @@ void UDPServer::Send(Packet & packet, boost::asio::ip::udp::endpoint endpoint) // Broadcasting void UDPServer::Broadcast(Packet & packet, int port) { + packet.UpdateSize(); m_Socket->set_option(boost::asio::socket_base::broadcast(true)); m_Socket->send_to( boost::asio::buffer( @@ -68,6 +70,7 @@ void UDPServer::Receive(Packet & packet, PlayerDefinition & playerDefinition) if (bytesRead > 0) { packet.ReconstructFromData(m_ReadBuffer, bytesRead); } + LOG_INFO("Received server list msg"); playerDefinition.Endpoint = m_ReceiverEndpoint; } @@ -90,6 +93,7 @@ int UDPServer::readBuffer() if (!m_Socket) { return 0; } + int addasdasd = m_Socket->available(); boost::system::error_code error; // Read size of packet m_Socket->receive_from(boost From c42e1e09672a172ca9877f815fcb0f448d88b72b Mon Sep 17 00:00:00 2001 From: stiffly Date: Tue, 23 Feb 2016 11:07:41 +0100 Subject: [PATCH 331/355] SoundSystem Fix. Now subscribes to an event that was thought to be listened to. --- src/Game/Systems/SoundSystem.cpp | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/src/Game/Systems/SoundSystem.cpp b/src/Game/Systems/SoundSystem.cpp index 56c1f018..b4a37ad0 100644 --- a/src/Game/Systems/SoundSystem.cpp +++ b/src/Game/Systems/SoundSystem.cpp @@ -14,6 +14,7 @@ SoundSystem::SoundSystem(SystemParams params) EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &SoundSystem::OnPlayerDamage); EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &SoundSystem::OnCaptured); EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &SoundSystem::OnTriggerTouch); + EVENT_SUBSCRIBE_MEMBER(m_EPlayerDeath, &SoundSystem::OnPlayerDeath); } } @@ -111,7 +112,12 @@ bool SoundSystem::OnCaptured(const Events::Captured & e) // Testing purposes atm... bool SoundSystem::OnPlayerDamage(const Events::PlayerDamage & e) { - // Should check for only local players here... + if (!IsClient) { // Only play for clients + return false; + } + if (LocalPlayer.ID = e.Victim.ID) { // You're local player was the one who took dmg + return false; + } std::uniform_int_distribution dist(1, 12); int rand = dist(generator); std::vector paths; @@ -131,8 +137,16 @@ bool SoundSystem::OnPlayerDamage(const Events::PlayerDamage & e) bool SoundSystem::OnPlayerDeath(const Events::PlayerDeath & e) { - Events::PlaySoundOnEntity ev; - ev.EmitterID = LocalPlayer.ID; + if (e.Player.ID != LocalPlayer.ID) { + return false; + } + if (!IsClient) { + return false; + } + // The local player is dead. The local player might be invalid? + // Play the sound from the listener. + // TODO: We might want to hear other players die. + Events::PlayBackgroundMusic ev; ev.FilePath = "Audio/die/die2.wav"; m_EventBroker->Publish(ev); return false; From fc7d62a5ad11655bfdd763477ce22fddaf15466b Mon Sep 17 00:00:00 2001 From: stiffly Date: Tue, 23 Feb 2016 11:07:56 +0100 Subject: [PATCH 332/355] Various clean ups. --- include/Engine/Network/HybridClient.h | 13 ----------- include/Engine/Network/HybridServer.h | 12 ---------- src/Engine/Network/Client.cpp | 1 - src/Engine/Network/HybridClient.cpp | 10 --------- src/Engine/Network/HybridServer.cpp | 9 -------- src/Engine/Network/Server.cpp | 5 +---- src/Engine/Network/TCPClient.cpp | 20 ----------------- src/Engine/Network/TCPServer.cpp | 32 --------------------------- src/Engine/Network/UDPClient.cpp | 12 ---------- src/Engine/Network/UDPServer.cpp | 10 --------- 10 files changed, 1 insertion(+), 123 deletions(-) delete mode 100644 include/Engine/Network/HybridClient.h delete mode 100644 include/Engine/Network/HybridServer.h delete mode 100644 src/Engine/Network/HybridClient.cpp delete mode 100644 src/Engine/Network/HybridServer.cpp diff --git a/include/Engine/Network/HybridClient.h b/include/Engine/Network/HybridClient.h deleted file mode 100644 index 8d96bf6e..00000000 --- a/include/Engine/Network/HybridClient.h +++ /dev/null @@ -1,13 +0,0 @@ -#ifndef HybridClient_h__ -#define HybridClient_h__ - -class HybridClient -{ -public: - HybridClient(); - ~HybridClient(); -private: - -}; - -#endif \ No newline at end of file diff --git a/include/Engine/Network/HybridServer.h b/include/Engine/Network/HybridServer.h deleted file mode 100644 index 48d6fe63..00000000 --- a/include/Engine/Network/HybridServer.h +++ /dev/null @@ -1,12 +0,0 @@ -#ifndef HybridServer_h__ -#define HybridServer_h__ - -class HybridServer -{ -public: - HybridServer(); - ~HybridServer(); -private: -}; - -#endif \ No newline at end of file diff --git a/src/Engine/Network/Client.cpp b/src/Engine/Network/Client.cpp index fc5b68e1..213e1815 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -203,7 +203,6 @@ void Client::parseServerlist(Packet& packet) std::string serverName = packet.ReadString(); int playersConnected = packet.ReadPrimitive(); //TODO: This should not happen when a client is connected to a server - LOG_INFO("Parsing a server list!"); m_Serverlist.push_back({ address, port, serverName, playersConnected }); } diff --git a/src/Engine/Network/HybridClient.cpp b/src/Engine/Network/HybridClient.cpp deleted file mode 100644 index 4200e8e3..00000000 --- a/src/Engine/Network/HybridClient.cpp +++ /dev/null @@ -1,10 +0,0 @@ -#include "Network/HybridClient.h" - - -HybridClient::HybridClient() -{ -} - -HybridClient::~HybridClient() -{ -} \ No newline at end of file diff --git a/src/Engine/Network/HybridServer.cpp b/src/Engine/Network/HybridServer.cpp deleted file mode 100644 index bfcdaee0..00000000 --- a/src/Engine/Network/HybridServer.cpp +++ /dev/null @@ -1,9 +0,0 @@ -#include "Network/HybridServer.h" - -HybridServer::HybridServer() -{ -} - -HybridServer::~HybridServer() -{ -} \ No newline at end of file diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index 157f74dd..8783a7b0 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -399,10 +399,7 @@ void Server::parseServerlistRequest(boost::asio::ip::udp::endpoint endpoint) packet.WritePrimitive(m_Reliable.Port()); packet.WriteString("SERVERNAME"); packet.WritePrimitive(m_ConnectedPlayers.size()); - //PlayerDefinition pDef; - //pDef.Endpoint = boost::asio::ip::udp::endpoint(endpoint.address(), 13); - LOG_INFO("Parsing a server list request!"); - m_ServerlistRequest.Send(packet/*, endpoint*/); + m_ServerlistRequest.Send(packet); } void Server::disconnect(PlayerID playerID) diff --git a/src/Engine/Network/TCPClient.cpp b/src/Engine/Network/TCPClient.cpp index f2920ae5..f3394d3d 100644 --- a/src/Engine/Network/TCPClient.cpp +++ b/src/Engine/Network/TCPClient.cpp @@ -64,26 +64,6 @@ void TCPClient::Receive(Packet& packet) size_t TCPClient::readBuffer() { - //if (!m_Socket) { - // return 0; - //} - //boost::system::error_code error; - //// Read size of packet - //size_t bytesReceived = m_Socket->read_some(boost - // ::asio::buffer((void*)data, sizeof(int)), - // error); - //int sizeOfPacket = 0; - //memcpy(&sizeOfPacket, data, sizeof(int)); - - //// Read the rest of the message - //bytesReceived += m_Socket->read_some(boost - // ::asio::buffer((void*)(data + bytesReceived), sizeOfPacket - bytesReceived), - // error); - //if (error) { - // //LOG_ERROR("receive: %s", error.message().c_str()); - //} - //return bytesReceived; - if (!m_Socket) { return 0; } diff --git a/src/Engine/Network/TCPServer.cpp b/src/Engine/Network/TCPServer.cpp index ac2ba655..24a0b2c1 100644 --- a/src/Engine/Network/TCPServer.cpp +++ b/src/Engine/Network/TCPServer.cpp @@ -91,38 +91,6 @@ std::string TCPServer::GetAddress() return endpoint.address().to_string().c_str(); } -//void TCPServer::Receive(Packet & packet, PlayerDefinition & playerDefinition) -//{ -// int bytesRead = readBuffer(m_ReadBuffer, playerDefinition); -// if (bytesRead > 0) { -// packet.ReconstructFromData(m_ReadBuffer, bytesRead); -// } -// lastReceivedSocket = playerDefinition.TCPSocket; -//} -// -//int TCPServer::readBuffer(char* data, PlayerDefinition & playerDefinition) -//{ -// if (!playerDefinition.TCPSocket) { -// return 0; -// } -// boost::system::error_code error; -// // Read size of packet -// size_t bytesReceived = playerDefinition.TCPSocket->read_some(boost -// ::asio::buffer((void*)data, sizeof(int)), -// error); -// int sizeOfPacket = 0; -// memcpy(&sizeOfPacket, data, sizeof(int)); -// -// // Read the rest of the message -// bytesReceived += playerDefinition.TCPSocket->read_some(boost -// ::asio::buffer((void*)(data + bytesReceived), sizeOfPacket - bytesReceived), -// error); -// if (error) { -// //LOG_ERROR("receive: %s", error.message().c_str()); -// } -// return bytesReceived; -//} - void TCPServer::Receive(Packet & packet, PlayerDefinition & playerDefinition) { int bytesRead = readBuffer(playerDefinition); diff --git a/src/Engine/Network/UDPClient.cpp b/src/Engine/Network/UDPClient.cpp index 37b9b1a0..51c29920 100644 --- a/src/Engine/Network/UDPClient.cpp +++ b/src/Engine/Network/UDPClient.cpp @@ -35,18 +35,6 @@ void UDPClient::Receive(Packet& packet) int UDPClient::readBuffer() { - //if (!m_Socket) { - // return 0; - //} - //boost::system::error_code error; - //int bytesReceived = m_Socket->receive_from(boost - // ::asio::buffer((void*)data, BUFFERSIZE), - // m_ReceiverEndpoint, - // 0, error); - //if (error) { - // //LOG_ERROR("receive: %s", error.message().c_str()); - //} - //return bytesReceived; if (!m_Socket) { return 0; } diff --git a/src/Engine/Network/UDPServer.cpp b/src/Engine/Network/UDPServer.cpp index 2f941b04..635ebd4d 100644 --- a/src/Engine/Network/UDPServer.cpp +++ b/src/Engine/Network/UDPServer.cpp @@ -70,7 +70,6 @@ void UDPServer::Receive(Packet & packet, PlayerDefinition & playerDefinition) if (bytesRead > 0) { packet.ReconstructFromData(m_ReadBuffer, bytesRead); } - LOG_INFO("Received server list msg"); playerDefinition.Endpoint = m_ReceiverEndpoint; } @@ -81,15 +80,6 @@ bool UDPServer::IsSocketAvailable() int UDPServer::readBuffer() { - //boost::system::error_code error = boost::asio::error::host_not_found; - //unsigned int length = m_Socket->receive_from( - // boost::asio::buffer((void*)data - // , BUFFERSIZE) - // , m_ReceiverEndpoint, 0, error); - //if (error) { - // LOG_WARNING(error.message().c_str()); - //} - //return length; if (!m_Socket) { return 0; } From d77119bb2dfcf020abb33bab49043a1bc0e39257 Mon Sep 17 00:00:00 2001 From: stiffly Date: Tue, 23 Feb 2016 11:47:44 +0100 Subject: [PATCH 333/355] Fixed print for serverlist. --- src/Engine/Network/Client.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Engine/Network/Client.cpp b/src/Engine/Network/Client.cpp index 213e1815..903cd929 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -599,7 +599,7 @@ void Client::displayServerlist() LOG_INFO("This is a serverlist:\n"); for (int i = 0; i < m_Serverlist.size(); i++) { ServerInfo si = m_Serverlist[i]; - LOG_INFO("%s:%i\t%s\t%i\n", si.Address, si.Port, si.Name, si.PlayersConnected); + LOG_INFO("%s:%i\t%s\t%i\n", si.Address.c_str(), si.Port, si.Name.c_str(), si.PlayersConnected); } } From 91b0ac5fbde7fc731be49eda31b1c668ca8d0c6e Mon Sep 17 00:00:00 2001 From: Tleety Date: Tue, 23 Feb 2016 16:00:43 +0100 Subject: [PATCH 334/355] Some groundwork for cubemaps. --- assets | 2 +- include/Engine/Rendering/CubeMapPass.h | 26 +++++++++++++++ include/Engine/Rendering/DrawFinalPass.h | 5 ++- include/Engine/Rendering/Renderer.h | 2 ++ include/Engine/Rendering/Texture.h | 1 + resources/Shaders/ForwardPlus.frag.glsl | 8 +++-- src/Engine/Rendering/CubeMapPass.cpp | 39 +++++++++++++++++++++++ src/Engine/Rendering/DrawBloomPass.cpp | 2 ++ src/Engine/Rendering/DrawFinalPass.cpp | 33 +++++++++++++++++-- src/Engine/Rendering/PickingPass.cpp | 3 ++ src/Engine/Rendering/PickingPassState.cpp | 5 +-- src/Engine/Rendering/Renderer.cpp | 12 ++++--- src/Engine/Rendering/Texture.cpp | 2 ++ 13 files changed, 126 insertions(+), 14 deletions(-) create mode 100644 include/Engine/Rendering/CubeMapPass.h create mode 100644 src/Engine/Rendering/CubeMapPass.cpp diff --git a/assets b/assets index 1e7adc74..ba8e04f1 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit 1e7adc749e02144615a20a82c847d3c8df46ee3d +Subproject commit ba8e04f12be11034464b8446331286196953bb84 diff --git a/include/Engine/Rendering/CubeMapPass.h b/include/Engine/Rendering/CubeMapPass.h new file mode 100644 index 00000000..564329e2 --- /dev/null +++ b/include/Engine/Rendering/CubeMapPass.h @@ -0,0 +1,26 @@ +#ifndef CubeMapPass_h__ +#define CubeMapPass_h__ + +#include "IRenderer.h" +#include "ShaderProgram.h" + +class CubeMapPass +{ +public: + CubeMapPass(IRenderer* renderer); + ~CubeMapPass() { } + + void LoadTextures(); + void FillCubeMap(glm::vec3 originPosition); + void GenerateCubeMapTexture(); + + //GLuint CubeMapTexture() const { return m_CubeMapTexture; } + GLuint m_CubeMapTexture; + +private: + IRenderer* m_Renderer; + + std::vector m_CubeMapTestTextures; +}; + +#endif \ No newline at end of file diff --git a/include/Engine/Rendering/DrawFinalPass.h b/include/Engine/Rendering/DrawFinalPass.h index e3389471..1800c90e 100644 --- a/include/Engine/Rendering/DrawFinalPass.h +++ b/include/Engine/Rendering/DrawFinalPass.h @@ -4,6 +4,7 @@ #include "IRenderer.h" #include "DrawFinalPassState.h" #include "LightCullingPass.h" +#include "CubeMapPass.h" #include "FrameBuffer.h" #include "ShaderProgram.h" #include "Util/UnorderedMapVec2.h" @@ -13,7 +14,7 @@ class DrawFinalPass { public: - DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCullingPass); + DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCullingPass, CubeMapPass* cubeMapPass); ~DrawFinalPass() { } void InitializeTextures(); void InitializeFrameBuffers(); @@ -62,12 +63,14 @@ private: GLuint m_SceneTextureLowRes; GLuint m_DepthBuffer; GLuint m_DepthBufferLowRes; + GLuint m_CubeMapTexture; //maqke this component based i guess? GLuint m_ShieldPixelRate = 16; const IRenderer* m_Renderer; const LightCullingPass* m_LightCullingPass; + const CubeMapPass* m_CubeMapPass; ShaderProgram* m_ForwardPlusProgram; ShaderProgram* m_ExplosionEffectProgram; diff --git a/include/Engine/Rendering/Renderer.h b/include/Engine/Rendering/Renderer.h index aa87536b..720336aa 100644 --- a/include/Engine/Rendering/Renderer.h +++ b/include/Engine/Rendering/Renderer.h @@ -17,6 +17,7 @@ #include "DrawBloomPass.h" #include "DrawColorCorrectionPass.h" #include "SSAOPass.h" +#include "CubeMapPass.h" #include "../Core/EventBroker.h" #include "ImGuiRenderPass.h" #include "Camera.h" @@ -74,6 +75,7 @@ private: DrawBloomPass* m_DrawBloomPass; DrawColorCorrectionPass* m_DrawColorCorrectionPass; SSAOPass* m_SSAOPass; + CubeMapPass* m_CubeMapPass; //----------------------Functions----------------------// void InitializeWindow(); diff --git a/include/Engine/Rendering/Texture.h b/include/Engine/Rendering/Texture.h index 0fe650b3..d159e636 100644 --- a/include/Engine/Rendering/Texture.h +++ b/include/Engine/Rendering/Texture.h @@ -18,6 +18,7 @@ public: void Bind(GLenum textureUnit = GL_TEXTURE0); GLuint m_Texture = 0; + unsigned char* Data = nullptr; }; diff --git a/resources/Shaders/ForwardPlus.frag.glsl b/resources/Shaders/ForwardPlus.frag.glsl index f9b93091..78f2106f 100644 --- a/resources/Shaders/ForwardPlus.frag.glsl +++ b/resources/Shaders/ForwardPlus.frag.glsl @@ -22,6 +22,7 @@ layout (binding = 1) uniform sampler2D DiffuseTexture; layout (binding = 2) uniform sampler2D NormalMapTexture; layout (binding = 3) uniform sampler2D SpecularMapTexture; layout (binding = 4) uniform sampler2D GlowMapTexture; +layout (binding = 5) uniform samplerCube CubeMap; #define TILE_SIZE 16 @@ -132,7 +133,9 @@ void main() vec4 normal = V * CalcNormalMappedValue(Input.Normal, Input.Tangent, Input.BiTangent, Input.TextureCoordinate * NormalUVRepeat, NormalMapTexture); normal = normalize(normal); //vec4 normal = normalize(V * vec4(Input.Normal, 0.0)); - vec4 viewVec = normalize(-position); + vec4 viewVec = normalize(-position); + vec3 R = reflect(-viewVec.xyz, normal.xyz); + vec4 reflectionColor = texture(CubeMap, R); vec2 tilePos; tilePos.x = int(gl_FragCoord.x/TILE_SIZE); @@ -171,7 +174,8 @@ void main() if(pos <= FillPercentage) { color_result += FillColor; } - sceneColor = vec4(color_result.xyz, clamp(color_result.a, 0, 1)); + //sceneColor = vec4(color_result.xyz, clamp(color_result.a, 0, 1)); + sceneColor = vec4(reflectionColor.xyz, 1); color_result += glowTexel*GlowIntensity; bloomColor = vec4(clamp(color_result.xyz - 1.0, 0, 100), clamp(color_result.a, 0, 1)); diff --git a/src/Engine/Rendering/CubeMapPass.cpp b/src/Engine/Rendering/CubeMapPass.cpp new file mode 100644 index 00000000..153d8eb8 --- /dev/null +++ b/src/Engine/Rendering/CubeMapPass.cpp @@ -0,0 +1,39 @@ +#include "Rendering/CubeMapPass.h" + +CubeMapPass::CubeMapPass(IRenderer* renderer) + :m_Renderer(renderer) +{ + LoadTextures(); + GenerateCubeMapTexture(); +} + +/* + +*/ + +void CubeMapPass::LoadTextures() +{ + for (int i = 0; i < 6; i++){ + std::string str; + str = "Textures/Test/CubeMap/CubeMapTest0" + std::to_string(i) + ".png"; + Texture* img = ResourceManager::Load(str); + m_CubeMapTestTextures.push_back(img); + } +} + +void CubeMapPass::GenerateCubeMapTexture() +{ + glGenTextures(1, &m_CubeMapTexture); + glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapTexture); + + for (int i = 0; i < 6; i++) { + glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGBA32F, 256, 256, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_CubeMapTestTextures[i]->Data); + } + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); + GLERROR("Generate Cubemap"); +} + diff --git a/src/Engine/Rendering/DrawBloomPass.cpp b/src/Engine/Rendering/DrawBloomPass.cpp index 6bfb58eb..e8ad4cd5 100644 --- a/src/Engine/Rendering/DrawBloomPass.cpp +++ b/src/Engine/Rendering/DrawBloomPass.cpp @@ -52,6 +52,7 @@ void DrawBloomPass::InitializeBuffers() void DrawBloomPass::ClearBuffer() { + GLERROR("PRE"); m_GaussianFrameBuffer_horiz.Bind(); glClearColor(0.f, 0.f, 0.f, 0.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); @@ -60,6 +61,7 @@ void DrawBloomPass::ClearBuffer() glClearColor(0.f, 0.f, 0.f, 0.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_GaussianFrameBuffer_vert.Unbind(); + GLERROR("END"); } void DrawBloomPass::Draw(GLuint texture) diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index c16caa24..e7982a3d 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -1,10 +1,11 @@ #include "Rendering/DrawFinalPass.h" -DrawFinalPass::DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCullingPass) +DrawFinalPass::DrawFinalPass(IRenderer* renderer, LightCullingPass* lightCullingPass, CubeMapPass* cubeMapPass) + : m_Renderer(renderer) + , m_LightCullingPass(lightCullingPass) + , m_CubeMapPass(cubeMapPass) { //TODO: Make sure that uniforms are not sent into shader if not needed. - m_Renderer = renderer; - m_LightCullingPass = lightCullingPass; m_ShieldPixelRate = 8; InitializeTextures(); InitializeShaderPrograms(); @@ -261,20 +262,35 @@ void DrawFinalPass::Draw(RenderScene& scene, GLuint SSAOTexture) void DrawFinalPass::ClearBuffer() { + GLERROR("PRE"); m_FinalPassFrameBufferLowRes.Bind(); + GLERROR("Bind LowRes"); + glViewport(0, 0, m_Renderer->GetViewportSize().Width/m_ShieldPixelRate, m_Renderer->GetViewportSize().Height/m_ShieldPixelRate); glScissor(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); + GLERROR("ViewPort,Scissor LowRes"); + glClearColor(0.f, 0.f, 0.f, 0.f); + GLERROR("1"); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + GLERROR("2"); + glDisable(GL_SCISSOR_TEST); + GLERROR("3"); + m_FinalPassFrameBufferLowRes.Unbind(); + GLERROR("prebind HighRes"); m_FinalPassFrameBuffer.Bind(); + GLERROR("Bind HighRes"); glViewport(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); glScissor(0, 0, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); + GLERROR("ViewPort,Scissor LowRes"); glClearColor(0.f, 0.f, 0.f, 0.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_FinalPassFrameBuffer.Unbind(); + GLERROR("END"); } @@ -358,12 +374,15 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& case RawModel::MaterialType::SingleTextures: { if (explosionEffectJob->Model->IsSkinned()) { + m_ExplosionEffectSkinnedProgram->Bind(); GLERROR("Bind ExplosionEffectSkinned program"); //bind uniforms BindExplosionUniforms(explosionSkinnedHandle, explosionEffectJob, scene); //bind textures BindExplosionTextures(explosionSkinnedHandle, explosionEffectJob); + glActiveTexture(GL_TEXTURE5); + glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); std::vector frameBones; if (explosionEffectJob->AnimationOffset.animation != nullptr) { frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations, explosionEffectJob->AnimationOffset); @@ -378,6 +397,8 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& BindExplosionUniforms(explosionHandle, explosionEffectJob, scene); //bind textures BindExplosionTextures(explosionHandle, explosionEffectJob); + glActiveTexture(GL_TEXTURE5); + glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); } break; } @@ -436,6 +457,8 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& BindModelUniforms(forwardSkinnedHandle, modelJob, scene); //bind textures BindModelTextures(forwardSkinnedHandle, modelJob); + glActiveTexture(GL_TEXTURE5); + glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); std::vector frameBones; if (modelJob->AnimationOffset.animation != nullptr) { frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); @@ -451,6 +474,8 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& BindModelUniforms(forwardHandle, modelJob, scene); //bind textures BindModelTextures(forwardHandle, modelJob); + glActiveTexture(GL_TEXTURE5); + glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); } break; } @@ -809,6 +834,8 @@ void DrawFinalPass::BindModelUniforms(GLuint shaderHandle, std::shared_ptr& job) { + + switch (job->Type) { case RawModel::MaterialType::SingleTextures: case RawModel::MaterialType::Basic: diff --git a/src/Engine/Rendering/PickingPass.cpp b/src/Engine/Rendering/PickingPass.cpp index d1ed73dd..e0288348 100644 --- a/src/Engine/Rendering/PickingPass.cpp +++ b/src/Engine/Rendering/PickingPass.cpp @@ -64,6 +64,7 @@ void PickingPass::InitializeShaderPrograms() void PickingPass::Draw(RenderScene& scene) { + GLERROR("PRE"); PickingPassState* state = new PickingPassState(m_PickingBuffer.GetHandle()); //TODO: Render: Add code for more jobs than modeljobs. @@ -367,6 +368,7 @@ void PickingPass::Draw(RenderScene& scene) void PickingPass::ClearPicking() { + GLERROR("PRE"); m_PickingColorsToEntity.clear(); m_EntityColors.clear(); m_ColorCounter[0] = 0; @@ -376,6 +378,7 @@ void PickingPass::ClearPicking() glClearColor(0.f, 0.f, 0.f, 0.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_PickingBuffer.Unbind(); + GLERROR("END"); } diff --git a/src/Engine/Rendering/PickingPassState.cpp b/src/Engine/Rendering/PickingPassState.cpp index 0c4f4aca..f2d42bff 100644 --- a/src/Engine/Rendering/PickingPassState.cpp +++ b/src/Engine/Rendering/PickingPassState.cpp @@ -3,9 +3,9 @@ PickingPassState::PickingPassState(GLuint frameBuffer) { - GLERROR("---2"); + GLERROR("PRE"); BindFramebuffer(frameBuffer); - GLERROR("---3"); + GLERROR("Bind Framebuffer"); Enable(GL_DEPTH_TEST); Enable(GL_CULL_FACE); Disable(GL_BLEND); @@ -13,6 +13,7 @@ PickingPassState::PickingPassState(GLuint frameBuffer) glm::vec4 clearColor = glm::vec4(0.f); //ClearColor(clearColor); //Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + GLERROR("END"); } PickingPassState::~PickingPassState() diff --git a/src/Engine/Rendering/Renderer.cpp b/src/Engine/Rendering/Renderer.cpp index 0c668cad..8391599c 100644 --- a/src/Engine/Rendering/Renderer.cpp +++ b/src/Engine/Rendering/Renderer.cpp @@ -30,6 +30,7 @@ void Renderer::glfwFrameBufferCallback(GLFWwindow* window, int width, int height currentRenderer->m_LightCullingPass->OnWindowResize(); currentRenderer->m_PickingPass->OnWindowResize(); currentRenderer->m_DrawBloomPass->OnWindowResize(); + //TODO: CubeMapPass->OnWindowResize //If needed } void Renderer::InitializeWindow() @@ -88,9 +89,6 @@ void Renderer::InitializeShaders() //m_ExplosionEffectProgram->AddShader(std::shared_ptr(new FragmentShader("Shaders/ExplosionEffect.frag.glsl"))); //m_ExplosionEffectProgram->Compile(); //m_ExplosionEffectProgram->Link(); - - - } void Renderer::InputUpdate(double dt) @@ -108,6 +106,7 @@ void Renderer::Update(double dt) void Renderer::Draw(RenderFrame& frame) { + GLERROR("PRE"); ImGui::Combo("Draw textures", &m_DebugTextureToDraw, "Final\0Scene\0Bloom\0SceneLowRes\0BloomLowRes\0Gaussian\0Picking\0Ambient Occlusion"); ImGui::SliderFloat("SSAO sample radius", &m_SSAO_Radius, 0.01f, 5.0f); @@ -117,6 +116,7 @@ void Renderer::Draw(RenderFrame& frame) ImGui::SliderInt("SSAO Number of Samples", &m_SSAO_NumOfSamples, 2, 100); ImGui::SliderInt("SSAO Number of Turns", &m_SSAO_NumOfTurns, 0, 50); m_SSAOPass->Setting(m_SSAO_Radius, m_SSAO_Bias, m_SSAO_Contrast, m_SSAO_IntensityScale, m_SSAO_NumOfSamples, m_SSAO_NumOfTurns); + GLERROR("SSAO Settings"); //clear buffer 0 glClearColor(0.f, 0.f, 0.f, 0.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); @@ -127,6 +127,7 @@ void Renderer::Draw(RenderFrame& frame) m_DrawFinalPass->ClearBuffer(); m_DrawBloomPass->ClearBuffer(); PerformanceTimer::StopTimer("Renderer-ClearBuffers"); + GLERROR("ClearBuffers"); for (auto scene : frame.RenderScenes) { PerformanceTimer::StartTimer("Renderer-Depth"); m_PickingPass->Draw(*scene); @@ -239,9 +240,10 @@ void Renderer::InitializeRenderPasses() { m_PickingPass = new PickingPass(this, m_EventBroker); m_LightCullingPass = new LightCullingPass(this); - m_DrawFinalPass = new DrawFinalPass(this, m_LightCullingPass); + m_CubeMapPass = new CubeMapPass(this); + m_DrawFinalPass = new DrawFinalPass(this, m_LightCullingPass, m_CubeMapPass); m_DrawScreenQuadPass = new DrawScreenQuadPass(this); m_DrawBloomPass = new DrawBloomPass(this); m_DrawColorCorrectionPass = new DrawColorCorrectionPass(this); - m_SSAOPass = new SSAOPass(this); + m_SSAOPass = new SSAOPass(this); } diff --git a/src/Engine/Rendering/Texture.cpp b/src/Engine/Rendering/Texture.cpp index 256246a9..03347044 100644 --- a/src/Engine/Rendering/Texture.cpp +++ b/src/Engine/Rendering/Texture.cpp @@ -18,6 +18,7 @@ Texture::Texture(std::string path) this->Width = img->Width; this->Height = img->Height; + this->Data = img->Data; GLint format; switch (img->Format) { @@ -28,6 +29,7 @@ Texture::Texture(std::string path) format = GL_RGBA; break; } + // Construct the OpenGL texture glGenTextures(1, &m_Texture); From 8d23c531afc08de9dd39584d84f8016e6498e2ef Mon Sep 17 00:00:00 2001 From: Tleety Date: Tue, 23 Feb 2016 17:17:50 +0100 Subject: [PATCH 335/355] Cubemaps kinda functioning, still somthing wierd with the vectors. --- assets | 2 +- resources/Shaders/ForwardPlus.frag.glsl | 9 ++++++--- src/Engine/Rendering/CubeMapPass.cpp | 2 +- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/assets b/assets index ba8e04f1..89b40707 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit ba8e04f12be11034464b8446331286196953bb84 +Subproject commit 89b4070731584056402eac071845e9b1a0d156fb diff --git a/resources/Shaders/ForwardPlus.frag.glsl b/resources/Shaders/ForwardPlus.frag.glsl index 78f2106f..1b4d8c1e 100644 --- a/resources/Shaders/ForwardPlus.frag.glsl +++ b/resources/Shaders/ForwardPlus.frag.glsl @@ -134,7 +134,8 @@ void main() normal = normalize(normal); //vec4 normal = normalize(V * vec4(Input.Normal, 0.0)); vec4 viewVec = normalize(-position); - vec3 R = reflect(-viewVec.xyz, normal.xyz); + vec3 R = reflect(viewVec.xyz, normal.xyz); + R = vec3(P * vec4(R, 1.0)); vec4 reflectionColor = texture(CubeMap, R); vec2 tilePos; @@ -166,6 +167,8 @@ void main() vec4 color_result = mix((Color * diffuseTexel * DiffuseColor), Input.ExplosionColor, Input.ExplosionPercentageElapsed); color_result = color_result * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)); + float specularResult = (specularTexel.r + specularTexel.g + specularTexel.b)/3.0; + color_result = color_result * clamp(1/specularTexel, 0, 1) + reflectionColor * clamp(specularTexel, 0, 1); //vec4 color_result = (DiffuseColor + Input.ExplosionColor) * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)) * diffuseTexel * Color; @@ -174,8 +177,8 @@ void main() if(pos <= FillPercentage) { color_result += FillColor; } - //sceneColor = vec4(color_result.xyz, clamp(color_result.a, 0, 1)); - sceneColor = vec4(reflectionColor.xyz, 1); + sceneColor = vec4(color_result.xyz, clamp(color_result.a, 0, 1)); + //sceneColor = vec4(reflectionColor.xyz, 1); color_result += glowTexel*GlowIntensity; bloomColor = vec4(clamp(color_result.xyz - 1.0, 0, 100), clamp(color_result.a, 0, 1)); diff --git a/src/Engine/Rendering/CubeMapPass.cpp b/src/Engine/Rendering/CubeMapPass.cpp index 153d8eb8..cdfc704e 100644 --- a/src/Engine/Rendering/CubeMapPass.cpp +++ b/src/Engine/Rendering/CubeMapPass.cpp @@ -27,7 +27,7 @@ void CubeMapPass::GenerateCubeMapTexture() glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapTexture); for (int i = 0; i < 6; i++) { - glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGBA32F, 256, 256, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_CubeMapTestTextures[i]->Data); + glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGBA32F, 1024, 1024, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_CubeMapTestTextures[i]->Data); } glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); From e2831c5593604047cdca3eeb11e0046851176c72 Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Tue, 23 Feb 2016 17:29:33 +0100 Subject: [PATCH 336/355] CapturePointSystem fix, DamageIndicatorSystem fix --- include/Game/Systems/DamageIndicatorSystem.h | 16 ++- src/Game/Systems/CapturePointSystem.cpp | 53 ++++---- src/Game/Systems/DamageIndicatorSystem.cpp | 133 ++++++++++++++----- src/Game/Systems/PlayerDeathSystem.cpp | 5 +- src/Tests/HealthSystemTest.h | 1 - 5 files changed, 144 insertions(+), 64 deletions(-) diff --git a/include/Game/Systems/DamageIndicatorSystem.h b/include/Game/Systems/DamageIndicatorSystem.h index 053b196b..49ae249c 100644 --- a/include/Game/Systems/DamageIndicatorSystem.h +++ b/include/Game/Systems/DamageIndicatorSystem.h @@ -15,10 +15,11 @@ #include "Rendering/Util/CommonFunctions.h" -class DamageIndicatorSystem : public System +class DamageIndicatorSystem : public ImpureSystem { public: DamageIndicatorSystem(SystemParams params); + virtual void Update(double dt) override; private: EventRelay m_EPlayerDamage; @@ -28,6 +29,19 @@ private: bool OnSetCamera(const Events::SetCamera& e); EntityID m_CurrentCamera = -1; + struct DamageIndicatorStruct { + EntityWrapper spriteEntity; + glm::vec3 enemyPosition; + DamageIndicatorStruct(EntityWrapper sprite, glm::vec3 pos) + : spriteEntity(sprite) + , enemyPosition(pos) {} + }; + std::vector updateDamageIndicatorVector; + float CalculateAngle(EntityWrapper player, glm::vec3 enemyPos); + //for tests + int m_TestVar = 0; + bool m_Testing = false; + glm::vec3 DamageIndicatorTest(EntityWrapper player); }; #endif diff --git a/src/Game/Systems/CapturePointSystem.cpp b/src/Game/Systems/CapturePointSystem.cpp index 5fdd74cd..e4df9740 100644 --- a/src/Game/Systems/CapturePointSystem.cpp +++ b/src/Game/Systems/CapturePointSystem.cpp @@ -1,32 +1,37 @@ #include "Systems/CapturePointSystem.h" #include -CapturePointSystem::CapturePointSystem(SystemParams params) +CapturePointSystem::CapturePointSystem(SystemParams params) : System(params) , PureSystem("CapturePoint") { //subscribe/listenTo playerdamage,healthpickup events (using the eventBroker) - if (IsClient) { - EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &CapturePointSystem::OnTriggerTouch); - EVENT_SUBSCRIBE_MEMBER(m_ETriggerLeave, &CapturePointSystem::OnTriggerLeave); - EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &CapturePointSystem::OnCaptured); - } + EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &CapturePointSystem::OnTriggerTouch); + EVENT_SUBSCRIBE_MEMBER(m_ETriggerLeave, &CapturePointSystem::OnTriggerLeave); + EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &CapturePointSystem::OnCaptured); + } //here all capturepoints will update their component //NOTE: needs to run each frame, since we're possibly modifying the captureTimer for the capturePoints by dt void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, ComponentWrapper& cCapturePoint, double dt) { - if (!IsClient) { - return; - } - + //if (!IsClient) { + // return; + //} if (m_WinnerWasFound) { return; } const int capturePointNumber = cCapturePoint["CapturePointNumber"]; const bool hasTeamComponent = capturePointEntity.HasComponent("Team"); + if (m_NumberOfCapturePoints != 0) { + if (!m_CapturePointNumberToEntityMap[0].HasComponent("CapturePoint")) { + //if map has changed, the capturepoints has changed, now have to redo them + m_NumberOfCapturePoints = 0; + m_CapturePointNumberToEntityMap.clear(); + } + } //if point doesnt have a teamComponent yet, add one. since: //what if capture point has no team -> we cant get/use the team enum from it... if (!hasTeamComponent) { @@ -71,8 +76,7 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp std::map nextPossibleCapturePoint; nextPossibleCapturePoint["Red"] = -1; nextPossibleCapturePoint["Blue"] = -1; - for (int i = 0; i < m_NumberOfCapturePoints; i++) - { + for (int i = 0; i < m_NumberOfCapturePoints; i++) { if (!m_CapturePointNumberToEntityMap[i].HasComponent("Team")) { continue; } @@ -84,8 +88,7 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp nextPossibleCapturePoint["Blue"] = i + 1; } } - for (int i = m_NumberOfCapturePoints - 1; i >= 0; i--) - { + for (int i = m_NumberOfCapturePoints - 1; i >= 0; i--) { if (!m_CapturePointNumberToEntityMap[i].HasComponent("Team")) { continue; } @@ -100,8 +103,7 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp //reset timers and reset the bool that triggers this if (m_ResetTimers) { - for (int i = 0; i < m_NumberOfCapturePoints; i++) - { + for (int i = 0; i < m_NumberOfCapturePoints; i++) { ComponentWrapper& capturePoint = m_CapturePointNumberToEntityMap[i]["CapturePoint"]; if ((int)capturePoint["CapturePointNumber"] != nextPossibleCapturePoint["Red"] && (int)capturePoint["CapturePointNumber"] != nextPossibleCapturePoint["Blue"]) { @@ -116,8 +118,7 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp } //check how many players are standing inside and are healthy - for (size_t i = m_ETriggerTouchVector.size(); i > 0; i--) - { + for (size_t i = m_ETriggerTouchVector.size(); i > 0; i--) { auto triggerTouched = m_ETriggerTouchVector[i - 1]; if (std::get<1>(triggerTouched) == capturePointEntity) { //some player has touched this - lets figure out: what team, health @@ -176,8 +177,8 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp cCapturePoint["CaptureTimer"] = (double)cCapturePoint["CaptureTimer"] + timerDeltaChange; } //if capturePoint is owned by the team, and the other team has been trying to take it, then increase/decrease the timer towards 0.0 - if ((ownedBy == currentTeam && currentTeam == redTeam && (double)cCapturePoint["CaptureTimer"] < 0.0) || - (ownedBy == currentTeam && currentTeam == blueTeam && (double)cCapturePoint["CaptureTimer"] > 0.0)) { + if ((ownedBy == currentTeam && currentTeam == redTeam && (double)cCapturePoint["CaptureTimer"] < captureTimeToTakeOver) || + (ownedBy == currentTeam && currentTeam == blueTeam && (double)cCapturePoint["CaptureTimer"] > -captureTimeToTakeOver)) { cCapturePoint["CaptureTimer"] = (double)cCapturePoint["CaptureTimer"] + timerDeltaChange; } //check if captureTimer > captureTimeToTakeOver and if so change owner and publish the eCaptured event @@ -195,17 +196,14 @@ void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, Comp //check for possible winCondition = check if the homebase is owned by the other team bool checkForWinner = false; - if (capturePointNumber == m_RedTeamHomeCapturePoint && ownedBy != redTeam) - { + if (capturePointNumber == m_RedTeamHomeCapturePoint && ownedBy != redTeam) { checkForWinner = true; } - if (capturePointNumber == m_BlueTeamHomeCapturePoint && ownedBy != blueTeam) - { + if (capturePointNumber == m_BlueTeamHomeCapturePoint && ownedBy != blueTeam) { checkForWinner = true; } - if (checkForWinner && !m_WinnerWasFound) - { + if (checkForWinner && !m_WinnerWasFound) { //publish Win event Events::Win e; e.TeamThatWon = ownedBy; @@ -224,8 +222,7 @@ bool CapturePointSystem::OnTriggerTouch(const Events::TriggerTouch& e) bool CapturePointSystem::OnTriggerLeave(const Events::TriggerLeave& e) { - for (size_t i = 0; i < m_ETriggerTouchVector.size(); i++) - { + for (size_t i = 0; i < m_ETriggerTouchVector.size(); i++) { auto triggerTouched = m_ETriggerTouchVector[i]; if (std::get<0>(triggerTouched) == e.Entity && std::get<1>(triggerTouched) == e.Trigger) { m_ETriggerTouchVector.erase(m_ETriggerTouchVector.begin() + i); diff --git a/src/Game/Systems/DamageIndicatorSystem.cpp b/src/Game/Systems/DamageIndicatorSystem.cpp index 235eced0..65e1caf0 100644 --- a/src/Game/Systems/DamageIndicatorSystem.cpp +++ b/src/Game/Systems/DamageIndicatorSystem.cpp @@ -12,52 +12,42 @@ DamageIndicatorSystem::DamageIndicatorSystem(SystemParams params) auto entityFile = ResourceManager::Load("Schema/Entities/DamageIndicator.xml"); } +void DamageIndicatorSystem::Update(double dt) { + if (!IsServer) { + for (auto& iter = updateDamageIndicatorVector.begin(); iter != updateDamageIndicatorVector.end(); iter++) { + if (!iter->spriteEntity.Valid()) { + updateDamageIndicatorVector.erase(iter); + break; + } + auto angleBetweenVectors = CalculateAngle(LocalPlayer, iter->enemyPosition); + //simply set the rotation z-wise to the angleBetweenVectors + iter->spriteEntity["Transform"]["Orientation"] = glm::vec3(0, 0, angleBetweenVectors); + } + } +} + bool DamageIndicatorSystem::OnPlayerDamage(Events::PlayerDamage& e) { if (m_CurrentCamera == EntityID_Invalid) { return false; } - //if (e.Victim != LocalPlayer) { - // return false; - //} if (e.Victim.Valid() && e.Victim != LocalPlayer && !e.Victim.IsChildOf(LocalPlayer)) { return false; } if (!e.Inflictor.Valid() || !e.Victim.Valid()) { - return false; + return false; } - //grab players direction - auto playerOrientation = glm::quat((glm::vec3)e.Victim["Transform"]["Orientation"]); - - //get the position vectors, but ignore the y-height - auto enemyPosition = (glm::vec3)e.Inflictor["Transform"]["Position"]; - auto playerPosition = (glm::vec3)e.Victim["Transform"]["Position"]; - enemyPosition.y = 0.0f; - playerPosition.y = 0.0f; - - //calculate the enemy to player vector - auto enemyPlayerVector = glm::normalize(playerPosition - enemyPosition); - - //get angle from players current rotation, this angle is how much you rotate around the y-axis - auto playerAngle = glm::angle(playerOrientation); - auto playerRotationVector = glm::normalize(glm::rotateY(glm::vec3(0, 0, 1), playerAngle)); - - //dot product of players direction-vector and enemys-to-playervector will give the cos of the angle between the vectors - auto playerRotationDot = glm::dot(playerRotationVector, enemyPlayerVector); - //to get the angle between the vectors just do cos-inverse - auto angleBetweenVectors = glm::acos(playerRotationDot); - - //rotate the direction-vector 90 degrees to get the players side-vector - auto playerSideVector = glm::normalize(glm::rotateY(glm::vec3(0, 0, 1), playerAngle + 1.57f)); - //dot of sidevector positive = enemy is on the right side, dot sidevector negative = left side - auto playerSideVectorDot = glm::dot(playerSideVector, enemyPlayerVector); - if (playerSideVectorDot < 0) { - angleBetweenVectors = -angleBetweenVectors; + glm::vec3 inflictorPos = e.Inflictor["Transform"]["Position"]; + //if testing + if (m_Testing) { + inflictorPos = DamageIndicatorTest(e.Victim); } + float angleBetweenVectors = CalculateAngle(e.Victim, inflictorPos); + //load & set the "2d" sprite auto entityFile = ResourceManager::Load("Schema/Entities/DamageIndicator.xml"); EntityFileParser parser(entityFile); @@ -67,6 +57,10 @@ bool DamageIndicatorSystem::OnPlayerDamage(Events::PlayerDamage& e) //simply set the rotation z-wise to the angleBetweenVectors spriteWrapper["Transform"]["Orientation"] = glm::vec3(0, 0, angleBetweenVectors); + if (!IsServer) { + updateDamageIndicatorVector.emplace_back(spriteWrapper, inflictorPos); + } + return true; } @@ -74,3 +68,80 @@ bool DamageIndicatorSystem::OnSetCamera(const Events::SetCamera& e) { m_CurrentCamera = e.CameraEntity.ID; return true; } + +float DamageIndicatorSystem::CalculateAngle(EntityWrapper player, glm::vec3 enemyPos) { + //grab players direction + auto playerOrientation = glm::quat((glm::vec3)player["Transform"]["Orientation"]); + + //get the position vectors, but ignore the y-height + auto enemyPosition = enemyPos; + auto playerPosition = (glm::vec3)player["Transform"]["Position"]; + enemyPosition.y = 0.0f; + playerPosition.y = 0.0f; + + //calculate the enemy to player vector + auto enemyPlayerVector = glm::normalize(playerPosition - enemyPosition); + + //get the rotationvector relative to the z-axis + auto rotationVectorVec3 = glm::vec3(glm::toMat4(Transform::AbsoluteOrientation(player))*glm::vec4(0, 0, 1, 0)); + //rotate the direction-vector 90 degrees to get the players side-vector + auto playerSideVector = glm::vec3(glm::rotateY(rotationVectorVec3, 1.57f)); + + //dot product of players direction-vector and enemys-to-playervector will give the cos of the angle between the vectors + auto playerRotationDot = glm::dot(rotationVectorVec3, enemyPlayerVector); + //to get the angle between the vectors just do cos-inverse + auto angleBetweenVectors = glm::acos(playerRotationDot); + + //dot of sidevector positive = enemy is on the right side, dot sidevector negative = left side + auto playerSideVectorDot = glm::dot(playerSideVector, enemyPlayerVector); + if (playerSideVectorDot < 0) { + angleBetweenVectors = -angleBetweenVectors; + } + + return angleBetweenVectors; +} +glm::vec3 DamageIndicatorSystem::DamageIndicatorTest(EntityWrapper player) { + auto currentPos = (glm::vec3)player["Transform"]["Position"]; + + auto testVar = 1; + auto testVar2 = 1; + if (m_TestVar % 4 == 0) { + testVar = -1; + testVar2 = 1; + } + if (m_TestVar % 4 == 1) { + testVar = 1; + testVar2 = 1; + } + if (m_TestVar % 4 == 2) { + testVar *= -1; + testVar2 = -1; + } + if (m_TestVar % 4 == 3) { + testVar = 1; + testVar2 = -1; + } + m_TestVar++; + + auto inflictorPos = glm::vec3(currentPos.x + testVar*6.0f, currentPos.y, currentPos.z + testVar2*6.0f); + + //load the explosioneffect XML + auto deathEffect = ResourceManager::Load("Schema/Entities/PlayerDeathExplosionWithCamera.xml"); + EntityFileParser parser(deathEffect); + EntityID deathEffectID = parser.MergeEntities(m_World); + EntityWrapper deathEffectEW = EntityWrapper(m_World, deathEffectID); + + //components that we need from player + auto playerModel = player.FirstChildByName("PlayerModel"); + auto playerEntityModel = playerModel["Model"]; + auto playerEntityAnimation = playerModel["Animation"]; + + //copy the data from player to explosioneffectmodel + playerEntityModel.Copy(deathEffectEW["Model"]); + playerEntityAnimation.Copy(deathEffectEW["Animation"]); + + //copy the models position,orientation + deathEffectEW["Transform"]["Position"] = inflictorPos; + deathEffectEW["Transform"]["Orientation"] = (glm::vec3)player["Transform"]["Orientation"]; + return inflictorPos; +} diff --git a/src/Game/Systems/PlayerDeathSystem.cpp b/src/Game/Systems/PlayerDeathSystem.cpp index 40a98278..844d2ed1 100644 --- a/src/Game/Systems/PlayerDeathSystem.cpp +++ b/src/Game/Systems/PlayerDeathSystem.cpp @@ -33,9 +33,8 @@ void PlayerDeathSystem::createDeathEffect(EntityWrapper player) EntityWrapper deathEffectEW = EntityWrapper(m_World, deathEffectID); //components that we need from player - auto playerCamera = player.FirstChildByName("Camera"); auto playerModel = player.FirstChildByName("PlayerModel"); - if (!playerCamera.Valid() || !playerModel.Valid()) { + if (!playerModel.Valid()) { return; } if (!playerModel.HasComponent("Model") || !playerModel.HasComponent("Animation")) { @@ -44,7 +43,7 @@ void PlayerDeathSystem::createDeathEffect(EntityWrapper player) auto playerEntityModel = playerModel["Model"]; auto playerEntityAnimation = playerModel["Animation"]; - //copy the data from player to explisioneffectmodel + //copy the data from player to explosioneffectmodel playerEntityModel.Copy(deathEffectEW["Model"]); playerEntityAnimation.Copy(deathEffectEW["Animation"]); //freeze the animation diff --git a/src/Tests/HealthSystemTest.h b/src/Tests/HealthSystemTest.h index 685a06dd..275558d2 100644 --- a/src/Tests/HealthSystemTest.h +++ b/src/Tests/HealthSystemTest.h @@ -6,7 +6,6 @@ #include "Core/EventBroker.h" #include "Rendering/Renderer.h" #include "Core/InputManager.h" -#include "GUI/Frame.h" #include "Core/World.h" #include "Input/InputProxy.h" #include "Input/KeyboardInputHandler.h" From fa13c1d0654f38da20b608733e0294ca36fcaadf Mon Sep 17 00:00:00 2001 From: Jocke Date: Tue, 23 Feb 2016 18:24:46 +0100 Subject: [PATCH 337/355] Double jump is now working. --- include/Engine/Network/Client.h | 11 ++++--- include/Engine/Network/MessageType.h | 1 + include/Engine/Network/Server.h | 10 +++--- include/Game/Events/EDoubleJump.h | 2 +- include/Game/Systems/PlayerMovementSystem.h | 4 +++ src/Engine/Network/Client.cpp | 34 +++++++++++++++++++++ src/Engine/Network/Server.cpp | 15 +++++++-- src/Game/Systems/PlayerMovementSystem.cpp | 34 +++++++++++++++++---- 8 files changed, 93 insertions(+), 18 deletions(-) diff --git a/include/Engine/Network/Client.h b/include/Engine/Network/Client.h index 978c9b65..2b426cf4 100644 --- a/include/Engine/Network/Client.h +++ b/include/Engine/Network/Client.h @@ -21,6 +21,7 @@ #include "Core/ConfigFile.h" #include "Input/EInputCommand.h" #include "Core/EPlayerDamage.h" +#include "../Game/Events/EDoubleJump.h" #include "Network/EInterpolate.h" #include "Network/SnapshotFilter.h" #include "Core/EPlayerSpawned.h" @@ -34,7 +35,9 @@ public: void Connect(std::string address, int port); void Update() override; - +private: + UDPClient m_Unreliable; + TCPClient m_Reliable; std::vector m_PlayerSpawnEvents; void parseSpawnEvents(); // Save for children @@ -86,6 +89,7 @@ public: void parsePlayersSpawned(Packet& packet); void parseEntityDeletion(Packet& packet); void parseComponentDeletion(Packet& packet); + void parseDoubleJump(Packet& packet); void InterpolateFields(Packet & packet, const ComponentInfo & componentInfo, const EntityID & entityID, const std::string & componentType); void parseSnapshot(Packet& packet); void identifyPacketLoss(); @@ -110,9 +114,8 @@ public: EventRelay m_EPlayerSpawned; bool OnPlayerSpawned(const Events::PlayerSpawned& e); void parsePlayerDamage(Packet& packet); -private: - UDPClient m_Unreliable; - TCPClient m_Reliable; + EventRelay m_EPDoubleJump; + bool OnDoubleJump(Events::DoubleJump & e); }; #endif diff --git a/include/Engine/Network/MessageType.h b/include/Engine/Network/MessageType.h index a72f054e..6322b098 100644 --- a/include/Engine/Network/MessageType.h +++ b/include/Engine/Network/MessageType.h @@ -19,6 +19,7 @@ enum class MessageType EntityDeleted, ComponentDeleted, PlayerTransform, + OnDoubleJump, Invalid }; diff --git a/include/Engine/Network/Server.h b/include/Engine/Network/Server.h index b37bffab..dad45120 100644 --- a/include/Engine/Network/Server.h +++ b/include/Engine/Network/Server.h @@ -17,6 +17,7 @@ #include "Core/EPlayerDamage.h" #include "Network/EPlayerDisconnected.h" #include "Core/EPlayerSpawned.h" +#include "../Game/Events/EDoubleJump.h" #include "Core/EEntityDeleted.h" #include "Core/EComponentDeleted.h" @@ -54,7 +55,7 @@ private: std::vector m_InputCommandsToBroadcast; //Timers std::clock_t m_StartPingTime; - + // Packet loss logic PacketID m_PacketID = 0; PacketID m_PreviousPacketID = 0; @@ -77,9 +78,10 @@ private: void parsePlayerTransform(Packet& packet); void parseOnInputCommand(Packet& packet); void parseClientPing(); - void parsePing(); - void parseUDPConnect(Packet & packet); - void parseTCPConnect(Packet & packet); + void parsePing(); + bool parseDoubleJump(Packet& packet); + void parseUDPConnect(Packet& packet); + void parseTCPConnect(Packet& packet); void parseDisconnect(); bool shouldSendToClient(EntityWrapper childEntity); diff --git a/include/Game/Events/EDoubleJump.h b/include/Game/Events/EDoubleJump.h index 767d5b39..f5cad1fd 100644 --- a/include/Game/Events/EDoubleJump.h +++ b/include/Game/Events/EDoubleJump.h @@ -8,7 +8,7 @@ namespace Events struct DoubleJump : public Event { - + EntityID entityID; }; } diff --git a/include/Game/Systems/PlayerMovementSystem.h b/include/Game/Systems/PlayerMovementSystem.h index 2bcae866..a4008777 100644 --- a/include/Game/Systems/PlayerMovementSystem.h +++ b/include/Game/Systems/PlayerMovementSystem.h @@ -34,9 +34,13 @@ private: glm::vec3 m_LastPosition = glm::vec3(); // The logic for making the sound play when player is moving void playerStep(double dt); + // Spawn a hexagon at origin of an Entity + void spawnHexagon(EntityWrapper target); EventRelay m_EPlayerSpawned; bool OnPlayerSpawned(Events::PlayerSpawned& e); + EventRelay m_EPDoubleJump; + bool PlayerMovementSystem::OnDoubleJump(Events::DoubleJump & e); void updateMovementControllers(double dt); void updateVelocity(double dt); diff --git a/src/Engine/Network/Client.cpp b/src/Engine/Network/Client.cpp index a2f52adb..ad72571c 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -30,6 +30,7 @@ void Client::Connect(std::string address, int port) EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &Client::OnInputCommand); EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &Client::OnPlayerDamage); EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &Client::OnPlayerSpawned); + EVENT_SUBSCRIBE_MEMBER(m_EPDoubleJump, &Client::OnDoubleJump); auto config = ResourceManager::Load("Config.ini"); m_Address = address; if (address.empty()) { @@ -122,6 +123,9 @@ void Client::parseMessageType(Packet& packet) case MessageType::OnPlayerDamage: parsePlayerDamage(packet); break; + case MessageType::OnDoubleJump: + parseDoubleJump(packet); + break; default: break; } @@ -238,6 +242,20 @@ void Client::parseComponentDeletion(Packet & packet) } } +void Client::parseDoubleJump(Packet & packet) +{ + EntityID serverID = packet.ReadPrimitive(); + if (!serverClientMapsHasEntity(serverID)) { + return; + } + Events::DoubleJump e; + e.entityID = m_ServerIDToClientID.at(serverID); + // If player is local player to publish to prevent infinite feedback loop + if (e.entityID != m_LocalPlayer.ID) { + m_EventBroker->Publish(e); + } +} + void Client::updateFields(Packet& packet, const ComponentInfo& componentInfo, const EntityID& entityID) { for (auto field : componentInfo.FieldsInOrder) { @@ -415,6 +433,11 @@ bool Client::OnPlayerDamage(const Events::PlayerDamage & e) if (e.Inflictor != m_LocalPlayer) { return false; } + // Could this happen? + //if (!clientServerMapsHasEntity(e.Inflictor.ID) + // || !clientServerMapsHasEntity(e.Victim.ID)) { + // return; + //} Packet packet(MessageType::OnPlayerDamage, m_SendPacketID); packet.WritePrimitive(m_ClientIDToServerID.at(e.Inflictor.ID)); @@ -450,6 +473,17 @@ void Client::parsePlayerDamage(Packet& packet) } } +bool Client::OnDoubleJump(Events::DoubleJump & e) +{ + if (!clientServerMapsHasEntity(e.entityID) || e.entityID != m_LocalPlayer.ID) { + return false; + } + Packet packet(MessageType::OnDoubleJump); + packet.WritePrimitive(m_ClientIDToServerID.at(e.entityID)); + m_Reliable.Send(packet); + return true; +} + void Client::sendLocalPlayerTransform() { if (!m_LocalPlayer.Valid()) { diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index aa66433b..1a063067 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -1,6 +1,6 @@ #include "Network/Server.h" -Server::Server(World* world, EventBroker* eventBroker, int port) +Server::Server(World* world, EventBroker* eventBroker, int port) : Network(world, eventBroker) { ConfigFile* config = ResourceManager::Load("Config.ini"); @@ -120,6 +120,9 @@ void Server::parseMessageType(Packet& packet) case MessageType::PlayerTransform: parsePlayerTransform(packet); break; + case MessageType::OnDoubleJump: + parseDoubleJump(packet); + break; default: break; } @@ -279,7 +282,7 @@ void Server::parseTCPConnect(Packet & packet) // Read packet ID m_PreviousPacketID = m_PacketID; // Set previous packet id m_PacketID = packet.ReadPrimitive(); //Read new packet id - + LOG_INFO("Parsing connections"); // Check if player is already connected // Ska vara till lagd i TCPServer receive @@ -426,7 +429,7 @@ bool Server::OnPlayerDamage(const Events::PlayerDamage& e) packet.WritePrimitive(e.Damage); reliableBroadcast(packet); - return false; + return true; } void Server::parseClientPing() @@ -453,6 +456,12 @@ void Server::parsePing() } } +bool Server::parseDoubleJump(Packet & packet) +{ + reliableBroadcast(packet); + return true; +} + void Server::parseOnInputCommand(Packet& packet) { PlayerID player = -1; diff --git a/src/Game/Systems/PlayerMovementSystem.cpp b/src/Game/Systems/PlayerMovementSystem.cpp index 71fb16ee..ccd8c558 100644 --- a/src/Game/Systems/PlayerMovementSystem.cpp +++ b/src/Game/Systems/PlayerMovementSystem.cpp @@ -4,6 +4,7 @@ PlayerMovementSystem::PlayerMovementSystem(SystemParams params) : System(params) { EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &PlayerMovementSystem::OnPlayerSpawned); + EVENT_SUBSCRIBE_MEMBER(m_EPDoubleJump, &PlayerMovementSystem::OnDoubleJump); } PlayerMovementSystem::~PlayerMovementSystem() @@ -28,7 +29,6 @@ void PlayerMovementSystem::updateMovementControllers(double dt) if (!player.Valid()) { continue; } - // Aim pitch EntityWrapper cameraEntity = player.FirstChildByName("Camera"); if (cameraEntity.Valid()) { @@ -114,15 +114,14 @@ void PlayerMovementSystem::updateMovementControllers(double dt) if (isOnGround) { controller->SetDoubleJumping(false); } else { + // If IsServer and network is off this will not work if (IsClient) { //put a hexagon at the players feet - auto hexagonEffect = ResourceManager::Load("Schema/Entities/DoubleJumpHexagon.xml"); - EntityFileParser parser(hexagonEffect); - EntityID hexagonEffectID = parser.MergeEntities(m_World); - EntityWrapper hexagonEW = EntityWrapper(m_World, hexagonEffectID); - hexagonEW["Transform"]["Position"] = (glm::vec3)player["Transform"]["Position"]; + spawnHexagon(player); controller->SetDoubleJumping(true); + // Publish event for client to listen to Events::DoubleJump e; + e.entityID = player.ID; m_EventBroker->Publish(e); } } @@ -291,3 +290,26 @@ bool PlayerMovementSystem::OnPlayerSpawned(Events::PlayerSpawned& e) } return true; } + +bool PlayerMovementSystem::OnDoubleJump(Events::DoubleJump & e) +{ + // If entity does not exist, exit + if (!EntityWrapper(m_World, e.entityID).Valid()) { + return false; + } + // If entity IsLocalPlayer, exit + if (e.entityID == m_LocalPlayer.ID) { + return false; + } + spawnHexagon(EntityWrapper(m_World, e.entityID)); +} + +void PlayerMovementSystem::spawnHexagon(EntityWrapper target) +{ + //put a hexagon at the entitys... feet? + auto hexagonEffect = ResourceManager::Load("Schema/Entities/DoubleJumpHexagon.xml"); + EntityFileParser parser(hexagonEffect); + EntityID hexagonEffectID = parser.MergeEntities(m_World); + EntityWrapper hexagonEW = EntityWrapper(m_World, hexagonEffectID); + hexagonEW["Transform"]["Position"] = (glm::vec3)target["Transform"]["Position"]; +} \ No newline at end of file From 6465fe6ed68fd242d85a3411e46bf3a12cdbe6a2 Mon Sep 17 00:00:00 2001 From: Teejoon Date: Wed, 24 Feb 2016 13:22:41 +0100 Subject: [PATCH 338/355] Have fix the resizing errors --- include/Engine/Rendering/SSAOPass.h | 6 ++++-- src/Engine/Rendering/PickingPass.cpp | 18 +++--------------- src/Engine/Rendering/Renderer.cpp | 2 ++ src/Engine/Rendering/SSAOPass.cpp | 20 ++++++++++++-------- 4 files changed, 21 insertions(+), 25 deletions(-) diff --git a/include/Engine/Rendering/SSAOPass.h b/include/Engine/Rendering/SSAOPass.h index f15e20d3..792d1d82 100644 --- a/include/Engine/Rendering/SSAOPass.h +++ b/include/Engine/Rendering/SSAOPass.h @@ -14,11 +14,14 @@ class SSAOPass { public: SSAOPass(IRenderer* rendere); - ~SSAOPass() { }; + ~SSAOPass() { + delete m_DrawBloomPass; + }; void Draw(GLuint depthBuffer, Camera* camera); void Setting(float radius, float bias, float contrast, float intensityScale, int numOfSamples, int NumOfTurns); void ClearBuffer(); + void OnWindowResize(); //Return the SSAO of the texture sent to Draw GLuint SSAOTexture() const { return m_DrawBloomPass->GaussianTexture(); } @@ -31,7 +34,6 @@ private: void GenerateTexture(GLuint* texture, GLenum wrapping, GLenum filtering, glm::vec2 dimensions, GLint internalFormat, GLint format, GLenum type) const; - void ComputeAO(GLuint depthBuffer, Camera* camera); //void blurHorizontal(GLuint depthBuffer); //void blurVertical(GLuint depthBuffer); diff --git a/src/Engine/Rendering/PickingPass.cpp b/src/Engine/Rendering/PickingPass.cpp index d1ed73dd..4b4cd193 100644 --- a/src/Engine/Rendering/PickingPass.cpp +++ b/src/Engine/Rendering/PickingPass.cpp @@ -21,23 +21,13 @@ void PickingPass::InitializeTextures() { GenerateTexture(&m_PickingTexture, GL_CLAMP_TO_BORDER, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_RG8, GL_RG, GL_UNSIGNED_BYTE); + + 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); } void PickingPass::InitializeFrameBuffers() { - /* glGenRenderbuffers(1, &m_DepthBuffer); - glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBuffer); - glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height);*/ - - glGenTextures(1, &m_DepthBuffer); - - glBindTexture(GL_TEXTURE_2D, m_DepthBuffer); - glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH24_STENCIL8, (int)(m_Renderer->GetViewportSize().Width), (int)(m_Renderer->GetViewportSize().Height), 0, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, nullptr); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); - m_PickingBuffer.AddResource(std::shared_ptr(new Texture2D(&m_DepthBuffer, GL_DEPTH_ATTACHMENT))); m_PickingBuffer.AddResource(std::shared_ptr(new Texture2D(&m_PickingTexture, GL_COLOR_ATTACHMENT0))); m_PickingBuffer.Generate(); @@ -382,8 +372,6 @@ void PickingPass::ClearPicking() void PickingPass::OnWindowResize() { InitializeTextures(); - glBindRenderbuffer(GL_RENDERBUFFER, m_DepthBuffer); - glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height); m_PickingBuffer.Generate(); } diff --git a/src/Engine/Rendering/Renderer.cpp b/src/Engine/Rendering/Renderer.cpp index 0c668cad..5b3348c3 100644 --- a/src/Engine/Rendering/Renderer.cpp +++ b/src/Engine/Rendering/Renderer.cpp @@ -30,6 +30,7 @@ void Renderer::glfwFrameBufferCallback(GLFWwindow* window, int width, int height currentRenderer->m_LightCullingPass->OnWindowResize(); currentRenderer->m_PickingPass->OnWindowResize(); currentRenderer->m_DrawBloomPass->OnWindowResize(); + currentRenderer->m_SSAOPass->OnWindowResize(); } void Renderer::InitializeWindow() @@ -126,6 +127,7 @@ void Renderer::Draw(RenderFrame& frame) m_PickingPass->ClearPicking(); m_DrawFinalPass->ClearBuffer(); m_DrawBloomPass->ClearBuffer(); + m_SSAOPass->ClearBuffer(); PerformanceTimer::StopTimer("Renderer-ClearBuffers"); for (auto scene : frame.RenderScenes) { PerformanceTimer::StartTimer("Renderer-Depth"); diff --git a/src/Engine/Rendering/SSAOPass.cpp b/src/Engine/Rendering/SSAOPass.cpp index 331e040f..d4cdcb19 100644 --- a/src/Engine/Rendering/SSAOPass.cpp +++ b/src/Engine/Rendering/SSAOPass.cpp @@ -6,6 +6,7 @@ SSAOPass::SSAOPass(IRenderer* renderer) m_ScreenQuad = ResourceManager::Load("Models/Core/ScreenQuad.mesh"); + InitializeTexture(); InitializeBuffer(); InitializeShaderProgram(); Setting(0.1f, 0.012f, 1.0f, 1.0f, 13, 7); @@ -28,16 +29,16 @@ void SSAOPass::InitializeShaderProgram() m_SSAOViewSpaceZProgram->Link(); } +void SSAOPass::InitializeTexture() { + GenerateTexture(&m_SSAOTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_R8, GL_RED, GL_FLOAT); + GenerateTexture(&m_SSAOViewSpaceZTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_R32F, GL_RED, GL_FLOAT); +} void SSAOPass::InitializeBuffer() { - GenerateTexture(&m_SSAOTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_R8, GL_RED, GL_FLOAT); - m_SSAOFramBuffer.AddResource(std::shared_ptr(new Texture2D(&m_SSAOTexture, GL_COLOR_ATTACHMENT0))); m_SSAOFramBuffer.Generate(); - GenerateTexture(&m_SSAOViewSpaceZTexture, GL_CLAMP_TO_EDGE, GL_LINEAR, glm::vec2(m_Renderer->GetViewportSize().Width, m_Renderer->GetViewportSize().Height), GL_R32F, GL_RED, GL_FLOAT); - m_SSAOViewSpaceZFramBuffer.AddResource(std::shared_ptr(new Texture2D(&m_SSAOViewSpaceZTexture, GL_COLOR_ATTACHMENT0))); m_SSAOViewSpaceZFramBuffer.Generate(); } @@ -45,12 +46,12 @@ void SSAOPass::InitializeBuffer() void SSAOPass::ClearBuffer() { m_SSAOFramBuffer.Bind(); - glClearColor(0.f, 0.f, 0.f, 0.f); + glClearColor(1.f, 1.f, 1.f, 1.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_SSAOFramBuffer.Unbind(); m_SSAOViewSpaceZFramBuffer.Bind(); - glClearColor(0.f, 0.f, 0.f, 0.f); + glClearColor(1.f, 1.f, 1.f, 1.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_SSAOViewSpaceZFramBuffer.Unbind(); } @@ -136,6 +137,9 @@ void SSAOPass::Draw(GLuint depthBuffer, Camera* camera) m_DrawBloomPass->Draw(m_SSAOTexture); } -void ComputeAO(GLuint depthBuffer, Camera* camera) { - +void SSAOPass::OnWindowResize() { + m_DrawBloomPass->OnWindowResize(); + InitializeTexture(); + m_SSAOFramBuffer.Generate(); + m_SSAOViewSpaceZFramBuffer.Generate(); } \ No newline at end of file From 6f9ce8a0c16d1c65d05318e585857a3b02243468 Mon Sep 17 00:00:00 2001 From: Tleety Date: Wed, 24 Feb 2016 13:57:54 +0100 Subject: [PATCH 339/355] WIP --- include/Engine/Rendering/CubeMapPass.h | 5 +++-- resources/Shaders/ForwardPlus.frag.glsl | 8 +++++--- resources/Shaders/ForwardPlus.vert.glsl | 8 ++++---- src/Engine/Rendering/CubeMapPass.cpp | 23 +++++++++++------------ src/Engine/Rendering/DrawFinalPass.cpp | 7 +++++++ 5 files changed, 30 insertions(+), 21 deletions(-) diff --git a/include/Engine/Rendering/CubeMapPass.h b/include/Engine/Rendering/CubeMapPass.h index 564329e2..0840e2c8 100644 --- a/include/Engine/Rendering/CubeMapPass.h +++ b/include/Engine/Rendering/CubeMapPass.h @@ -10,7 +10,7 @@ public: CubeMapPass(IRenderer* renderer); ~CubeMapPass() { } - void LoadTextures(); + void LoadTextures(std::string input); void FillCubeMap(glm::vec3 originPosition); void GenerateCubeMapTexture(); @@ -19,8 +19,9 @@ public: private: IRenderer* m_Renderer; + std::string m_PreviusCubeMapTexture; - std::vector m_CubeMapTestTextures; + std::vector m_CubeMapTextures; }; #endif \ No newline at end of file diff --git a/resources/Shaders/ForwardPlus.frag.glsl b/resources/Shaders/ForwardPlus.frag.glsl index 1b4d8c1e..8b7a4824 100644 --- a/resources/Shaders/ForwardPlus.frag.glsl +++ b/resources/Shaders/ForwardPlus.frag.glsl @@ -12,6 +12,7 @@ uniform vec4 FillColor; uniform vec4 AmbientColor; uniform float FillPercentage; uniform float GlowIntensity = 10; +uniform vec3 CameraPosition; uniform vec2 DiffuseUVRepeat; uniform vec2 NormalUVRepeat; @@ -134,8 +135,9 @@ void main() normal = normalize(normal); //vec4 normal = normalize(V * vec4(Input.Normal, 0.0)); vec4 viewVec = normalize(-position); - vec3 R = reflect(viewVec.xyz, normal.xyz); - R = vec3(P * vec4(R, 1.0)); + vec3 I = normalize(vec3(M * vec4(Input.Position, 1.0)) - CameraPosition); + vec3 R = reflect(I, Input.Normal); + //R = vec3(P * vec4(R, 1.0)); vec4 reflectionColor = texture(CubeMap, R); vec2 tilePos; @@ -168,7 +170,7 @@ void main() vec4 color_result = mix((Color * diffuseTexel * DiffuseColor), Input.ExplosionColor, Input.ExplosionPercentageElapsed); color_result = color_result * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)); float specularResult = (specularTexel.r + specularTexel.g + specularTexel.b)/3.0; - color_result = color_result * clamp(1/specularTexel, 0, 1) + reflectionColor * clamp(specularTexel, 0, 1); + //color_result = color_result * clamp(1/specularTexel, 0, 1) + reflectionColor * clamp(specularTexel, 0, 1); //vec4 color_result = (DiffuseColor + Input.ExplosionColor) * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)) * diffuseTexel * Color; diff --git a/resources/Shaders/ForwardPlus.vert.glsl b/resources/Shaders/ForwardPlus.vert.glsl index d475d825..32daf240 100644 --- a/resources/Shaders/ForwardPlus.vert.glsl +++ b/resources/Shaders/ForwardPlus.vert.glsl @@ -23,12 +23,12 @@ out VertexData{ void main() { gl_Position = P*V*M * vec4(Position, 1.0); - + mat4 TIM = transpose(inverse(M)); Output.Position = Position; Output.TextureCoordinate = TextureCoords; - Output.Normal = vec3(M * vec4(Normal, 0.0)); - Output.Tangent = vec3(M * vec4(Tangent, 0.0)); - Output.BiTangent = vec3(M * vec4(BiTangent, 0.0)); + Output.Normal = vec3(TIM) * Normal; + Output.Tangent = vec3(TIM) * Tangent; + Output.BiTangent = vec3(TIM) * BiTangent; Output.ExplosionColor = vec4(1.0); Output.ExplosionPercentageElapsed = 0.0; } \ No newline at end of file diff --git a/src/Engine/Rendering/CubeMapPass.cpp b/src/Engine/Rendering/CubeMapPass.cpp index cdfc704e..b64b77f1 100644 --- a/src/Engine/Rendering/CubeMapPass.cpp +++ b/src/Engine/Rendering/CubeMapPass.cpp @@ -3,21 +3,20 @@ CubeMapPass::CubeMapPass(IRenderer* renderer) :m_Renderer(renderer) { - LoadTextures(); + LoadTextures("Nevada"); GenerateCubeMapTexture(); } -/* - -*/ - -void CubeMapPass::LoadTextures() +void CubeMapPass::LoadTextures(std::string input) { - for (int i = 0; i < 6; i++){ - std::string str; - str = "Textures/Test/CubeMap/CubeMapTest0" + std::to_string(i) + ".png"; - Texture* img = ResourceManager::Load(str); - m_CubeMapTestTextures.push_back(img); + if (m_PreviusCubeMapTexture != input) { + m_CubeMapTextures.clear(); + for (int i = 0; i < 6; i++) { + std::string str; + str = "Textures/Test/CubeMap/" + input + "/CubeMapTest0" + std::to_string(i) + ".png"; + Texture* img = ResourceManager::Load(str); + m_CubeMapTextures.push_back(img); + } } } @@ -27,7 +26,7 @@ void CubeMapPass::GenerateCubeMapTexture() glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapTexture); for (int i = 0; i < 6; i++) { - glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGBA32F, 1024, 1024, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_CubeMapTestTextures[i]->Data); + glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGBA32F, m_CubeMapTextures[0]->Width, m_CubeMapTextures[0]->Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_CubeMapTextures[i]->Data); } glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); diff --git a/src/Engine/Rendering/DrawFinalPass.cpp b/src/Engine/Rendering/DrawFinalPass.cpp index e7982a3d..6cd2c1f1 100644 --- a/src/Engine/Rendering/DrawFinalPass.cpp +++ b/src/Engine/Rendering/DrawFinalPass.cpp @@ -383,6 +383,8 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& BindExplosionTextures(explosionSkinnedHandle, explosionEffectJob); glActiveTexture(GL_TEXTURE5); glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); + glUniform3fv(glGetUniformLocation(forwardHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); + std::vector frameBones; if (explosionEffectJob->AnimationOffset.animation != nullptr) { frameBones = explosionEffectJob->Skeleton->GetFrameBones(explosionEffectJob->Animations, explosionEffectJob->AnimationOffset); @@ -399,6 +401,8 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& BindExplosionTextures(explosionHandle, explosionEffectJob); glActiveTexture(GL_TEXTURE5); glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); + glUniform3fv(glGetUniformLocation(forwardHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); + } break; } @@ -459,6 +463,8 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& BindModelTextures(forwardSkinnedHandle, modelJob); glActiveTexture(GL_TEXTURE5); glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); + glUniform3fv(glGetUniformLocation(forwardHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); + std::vector frameBones; if (modelJob->AnimationOffset.animation != nullptr) { frameBones = modelJob->Skeleton->GetFrameBones(modelJob->Animations, modelJob->AnimationOffset); @@ -476,6 +482,7 @@ void DrawFinalPass::DrawModelRenderQueues(std::list>& BindModelTextures(forwardHandle, modelJob); glActiveTexture(GL_TEXTURE5); glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapPass->m_CubeMapTexture); + glUniform3fv(glGetUniformLocation(forwardHandle, "CameraPosition"), 1, glm::value_ptr(scene.Camera->Position())); } break; } From af68236e7186774ba25111523a5cbacb4860eaab Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Wed, 24 Feb 2016 13:58:05 +0100 Subject: [PATCH 340/355] now using a define INDICATOR_TEST to activate the DamageIndicatorSystem test. --- include/Game/Systems/DamageIndicatorSystem.h | 6 ++++-- src/Game/Systems/DamageIndicatorSystem.cpp | 6 ++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/include/Game/Systems/DamageIndicatorSystem.h b/include/Game/Systems/DamageIndicatorSystem.h index 49ae249c..ae9ba195 100644 --- a/include/Game/Systems/DamageIndicatorSystem.h +++ b/include/Game/Systems/DamageIndicatorSystem.h @@ -14,6 +14,7 @@ #include #include "Rendering/Util/CommonFunctions.h" +//#define INDICATOR_TEST class DamageIndicatorSystem : public ImpureSystem { @@ -40,8 +41,9 @@ private: float CalculateAngle(EntityWrapper player, glm::vec3 enemyPos); //for tests - int m_TestVar = 0; - bool m_Testing = false; +#ifdef INDICATOR_TEST glm::vec3 DamageIndicatorTest(EntityWrapper player); + int m_TestVar = 0; +#endif }; #endif diff --git a/src/Game/Systems/DamageIndicatorSystem.cpp b/src/Game/Systems/DamageIndicatorSystem.cpp index 65e1caf0..92fbe607 100644 --- a/src/Game/Systems/DamageIndicatorSystem.cpp +++ b/src/Game/Systems/DamageIndicatorSystem.cpp @@ -42,9 +42,9 @@ bool DamageIndicatorSystem::OnPlayerDamage(Events::PlayerDamage& e) glm::vec3 inflictorPos = e.Inflictor["Transform"]["Position"]; //if testing - if (m_Testing) { +#ifdef INDICATOR_TEST inflictorPos = DamageIndicatorTest(e.Victim); - } +#endif float angleBetweenVectors = CalculateAngle(e.Victim, inflictorPos); @@ -100,6 +100,7 @@ float DamageIndicatorSystem::CalculateAngle(EntityWrapper player, glm::vec3 enem return angleBetweenVectors; } +#ifdef INDICATOR_TEST glm::vec3 DamageIndicatorSystem::DamageIndicatorTest(EntityWrapper player) { auto currentPos = (glm::vec3)player["Transform"]["Position"]; @@ -145,3 +146,4 @@ glm::vec3 DamageIndicatorSystem::DamageIndicatorTest(EntityWrapper player) { deathEffectEW["Transform"]["Orientation"] = (glm::vec3)player["Transform"]["Orientation"]; return inflictorPos; } +#endif \ No newline at end of file From 5af4f9d8e72795e4345cdc00623801d0c08bf51c Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Wed, 24 Feb 2016 14:06:41 +0100 Subject: [PATCH 341/355] Removed a comment originating from HUDDesynch branch --- src/Game/Systems/CapturePointSystem.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/Game/Systems/CapturePointSystem.cpp b/src/Game/Systems/CapturePointSystem.cpp index e4df9740..b45f6ced 100644 --- a/src/Game/Systems/CapturePointSystem.cpp +++ b/src/Game/Systems/CapturePointSystem.cpp @@ -16,9 +16,6 @@ CapturePointSystem::CapturePointSystem(SystemParams params) //NOTE: needs to run each frame, since we're possibly modifying the captureTimer for the capturePoints by dt void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, ComponentWrapper& cCapturePoint, double dt) { - //if (!IsClient) { - // return; - //} if (m_WinnerWasFound) { return; } From 607e83134df77faae4a276189494a8cf5bd64ef7 Mon Sep 17 00:00:00 2001 From: Tleety Date: Wed, 24 Feb 2016 14:16:49 +0100 Subject: [PATCH 342/355] Cubemaps working --- resources/Shaders/ForwardPlus.frag.glsl | 4 ++-- resources/Shaders/ForwardPlus.vert.glsl | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/resources/Shaders/ForwardPlus.frag.glsl b/resources/Shaders/ForwardPlus.frag.glsl index 8b7a4824..cddd6d6b 100644 --- a/resources/Shaders/ForwardPlus.frag.glsl +++ b/resources/Shaders/ForwardPlus.frag.glsl @@ -136,7 +136,7 @@ void main() //vec4 normal = normalize(V * vec4(Input.Normal, 0.0)); vec4 viewVec = normalize(-position); vec3 I = normalize(vec3(M * vec4(Input.Position, 1.0)) - CameraPosition); - vec3 R = reflect(I, Input.Normal); + vec3 R = reflect(-I, Input.Normal); //R = vec3(P * vec4(R, 1.0)); vec4 reflectionColor = texture(CubeMap, R); @@ -170,7 +170,7 @@ void main() vec4 color_result = mix((Color * diffuseTexel * DiffuseColor), Input.ExplosionColor, Input.ExplosionPercentageElapsed); color_result = color_result * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)); float specularResult = (specularTexel.r + specularTexel.g + specularTexel.b)/3.0; - //color_result = color_result * clamp(1/specularTexel, 0, 1) + reflectionColor * clamp(specularTexel, 0, 1); + color_result = color_result * clamp(1/specularTexel, 0, 1) + reflectionColor * clamp(specularTexel, 0, 1); //vec4 color_result = (DiffuseColor + Input.ExplosionColor) * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)) * diffuseTexel * Color; diff --git a/resources/Shaders/ForwardPlus.vert.glsl b/resources/Shaders/ForwardPlus.vert.glsl index 32daf240..26686222 100644 --- a/resources/Shaders/ForwardPlus.vert.glsl +++ b/resources/Shaders/ForwardPlus.vert.glsl @@ -26,9 +26,9 @@ void main() mat4 TIM = transpose(inverse(M)); Output.Position = Position; Output.TextureCoordinate = TextureCoords; - Output.Normal = vec3(TIM) * Normal; - Output.Tangent = vec3(TIM) * Tangent; - Output.BiTangent = vec3(TIM) * BiTangent; + Output.Normal = vec3(TIM * vec4(Normal, 0.0)); + Output.Tangent = vec3(TIM * vec4(Tangent, 0.0)); + Output.BiTangent = vec3(TIM * vec4(BiTangent, 0.0)); Output.ExplosionColor = vec4(1.0); Output.ExplosionPercentageElapsed = 0.0; } \ No newline at end of file From f41e0b29be13badc2ba84aef79611a0734da8aee Mon Sep 17 00:00:00 2001 From: Tleety Date: Wed, 24 Feb 2016 14:21:48 +0100 Subject: [PATCH 343/355] assets --- assets | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/assets b/assets index 89b40707..10a61165 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit 89b4070731584056402eac071845e9b1a0d156fb +Subproject commit 10a611659ddaadfea6a560e707d395834855a979 From 7394436e7a0f811e8e536595bd6b791c3b28ca45 Mon Sep 17 00:00:00 2001 From: stiffly Date: Wed, 24 Feb 2016 14:23:54 +0100 Subject: [PATCH 344/355] Removed unnecessary comment. --- src/Game/Systems/CapturePointSystem.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/Game/Systems/CapturePointSystem.cpp b/src/Game/Systems/CapturePointSystem.cpp index 598a1a8e..f5e37429 100644 --- a/src/Game/Systems/CapturePointSystem.cpp +++ b/src/Game/Systems/CapturePointSystem.cpp @@ -16,9 +16,6 @@ CapturePointSystem::CapturePointSystem(SystemParams params) //NOTE: needs to run each frame, since we're possibly modifying the captureTimer for the capturePoints by dt void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, ComponentWrapper& cCapturePoint, double dt) { - //if (!IsClient) { - // return; - //} if (m_WinnerWasFound) { return; } From feeff5b164a86f88346046b2d84ac45af15b867b Mon Sep 17 00:00:00 2001 From: Tleety Date: Wed, 24 Feb 2016 14:47:47 +0100 Subject: [PATCH 345/355] Debug tool for different CubeMap changed cubemap influence. --- include/Engine/Rendering/CubeMapPass.h | 2 +- include/Engine/Rendering/Renderer.h | 1 + resources/Shaders/ForwardPlus.frag.glsl | 2 +- src/Engine/Rendering/CubeMapPass.cpp | 6 ++++-- src/Engine/Rendering/Renderer.cpp | 6 ++++++ 5 files changed, 13 insertions(+), 4 deletions(-) diff --git a/include/Engine/Rendering/CubeMapPass.h b/include/Engine/Rendering/CubeMapPass.h index 0840e2c8..3cda8cad 100644 --- a/include/Engine/Rendering/CubeMapPass.h +++ b/include/Engine/Rendering/CubeMapPass.h @@ -15,7 +15,7 @@ public: void GenerateCubeMapTexture(); //GLuint CubeMapTexture() const { return m_CubeMapTexture; } - GLuint m_CubeMapTexture; + GLuint m_CubeMapTexture = -1; private: IRenderer* m_Renderer; diff --git a/include/Engine/Rendering/Renderer.h b/include/Engine/Rendering/Renderer.h index 720336aa..f3a6bf31 100644 --- a/include/Engine/Rendering/Renderer.h +++ b/include/Engine/Rendering/Renderer.h @@ -59,6 +59,7 @@ private: Model* m_UnitSphere; int m_DebugTextureToDraw = 0; + int m_CubeMapTexture = 0; bool m_ResizeWindow = false; float m_SSAO_Radius = 1.0f; float m_SSAO_Bias = 0.05f; diff --git a/resources/Shaders/ForwardPlus.frag.glsl b/resources/Shaders/ForwardPlus.frag.glsl index cddd6d6b..6fbc9c27 100644 --- a/resources/Shaders/ForwardPlus.frag.glsl +++ b/resources/Shaders/ForwardPlus.frag.glsl @@ -170,7 +170,7 @@ void main() vec4 color_result = mix((Color * diffuseTexel * DiffuseColor), Input.ExplosionColor, Input.ExplosionPercentageElapsed); color_result = color_result * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)); float specularResult = (specularTexel.r + specularTexel.g + specularTexel.b)/3.0; - color_result = color_result * clamp(1/specularTexel, 0, 1) + reflectionColor * clamp(specularTexel, 0, 1); + color_result = color_result * clamp(1/specularTexel, 0, 1)*2 + reflectionColor * clamp(specularTexel, 0, 1)/2; //vec4 color_result = (DiffuseColor + Input.ExplosionColor) * (totalLighting.Diffuse + (totalLighting.Specular * specularTexel)) * diffuseTexel * Color; diff --git a/src/Engine/Rendering/CubeMapPass.cpp b/src/Engine/Rendering/CubeMapPass.cpp index b64b77f1..75f5e1c9 100644 --- a/src/Engine/Rendering/CubeMapPass.cpp +++ b/src/Engine/Rendering/CubeMapPass.cpp @@ -4,7 +4,6 @@ CubeMapPass::CubeMapPass(IRenderer* renderer) :m_Renderer(renderer) { LoadTextures("Nevada"); - GenerateCubeMapTexture(); } void CubeMapPass::LoadTextures(std::string input) @@ -17,12 +16,15 @@ void CubeMapPass::LoadTextures(std::string input) Texture* img = ResourceManager::Load(str); m_CubeMapTextures.push_back(img); } + GenerateCubeMapTexture(); } } void CubeMapPass::GenerateCubeMapTexture() { - glGenTextures(1, &m_CubeMapTexture); + if (m_CubeMapTexture == -1) { + glGenTextures(1, &m_CubeMapTexture); + } glBindTexture(GL_TEXTURE_CUBE_MAP, m_CubeMapTexture); for (int i = 0; i < 6; i++) { diff --git a/src/Engine/Rendering/Renderer.cpp b/src/Engine/Rendering/Renderer.cpp index 8391599c..a3a53591 100644 --- a/src/Engine/Rendering/Renderer.cpp +++ b/src/Engine/Rendering/Renderer.cpp @@ -108,6 +108,12 @@ void Renderer::Draw(RenderFrame& frame) { GLERROR("PRE"); ImGui::Combo("Draw textures", &m_DebugTextureToDraw, "Final\0Scene\0Bloom\0SceneLowRes\0BloomLowRes\0Gaussian\0Picking\0Ambient Occlusion"); + ImGui::Combo("CubeMap", &m_CubeMapTexture, "Nevada(512)\0Sky(1024)"); + if(m_CubeMapTexture == 0) { + m_CubeMapPass->LoadTextures("Nevada"); + } else if (m_CubeMapTexture == 1) { + m_CubeMapPass->LoadTextures("Sky"); + } ImGui::SliderFloat("SSAO sample radius", &m_SSAO_Radius, 0.01f, 5.0f); ImGui::SliderFloat("SSAO bias", &m_SSAO_Bias, 0.0f, 0.1f); From ef87102d1f141810c2ebb3b2bc966f76d2849abc Mon Sep 17 00:00:00 2001 From: verysecrethero Date: Wed, 24 Feb 2016 17:53:37 +0100 Subject: [PATCH 346/355] Ammo,HealthPickup now takes in account for possible parenting/childing of the pickup. Also saved the xml files with the new scaling --- include/Game/Systems/AmmoPickupSystem.h | 1 + include/Game/Systems/PickupSpawnSystem.h | 1 + resources/Schema/Entities/AmmoPickup.xml | 10 +++++----- resources/Schema/Entities/HealthPickup.xml | 10 +++++----- src/Game/Systems/AmmoPickupSystem.cpp | 5 +++-- src/Game/Systems/PickupSpawnSystem.cpp | 3 ++- 6 files changed, 17 insertions(+), 13 deletions(-) diff --git a/include/Game/Systems/AmmoPickupSystem.h b/include/Game/Systems/AmmoPickupSystem.h index a54b8495..0fbd9e08 100644 --- a/include/Game/Systems/AmmoPickupSystem.h +++ b/include/Game/Systems/AmmoPickupSystem.h @@ -26,6 +26,7 @@ private: double AmmoGain; double RespawnTimer; double DecreaseThisRespawnTimer; + EntityID parentID; }; std::vector m_ETriggerTouchVector; }; diff --git a/include/Game/Systems/PickupSpawnSystem.h b/include/Game/Systems/PickupSpawnSystem.h index f912e8ff..66c5f630 100644 --- a/include/Game/Systems/PickupSpawnSystem.h +++ b/include/Game/Systems/PickupSpawnSystem.h @@ -27,6 +27,7 @@ private: double HealthGain; double RespawnTimer; double DecreaseThisRespawnTimer; + EntityID parentID; }; std::vector m_ETriggerTouchVector; }; diff --git a/resources/Schema/Entities/AmmoPickup.xml b/resources/Schema/Entities/AmmoPickup.xml index 1d1435f7..bebde467 100644 --- a/resources/Schema/Entities/AmmoPickup.xml +++ b/resources/Schema/Entities/AmmoPickup.xml @@ -2,18 +2,18 @@ - Models/Props/PickUps/AmmoPickUp.mesh - 0.1 - + 8 + - - + + + diff --git a/resources/Schema/Entities/HealthPickup.xml b/resources/Schema/Entities/HealthPickup.xml index c6fbc4f4..b4b83392 100644 --- a/resources/Schema/Entities/HealthPickup.xml +++ b/resources/Schema/Entities/HealthPickup.xml @@ -2,18 +2,18 @@ - Models/Props/PickUps/HealthPickUp.mesh - 0.1 - + 8 + - - + + + diff --git a/src/Game/Systems/AmmoPickupSystem.cpp b/src/Game/Systems/AmmoPickupSystem.cpp index f6778fe4..250fa494 100644 --- a/src/Game/Systems/AmmoPickupSystem.cpp +++ b/src/Game/Systems/AmmoPickupSystem.cpp @@ -29,6 +29,7 @@ void AmmoPickupSystem::Update(double dt) newAmmoPickupEntity["Transform"]["Position"] = ammoPickupPosition.Pos; newAmmoPickupEntity["AmmoPickup"]["AmmoGain"] = ammoPickupPosition.AmmoGain; newAmmoPickupEntity["AmmoPickup"]["RespawnTimer"] = ammoPickupPosition.RespawnTimer; + m_World->SetParent(newAmmoPickupEntity.ID, ammoPickupPosition.parentID); //erase the current element (AmmoPickupPosition) m_ETriggerTouchVector.erase(it); @@ -69,8 +70,8 @@ bool AmmoPickupSystem::OnTriggerTouch(Events::TriggerTouch& e) //copy position, ammogain, respawntimer (twice since one of the values will be counted down to 0, the other will be set in the new object) //we need to copy all values since each value can be different for each ammoPickup - m_ETriggerTouchVector.push_back({ (glm::vec3)e.Trigger["Transform"]["Position"] ,e.Trigger["AmmoPickup"]["AmmoGain"], - e.Trigger["AmmoPickup"]["RespawnTimer"],e.Trigger["AmmoPickup"]["RespawnTimer"] }); + m_ETriggerTouchVector.push_back({ e.Trigger["Transform"]["Position"], e.Trigger["AmmoPickup"]["AmmoGain"], + e.Trigger["AmmoPickup"]["RespawnTimer"], e.Trigger["AmmoPickup"]["RespawnTimer"], m_World->GetParent(e.Trigger.ID) }); //delete the ammopickup m_World->DeleteEntity(e.Trigger.ID); diff --git a/src/Game/Systems/PickupSpawnSystem.cpp b/src/Game/Systems/PickupSpawnSystem.cpp index 159f716b..abf59007 100644 --- a/src/Game/Systems/PickupSpawnSystem.cpp +++ b/src/Game/Systems/PickupSpawnSystem.cpp @@ -29,6 +29,7 @@ void PickupSpawnSystem::Update(double dt) newHealthPickupEntity["Transform"]["Position"] = healthPickupPosition.Pos; newHealthPickupEntity["HealthPickup"]["HealthGain"] = healthPickupPosition.HealthGain; newHealthPickupEntity["HealthPickup"]["RespawnTimer"] = healthPickupPosition.RespawnTimer; + m_World->SetParent(newHealthPickupEntity.ID, healthPickupPosition.parentID); //erase the current element (healthPickupPosition) m_ETriggerTouchVector.erase(it); @@ -58,7 +59,7 @@ bool PickupSpawnSystem::OnTriggerTouch(Events::TriggerTouch& e) //copy position, healthgain, respawntimer (twice since one of the values will be counted down to 0, the other will be set in the new object) //we need to copy all values since each value can be different for each healthPickup m_ETriggerTouchVector.push_back({ (glm::vec3)e.Trigger["Transform"]["Position"] ,e.Trigger["HealthPickup"]["HealthGain"], - e.Trigger["HealthPickup"]["RespawnTimer"],e.Trigger["HealthPickup"]["RespawnTimer"] }); + e.Trigger["HealthPickup"]["RespawnTimer"],e.Trigger["HealthPickup"]["RespawnTimer"], m_World->GetParent(e.Trigger.ID) }); //delete the healthpickup m_World->DeleteEntity(e.Trigger.ID); From f10958c26808d770a4becbf825e4e127c97f9762 Mon Sep 17 00:00:00 2001 From: stiffly Date: Thu, 25 Feb 2016 11:50:29 +0100 Subject: [PATCH 347/355] Capturepoint logic is now purely done on the serverside. --- src/Game/Systems/CapturePointSystem.cpp | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/Game/Systems/CapturePointSystem.cpp b/src/Game/Systems/CapturePointSystem.cpp index b45f6ced..c99a36a6 100644 --- a/src/Game/Systems/CapturePointSystem.cpp +++ b/src/Game/Systems/CapturePointSystem.cpp @@ -6,9 +6,11 @@ CapturePointSystem::CapturePointSystem(SystemParams params) , PureSystem("CapturePoint") { //subscribe/listenTo playerdamage,healthpickup events (using the eventBroker) - EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &CapturePointSystem::OnTriggerTouch); - EVENT_SUBSCRIBE_MEMBER(m_ETriggerLeave, &CapturePointSystem::OnTriggerLeave); - EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &CapturePointSystem::OnCaptured); + if (!IsClient) { + EVENT_SUBSCRIBE_MEMBER(m_ETriggerTouch, &CapturePointSystem::OnTriggerTouch); + EVENT_SUBSCRIBE_MEMBER(m_ETriggerLeave, &CapturePointSystem::OnTriggerLeave); + EVENT_SUBSCRIBE_MEMBER(m_ECaptured, &CapturePointSystem::OnCaptured); + } } @@ -16,6 +18,9 @@ CapturePointSystem::CapturePointSystem(SystemParams params) //NOTE: needs to run each frame, since we're possibly modifying the captureTimer for the capturePoints by dt void CapturePointSystem::UpdateComponent(EntityWrapper& capturePointEntity, ComponentWrapper& cCapturePoint, double dt) { + if (IsClient) { + return; + } if (m_WinnerWasFound) { return; } From 8ce6308649a93f69099e13c9f9dd6618f0300e8b Mon Sep 17 00:00:00 2001 From: stiffly Date: Thu, 25 Feb 2016 11:56:40 +0100 Subject: [PATCH 348/355] In snapshot: now sends player information and also CP information. Now it is no longer true that they will arrive in pre order. Appropriate actions were therefor implemented. --- include/Engine/Network/Client.h | 1 - src/Engine/Network/Client.cpp | 25 ++++------- src/Engine/Network/Server.cpp | 80 +++++++++++++++++---------------- 3 files changed, 50 insertions(+), 56 deletions(-) diff --git a/include/Engine/Network/Client.h b/include/Engine/Network/Client.h index d08b863a..7d23670a 100644 --- a/include/Engine/Network/Client.h +++ b/include/Engine/Network/Client.h @@ -103,7 +103,6 @@ public: void parseComponentDeletion(Packet& packet); void InterpolateFields(Packet & packet, const ComponentInfo & componentInfo, const EntityID & entityID, const std::string & componentType); void parseSnapshot(Packet& packet); - void UpdateLocalCapturePointHUD(EntityWrapper capturePointHUD); void identifyPacketLoss(); void hasServerTimedOut(); EntityID createPlayer(); diff --git a/src/Engine/Network/Client.cpp b/src/Engine/Network/Client.cpp index 903cd929..5fb5c487 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -348,9 +348,7 @@ void Client::parseSnapshot(Packet& packet) EntityWrapper localEntity(m_World, localEntityID); // Update entity if (m_World->HasComponent(localEntityID, componentType)) { - if (localEntity.Name() == "CapturePointHUD") { - UpdateLocalCapturePointHUD(localEntity); - } + SharedComponentWrapper newComponent = createSharedComponent(packet, localEntityID, componentInfo); bool shouldApply = true; // Apply potential filter function @@ -361,6 +359,7 @@ void Client::parseSnapshot(Packet& packet) ComponentWrapper currentComponent = m_World->GetComponent(localEntityID, componentType); memcpy(currentComponent.Data, newComponent.Data, componentInfo.Stride); } + //if (localEntity != m_LocalPlayer && !localEntity.IsChildOf(m_LocalPlayer)) { // updateFields(packet, componentInfo, localEntityID); //} else { @@ -377,7 +376,11 @@ void Client::parseSnapshot(Packet& packet) if (serverParentID == EntityID_Invalid) { newLocalEntityID = m_World->CreateEntity(EntityID_Invalid); } else { - newLocalEntityID = m_World->CreateEntity(m_ServerIDToClientID.at(serverParentID)); + if (serverClientMapsHasEntity(serverParentID)) { + newLocalEntityID = m_World->CreateEntity(m_ServerIDToClientID.at(serverParentID)); + } else { + newLocalEntityID = m_World->CreateEntity(EntityID_Invalid); + } } m_World->SetName(newLocalEntityID, serverEntityName); insertIntoServerClientMaps(serverEntityID, newLocalEntityID); @@ -387,7 +390,7 @@ void Client::parseSnapshot(Packet& packet) } // Parent logic // This should be enough beacause we know that the entities arives in pre-order (there will always be a parent) - if (serverParentID != EntityID_Invalid) { + if (serverParentID != EntityID_Invalid && serverClientMapsHasEntity(serverParentID)) { EntityID localEntityID = m_ServerIDToClientID.at(serverEntityID); m_World->SetParent(localEntityID, m_ServerIDToClientID.at(serverParentID)); } @@ -395,18 +398,6 @@ void Client::parseSnapshot(Packet& packet) parseSpawnEvents(); } - -void Client::UpdateLocalCapturePointHUD(EntityWrapper capturePointHUD) -{ - //auto children = m_World->GetChildren(capturePointHUD.ID); - //for (auto it = children.first; it != children.second; it++) { - // it->first - //} - // - //EntityWrapper& localHUD = m_LocalPlayer.FirstChildByName("HUD").FirstChildByName("CapturePointHUD"); - //m_World->GetComponentPools() -} - void Client::disconnect() { m_IsConnected = false; diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index 8783a7b0..aa7d71d5 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -65,7 +65,7 @@ void Server::Update() PlayerDefinition localArea; localArea.Endpoint = boost::asio::ip::udp::endpoint(); m_ServerlistRequest.Receive(packet, localArea); - if(packet.GetMessageType() == MessageType::ServerlistRequest) { + if (packet.GetMessageType() == MessageType::ServerlistRequest) { packet.ReadPrimitive(); // Pop size packet.ReadPrimitive(); // Pop MsgType packet.ReadPrimitive(); // Pop packet ID @@ -76,7 +76,7 @@ void Server::Update() } // Check if players have disconnected - for (int i = 0; i < m_PlayersToDisconnect.size(); i++) { + for (int i = 0; i < m_PlayersToDisconnect.size(); i++) { disconnect(m_PlayersToDisconnect.at(i)); } m_PlayersToDisconnect.clear(); @@ -136,7 +136,7 @@ void Server::parseMessageType(Packet& packet) parseOnPlayerDamage(packet); break; case MessageType::PlayerTransform: - parsePlayerTransform(packet); + parsePlayerTransform(packet); break; default: break; @@ -191,43 +191,41 @@ void Server::addPlayersToPacket(Packet & packet, EntityID entityID) // HACK: Only sync players for now, since the map turned out to be TOO LARGE to send in one snapshot and Simon's computer shits itself // HACK: Also checked CapturePointHUD for now. (this would get out of sync); EntityWrapper childEntity(m_World, childEntityID); - if (!shouldSendToClient(childEntity)) { - continue; - } - - // Write EntityID and parentsID and Entity name - packet.WritePrimitive(childEntityID); - packet.WritePrimitive(entityID); - packet.WriteString(m_World->GetName(childEntityID)); - // Write components to child - int numberOfComponents = 0; - for (auto& i : worldComponentPools) { - if (i.second->KnowsEntity(childEntityID)) { - numberOfComponents++; + if (shouldSendToClient(childEntity)) { + // Write EntityID and parentsID and Entity name + packet.WritePrimitive(childEntityID); + packet.WritePrimitive(entityID); + packet.WriteString(m_World->GetName(childEntityID)); + // Write components to child + int numberOfComponents = 0; + for (auto& i : worldComponentPools) { + if (i.second->KnowsEntity(childEntityID)) { + numberOfComponents++; + } } - } - // Write how many components should be read - packet.WritePrimitive(numberOfComponents); - for (auto& i : worldComponentPools) { - // If the entity exist in the pool - if (i.second->KnowsEntity(childEntityID)) { - ComponentWrapper componentWrapper = i.second->GetByEntity(childEntityID); - // ComponentType - packet.WriteString(componentWrapper.Info.Name); - // Loop through fields - for (auto& componentField : componentWrapper.Info.FieldsInOrder) { - ComponentInfo::Field_t fieldInfo = componentWrapper.Info.Fields.at(componentField); - if (fieldInfo.Type == "string") { - std::string& value = componentWrapper[componentField]; - packet.WriteString(value); - } else { - packet.WriteData(componentWrapper.Data + fieldInfo.Offset, fieldInfo.Stride); + // Write how many components should be read + packet.WritePrimitive(numberOfComponents); + for (auto& i : worldComponentPools) { + // If the entity exist in the pool + if (i.second->KnowsEntity(childEntityID)) { + ComponentWrapper componentWrapper = i.second->GetByEntity(childEntityID); + // ComponentType + packet.WriteString(componentWrapper.Info.Name); + // Loop through fields + for (auto& componentField : componentWrapper.Info.FieldsInOrder) { + ComponentInfo::Field_t fieldInfo = componentWrapper.Info.Fields.at(componentField); + if (fieldInfo.Type == "string") { + std::string& value = componentWrapper[componentField]; + packet.WriteString(value); + } else { + packet.WriteData(componentWrapper.Data + fieldInfo.Offset, fieldInfo.Stride); + } } } } } // Go to to your children - addChildrenToPacket(packet, childEntityID); + addPlayersToPacket(packet, childEntityID); } } @@ -343,7 +341,7 @@ void Server::parseTCPConnect(Packet & packet) // Read packet ID m_PreviousPacketID = m_PacketID; // Set previous packet id m_PacketID = packet.ReadPrimitive(); //Read new packet id - + LOG_INFO("Parsing connections"); // Check if player is already connected // Ska vara till lagd i TCPServer receive @@ -455,8 +453,7 @@ bool Server::OnInputCommand(const Events::InputCommand & e) } isReadingData = !isReadingData; m_SaveDataTimer = std::clock(); - } - else if (e.Command == "KickPlayer" && e.Value > 0) { + } else if (e.Command == "KickPlayer" && e.Value > 0) { kick(0); } @@ -595,8 +592,15 @@ void Server::parsePlayerTransform(Packet& packet) bool Server::shouldSendToClient(EntityWrapper childEntity) { + auto children = m_World->GetChildren(childEntity.ID); + for (auto it = children.first; it != children.second; it++) { + EntityWrapper child(m_World, it->second); + if(child.HasComponent("CapturePoint")) { + return true; + } + } return childEntity.HasComponent("Player") || childEntity.FirstParentWithComponent("Player").Valid() - || childEntity.HasComponent("CapturePoint") || childEntity.FirstParentWithComponent("CapturePoint").Valid(); + || childEntity.HasComponent("CapturePoint"); } PlayerID Server::GetPlayerIDFromEndpoint() From 508d8a6f008e3323da73c03035ab4c9b7df5e996 Mon Sep 17 00:00:00 2001 From: Jocke Date: Thu, 25 Feb 2016 14:24:38 +0100 Subject: [PATCH 349/355] Fixed memory leak in TCPServer::AcceptNewConnections caused by acceptor->async_accept(). Fixed some formating and comments. --- include/Engine/Network/TCPServer.h | 5 ++-- src/Engine/Network/Client.cpp | 24 +++++++++------- src/Engine/Network/Server.cpp | 4 +-- src/Engine/Network/TCPServer.cpp | 45 +++++++++++++----------------- 4 files changed, 37 insertions(+), 41 deletions(-) diff --git a/include/Engine/Network/TCPServer.h b/include/Engine/Network/TCPServer.h index 9cc7646a..61184470 100644 --- a/include/Engine/Network/TCPServer.h +++ b/include/Engine/Network/TCPServer.h @@ -22,10 +22,9 @@ private: std::unique_ptr acceptor; boost::shared_ptr lastReceivedSocket; - void handle_accept(boost::shared_ptr socket, - int& nextPlayerID, std::map& connectedPlayers, - const boost::system::error_code& error); int readBuffer(char* data, PlayerDefinition& playerDefinition); + PlayerID getPlayerIDFromEndpoint(const std::map& connectedPlayers, + boost::asio::ip::address address, unsigned short port); }; #endif \ No newline at end of file diff --git a/src/Engine/Network/Client.cpp b/src/Engine/Network/Client.cpp index ad72571c..c11f86f5 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -1,7 +1,7 @@ #include "Network/Client.h" using namespace boost::asio::ip; -Client::Client(World* world, EventBroker* eventBroker) +Client::Client(World* world, EventBroker* eventBroker) : Network(world, eventBroker) { // Asumes root node is EntityID_Invalid @@ -194,12 +194,12 @@ void Client::parseSpawnEvents() } e.Player = EntityWrapper(m_World, m_ServerIDToClientID.at(m_PlayerSpawnEvents.at(i).Player.ID)); //e.Spawner = EntityWrapper(m_World, m_ServerIDToClientID.at(m_PlayerSpawnEvents.at(i).Spawner.ID)); - e.PlayerID = -1; + e.PlayerID = -1; e.PlayerName = m_PlayerSpawnEvents.at(i).PlayerName; m_EventBroker->Publish(e); } m_PlayerSpawnEvents = tempSpawn; - // m_PlayerSpawnEvents.clear(); + // m_PlayerSpawnEvents.clear(); } void Client::parsePlayersSpawned(Packet& packet) @@ -243,14 +243,14 @@ void Client::parseComponentDeletion(Packet & packet) } void Client::parseDoubleJump(Packet & packet) -{ +{ EntityID serverID = packet.ReadPrimitive(); if (!serverClientMapsHasEntity(serverID)) { return; } Events::DoubleJump e; e.entityID = m_ServerIDToClientID.at(serverID); - // If player is local player to publish to prevent infinite feedback loop + // If player is local player do not publish to prevent infinite feedback loop if (e.entityID != m_LocalPlayer.ID) { m_EventBroker->Publish(e); } @@ -330,9 +330,10 @@ void Client::parseSnapshot(Packet& packet) if (serverClientMapsHasEntity(serverEntityID)) { EntityID localEntityID = m_ServerIDToClientID.at(serverEntityID); EntityWrapper localEntity(m_World, localEntityID); - + // Update entity if (m_World->HasComponent(localEntityID, componentType)) { + // TODO Fix memory leak here SharedComponentWrapper newComponent = createSharedComponent(packet, localEntityID, componentInfo); bool shouldApply = true; // Apply potential filter function @@ -343,6 +344,7 @@ void Client::parseSnapshot(Packet& packet) ComponentWrapper currentComponent = m_World->GetComponent(localEntityID, componentType); memcpy(currentComponent.Data, newComponent.Data, componentInfo.Stride); } + //if (localEntity != m_LocalPlayer && !localEntity.IsChildOf(m_LocalPlayer)) { // updateFields(packet, componentInfo, localEntityID); //} else { @@ -371,7 +373,9 @@ void Client::parseSnapshot(Packet& packet) // This should be enough beacause we know that the entities arives in pre-order (there will always be a parent) if (serverParentID != EntityID_Invalid) { EntityID localEntityID = m_ServerIDToClientID.at(serverEntityID); - m_World->SetParent(localEntityID, m_ServerIDToClientID.at(serverParentID)); + if (m_World->GetParent(localEntityID) != m_ServerIDToClientID.at(serverParentID)) { + m_World->SetParent(localEntityID, m_ServerIDToClientID.at(serverParentID)); + } } } parseSpawnEvents(); @@ -461,7 +465,7 @@ void Client::parsePlayerDamage(Packet& packet) Events::PlayerDamage e; PlayerID victimID = packet.ReadPrimitive(); PlayerID inflictorID = packet.ReadPrimitive(); - if(!serverClientMapsHasEntity(victimID) || !serverClientMapsHasEntity(inflictorID)){ + if (!serverClientMapsHasEntity(victimID) || !serverClientMapsHasEntity(inflictorID)) { return; } e.Inflictor = EntityWrapper(m_World, m_ServerIDToClientID.at(victimID)); @@ -501,7 +505,7 @@ void Client::sendLocalPlayerTransform() packet.WritePrimitive(orientation.x); packet.WritePrimitive(orientation.y); packet.WritePrimitive(orientation.z); - + bool hasAssaultWeapon = m_LocalPlayer.HasComponent("AssaultWeapon"); packet.WritePrimitive(hasAssaultWeapon); if (hasAssaultWeapon) { @@ -509,7 +513,7 @@ void Client::sendLocalPlayerTransform() packet.WritePrimitive((int)cAssaultWeapon["MagazineAmmo"]); packet.WritePrimitive((int)cAssaultWeapon["Ammo"]); } - + m_Unreliable.Send(packet); } diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index 1a063067..547e1641 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -28,9 +28,8 @@ Server::~Server() void Server::Update() { - PlayerDefinition pd; - m_Reliable.AcceptNewConnections(m_NextPlayerID, m_ConnectedPlayers); + for (auto& kv : m_ConnectedPlayers) { while (kv.second.TCPSocket->available()) { // Packet will get real data in receive @@ -46,6 +45,7 @@ void Server::Update() } } + PlayerDefinition pd; while (m_Unreliable.IsSocketAvailable()) { // Packet will get real data in receive Packet packet(MessageType::Invalid); diff --git a/src/Engine/Network/TCPServer.cpp b/src/Engine/Network/TCPServer.cpp index a449e684..6fdc28ce 100644 --- a/src/Engine/Network/TCPServer.cpp +++ b/src/Engine/Network/TCPServer.cpp @@ -4,22 +4,33 @@ using namespace boost::asio::ip; TCPServer::TCPServer() { acceptor = std::unique_ptr(new tcp::acceptor(m_IOService, tcp::endpoint(tcp::v4(), 27666))); + // Make the acceptor non-blocking so we wont get stuck in AcceptNewConnections(). + acceptor->non_blocking(true); } TCPServer::~TCPServer() -{ -} +{ } void TCPServer::AcceptNewConnections(int& nextPlayerID, std::map& connectedPlayers) { + boost::system::error_code error; boost::shared_ptr newSocket = boost::shared_ptr(new tcp::socket(m_IOService)); - m_IOService.poll(); - acceptor->async_accept(*newSocket, - boost::bind(&TCPServer::handle_accept, this, newSocket, boost::ref(nextPlayerID), boost::ref(connectedPlayers), - boost::asio::placeholders::error)); + acceptor->accept(*newSocket, error); + // If no error occured add new tcp connection + if (!error) { + // Add tcp socket to connections + boost::asio::ip::tcp::no_delay option(true); + newSocket->set_option(option); + PlayerDefinition pd; + pd.StopTime = std::clock(); + pd.TCPSocket = newSocket; + pd.TCPAddress = newSocket.get()->remote_endpoint().address(); + pd.TCPPort = newSocket.get()->remote_endpoint().port(); + connectedPlayers[nextPlayerID++] = pd; + } } -PlayerID GetPlayerIDFromEndpoint(const std::map& connectedPlayers, +PlayerID TCPServer::getPlayerIDFromEndpoint(const std::map& connectedPlayers, boost::asio::ip::address address, unsigned short port) { for (auto& kv : connectedPlayers) { @@ -31,24 +42,6 @@ PlayerID GetPlayerIDFromEndpoint(const std::map& con return -1; } -void TCPServer::handle_accept(boost::shared_ptr socket, - int& nextPlayerID, std::map& connectedPlayers, - const boost::system::error_code& error) -{ - if (!error && GetPlayerIDFromEndpoint(connectedPlayers, socket->remote_endpoint().address(), - socket->remote_endpoint().port()) == -1) { - // Add tcp socket to connections - boost::asio::ip::tcp::no_delay option(true); - socket->set_option(option); - PlayerDefinition pd; - pd.StopTime = std::clock(); - pd.TCPSocket = socket; - pd.TCPAddress = socket.get()->remote_endpoint().address(); - pd.TCPPort = socket.get()->remote_endpoint().port(); - connectedPlayers[nextPlayerID++] = pd; - } -} - void TCPServer::Send(Packet & packet, PlayerDefinition & playerDefinition) { try { @@ -73,7 +66,7 @@ void TCPServer::Send(Packet & packet) } void TCPServer::Disconnect() -{ +{ } From 059fe5c6c0b76e973d1f7c9f0db55b5d09a9f970 Mon Sep 17 00:00:00 2001 From: Jocke Date: Thu, 25 Feb 2016 16:04:27 +0100 Subject: [PATCH 350/355] Fixed typo m_EPDoubleJump to m_EDoubleJump. --- include/Engine/Network/Client.h | 2 +- include/Game/Systems/PlayerMovementSystem.h | 2 +- src/Engine/Network/Client.cpp | 2 +- src/Game/Systems/PlayerMovementSystem.cpp | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/include/Engine/Network/Client.h b/include/Engine/Network/Client.h index 10a78bfd..a983a685 100644 --- a/include/Engine/Network/Client.h +++ b/include/Engine/Network/Client.h @@ -131,7 +131,7 @@ private: EventRelay m_EPlayerSpawned; bool OnPlayerSpawned(const Events::PlayerSpawned& e); EventRelay< Client, Events::SearchForServers> m_ESearchForServers; - EventRelay m_EPDoubleJump; + EventRelay m_EDoubleJump; bool OnDoubleJump(Events::DoubleJump & e); bool OnSearchForServers(const Events::SearchForServers& e); UDPClient m_ServerlistRequest; diff --git a/include/Game/Systems/PlayerMovementSystem.h b/include/Game/Systems/PlayerMovementSystem.h index 43b0c4e3..92aa1915 100644 --- a/include/Game/Systems/PlayerMovementSystem.h +++ b/include/Game/Systems/PlayerMovementSystem.h @@ -39,7 +39,7 @@ private: EventRelay m_EPlayerSpawned; bool OnPlayerSpawned(Events::PlayerSpawned& e); - EventRelay m_EPDoubleJump; + EventRelay m_EDoubleJump; bool PlayerMovementSystem::OnDoubleJump(Events::DoubleJump & e); void updateMovementControllers(double dt); diff --git a/src/Engine/Network/Client.cpp b/src/Engine/Network/Client.cpp index dbd21d60..6ffce751 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -32,7 +32,7 @@ void Client::Connect(std::string address, int port) EVENT_SUBSCRIBE_MEMBER(m_EInputCommand, &Client::OnInputCommand); EVENT_SUBSCRIBE_MEMBER(m_EPlayerDamage, &Client::OnPlayerDamage); EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &Client::OnPlayerSpawned); - EVENT_SUBSCRIBE_MEMBER(m_EPDoubleJump, &Client::OnDoubleJump); + EVENT_SUBSCRIBE_MEMBER(m_EDoubleJump, &Client::OnDoubleJump); EVENT_SUBSCRIBE_MEMBER(m_ESearchForServers, &Client::OnSearchForServers); auto config = ResourceManager::Load("Config.ini"); m_Address = address; diff --git a/src/Game/Systems/PlayerMovementSystem.cpp b/src/Game/Systems/PlayerMovementSystem.cpp index b69e8380..2e2502ec 100644 --- a/src/Game/Systems/PlayerMovementSystem.cpp +++ b/src/Game/Systems/PlayerMovementSystem.cpp @@ -4,7 +4,7 @@ PlayerMovementSystem::PlayerMovementSystem(SystemParams params) : System(params) { EVENT_SUBSCRIBE_MEMBER(m_EPlayerSpawned, &PlayerMovementSystem::OnPlayerSpawned); - EVENT_SUBSCRIBE_MEMBER(m_EPDoubleJump, &PlayerMovementSystem::OnDoubleJump); + EVENT_SUBSCRIBE_MEMBER(m_EDoubleJump, &PlayerMovementSystem::OnDoubleJump); } PlayerMovementSystem::~PlayerMovementSystem() From 89d0d5753f8745b58ef561f5aa76e239550075fd Mon Sep 17 00:00:00 2001 From: William Moberg Date: Thu, 25 Feb 2016 16:16:24 +0100 Subject: [PATCH 351/355] Fix for player teleporting to (0,0,0). Saves player previous position in CollisionSystem instead of Physics component so it won't be saved when editing Players. --- include/Engine/Collision/CollisionSystem.h | 1 + resources/Schema/Components/Physics.xml | 1 - resources/Schema/Components/Physics.xsd | 1 - resources/Schema/Entities/Player.xml | 1 - resources/Schema/Entities/PlayerRed.xml | 1 - src/Engine/Collision/CollisionSystem.cpp | 88 +++++++++++----------- 6 files changed, 46 insertions(+), 47 deletions(-) diff --git a/include/Engine/Collision/CollisionSystem.h b/include/Engine/Collision/CollisionSystem.h index 9cd2fe63..19adea35 100644 --- a/include/Engine/Collision/CollisionSystem.h +++ b/include/Engine/Collision/CollisionSystem.h @@ -24,6 +24,7 @@ public: private: Octree* m_Octree; std::vector m_OctreeResult; + std::unordered_map m_PrevPositions; }; #endif \ No newline at end of file diff --git a/resources/Schema/Components/Physics.xml b/resources/Schema/Components/Physics.xml index 84b6aba3..6cb73c75 100644 --- a/resources/Schema/Components/Physics.xml +++ b/resources/Schema/Components/Physics.xml @@ -2,7 +2,6 @@ true - false 0.33 diff --git a/resources/Schema/Components/Physics.xsd b/resources/Schema/Components/Physics.xsd index 206e2a23..7fed1fb5 100644 --- a/resources/Schema/Components/Physics.xsd +++ b/resources/Schema/Components/Physics.xsd @@ -13,7 +13,6 @@ m/s^2 - The largest height of a "stair-step" that can be walked over diff --git a/resources/Schema/Entities/Player.xml b/resources/Schema/Entities/Player.xml index 7a5d2eb4..4f012955 100644 --- a/resources/Schema/Entities/Player.xml +++ b/resources/Schema/Entities/Player.xml @@ -13,7 +13,6 @@ - diff --git a/resources/Schema/Entities/PlayerRed.xml b/resources/Schema/Entities/PlayerRed.xml index cd01632e..d56fa3c1 100644 --- a/resources/Schema/Entities/PlayerRed.xml +++ b/resources/Schema/Entities/PlayerRed.xml @@ -13,7 +13,6 @@ - diff --git a/src/Engine/Collision/CollisionSystem.cpp b/src/Engine/Collision/CollisionSystem.cpp index fcc3665f..9689bf13 100644 --- a/src/Engine/Collision/CollisionSystem.cpp +++ b/src/Engine/Collision/CollisionSystem.cpp @@ -16,51 +16,51 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c EntityAABB& boxA = *boundingBox; bool everHitTheGround = false; - glm::vec3 size = boxA.Size(); - float diameter = std::min(size.x, size.z); - glm::vec3 prevOrigin = (glm::vec3)cPhysics["PrevOrigin"]; - glm::vec3 toCurrentPos = boxA.Origin() - prevOrigin; - float rayLength = glm::length(toCurrentPos) + 0.5f*diameter; - //If the entity has moved farther than the size of its box, we need to handle it specially. - bool traceCollision = rayLength > diameter; - //hack solution: If prevOrigin is less than -9000 in all dimensions, - //then it means it is not set, i.e. this is the first collision check for the entity. - if (traceCollision && glm::any(glm::greaterThan((glm::vec3)cPhysics["PrevOrigin"], glm::vec3(-9000.f)))) { - Ray ray(prevOrigin, toCurrentPos); - m_OctreeResult.clear(); - m_Octree->ObjectsPossiblyHitByRay(ray, m_OctreeResult); - for (auto& boxB : m_OctreeResult) { - if (boxA.Entity == boxB.Entity) { - continue; - } - bool hit; - float dist; - if (boxB.Entity.HasComponent("Model")) { - RawModel* model; - std::string res = (std::string)boxB.Entity["Model"]["Resource"]; - try { - model = ResourceManager::Load(res); - } catch (const std::exception&) { + auto prevPosIt = m_PrevPositions.find(entity); + if (prevPosIt != m_PrevPositions.end()) { + glm::vec3 size = boxA.Size(); + float diameter = std::min(size.x, size.z); + glm::vec3 prevOrigin = prevPosIt->second; + glm::vec3 toCurrentPos = boxA.Origin() - prevOrigin; + float rayLength = glm::length(toCurrentPos) + 0.5f*diameter; + //If the entity has moved farther than the size of its box, we need to handle it specially. + if (rayLength > diameter) { + Ray ray(prevOrigin, toCurrentPos); + m_OctreeResult.clear(); + m_Octree->ObjectsPossiblyHitByRay(ray, m_OctreeResult); + for (auto& boxB : m_OctreeResult) { + if (boxA.Entity == boxB.Entity) { continue; } - float u, v; - hit = Collision::RayVsModel(ray, model->Vertices(), model->m_Indices, Transform::ModelMatrix(boxB.Entity), dist, u, v); - } else { - hit = Collision::RayVsAABB(ray, boxB, dist); - } - if (hit && dist < rayLength) { - //Set the entity to where it was colliding, minus the maximum box size. - //TODO: Perhaps this should be done slightly more properly. - glm::vec3 newOriginPos = ray.Origin() + (dist - 0.707107f*diameter) * ray.Direction(); - glm::vec3 resolve = newOriginPos - boxA.Origin(); - (glm::vec3&)cTransform["Position"] += resolve; - boxA = *Collision::EntityAbsoluteAABB(entity); - if (resolve.y > 0) { - everHitTheGround = true; - (bool)cPhysics["IsOnGround"] = true; - ((glm::vec3&)cPhysics["Velocity"]).y = 0.f; + bool hit; + float dist; + if (boxB.Entity.HasComponent("Model")) { + RawModel* model; + std::string res = (std::string)boxB.Entity["Model"]["Resource"]; + try { + model = ResourceManager::Load(res); + } catch (const std::exception&) { + continue; + } + float u, v; + hit = Collision::RayVsModel(ray, model->Vertices(), model->m_Indices, Transform::ModelMatrix(boxB.Entity), dist, u, v); + } else { + hit = Collision::RayVsAABB(ray, boxB, dist); + } + if (hit && dist < rayLength) { + //Set the entity to where it was colliding, minus the maximum box size. + //TODO: Perhaps this should be done slightly more properly. + glm::vec3 newOriginPos = ray.Origin() + (dist - 0.707107f*diameter) * ray.Direction(); + glm::vec3 resolve = newOriginPos - boxA.Origin(); + (glm::vec3&)cTransform["Position"] += resolve; + boxA = *Collision::EntityAbsoluteAABB(entity); + if (resolve.y > 0) { + everHitTheGround = true; + (bool)cPhysics["IsOnGround"] = true; + ((glm::vec3&)cPhysics["Velocity"]).y = 0.f; + } + break; } - break; } } } @@ -90,6 +90,7 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c float verticalStepHeight = (float)(double)cPhysics["VerticalStepHeight"]; if (Collision::AABBvsTriangles(boxA, model->Vertices(), model->m_Indices, modelMatrix, inOutVelocity, verticalStepHeight, isOnGround, resolutionVector)) { (glm::vec3&)cTransform["Position"] += resolutionVector; + boxA = *Collision::EntityAbsoluteAABB(entity); cPhysics["Velocity"] = inOutVelocity; if (isOnGround) { everHitTheGround = true; @@ -99,6 +100,7 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c } else if (Collision::AABBVsAABB(boxA, boxB, resolutionVector)) { //Enter here if boxB has no Model. (glm::vec3&)cTransform["Position"] += resolutionVector; + boxA = *Collision::EntityAbsoluteAABB(entity); if (resolutionVector.y > 0) { everHitTheGround = true; (bool)cPhysics["IsOnGround"] = true; @@ -112,5 +114,5 @@ void CollisionSystem::UpdateComponent(EntityWrapper& entity, ComponentWrapper& c (bool)cPhysics["IsOnGround"] = false; } - (glm::vec3&)cPhysics["PrevOrigin"] = boxA.Origin(); + m_PrevPositions[entity] = boxA.Origin(); } From 9e6c67596d0d3c43e4d628c35a2ff9a6f14f985d Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Thu, 25 Feb 2016 17:51:28 +0100 Subject: [PATCH 352/355] Basic editor copy and paste. Doesn't actually copy the entity until you paste it. --- include/Engine/Core/EntityWrapper.h | 2 ++ include/Engine/Core/World.h | 2 +- include/Engine/Editor/EditorGUI.h | 8 ++++++ include/Engine/Editor/EditorSystem.h | 1 + src/Engine/Core/EntityWrapper.cpp | 37 +++++++++++++++++++++++++++- src/Engine/Core/World.cpp | 2 +- src/Engine/Editor/EditorGUI.cpp | 13 ++++++++++ src/Engine/Editor/EditorSystem.cpp | 6 +++++ src/Engine/Network/Server.cpp | 4 +-- src/Game/Systems/SpawnerSystem.cpp | 2 +- 10 files changed, 71 insertions(+), 6 deletions(-) diff --git a/include/Engine/Core/EntityWrapper.h b/include/Engine/Core/EntityWrapper.h index b0e65d9e..4643e28b 100644 --- a/include/Engine/Core/EntityWrapper.h +++ b/include/Engine/Core/EntityWrapper.h @@ -29,6 +29,7 @@ struct EntityWrapper EntityWrapper Parent(); EntityWrapper FirstChildByName(const std::string& name); EntityWrapper FirstParentWithComponent(const std::string& componentType); + EntityWrapper Clone(EntityWrapper parent = EntityWrapper::Invalid); bool IsChildOf(EntityWrapper potentialParent); bool Valid() const; @@ -39,6 +40,7 @@ struct EntityWrapper private: EntityWrapper firstChildByNameRecursive(const std::string& name, EntityID parent); + EntityWrapper cloneRecursive(EntityWrapper entity, EntityWrapper parent); }; namespace std diff --git a/include/Engine/Core/World.h b/include/Engine/Core/World.h index 1604df37..c9f738ce 100644 --- a/include/Engine/Core/World.h +++ b/include/Engine/Core/World.h @@ -40,7 +40,7 @@ public: // Change the parent of an entity void SetParent(EntityID entity, EntityID parent); // Get children of an entity - const std::pair::const_iterator, std::unordered_multimap::const_iterator> GetChildren(EntityID entity); + const std::pair::const_iterator, std::unordered_multimap::const_iterator> GetDirectChildren(EntityID entity); // Get all component pools const std::unordered_map& GetComponentPools() const { return m_ComponentPools; } // Get the entity children map diff --git a/include/Engine/Editor/EditorGUI.h b/include/Engine/Editor/EditorGUI.h index 7a0289c6..57574e66 100644 --- a/include/Engine/Editor/EditorGUI.h +++ b/include/Engine/Editor/EditorGUI.h @@ -73,6 +73,12 @@ public: // Called when the user means to rename an entity. typedef std::function OnEntityChangeName_t; void SetEntityChangeNameCallback(OnEntityChangeName_t f) { m_OnEntityChangeName = f; } + // Called when the user pastes an entity previously "copied" + // @param EntityWrapper The entity to copy + // @param EntityWrapper The entity to parent the new copy to + // @return The new copy of the entity + typedef std::function OnEntityPaste_t; + void SetEntityPasteCallback(OnEntityPaste_t f) { m_OnEntityPaste = f; } // Called when the user means to attach a new component to an entity. typedef std::function OnComponentAttach_t; void SetComponentAttachCallback(OnComponentAttach_t f) { m_OnComponentAttach = f; } @@ -111,6 +117,7 @@ private: std::string m_DroppedFile = ""; bool m_Paused = false; bool m_MouseLocked = false; + EntityWrapper m_CopyTarget = EntityWrapper::Invalid; // Callbacks OnEntitySelectedCallback_t m_OnEntitySelected = nullptr; @@ -124,6 +131,7 @@ private: OnComponentDelete_t m_OnComponentDelete = nullptr; OnWidgetMode_t m_OnWidgetMode = nullptr; OnWidgetSpace_t m_OnWidgetSpace = nullptr; + OnEntityPaste_t m_OnEntityPaste = nullptr; // Events EventRelay m_EKeyDown; diff --git a/include/Engine/Editor/EditorSystem.h b/include/Engine/Editor/EditorSystem.h index fcaa2e47..06ee53b6 100644 --- a/include/Engine/Editor/EditorSystem.h +++ b/include/Engine/Editor/EditorSystem.h @@ -56,6 +56,7 @@ private: void OnEntityDelete(EntityWrapper entity); void OnEntityChangeParent(EntityWrapper entity, EntityWrapper parent); void OnEntityChangeName(EntityWrapper entity, const std::string& name); + EntityWrapper OnEntityPaste(EntityWrapper entityToCopy, EntityWrapper parent); void OnComponentAttach(EntityWrapper entity, const std::string& componentType); void OnComponentDelete(EntityWrapper entity, const std::string& componentType); void OnWidgetSpace(EditorGUI::WidgetSpace widgetSpace); diff --git a/src/Engine/Core/EntityWrapper.cpp b/src/Engine/Core/EntityWrapper.cpp index 4b45b8d0..ace1f4a7 100644 --- a/src/Engine/Core/EntityWrapper.cpp +++ b/src/Engine/Core/EntityWrapper.cpp @@ -51,6 +51,17 @@ EntityWrapper EntityWrapper::FirstParentWithComponent(const std::string& compone return EntityWrapper::Invalid; } +EntityWrapper EntityWrapper::Clone(EntityWrapper parent /*= Invalid*/) +{ + if (!Valid()) { + return EntityWrapper::Invalid; + } + + EntityWrapper clone = cloneRecursive(*this, EntityWrapper::Invalid); + this->World->SetParent(clone.ID, parent.ID); + return clone; +} + bool EntityWrapper::IsChildOf(EntityWrapper potentialParent) { EntityWrapper entity = *this; @@ -111,7 +122,7 @@ EntityWrapper EntityWrapper::firstChildByNameRecursive(const std::string& name, return EntityWrapper::Invalid; } - auto itPair = this->World->GetChildren(parent); + auto itPair = this->World->GetDirectChildren(parent); if (itPair.first == itPair.second) { return EntityWrapper::Invalid; } @@ -131,3 +142,27 @@ EntityWrapper EntityWrapper::firstChildByNameRecursive(const std::string& name, return EntityWrapper::Invalid; } +EntityWrapper EntityWrapper::cloneRecursive(EntityWrapper entity, EntityWrapper parent) +{ + EntityWrapper clone = EntityWrapper(entity.World, entity.World->CreateEntity(parent.ID)); + entity.World->SetName(clone.ID, entity.Name()); + + // Clone components + for (auto& kv : entity.World->GetComponentPools()) { + if (kv.second->KnowsEntity(entity.ID)) { + ComponentWrapper c1 = kv.second->GetByEntity(entity.ID); + ComponentWrapper c2 = entity.World->AttachComponent(clone.ID, kv.first); + c1.Copy(c2); + } + } + + // Clone children + auto children = entity.World->GetDirectChildren(entity.ID); + for (auto it = children.first; it != children.second; ++it) { + EntityWrapper child(entity.World, it->second); + cloneRecursive(child, clone); + } + + return clone; +} + diff --git a/src/Engine/Core/World.cpp b/src/Engine/Core/World.cpp index 8788a92e..9b323ff4 100644 --- a/src/Engine/Core/World.cpp +++ b/src/Engine/Core/World.cpp @@ -127,7 +127,7 @@ void World::SetParent(EntityID entity, EntityID parent) m_EntityChildren.insert(std::make_pair(parent, entity)); } -const std::pair::const_iterator, std::unordered_multimap::const_iterator> World::GetChildren(EntityID entity) +const std::pair::const_iterator, std::unordered_multimap::const_iterator> World::GetDirectChildren(EntityID entity) { return m_EntityChildren.equal_range(entity); } diff --git a/src/Engine/Editor/EditorGUI.cpp b/src/Engine/Editor/EditorGUI.cpp index 70775a2b..f2690f13 100644 --- a/src/Engine/Editor/EditorGUI.cpp +++ b/src/Engine/Editor/EditorGUI.cpp @@ -598,6 +598,19 @@ bool EditorGUI::OnKeyDown(const Events::KeyDown& e) entityImport(m_World); } + if (e.ModCtrl && e.KeyCode == GLFW_KEY_C) { + m_CopyTarget = m_CurrentSelection; + } + + if (e.ModCtrl && e.KeyCode == GLFW_KEY_V) { + if (m_OnEntityPaste != nullptr) { + EntityWrapper copy = m_OnEntityPaste(m_CopyTarget, m_CurrentSelection); + if (copy != EntityWrapper::Invalid) { + SelectEntity(copy); + } + } + } + if (e.KeyCode == GLFW_KEY_DELETE) { if (m_CurrentSelection.Valid()) { entityDelete(m_CurrentSelection); diff --git a/src/Engine/Editor/EditorSystem.cpp b/src/Engine/Editor/EditorSystem.cpp index 97ea9d53..4bee1427 100644 --- a/src/Engine/Editor/EditorSystem.cpp +++ b/src/Engine/Editor/EditorSystem.cpp @@ -28,6 +28,7 @@ EditorSystem::EditorSystem(SystemParams params, IRenderer* renderer, RenderFrame m_EditorGUI->SetEntityDeleteCallback(std::bind(&EditorSystem::OnEntityDelete, this, std::placeholders::_1)); m_EditorGUI->SetEntityChangeParentCallback(std::bind(&EditorSystem::OnEntityChangeParent, this, std::placeholders::_1, std::placeholders::_2)); m_EditorGUI->SetEntityChangeNameCallback(std::bind(&EditorSystem::OnEntityChangeName, this, std::placeholders::_1, std::placeholders::_2)); + m_EditorGUI->SetEntityPasteCallback(std::bind(&EditorSystem::OnEntityPaste, this, std::placeholders::_1, std::placeholders::_2)); m_EditorGUI->SetComponentAttachCallback(std::bind(&EditorSystem::OnComponentAttach, this, std::placeholders::_1, std::placeholders::_2)); m_EditorGUI->SetComponentDeleteCallback(std::bind(&EditorSystem::OnComponentDelete, this, std::placeholders::_1, std::placeholders::_2)); m_EditorGUI->SetWidgetModeCallback(std::bind(&EditorSystem::setWidgetMode, this, std::placeholders::_1)); @@ -160,6 +161,11 @@ void EditorSystem::OnEntityChangeName(EntityWrapper entity, const std::string& n } } +EntityWrapper EditorSystem::OnEntityPaste(EntityWrapper entityToCopy, EntityWrapper parent) +{ + return entityToCopy.Clone(parent); +} + void EditorSystem::OnComponentAttach(EntityWrapper entity, const std::string& componentType) { if (entity.Valid()) { diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index 8783a7b0..d4c82884 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -183,7 +183,7 @@ void Server::addInputCommandsToPacket(Packet& packet) void Server::addPlayersToPacket(Packet & packet, EntityID entityID) { - auto itPair = m_World->GetChildren(entityID); + auto itPair = m_World->GetDirectChildren(entityID); std::unordered_map worldComponentPools = m_World->GetComponentPools(); // Loop through every child for (auto it = itPair.first; it != itPair.second; it++) { @@ -233,7 +233,7 @@ void Server::addPlayersToPacket(Packet & packet, EntityID entityID) void Server::addChildrenToPacket(Packet & packet, EntityID entityID) { - auto itPair = m_World->GetChildren(entityID); + auto itPair = m_World->GetDirectChildren(entityID); std::unordered_map worldComponentPools = m_World->GetComponentPools(); // Loop through every child for (auto it = itPair.first; it != itPair.second; it++) { diff --git a/src/Game/Systems/SpawnerSystem.cpp b/src/Game/Systems/SpawnerSystem.cpp index 90f677fe..6500460f 100644 --- a/src/Game/Systems/SpawnerSystem.cpp +++ b/src/Game/Systems/SpawnerSystem.cpp @@ -36,7 +36,7 @@ EntityWrapper SpawnerSystem::Spawn(EntityWrapper spawner, EntityWrapper parent / } // Find any SpawnPoints existing as children of spawner - auto children = spawner.World->GetChildren(spawner.ID); + auto children = spawner.World->GetDirectChildren(spawner.ID); std::vector spawnPoints; for (auto kv = children.first; kv != children.second; ++kv) { const EntityID& child = kv->second; From 034368367807a51bcdcf8417f6df11cab321bdf4 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Thu, 25 Feb 2016 17:51:40 +0100 Subject: [PATCH 353/355] Fixed cubemaps being generated over and over again each frame. --- src/Engine/Rendering/CubeMapPass.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Engine/Rendering/CubeMapPass.cpp b/src/Engine/Rendering/CubeMapPass.cpp index 75f5e1c9..e2a55b74 100644 --- a/src/Engine/Rendering/CubeMapPass.cpp +++ b/src/Engine/Rendering/CubeMapPass.cpp @@ -17,6 +17,7 @@ void CubeMapPass::LoadTextures(std::string input) m_CubeMapTextures.push_back(img); } GenerateCubeMapTexture(); + m_PreviusCubeMapTexture = input; } } From 18450ff4f37e5b296bb6e813a3717d744272a6d9 Mon Sep 17 00:00:00 2001 From: Jocke Date: Fri, 26 Feb 2016 11:08:05 +0100 Subject: [PATCH 354/355] Death explosion should always get triggered now. (I hope) --- include/Engine/Network/Client.h | 1 + src/Engine/Network/Client.cpp | 10 ++++++++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/include/Engine/Network/Client.h b/include/Engine/Network/Client.h index 968c4bba..be76e265 100644 --- a/include/Engine/Network/Client.h +++ b/include/Engine/Network/Client.h @@ -19,6 +19,7 @@ #include "Core/World.h" #include "Core/EventBroker.h" #include "Core/ConfigFile.h" +#include "Core/EPlayerDeath.h" #include "Input/EInputCommand.h" #include "Core/EPlayerDamage.h" #include "../Game/Events/EDoubleJump.h" diff --git a/src/Engine/Network/Client.cpp b/src/Engine/Network/Client.cpp index d94ccbc6..d8da7e16 100644 --- a/src/Engine/Network/Client.cpp +++ b/src/Engine/Network/Client.cpp @@ -261,8 +261,14 @@ void Client::parseEntityDeletion(Packet & packet) if (m_ServerIDToClientID.find(entityToDelete) != m_ServerIDToClientID.end()) { EntityID localEntity = m_ServerIDToClientID.at(entityToDelete); if (m_World->ValidEntity(localEntity)) { - m_World->DeleteEntity(localEntity); - deleteFromServerClientMaps(entityToDelete, localEntity); + if (m_World->HasComponent(localEntity,"Player")) { + Events::PlayerDeath e; + e.Player = EntityWrapper(m_World, localEntity); + m_EventBroker->Publish(e); + } else { + m_World->DeleteEntity(localEntity); + deleteFromServerClientMaps(entityToDelete, localEntity); + } } } } From 0c60b637c30908893012b37f5be14b7269f3bbb9 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Fri, 26 Feb 2016 12:52:10 +0100 Subject: [PATCH 355/355] Who's merging without compiling? --- src/Engine/Network/Server.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Engine/Network/Server.cpp b/src/Engine/Network/Server.cpp index 30d3b67d..7c614cee 100644 --- a/src/Engine/Network/Server.cpp +++ b/src/Engine/Network/Server.cpp @@ -601,7 +601,7 @@ void Server::parsePlayerTransform(Packet& packet) bool Server::shouldSendToClient(EntityWrapper childEntity) { - auto children = m_World->GetChildren(childEntity.ID); + auto children = m_World->GetDirectChildren(childEntity.ID); for (auto it = children.first; it != children.second; it++) { EntityWrapper child(m_World, it->second); if(child.HasComponent("CapturePoint")) {