From 5e402af093dc3f122e57d03c069125b92a911823 Mon Sep 17 00:00:00 2001 From: Stiffly Date: Thu, 17 Apr 2014 00:08:27 +0200 Subject: [PATCH 01/65] Added ParticleSystem skeleton plus basic temporary implementation. --- src/GameWorld.cpp | 2 +- src/Systems/ParticleSystem.cpp | 47 +++++++++++++++++++ src/Systems/ParticleSystem.h | 33 +++++++++++++ vs11/Returngeance/Returngeance.vcxproj | 2 + .../Returngeance/Returngeance.vcxproj.filters | 38 ++++----------- 5 files changed, 91 insertions(+), 31 deletions(-) create mode 100644 src/Systems/ParticleSystem.cpp create mode 100644 src/Systems/ParticleSystem.h diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index 7a5a543..371dd2e 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -98,7 +98,7 @@ void GameWorld::AddSystems() //AddSystem("LevelGenerationSystem"); AddSystem("InputSystem"); //AddSystem("CollisionSystem"); - ////AddSystem("ParticleSystem"); + //AddSystem("ParticleSystem"); //AddSystem("PlayerSystem"); AddSystem("FreeSteeringSystem"); AddSystem("SoundSystem"); diff --git a/src/Systems/ParticleSystem.cpp b/src/Systems/ParticleSystem.cpp new file mode 100644 index 0000000..3df99a0 --- /dev/null +++ b/src/Systems/ParticleSystem.cpp @@ -0,0 +1,47 @@ +#include "ParticleSystem.h" +#include "PrecompiledHeader.h" + +#include "World.h" +void Systems::ParticleSystem::Update(double dt) +{ + +} + +void Systems::ParticleSystem::UpdateEntity(double dt, EntityID entity, EntityID parent) +{ + auto transformComponent = m_World->GetComponent(entity, "Transform"); + if(!transformComponent) + return; + + transformComponent->Position.y --; + + timeLived[entity] += dt; + + auto emitterComponent = m_World->GetComponent(entity, "ParticleEmitter"); + + + +} + +void Systems::ParticleSystem::RegisterComponents(ComponentFactory* cf) +{ + cf->Register("ParticleEmitter", []() { return new Components::ParticleEmitter(); }); +} + +void Systems::ParticleSystem::SpawnParticles() +{ + for(int i = 0; i < 100; i++) + { + auto particle = m_World->CreateEntity(); + auto transform = m_World->AddComponent(particle, "Transform"); + transform->Position = glm::vec3(0); + particles.push_back(particle); + } +} + +void Systems::ParticleSystem::Draw(double dt) +{ + +} + + diff --git a/src/Systems/ParticleSystem.h b/src/Systems/ParticleSystem.h new file mode 100644 index 0000000..4211d89 --- /dev/null +++ b/src/Systems/ParticleSystem.h @@ -0,0 +1,33 @@ +#ifndef ParticleSystem_h__ +#define ParticleSystem_h__ + +#include "System.h" +#include "Components/Transform.h" +#include "Components/ParticleEmitter.h" + + +namespace Systems +{ + + +class ParticleSystem : public System +{ +public: + ParticleSystem(World* world); + void RegisterComponents(ComponentFactory* cf) override; + + void Update(double dt) override; + void UpdateEntity(double dt, EntityID entity, EntityID parent) override; + +private: + void SpawnParticles(); + + + +}; + + +} + + +#endif // ParticleSystem_h__ \ No newline at end of file diff --git a/vs11/Returngeance/Returngeance.vcxproj b/vs11/Returngeance/Returngeance.vcxproj index 4726981..40cd9be 100755 --- a/vs11/Returngeance/Returngeance.vcxproj +++ b/vs11/Returngeance/Returngeance.vcxproj @@ -109,6 +109,7 @@ + @@ -151,6 +152,7 @@ + diff --git a/vs11/Returngeance/Returngeance.vcxproj.filters b/vs11/Returngeance/Returngeance.vcxproj.filters index 26bcf35..185a9c4 100755 --- a/vs11/Returngeance/Returngeance.vcxproj.filters +++ b/vs11/Returngeance/Returngeance.vcxproj.filters @@ -50,6 +50,9 @@ + + Particle System\Systems + @@ -157,36 +160,6 @@ Rendering - - Physics\Components - - - Physics\Components - - - Physics\Components - - - Physics\Components - - - Physics\Components - - - Physics\Components - - - Physics\Components - - - Physics\Components - - - Physics\Components - - - Physics\Components - Physics\Components @@ -242,6 +215,11 @@ Audio + + + + Particle System\Systems + From f9a74252496224d7d1b9256d61b97b08a62d5661 Mon Sep 17 00:00:00 2001 From: Tleety Date: Thu, 17 Apr 2014 00:54:01 +0200 Subject: [PATCH 02/65] Added Comments in Renderer.cpp --- src/Renderer.cpp | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/src/Renderer.cpp b/src/Renderer.cpp index e7dfed6..55cd40b 100755 --- a/src/Renderer.cpp +++ b/src/Renderer.cpp @@ -280,16 +280,19 @@ void Renderer::DrawScene() void Renderer::DrawShadowMap() { - glEnable(GL_DEPTH_TEST); - glEnable(GL_CULL_FACE); - glCullFace(GL_FRONT); + glEnable(GL_DEPTH_TEST);//Tests where objects are and display them correctly + glEnable(GL_CULL_FACE); //removes triangles on the wrong side of the object + glCullFace(GL_FRONT); //Make it so that only the back faces are rendered + //Binds the FBO and sets the veiwport, witch in effect is how large the shadowmap is and what resolution it has. glBindFramebuffer(GL_FRAMEBUFFER, m_ShadowFrameBuffer); glViewport(0, 0, m_ShadowMapRes, m_ShadowMapRes); glClear(GL_DEPTH_BUFFER_BIT); //glClearColor(0.0f, 0.0f, 0.0f, 0.0f); + + //Creates the "camera" for the shadowmap from the direction of the sun. glm::mat4 depthViewMatrix = glm::lookAt(m_SunPosition, m_SunTarget, glm::vec3(0, 1, 0)) * glm::translate(-m_Camera->Position() * glm::vec3(1, 0, 0)); // glm::mat4 depthViewMatrix = glm::lookAt(m_SunPosition, m_SunTarget, glm::vec3(0, 1, 0)); glm::mat4 depthCamera = m_SunProjection * depthViewMatrix; @@ -299,7 +302,9 @@ void Renderer::DrawShadowMap() glm::mat4 MVP; m_ShaderProgramShadows.Bind(); - glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); + glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); //Draws filled polygons + + //For each model, render them to the shadowmap for (auto tuple : ModelsToRender) { Model* model; From 55221cca12a45b97ba1d127a21a7454dbe73a540 Mon Sep 17 00:00:00 2001 From: Stiffly Date: Tue, 22 Apr 2014 16:52:14 +0200 Subject: [PATCH 03/65] Implemented Spawn and Remove function for particles. Also added a Particle component. --- src/Components/Particle.h | 24 ++++++++++ src/Components/ParticleEmitter.h | 11 ++--- src/GameWorld.h | 1 + src/Systems/ParticleSystem.cpp | 47 +++++++++++++++---- src/Systems/ParticleSystem.h | 13 +++-- vs11/Returngeance/Returngeance.vcxproj | 1 + .../Returngeance/Returngeance.vcxproj.filters | 3 ++ 7 files changed, 82 insertions(+), 18 deletions(-) create mode 100644 src/Components/Particle.h diff --git a/src/Components/Particle.h b/src/Components/Particle.h new file mode 100644 index 0000000..71ac940 --- /dev/null +++ b/src/Components/Particle.h @@ -0,0 +1,24 @@ +#ifndef Components_Particle_h__ +#define Components_Particle_h__ + +#include "System.h" +#include "Component.h" +#include "Components/Transform.h" +#include "Components/ParticleEmitter.h" +#include "Color.h" +#include + +namespace Components +{ + + struct Particle : Component + { + std::vector ColorSpectrum; + std::vector ScaleSpectrum; + double LifeTime; + std::vector VelocitySpectrum; + std::vector AngularVelocitySpectrum; + }; + +} +#endif // !Components_Particle_h__ \ No newline at end of file diff --git a/src/Components/ParticleEmitter.h b/src/Components/ParticleEmitter.h index 48248a8..9f5e20f 100755 --- a/src/Components/ParticleEmitter.h +++ b/src/Components/ParticleEmitter.h @@ -1,10 +1,7 @@ #ifndef Components_ParticleEmitter_h__ #define Components_ParticleEmitter_h__ -#include "System.h" #include "Component.h" -#include "Components/Transform.h" -#include "Components/ParticleEmitter.h" #include "Color.h" #include @@ -13,15 +10,15 @@ namespace Components struct ParticleEmitter : Component { - int ParticleTemplate; + EntityID ParticleTemplate; float SpawnFrequency; int SpawnCount; std::vector ColorSpectrum; std::vector ScaleSpectrum; float SpreadAngle; - float LifeTime; - std::vector VelocitySpectrum; - std::vector AngularVelocitySpectrum; + double LifeTime; + std::vector VelocitySpectrum; + std::vector AngularVelocitySpectrum; }; } diff --git a/src/GameWorld.h b/src/GameWorld.h index 264ec4d..4f74358 100755 --- a/src/GameWorld.h +++ b/src/GameWorld.h @@ -20,6 +20,7 @@ #include "Components/Input.h" #include "Components/Model.h" #include "Components/ParticleEmitter.h" +#include "Components/Particle.h" #include "Components/PointLight.h" #include "Components/SoundEmitter.h" #include "Components/Sprite.h" diff --git a/src/Systems/ParticleSystem.cpp b/src/Systems/ParticleSystem.cpp index bc23511..d742e5d 100644 --- a/src/Systems/ParticleSystem.cpp +++ b/src/Systems/ParticleSystem.cpp @@ -3,9 +3,10 @@ #include "World.h" + void Systems::ParticleSystem::Update(double dt) { - + m_TimeSinceLastSpawn += dt; } void Systems::ParticleSystem::UpdateEntity(double dt, EntityID entity, EntityID parent) @@ -13,26 +14,56 @@ void Systems::ParticleSystem::UpdateEntity(double dt, EntityID entity, EntityID auto transformComponent = m_World->GetComponent(entity, "Transform"); if(!transformComponent) return; - - - auto emitterComponent = m_World->GetComponent(entity, "ParticleEmitter"); + if(emitterComponent) + { + if(m_TimeSinceLastSpawn > emitterComponent->SpawnFrequency) + { + SpawnParticles(entity, emitterComponent->SpawnCount, emitterComponent->SpreadAngle); + m_TimeSinceLastSpawn = 0; + } + + std::list::iterator it; + for(it = m_ParticleEmitter[entity].begin(); it == m_ParticleEmitter[entity].end();) + { + it->TimeLived += dt; + auto particleComponent = m_World->GetComponent(it->ParticleID, "Particle"); + if(it->TimeLived > particleComponent->LifeTime) + { + m_ParticleEmitter[entity].erase(it); + break; + } + else + { + it++; + } + + } + } } void Systems::ParticleSystem::RegisterComponents(ComponentFactory* cf) { cf->Register("ParticleEmitter", []() { return new Components::ParticleEmitter(); }); + cf->Register("Particle", []() { return new Components::Particle(); }); } -void Systems::ParticleSystem::SpawnParticles() +void Systems::ParticleSystem::SpawnParticles(EntityID emitterID, float spawnCount, float spreadAngle) { - for(int i = 0; i < 100; i++) + std::list particles; + for(int i = 0; i < spawnCount; i++) { - auto particle = m_World->CreateEntity(); - auto transform = m_World->AddComponent(particle, "Transform"); + auto ent = m_World->CreateEntity(); + auto transform = m_World->AddComponent(ent, "Transform"); transform->Position = glm::vec3(0); + auto particle = m_World->AddComponent(ent, "Particle"); + particle->LifeTime = 4; + ParticleData data; + data.ParticleID = ent; + data.TimeLived = 0; + m_ParticleEmitter[emitterID].push_back(data); } } diff --git a/src/Systems/ParticleSystem.h b/src/Systems/ParticleSystem.h index 35dfee1..8414a96 100644 --- a/src/Systems/ParticleSystem.h +++ b/src/Systems/ParticleSystem.h @@ -4,11 +4,17 @@ #include "System.h" #include "Components/Transform.h" #include "Components/ParticleEmitter.h" +#include "Components/Particle.h" namespace Systems { + struct ParticleData + { + EntityID ParticleID; + double TimeLived; + }; class ParticleSystem : public System { @@ -21,12 +27,13 @@ public: void UpdateEntity(double dt, EntityID entity, EntityID parent) override; void Draw(double dt); private: - void SpawnParticles(); + void SpawnParticles(EntityID emitterID, float spawnCount, float spreadAngle); + std::map> m_ParticleEmitter; + double m_TimeSinceLastSpawn; }; - } -#endif // ParticleSystem_h__ \ No newline at end of file +#endif // !ParticleSystem_h__ \ No newline at end of file diff --git a/vs11/Returngeance/Returngeance.vcxproj b/vs11/Returngeance/Returngeance.vcxproj index 40cd9be..3cfd619 100755 --- a/vs11/Returngeance/Returngeance.vcxproj +++ b/vs11/Returngeance/Returngeance.vcxproj @@ -127,6 +127,7 @@ + diff --git a/vs11/Returngeance/Returngeance.vcxproj.filters b/vs11/Returngeance/Returngeance.vcxproj.filters index 185a9c4..35f6ce6 100755 --- a/vs11/Returngeance/Returngeance.vcxproj.filters +++ b/vs11/Returngeance/Returngeance.vcxproj.filters @@ -220,6 +220,9 @@ Particle System\Systems + + Particle System\Components + From 78d4dbf8c2deb99ac1b6bd880fb5370d2b066588 Mon Sep 17 00:00:00 2001 From: Stiffly Date: Tue, 22 Apr 2014 17:59:55 +0200 Subject: [PATCH 04/65] Added scale and color interpolation --- src/Systems/ParticleSystem.cpp | 32 +++++++++++++++++++++++++++++--- src/Systems/ParticleSystem.h | 6 +++++- 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/src/Systems/ParticleSystem.cpp b/src/Systems/ParticleSystem.cpp index d742e5d..8488d3d 100644 --- a/src/Systems/ParticleSystem.cpp +++ b/src/Systems/ParticleSystem.cpp @@ -27,9 +27,10 @@ void Systems::ParticleSystem::UpdateEntity(double dt, EntityID entity, EntityID std::list::iterator it; for(it = m_ParticleEmitter[entity].begin(); it == m_ParticleEmitter[entity].end();) { - it->TimeLived += dt; auto particleComponent = m_World->GetComponent(it->ParticleID, "Particle"); - if(it->TimeLived > particleComponent->LifeTime) + + int timeLived = glfwGetTime() - it->SpawnTime; + if(timeLived > particleComponent->LifeTime) { m_ParticleEmitter[entity].erase(it); break; @@ -39,7 +40,20 @@ void Systems::ParticleSystem::UpdateEntity(double dt, EntityID entity, EntityID it++; } + // Interpolates the color for each color channel by the start and end value. Decides how much the color should be interpolated based on time. + // How big fraction the color is multiplied with + float timeProgress = timeLived / particleComponent->LifeTime; + // The difference between the start and end value + float deltaColor = glm::abs(particleComponent->ColorSpectrum[0].r - particleComponent->ColorSpectrum[1].r); + it->color.r = particleComponent->ColorSpectrum[0].r + deltaColor * timeProgress; + deltaColor = glm::abs(particleComponent->ColorSpectrum[0].g - particleComponent->ColorSpectrum[1].g); + it->color.g = particleComponent->ColorSpectrum[0].g + deltaColor * timeProgress; + deltaColor = glm::abs(particleComponent->ColorSpectrum[0].b - particleComponent->ColorSpectrum[1].b); + it->color.b = particleComponent->ColorSpectrum[0].b + deltaColor * timeProgress; + //Interpolates the scale for the particle + float deltaScale = glm::abs(particleComponent->ScaleSpectrum[0] - particleComponent->ScaleSpectrum[1]); + it->Scale = particleComponent->ScaleSpectrum[0] + deltaScale * timeProgress; } } } @@ -56,13 +70,25 @@ void Systems::ParticleSystem::SpawnParticles(EntityID emitterID, float spawnCoun for(int i = 0; i < spawnCount; i++) { auto ent = m_World->CreateEntity(); + auto transform = m_World->AddComponent(ent, "Transform"); transform->Position = glm::vec3(0); + auto particle = m_World->AddComponent(ent, "Particle"); particle->LifeTime = 4; + Color startColor = {.4f, .45f, .2f}; + particle->ColorSpectrum.push_back(startColor); + Color endColor = {0.f, 45.f, 23.f}; + particle->ColorSpectrum.push_back(endColor); + particle->ScaleSpectrum.push_back(1); + particle->ScaleSpectrum.push_back(30); + ParticleData data; data.ParticleID = ent; - data.TimeLived = 0; + data.SpawnTime = glfwGetTime(); + data.color = particle->ColorSpectrum[0]; + data.Scale = particle->ScaleSpectrum[0]; + m_ParticleEmitter[emitterID].push_back(data); } } diff --git a/src/Systems/ParticleSystem.h b/src/Systems/ParticleSystem.h index 8414a96..84674e6 100644 --- a/src/Systems/ParticleSystem.h +++ b/src/Systems/ParticleSystem.h @@ -5,6 +5,8 @@ #include "Components/Transform.h" #include "Components/ParticleEmitter.h" #include "Components/Particle.h" +#include "Color.h" +#include namespace Systems @@ -13,7 +15,9 @@ namespace Systems struct ParticleData { EntityID ParticleID; - double TimeLived; + double SpawnTime; + float Scale; + Color color; }; class ParticleSystem : public System From bdac6fa9f955934306e3e089248546863ef665fb Mon Sep 17 00:00:00 2001 From: Stiffly Date: Tue, 22 Apr 2014 18:58:41 +0200 Subject: [PATCH 05/65] Added velocity interpolation --- src/GameWorld.cpp | 13 +++++++++++++ src/Systems/ParticleSystem.cpp | 24 ++++++++++++++++++++---- src/Systems/ParticleSystem.h | 4 ++-- 3 files changed, 35 insertions(+), 6 deletions(-) diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index 5d471b8..455c105 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -90,6 +90,19 @@ void GameWorld::Initialize() emitter->Loop = true; GetSystem("SoundSystem")->PlaySound(emitter); }*/ + +// { +// // Particle emitter +// auto ent = CreateEntity(); +// auto transform = AddComponent(ent, "Transform"); +// transform->Position = glm::vec3(0); +// auto emitter = AddComponent(ent, "ParticleEmitter"); +// emitter->LifeTime = 4; +// emitter->SpawnCount = 3; +// emitter->SpreadAngle = 35; +// emitter->SpawnFrequency = 0.3; +// //emitter-> +// } } void GameWorld::Update(double dt) diff --git a/src/Systems/ParticleSystem.cpp b/src/Systems/ParticleSystem.cpp index 8488d3d..d379ba9 100644 --- a/src/Systems/ParticleSystem.cpp +++ b/src/Systems/ParticleSystem.cpp @@ -4,6 +4,11 @@ #include "World.h" +Systems::ParticleSystem::ParticleSystem(World *m_World) : System(m_World) +{ + m_TimeSinceLastSpawn = 0; +} + void Systems::ParticleSystem::Update(double dt) { m_TimeSinceLastSpawn += dt; @@ -23,13 +28,14 @@ void Systems::ParticleSystem::UpdateEntity(double dt, EntityID entity, EntityID SpawnParticles(entity, emitterComponent->SpawnCount, emitterComponent->SpreadAngle); m_TimeSinceLastSpawn = 0; } - + std::cout<::iterator it; for(it = m_ParticleEmitter[entity].begin(); it == m_ParticleEmitter[entity].end();) { auto particleComponent = m_World->GetComponent(it->ParticleID, "Particle"); - int timeLived = glfwGetTime() - it->SpawnTime; + double timeLived = glfwGetTime() - it->SpawnTime; + std::cout< particleComponent->LifeTime) { m_ParticleEmitter[entity].erase(it); @@ -51,9 +57,17 @@ void Systems::ParticleSystem::UpdateEntity(double dt, EntityID entity, EntityID deltaColor = glm::abs(particleComponent->ColorSpectrum[0].b - particleComponent->ColorSpectrum[1].b); it->color.b = particleComponent->ColorSpectrum[0].b + deltaColor * timeProgress; - //Interpolates the scale for the particle + //Interpolates the scale of the particle float deltaScale = glm::abs(particleComponent->ScaleSpectrum[0] - particleComponent->ScaleSpectrum[1]); it->Scale = particleComponent->ScaleSpectrum[0] + deltaScale * timeProgress; + + //Interpolates the velocity of the particle + float deltaVelocity = glm::abs(particleComponent->VelocitySpectrum[0].x - particleComponent->VelocitySpectrum[1].x); + it->Velocity.x = particleComponent->VelocitySpectrum[0].x + deltaVelocity * timeProgress; + deltaVelocity = glm::abs(particleComponent->VelocitySpectrum[0].y - particleComponent->VelocitySpectrum[1].y); + it->Velocity.y = particleComponent->VelocitySpectrum[0].y + deltaVelocity * timeProgress; + deltaVelocity = glm::abs(particleComponent->VelocitySpectrum[0].z - particleComponent->VelocitySpectrum[1].z); + it->Velocity.z = particleComponent->VelocitySpectrum[0].z + deltaVelocity * timeProgress; } } } @@ -75,13 +89,15 @@ void Systems::ParticleSystem::SpawnParticles(EntityID emitterID, float spawnCoun transform->Position = glm::vec3(0); auto particle = m_World->AddComponent(ent, "Particle"); - particle->LifeTime = 4; + particle->LifeTime = 4000; Color startColor = {.4f, .45f, .2f}; particle->ColorSpectrum.push_back(startColor); Color endColor = {0.f, 45.f, 23.f}; particle->ColorSpectrum.push_back(endColor); particle->ScaleSpectrum.push_back(1); particle->ScaleSpectrum.push_back(30); + particle->VelocitySpectrum.push_back(glm::vec3(0, -.2, 0)); + particle->VelocitySpectrum.push_back(glm::vec3(0, -3, 0)); ParticleData data; data.ParticleID = ent; diff --git a/src/Systems/ParticleSystem.h b/src/Systems/ParticleSystem.h index 84674e6..3c24e79 100644 --- a/src/Systems/ParticleSystem.h +++ b/src/Systems/ParticleSystem.h @@ -18,13 +18,13 @@ namespace Systems double SpawnTime; float Scale; Color color; + glm::vec3 Velocity; }; class ParticleSystem : public System { public: - ParticleSystem(World* world) - :System(world) { }; + ParticleSystem(World* world); void RegisterComponents(ComponentFactory* cf) override; void Update(double dt) override; From 100f8f5be4aed93d8c1cb3172065109ceb221446 Mon Sep 17 00:00:00 2001 From: Stiffly Date: Wed, 23 Apr 2014 21:33:43 +0200 Subject: [PATCH 06/65] Bug fix: checked for particles not created --- src/GameWorld.cpp | 24 ++++++++++++------------ src/Systems/ParticleSystem.cpp | 3 +++ 2 files changed, 15 insertions(+), 12 deletions(-) diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index 455c105..1743d6d 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -91,18 +91,18 @@ void GameWorld::Initialize() GetSystem("SoundSystem")->PlaySound(emitter); }*/ -// { -// // Particle emitter -// auto ent = CreateEntity(); -// auto transform = AddComponent(ent, "Transform"); -// transform->Position = glm::vec3(0); -// auto emitter = AddComponent(ent, "ParticleEmitter"); -// emitter->LifeTime = 4; -// emitter->SpawnCount = 3; -// emitter->SpreadAngle = 35; -// emitter->SpawnFrequency = 0.3; -// //emitter-> -// } + { + // Particle emitter + auto ent = CreateEntity(); + auto transform = AddComponent(ent, "Transform"); + transform->Position = glm::vec3(0); + auto emitter = AddComponent(ent, "ParticleEmitter"); + emitter->LifeTime = 4; + emitter->SpawnCount = 3; + emitter->SpreadAngle = 35; + emitter->SpawnFrequency = 0.3; + //emitter-> + } } void GameWorld::Update(double dt) diff --git a/src/Systems/ParticleSystem.cpp b/src/Systems/ParticleSystem.cpp index d379ba9..048832d 100644 --- a/src/Systems/ParticleSystem.cpp +++ b/src/Systems/ParticleSystem.cpp @@ -28,11 +28,14 @@ void Systems::ParticleSystem::UpdateEntity(double dt, EntityID entity, EntityID SpawnParticles(entity, emitterComponent->SpawnCount, emitterComponent->SpreadAngle); m_TimeSinceLastSpawn = 0; } + std::cout<::iterator it; for(it = m_ParticleEmitter[entity].begin(); it == m_ParticleEmitter[entity].end();) { auto particleComponent = m_World->GetComponent(it->ParticleID, "Particle"); + if(!particleComponent) + break; double timeLived = glfwGetTime() - it->SpawnTime; std::cout< Date: Wed, 23 Apr 2014 22:46:19 +0200 Subject: [PATCH 07/65] Bug fix: fixed time to correct resolution, seconds. --- src/GameWorld.cpp | 6 +++--- src/Systems/ParticleSystem.cpp | 26 ++++++++++++++------------ src/Systems/ParticleSystem.h | 1 - 3 files changed, 17 insertions(+), 16 deletions(-) diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index 1743d6d..242d0bc 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -49,7 +49,7 @@ void GameWorld::Initialize() model->ModelFile = "Models/Placeholders/tank/Chassi.obj"; } - for(int i = 0; i < 83; i++) + for(int i = 0; i < 2; i++) { auto light = CreateEntity(); auto transform = AddComponent(light, "Transform"); @@ -67,7 +67,7 @@ void GameWorld::Initialize() model->ModelFile = "Models/Placeholders/PhysicsTest/PointLight.obj"; } - for(int i = 0; i < 500; i++) + for(int i = 0; i < 3; i++) { auto ball = CreateEntity(); auto transform = AddComponent(ball, "Transform"); @@ -100,7 +100,7 @@ void GameWorld::Initialize() emitter->LifeTime = 4; emitter->SpawnCount = 3; emitter->SpreadAngle = 35; - emitter->SpawnFrequency = 0.3; + emitter->SpawnFrequency = 0.01; //emitter-> } } diff --git a/src/Systems/ParticleSystem.cpp b/src/Systems/ParticleSystem.cpp index 048832d..d2ccc8c 100644 --- a/src/Systems/ParticleSystem.cpp +++ b/src/Systems/ParticleSystem.cpp @@ -25,23 +25,25 @@ void Systems::ParticleSystem::UpdateEntity(double dt, EntityID entity, EntityID { if(m_TimeSinceLastSpawn > emitterComponent->SpawnFrequency) { - SpawnParticles(entity, emitterComponent->SpawnCount, emitterComponent->SpreadAngle); - m_TimeSinceLastSpawn = 0; + if(m_ParticleEmitter[entity].size() < 100) + { + SpawnParticles(entity, emitterComponent->SpawnCount, emitterComponent->SpreadAngle); + m_TimeSinceLastSpawn = 0; + } + std::cout<<"Particle count: "<::iterator it; - for(it = m_ParticleEmitter[entity].begin(); it == m_ParticleEmitter[entity].end();) + for(it = m_ParticleEmitter[entity].begin(); it != m_ParticleEmitter[entity].end();) { auto particleComponent = m_World->GetComponent(it->ParticleID, "Particle"); - if(!particleComponent) - break; + double timeLived = glfwGetTime() - it->SpawnTime; - std::cout< particleComponent->LifeTime) { m_ParticleEmitter[entity].erase(it); + std::cout<<"Removed dead particle..."<LifeTime; // The difference between the start and end value float deltaColor = glm::abs(particleComponent->ColorSpectrum[0].r - particleComponent->ColorSpectrum[1].r); @@ -70,7 +72,7 @@ void Systems::ParticleSystem::UpdateEntity(double dt, EntityID entity, EntityID deltaVelocity = glm::abs(particleComponent->VelocitySpectrum[0].y - particleComponent->VelocitySpectrum[1].y); it->Velocity.y = particleComponent->VelocitySpectrum[0].y + deltaVelocity * timeProgress; deltaVelocity = glm::abs(particleComponent->VelocitySpectrum[0].z - particleComponent->VelocitySpectrum[1].z); - it->Velocity.z = particleComponent->VelocitySpectrum[0].z + deltaVelocity * timeProgress; + it->Velocity.z = particleComponent->VelocitySpectrum[0].z + deltaVelocity * timeProgress;*/ } } } @@ -83,7 +85,6 @@ void Systems::ParticleSystem::RegisterComponents(ComponentFactory* cf) void Systems::ParticleSystem::SpawnParticles(EntityID emitterID, float spawnCount, float spreadAngle) { - std::list particles; for(int i = 0; i < spawnCount; i++) { auto ent = m_World->CreateEntity(); @@ -92,7 +93,7 @@ void Systems::ParticleSystem::SpawnParticles(EntityID emitterID, float spawnCoun transform->Position = glm::vec3(0); auto particle = m_World->AddComponent(ent, "Particle"); - particle->LifeTime = 4000; + particle->LifeTime = 4; Color startColor = {.4f, .45f, .2f}; particle->ColorSpectrum.push_back(startColor); Color endColor = {0.f, 45.f, 23.f}; @@ -110,6 +111,7 @@ void Systems::ParticleSystem::SpawnParticles(EntityID emitterID, float spawnCoun m_ParticleEmitter[emitterID].push_back(data); } + std::cout<<"Added "< - namespace Systems { From 5997ee232054f1ee99eb506120888a44d4dd5393 Mon Sep 17 00:00:00 2001 From: Stiffly Date: Thu, 24 Apr 2014 00:00:29 +0200 Subject: [PATCH 08/65] Added models and temporary "fly everywhere" direction to particles --- src/Components/Particle.h | 2 -- src/GameWorld.cpp | 4 ++-- src/Systems/ParticleSystem.cpp | 40 ++++++++++++++++++++++------------ src/Systems/ParticleSystem.h | 2 ++ 4 files changed, 30 insertions(+), 18 deletions(-) diff --git a/src/Components/Particle.h b/src/Components/Particle.h index 71ac940..b169ee2 100644 --- a/src/Components/Particle.h +++ b/src/Components/Particle.h @@ -3,8 +3,6 @@ #include "System.h" #include "Component.h" -#include "Components/Transform.h" -#include "Components/ParticleEmitter.h" #include "Color.h" #include diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index 242d0bc..d11cce1 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -98,9 +98,9 @@ void GameWorld::Initialize() transform->Position = glm::vec3(0); auto emitter = AddComponent(ent, "ParticleEmitter"); emitter->LifeTime = 4; - emitter->SpawnCount = 3; + emitter->SpawnCount = 1; emitter->SpreadAngle = 35; - emitter->SpawnFrequency = 0.01; + emitter->SpawnFrequency = 0.05; //emitter-> } } diff --git a/src/Systems/ParticleSystem.cpp b/src/Systems/ParticleSystem.cpp index d2ccc8c..e62218d 100644 --- a/src/Systems/ParticleSystem.cpp +++ b/src/Systems/ParticleSystem.cpp @@ -25,31 +25,37 @@ void Systems::ParticleSystem::UpdateEntity(double dt, EntityID entity, EntityID { if(m_TimeSinceLastSpawn > emitterComponent->SpawnFrequency) { - if(m_ParticleEmitter[entity].size() < 100) + //if(m_ParticleEmitter[entity].size() < 100) // TEMP { SpawnParticles(entity, emitterComponent->SpawnCount, emitterComponent->SpreadAngle); m_TimeSinceLastSpawn = 0; } - std::cout<<"Particle count: "<::iterator it; - for(it = m_ParticleEmitter[entity].begin(); it != m_ParticleEmitter[entity].end();) + for(it = m_ParticleEmitter[entity].begin(); it != m_ParticleEmitter[entity].end(); it++) { - auto particleComponent = m_World->GetComponent(it->ParticleID, "Particle"); - - + EntityID particleID = it->ParticleID; + auto particleComponent = m_World->GetComponent(particleID, "Particle"); double timeLived = glfwGetTime() - it->SpawnTime; if(timeLived > particleComponent->LifeTime) { m_ParticleEmitter[entity].erase(it); - std::cout<<"Removed dead particle..."<GetComponent(particleID, "Transform"); + float speed = 10 * dt; + transformComponent->Position.x += it->Direction.x * speed; + transformComponent->Position.y += it->Direction.y * speed; + transformComponent->Position.z += it->Direction.z * speed; + // Interpolates the color for each color channel by the start and end value. Decides how much the color should be interpolated based on time. /*// How big fraction the color is multiplied with @@ -90,24 +96,30 @@ void Systems::ParticleSystem::SpawnParticles(EntityID emitterID, float spawnCoun auto ent = m_World->CreateEntity(); auto transform = m_World->AddComponent(ent, "Transform"); - transform->Position = glm::vec3(0); + transform->Position = glm::vec3(0, 20, 0); + transform->Scale = glm::vec3(1, 1, 0); auto particle = m_World->AddComponent(ent, "Particle"); particle->LifeTime = 4; - Color startColor = {.4f, .45f, .2f}; + /*Color startColor = {.4f, .45f, .2f}; particle->ColorSpectrum.push_back(startColor); Color endColor = {0.f, 45.f, 23.f}; particle->ColorSpectrum.push_back(endColor); particle->ScaleSpectrum.push_back(1); particle->ScaleSpectrum.push_back(30); particle->VelocitySpectrum.push_back(glm::vec3(0, -.2, 0)); - particle->VelocitySpectrum.push_back(glm::vec3(0, -3, 0)); + particle->VelocitySpectrum.push_back(glm::vec3(0, -3, 0));*/ + + auto model = m_World->AddComponent(ent, "Model"); + model->ModelFile = "Models/Placeholders/PhysicsTest/Cube.obj"; ParticleData data; data.ParticleID = ent; data.SpawnTime = glfwGetTime(); - data.color = particle->ColorSpectrum[0]; - data.Scale = particle->ScaleSpectrum[0]; +// data.color = particle->ColorSpectrum[0]; +// data.Scale = particle->ScaleSpectrum[0]; + data.Direction = glm::vec3(((double)rand() / ((double)RAND_MAX + 1) * 2) -1, ((double)rand() / ((double)RAND_MAX + 1) * 2) -1, ((double)rand() / ((double)RAND_MAX + 1) * 2) -1); + data.Direction = glm::normalize(data.Direction); m_ParticleEmitter[emitterID].push_back(data); } diff --git a/src/Systems/ParticleSystem.h b/src/Systems/ParticleSystem.h index 53bf08e..9b70082 100644 --- a/src/Systems/ParticleSystem.h +++ b/src/Systems/ParticleSystem.h @@ -5,6 +5,7 @@ #include "Components/Transform.h" #include "Components/ParticleEmitter.h" #include "Components/Particle.h" +#include "Components/Model.h" #include "Color.h" #include @@ -18,6 +19,7 @@ namespace Systems float Scale; Color color; glm::vec3 Velocity; + glm::vec3 Direction; }; class ParticleSystem : public System From 6d75336496a71439e1136218794d1ba15e4b0d31 Mon Sep 17 00:00:00 2001 From: Tleety Date: Thu, 24 Apr 2014 00:11:16 +0200 Subject: [PATCH 09/65] Started on deferred rendering framework. --- src/Renderer.cpp | 192 ++++++++++++++---- src/Renderer.h | 10 + src/Shaders/First_pass.frag.glsl | 12 ++ src/Shaders/First_pass.vert.glsl | 16 ++ src/Shaders/Second_pass.frag.glsl | 24 +++ src/Shaders/Second_pass.vert.glsl | 9 + src/Shaders/geometry_pass.frag.glsl | 20 -- src/Shaders/geometry_pass.vert.glsl | 20 -- src/Util/defferedUtil.h | 28 +++ src/gBuffer.cpp | 40 ---- src/gBuffer.h | 35 ---- vs11/Returngeance/Returngeance.vcxproj | 18 ++ .../Returngeance/Returngeance.vcxproj.filters | 15 ++ 13 files changed, 289 insertions(+), 150 deletions(-) create mode 100644 src/Shaders/First_pass.frag.glsl create mode 100644 src/Shaders/First_pass.vert.glsl create mode 100644 src/Shaders/Second_pass.frag.glsl create mode 100644 src/Shaders/Second_pass.vert.glsl delete mode 100644 src/Shaders/geometry_pass.frag.glsl delete mode 100644 src/Shaders/geometry_pass.vert.glsl create mode 100644 src/Util/defferedUtil.h delete mode 100644 src/gBuffer.cpp delete mode 100644 src/gBuffer.h diff --git a/src/Renderer.cpp b/src/Renderer.cpp index 55cd40b..50c820b 100755 --- a/src/Renderer.cpp +++ b/src/Renderer.cpp @@ -72,6 +72,8 @@ void Renderer::Initialize() glEnable(GL_DEPTH_TEST); LoadContent(); + + FrameBufferTextures(); } void Renderer::LoadContent() @@ -110,6 +112,11 @@ void Renderer::LoadContent() m_ShaderProgramSkybox.Compile(); m_ShaderProgramSkybox.Link(); + m_FirstPassProgram.AddShader(std::shared_ptr(new VertexShader("Shaders/First_pass.vert.glsl"))); + m_FirstPassProgram.AddShader(std::shared_ptr(new FragmentShader("Shaders/First_pass.frag.glsl"))); + m_FirstPassProgram.Compile(); + m_FirstPassProgram.Link(); + m_Skybox = std::make_shared("Textures/Skybox/Sunset", "jpg"); m_DebugAABB = CreateAABB(); @@ -147,43 +154,17 @@ void Renderer::Draw(double dt) { glDisable(GL_BLEND); - DrawSkybox(); - DrawShadowMap(); - DrawScene(); - -#ifdef DEBUG - // Draw bounding boxes - if (m_DrawBounds) - { - glEnable(GL_BLEND); - glBlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ZERO); - m_ShaderProgramDebugAABB.Bind(); - for (auto tuple : AABBsToRender) - { - glm::mat4 modelMatrix; - bool colliding; - std::tie(modelMatrix, colliding) = tuple; - // Model matrix - glm::mat4 cameraMatrix = m_Camera->ProjectionMatrix() * m_Camera->ViewMatrix(); - glm::mat4 MVP = cameraMatrix * modelMatrix; - glUniformMatrix4fv(glGetUniformLocation(m_ShaderProgramDebugAABB.GetHandle(), "MVP"), 1, GL_FALSE, glm::value_ptr(MVP)); - // Color - glm::vec4 color(1.f, 1.f, 1.f, 0.f); - if (colliding) - color = glm::vec4(1.f, 0.f, 0.f, 0.f); - glUniform4fv(glGetUniformLocation(m_ShaderProgramDebugAABB.GetHandle(), "Color"), 1, glm::value_ptr(color)); - glBindVertexArray(m_DebugAABB); - glDrawArrays(GL_LINES, 0, 24); - } - } - - DrawDebugShadowMap(); -#endif + DrawFBO(); ClearStuff(); glfwSwapBuffers(m_Window); } +#pragma region TempRegion + + + + void Renderer::DrawSkybox() { glBindFramebuffer(GL_FRAMEBUFFER, 0); @@ -199,8 +180,8 @@ void Renderer::DrawSkybox() void Renderer::DrawScene() { - glBindFramebuffer(GL_FRAMEBUFFER, 0); - glViewport(0, 0, WIDTH, HEIGHT); +// glBindFramebuffer(GL_FRAMEBUFFER, 0); +// glViewport(0, 0, WIDTH, HEIGHT); glClear(GL_DEPTH_BUFFER_BIT); //glClearColor(1.0f, 1.0f, 0.0f, 1.0f); @@ -537,6 +518,7 @@ GLuint Renderer::CreateSkybox() return vao; } + void Renderer::ClearStuff() { AABBsToRender.clear(); @@ -549,4 +531,144 @@ void Renderer::ClearStuff() Light_quadraticAttenuation.clear(); Light_spotExponent.clear(); Lights = 0; -} \ No newline at end of file +} + +#pragma endregion + +void Renderer::FrameBufferTextures() +{ + m_fb = 0; + + glGenFramebuffers(1, &m_fb); + GLERROR("GLERROR: Failed to generate frame buffer"); + glGenTextures(1, &m_fb_PositionTexture); + GLERROR("GLERROR: Failed to generate Position texture"); + glBindTexture(GL_TEXTURE_2D, m_fb_PositionTexture); + GLERROR("GLERROR: Failed to bind Position texture"); + glTexImage2D( + GL_TEXTURE_2D, + 0, + GL_RGB16F, + WIDTH, + HEIGHT, + 0, + GL_RGBA, + GL_UNSIGNED_BYTE, + NULL + ); + GLERROR("GLERROR: Failed to generate Position texture image"); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + GLERROR("GLERROR: Failed to generate Position Parameters"); + + glGenTextures(1, &m_fb_NormalsTexture); + GLERROR("GLERROR: Failed to generate Normal texture"); + glBindTexture(GL_TEXTURE_2D, m_fb_NormalsTexture); + GLERROR("GLERROR: Failed to bind Normal texture"); + glTexImage2D( + GL_TEXTURE_2D, + 0, + GL_RGB16F, + WIDTH, + HEIGHT, + 0, + GL_RGBA, + GL_UNSIGNED_BYTE, + NULL + ); + GLERROR("GLERROR: Failed to generate Normal texture image"); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + GLERROR("GLERROR: Failed to generate Normals Parameters"); + + glBindFramebuffer(GL_FRAMEBUFFER, m_fb); + GLERROR("GLERROR: Failed to bind framebuffer"); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_fb_PositionTexture, 0); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, m_fb_NormalsTexture, 0); + GLERROR("GLERROR: Failed to FrameBufferTexture2D"); + + m_rb = 0; + glGenRenderbuffers(1, &m_rb); + GLERROR("GLERROR: Failed to generate RenderBuffer"); + glBindRenderbuffer(GL_RENDERBUFFER, m_rb); + GLERROR("GLERROR: Failed to bind RenderBuffer"); + glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, WIDTH, HEIGHT); + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_rb); + + draw_bufs[1] = GL_COLOR_ATTACHMENT0; + draw_bufs[2] = GL_COLOR_ATTACHMENT1; + + +} + +void Renderer::DrawFBO() +{ + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + glBindFramebuffer(GL_FRAMEBUFFER, m_fb); + glEnable(GL_DEPTH_TEST); + glEnable(GL_CULL_FACE); + glCullFace(GL_BACK); +#ifdef DEBUG + glDisable(GL_CULL_FACE); + glPolygonMode(GL_BACK, GL_LINE); +#endif + + // Draw models + glm::mat4 depthViewMatrix = glm::lookAt(m_SunPosition, m_SunTarget, glm::vec3(0, 1, 0)) * glm::translate(-m_Camera->Position() * glm::vec3(1, 0, 0)); + glm::mat4 depthCamera = m_SunProjection * depthViewMatrix; + glm::mat4 biasMatrix( + 0.5, 0.0, 0.0, 0.0, + 0.0, 0.5, 0.0, 0.0, + 0.0, 0.0, 0.5, 0.0, + 0.5, 0.5, 0.5, 1.0 + ); + + m_ShaderProgram.Bind(); + if (m_DrawWireframe) + { + glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); + } + glm::mat4 cameraMatrix = m_Camera->ProjectionMatrix() * m_Camera->ViewMatrix(); + glm::mat4 depthCameraMatrix = biasMatrix * depthCamera; + glm::mat4 MVP; + glm::mat4 depthMVP; + for (auto tuple : ModelsToRender) + { + Model* model; + glm::mat4 modelMatrix; + bool visible; + std::tie(model, modelMatrix, visible, std::ignore) = tuple; + if (!visible) + continue; + + MVP = cameraMatrix * modelMatrix; + depthMVP = depthCameraMatrix * modelMatrix; + glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "M"), 1, GL_FALSE, glm::value_ptr(modelMatrix)); + glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "V"), 1, GL_FALSE, glm::value_ptr( m_Camera->ViewMatrix())); + glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "P"), 1, GL_FALSE, glm::value_ptr(m_Camera->ProjectionMatrix())); + glBindVertexArray(model->VAO); +// for (auto texGroup : model->TextureGroups) +// { +// glActiveTexture(GL_TEXTURE0); +// glBindTexture(GL_TEXTURE_2D, *texGroup.Texture); +// glDrawArrays(GL_TRIANGLES, texGroup.StartIndex, texGroup.EndIndex - texGroup.StartIndex + 1); +// } + } + +#ifdef DEBUG + // Debug draw model normals + if (m_DrawNormals) + { + m_ShaderProgramNormals.Bind(); + glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); + DrawModels(m_ShaderProgramNormals); + } +#endif + + //glDrawBuffers(2, draw_bufs); +} + diff --git a/src/Renderer.h b/src/Renderer.h index 8d0da1f..3243eef 100755 --- a/src/Renderer.h +++ b/src/Renderer.h @@ -88,9 +88,16 @@ private: GLuint m_ShadowFrameBuffer; GLuint m_ShadowDepthTexture; + GLuint m_fb_PositionTexture; + GLuint m_fb_NormalsTexture; + GLuint m_fb; + GLuint m_rb; + GLenum draw_bufs[2]; + std::shared_ptr m_Camera; ShaderProgram m_ShaderProgram; + ShaderProgram m_FirstPassProgram; ShaderProgram m_ShaderProgramNormals; ShaderProgram m_ShaderProgramShadows; ShaderProgram m_ShaderProgramShadowsDrawDepth; @@ -102,6 +109,9 @@ private: void DrawModels(ShaderProgram &shader); void DrawShadowMap(); void CreateShadowMap(int resolution); + void FrameBufferTextures(); + void DrawFBO(); + GLuint CreateQuad(); void DrawDebugShadowMap(); GLuint CreateAABB(); diff --git a/src/Shaders/First_pass.frag.glsl b/src/Shaders/First_pass.frag.glsl new file mode 100644 index 0000000..df66547 --- /dev/null +++ b/src/Shaders/First_pass.frag.glsl @@ -0,0 +1,12 @@ +#version 400 + +in vec3 p_eye; +in vec3 n_eye; + +layout (location = 0) out vec4 def_p; // "go to GL_COLOR_ATTACHMENT0" +layout (location = 1) out vec4 def_n; // "go to GL_COLOR_ATTACHMENT1" + +void main () { + def_p = vec4(p_eye, 1.0); + def_n = vec4(n_eye, 1.0); +} \ No newline at end of file diff --git a/src/Shaders/First_pass.vert.glsl b/src/Shaders/First_pass.vert.glsl new file mode 100644 index 0000000..f6cd49c --- /dev/null +++ b/src/Shaders/First_pass.vert.glsl @@ -0,0 +1,16 @@ +#version 400 + +layout(location = 0) in vec3 vp; +layout(location = 1) in vec3 vn; +layout(location = 2) in vec2 TextureCoord; + +uniform mat4 P, V, M; + +out vec3 p_eye; +out vec3 n_eye; + +void main () { + p_eye = (V * M * vec4 (vp, 1.0)).xyz; + n_eye = (V * M * vec4 (vn, 0.0)).xyz; + gl_Position = P * vec4 (p_eye, 1.0); +} \ No newline at end of file diff --git a/src/Shaders/Second_pass.frag.glsl b/src/Shaders/Second_pass.frag.glsl new file mode 100644 index 0000000..5792748 --- /dev/null +++ b/src/Shaders/Second_pass.frag.glsl @@ -0,0 +1,24 @@ +#version 430 + +uniform sampler2D tDiffuse; +uniform sampler2D tPosition; +uniform sampler2D tNormals; +uniform vec3 cameraPosition; + +void main( void ) +{ + vec4 image = texture2D( tDiffuse, gl_TexCoord[0].xy ); + vec4 position = texture2D( tPosition, gl_TexCoord[0].xy ); + vec4 normal = texture2D( tNormals, gl_TexCoord[0].xy ); + + vec3 light = vec3(50,100,50); + vec3 lightDir = light - position.xyz ; + + normal = normalize(normal); + lightDir = normalize(lightDir); + + vec3 eyeDir = normalize(cameraPosition-position.xyz); + vec3 vHalfVector = normalize(lightDir.xyz+eyeDir); + + gl_FragColor = max(dot(normal,lightDir),0) * image + pow(max(dot(normal,vHalfVector),0.0), 100) * 1.5; +} diff --git a/src/Shaders/Second_pass.vert.glsl b/src/Shaders/Second_pass.vert.glsl new file mode 100644 index 0000000..23a3280 --- /dev/null +++ b/src/Shaders/Second_pass.vert.glsl @@ -0,0 +1,9 @@ +#version 430 + +void main( void ) +{ + gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; + gl_TexCoord[0] = gl_MultiTexCoord0; + + gl_FrontColor = vec4(1.0, 1.0, 1.0, 1.0); +} diff --git a/src/Shaders/geometry_pass.frag.glsl b/src/Shaders/geometry_pass.frag.glsl deleted file mode 100644 index 4fe34ba..0000000 --- a/src/Shaders/geometry_pass.frag.glsl +++ /dev/null @@ -1,20 +0,0 @@ -#version 430 - -in vec2 TexCoord0; -in vec3 Normal0; -in vec3 WorldPos0; - -layout (location = 0) out vec3 WorldPosOut; -layout (location = 1) out vec3 DiffuseOut; -layout (location = 2) out vec3 NormalOut; -layout (location = 3) out vec3 TexCoordOut; - -uniform sampler2D gColorMap; - -void main() -{ - WorldPosOut = WorldPos0; - DiffuseOut = texture(gColorMap, TexCoord0).xyz; - NormalOut = normalize(Normal0); - TexCoordOut = vec3(TexCoord0, 0.0); -} \ No newline at end of file diff --git a/src/Shaders/geometry_pass.vert.glsl b/src/Shaders/geometry_pass.vert.glsl deleted file mode 100644 index c431ba9..0000000 --- a/src/Shaders/geometry_pass.vert.glsl +++ /dev/null @@ -1,20 +0,0 @@ -#version 430 - -layout (location = 0) in vec3 Position; -layout (location = 1) in vec2 TexCoord; -layout (location = 2) in vec3 Normal; - -uniform mat4 gWVP; -uniform mat4 gWorld; - -out vec2 TexCoord0; -out vec3 Normal0; -out vec3 WorldPos0; - -void main() -{ - gl_Position = gWVP * vec4(Position, 1.0); - TexCoord0 = TexCoord; - Normal0 = (gWorld * vec4(Normal, 0.0)).xyz; - WorldPos0 = (gWorld * vec4(Position, 1.0)).xyz; -} \ No newline at end of file diff --git a/src/Util/defferedUtil.h b/src/Util/defferedUtil.h new file mode 100644 index 0000000..d362fac --- /dev/null +++ b/src/Util/defferedUtil.h @@ -0,0 +1,28 @@ +#ifndef UTIL_H +#define UTIL_H + +#include +#include +#include + +#define ZERO_MEM(a) memset(a, 0, sizeof(a)) + +#define ARRAY_SIZE_IN_ELEMENTS(a) (sizeof(a)/sizeof(a[0])) + +#define INVALID_OGL_VALUE 0xFFFFFFFF + +#define SAFE_DELETE(p) if (p) { delete p; p = NULL; } + +#define GLExitIfError() \ +{ \ + GLenum Error = glGetError(); \ + \ + if (Error != GL_NO_ERROR) { \ + printf("OpenGL error in %s:%d: 0x%x\n", __FILE__, __LINE__, Error); \ + exit(0); \ + } \ +} + +#define GLCheckError() (glGetError() == GL_NO_ERROR) + +#endif /* UTIL_H */ diff --git a/src/gBuffer.cpp b/src/gBuffer.cpp deleted file mode 100644 index 5acf690..0000000 --- a/src/gBuffer.cpp +++ /dev/null @@ -1,40 +0,0 @@ -#include "PrecompiledHeader.h" -#include "gBuffer.h" - -bool GBuffer::Init(unsigned int WindowWidth, unsigned int WindowHeight) -{ - // Create the FBO - glGenFramebuffers(1, &m_fbo); - glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbo); - - // Create the gbuffer textures - glGenTextures(ARRAY_SIZE_IN_ELEMENTS(m_textures), m_textures); - glGenTextures(1, &m_depthTexture); - - for (unsigned int i = 0 ; i < ARRAY_SIZE_IN_ELEMENTS(m_textures) ; i++) { - glBindTexture(GL_TEXTURE_2D, m_textures[i]); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, WindowWidth, WindowHeight, 0, GL_RGB, GL_FLOAT, NULL); - glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, m_textures[i], 0); - } - - // depth - glBindTexture(GL_TEXTURE_2D, m_depthTexture); - glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32F, WindowWidth, WindowHeight, 0, GL_DEPTH_COMPONENT, GL_FLOAT, - NULL); - glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_depthTexture, 0); - - GLenum DrawBuffers[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3 }; - glDrawBuffers(ARRAY_SIZE_IN_ELEMENTS(DrawBuffers), DrawBuffers); - - GLenum Status = glCheckFramebufferStatus(GL_FRAMEBUFFER); - - if (Status != GL_FRAMEBUFFER_COMPLETE) { - printf("FB error, status: 0x%x\n", Status); - return false; - } - - // restore default FBO - glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); - - return true; -} \ No newline at end of file diff --git a/src/gBuffer.h b/src/gBuffer.h deleted file mode 100644 index 721eb15..0000000 --- a/src/gBuffer.h +++ /dev/null @@ -1,35 +0,0 @@ -#ifndef gBuffer_h__ -#define gBuffer_h__ - -#include - -class GBuffer -{ -public: - - enum GBUFFER_TEXTURE_TYPE { - GBUFFER_TEXTURE_TYPE_POSITION, - GBUFFER_TEXTURE_TYPE_DIFFUSE, - GBUFFER_TEXTURE_TYPE_NORMAL, - GBUFFER_TEXTURE_TYPE_TEXCOORD, - GBUFFER_NUM_TEXTURES - }; - - GBuffer(); - - ~GBuffer(); - - bool Init(unsigned int WindowWidth, unsigned int WindowHeight); - - void BindForWriting(); - - void BindForReading(); - -private: - - GLuint m_fbo; - GLuint m_textures[GBUFFER_NUM_TEXTURES]; - GLuint m_depthTexture; -}; - -#endif //gBuffer_h__ \ No newline at end of file diff --git a/vs11/Returngeance/Returngeance.vcxproj b/vs11/Returngeance/Returngeance.vcxproj index 4726981..46c68eb 100755 --- a/vs11/Returngeance/Returngeance.vcxproj +++ b/vs11/Returngeance/Returngeance.vcxproj @@ -156,15 +156,33 @@ + + + + + true + + + + + + + + + true + + + true + diff --git a/vs11/Returngeance/Returngeance.vcxproj.filters b/vs11/Returngeance/Returngeance.vcxproj.filters index 672e8dd..0186e7f 100755 --- a/vs11/Returngeance/Returngeance.vcxproj.filters +++ b/vs11/Returngeance/Returngeance.vcxproj.filters @@ -214,6 +214,9 @@ + + Util + @@ -249,5 +252,17 @@ Shaders + + Shaders + + + Shaders + + + Shaders + + + Shaders + \ No newline at end of file From b07605594d748c6feff89de1e1f4feac625086f3 Mon Sep 17 00:00:00 2001 From: Stiffly Date: Thu, 24 Apr 2014 00:44:26 +0200 Subject: [PATCH 10/65] Fixed loop, can't miss particles. (tried to add physics to particles) --- src/Systems/ParticleSystem.cpp | 30 +++++++++++++++++++++--------- src/Systems/ParticleSystem.h | 2 ++ 2 files changed, 23 insertions(+), 9 deletions(-) diff --git a/src/Systems/ParticleSystem.cpp b/src/Systems/ParticleSystem.cpp index e62218d..7cdec83 100644 --- a/src/Systems/ParticleSystem.cpp +++ b/src/Systems/ParticleSystem.cpp @@ -34,21 +34,24 @@ void Systems::ParticleSystem::UpdateEntity(double dt, EntityID entity, EntityID } std::list::iterator it; - for(it = m_ParticleEmitter[entity].begin(); it != m_ParticleEmitter[entity].end(); it++) + for(it = m_ParticleEmitter[entity].begin(); it != m_ParticleEmitter[entity].end();) { EntityID particleID = it->ParticleID; auto particleComponent = m_World->GetComponent(particleID, "Particle"); double timeLived = glfwGetTime() - it->SpawnTime; if(timeLived > particleComponent->LifeTime) { + + m_World->RemoveEntity(particleID); m_ParticleEmitter[entity].erase(it); //std::cout<<"Removed dead particle..."<GetComponent(particleID, "Transform"); float speed = 10 * dt; @@ -113,6 +116,14 @@ void Systems::ParticleSystem::SpawnParticles(EntityID emitterID, float spawnCoun auto model = m_World->AddComponent(ent, "Model"); model->ModelFile = "Models/Placeholders/PhysicsTest/Cube.obj"; + /*auto physics = m_World->AddComponent(ent, "Physics"); + physics->Mass = 1; + + auto physicShape = m_World->AddComponent(ent, "Box"); + physicShape->Width = 0.5; + physicShape->Height = 0.5; + physicShape->Depth = 0.5;*/ + ParticleData data; data.ParticleID = ent; data.SpawnTime = glfwGetTime(); @@ -123,12 +134,13 @@ void Systems::ParticleSystem::SpawnParticles(EntityID emitterID, float spawnCoun m_ParticleEmitter[emitterID].push_back(data); } - std::cout<<"Added "< From be90953f2280aef5ecf91976e0cc11a5d19a9a9d Mon Sep 17 00:00:00 2001 From: ViktorLjung Date: Thu, 24 Apr 2014 23:29:28 +0200 Subject: [PATCH 11/65] Rigidbody position not updating in debug FIXED --- src/Systems/PhysicsSystem.cpp | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/src/Systems/PhysicsSystem.cpp b/src/Systems/PhysicsSystem.cpp index b275ad8..b4f8200 100644 --- a/src/Systems/PhysicsSystem.cpp +++ b/src/Systems/PhysicsSystem.cpp @@ -143,13 +143,10 @@ void Systems::PhysicsSystem::UpdateEntity(double dt, EntityID entity, EntityID p } else if(m_RigidBodies.find(entity) != m_RigidBodies.end()) { - if(m_RigidBodies[entity]->isActive()) - { - hkVector4 position = m_RigidBodies[entity]->getPosition(); - transformComponent->Position = glm::vec3(position(0), position(1), position(2)); - hkQuaternion orientation = m_RigidBodies[entity]->getRotation(); - transformComponent->Orientation = glm::quat(orientation(3),orientation(0), orientation(1), orientation(2)); - } + hkVector4 position = m_RigidBodies[entity]->getPosition(); + transformComponent->Position = glm::vec3(position(0), position(1), position(2)); + hkQuaternion orientation = m_RigidBodies[entity]->getRotation(); + transformComponent->Orientation = glm::quat(orientation(3),orientation(0), orientation(1), orientation(2)); } @@ -271,6 +268,7 @@ void Systems::PhysicsSystem::OnEntityCommit( EntityID entity ) { m_PhysicsWorld->addEntity(rigidBody); m_RigidBodies[entity] = rigidBody; + shape->removeReference(); rigidBody->removeReference(); } From c4e127b154ada53860b9fd3f6f07c248e450b6ef Mon Sep 17 00:00:00 2001 From: ViktorLjung Date: Thu, 24 Apr 2014 23:30:46 +0200 Subject: [PATCH 12/65] Added VehicleSetup to Physics filter. --- vs11/Returngeance/Returngeance.vcxproj.filters | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/vs11/Returngeance/Returngeance.vcxproj.filters b/vs11/Returngeance/Returngeance.vcxproj.filters index b8f30e6..dfd85bb 100755 --- a/vs11/Returngeance/Returngeance.vcxproj.filters +++ b/vs11/Returngeance/Returngeance.vcxproj.filters @@ -50,7 +50,9 @@ - + + Physics + @@ -213,7 +215,6 @@ Audio - Physics\Components @@ -226,6 +227,9 @@ Physics\Components + + Physics + From 166a9f48f1e9d3a2d7c2db5fe575272f362d18ba Mon Sep 17 00:00:00 2001 From: Stiffly Date: Fri, 25 Apr 2014 00:24:13 +0200 Subject: [PATCH 13/65] Added support for multiple emitters. (ParticleEmitter component now friend class to ParticleSystem) --- src/Components/ParticleEmitter.h | 7 +++++++ src/GameWorld.cpp | 27 ++++++++++++++++----------- src/Systems/ParticleSystem.cpp | 26 +++++++++++++------------- src/Systems/ParticleSystem.h | 4 ++-- 4 files changed, 38 insertions(+), 26 deletions(-) diff --git a/src/Components/ParticleEmitter.h b/src/Components/ParticleEmitter.h index 9f5e20f..46ad8fb 100755 --- a/src/Components/ParticleEmitter.h +++ b/src/Components/ParticleEmitter.h @@ -5,11 +5,15 @@ #include "Color.h" #include +namespace Systems { class ParticleSystem; } + namespace Components { struct ParticleEmitter : Component { + friend class Systems::ParticleSystem; + EntityID ParticleTemplate; float SpawnFrequency; int SpawnCount; @@ -19,6 +23,9 @@ struct ParticleEmitter : Component double LifeTime; std::vector VelocitySpectrum; std::vector AngularVelocitySpectrum; + +private: + double TimeSinceLastSpawn; }; } diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index d11cce1..be62e0a 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -77,7 +77,7 @@ void GameWorld::Initialize() auto model = AddComponent(ball, "Model"); model->ModelFile = "Models/Placeholders/PhysicsTest/Sphere.obj"; auto sphere = AddComponent(ball, "Sphere"); - sphere->Radius = 0.5; + sphere->Radius = 0.05; auto physics = AddComponent(ball, "Physics"); physics->Mass = 1; } @@ -92,16 +92,21 @@ void GameWorld::Initialize() }*/ { - // Particle emitter - auto ent = CreateEntity(); - auto transform = AddComponent(ent, "Transform"); - transform->Position = glm::vec3(0); - auto emitter = AddComponent(ent, "ParticleEmitter"); - emitter->LifeTime = 4; - emitter->SpawnCount = 1; - emitter->SpreadAngle = 35; - emitter->SpawnFrequency = 0.05; - //emitter-> + for(int i = 0; i < 4 ; i++) + { + // Particle emitter + auto ent = CreateEntity(); + auto transform = AddComponent(ent, "Transform"); + transform->Position = glm::vec3(i * 10, 20, 0); + auto emitter = AddComponent(ent, "ParticleEmitter"); + emitter->LifeTime = 2; + emitter->SpawnCount = 1; + emitter->SpreadAngle = 35; + emitter->SpawnFrequency = 2; + auto model = AddComponent(ent, "Model"); + model->ModelFile = "Models/Placeholders/PhysicsTest/PointLight.obj"; + //emitter-> + } } } diff --git a/src/Systems/ParticleSystem.cpp b/src/Systems/ParticleSystem.cpp index 7cdec83..22075bc 100644 --- a/src/Systems/ParticleSystem.cpp +++ b/src/Systems/ParticleSystem.cpp @@ -6,12 +6,12 @@ Systems::ParticleSystem::ParticleSystem(World *m_World) : System(m_World) { - m_TimeSinceLastSpawn = 0; + } void Systems::ParticleSystem::Update(double dt) { - m_TimeSinceLastSpawn += dt; + } void Systems::ParticleSystem::UpdateEntity(double dt, EntityID entity, EntityID parent) @@ -23,14 +23,13 @@ void Systems::ParticleSystem::UpdateEntity(double dt, EntityID entity, EntityID auto emitterComponent = m_World->GetComponent(entity, "ParticleEmitter"); if(emitterComponent) { - if(m_TimeSinceLastSpawn > emitterComponent->SpawnFrequency) + emitterComponent->TimeSinceLastSpawn += dt; + + auto transformComponent = m_World->GetComponent(entity, "Transform"); + if(emitterComponent->TimeSinceLastSpawn > emitterComponent->SpawnFrequency) { - //if(m_ParticleEmitter[entity].size() < 100) // TEMP - { - SpawnParticles(entity, emitterComponent->SpawnCount, emitterComponent->SpreadAngle); - m_TimeSinceLastSpawn = 0; - } - //std::cout<<"Particle count: "<Position, emitterComponent->SpawnCount, emitterComponent->SpreadAngle); + emitterComponent->TimeSinceLastSpawn = 0; } std::list::iterator it; @@ -54,7 +53,7 @@ void Systems::ParticleSystem::UpdateEntity(double dt, EntityID entity, EntityID } auto transformComponent = m_World->GetComponent(particleID, "Transform"); - float speed = 10 * dt; + float speed = 20 * dt; transformComponent->Position.x += it->Direction.x * speed; transformComponent->Position.y += it->Direction.y * speed; transformComponent->Position.z += it->Direction.z * speed; @@ -92,14 +91,16 @@ void Systems::ParticleSystem::RegisterComponents(ComponentFactory* cf) cf->Register("Particle", []() { return new Components::Particle(); }); } -void Systems::ParticleSystem::SpawnParticles(EntityID emitterID, float spawnCount, float spreadAngle) +void Systems::ParticleSystem::SpawnParticles(EntityID emitterID, glm::vec3 pos, float spawnCount, float spreadAngle) { for(int i = 0; i < spawnCount; i++) { auto ent = m_World->CreateEntity(); auto transform = m_World->AddComponent(ent, "Transform"); - transform->Position = glm::vec3(0, 20, 0); + transform->Position.x = pos.x; + transform->Position.y = pos.y; + transform->Position.z = pos.z; transform->Scale = glm::vec3(1, 1, 0); auto particle = m_World->AddComponent(ent, "Particle"); @@ -134,7 +135,6 @@ void Systems::ParticleSystem::SpawnParticles(EntityID emitterID, float spawnCoun m_ParticleEmitter[emitterID].push_back(data); } - //std::cout<<"Added "<> m_ParticleEmitter; - double m_TimeSinceLastSpawn; + std::map m_TimeSinceLastSpawn; }; From f02954a62c3dc1bf1d6ac72d48eb1fc1213694c4 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Fri, 25 Apr 2014 01:05:53 +0200 Subject: [PATCH 14/65] Box and Sphere components renamed to BoxShape and SphereShape --- src/Components/{Box.h => BoxShape.h} | 4 ++-- src/Components/{Sphere.h => SphereShape.h} | 4 ++-- src/GameWorld.cpp | 10 +++------- src/GameWorld.h | 4 ++-- src/Systems/PhysicsSystem.cpp | 12 ++++++------ src/Systems/PhysicsSystem.h | 4 ++-- vs11/Returngeance/Returngeance.vcxproj | 4 ++-- vs11/Returngeance/Returngeance.vcxproj.filters | 12 ++++++------ 8 files changed, 25 insertions(+), 29 deletions(-) rename src/Components/{Box.h => BoxShape.h} (85%) rename src/Components/{Sphere.h => SphereShape.h} (80%) diff --git a/src/Components/Box.h b/src/Components/BoxShape.h similarity index 85% rename from src/Components/Box.h rename to src/Components/BoxShape.h index b9ddea7..dc836ec 100644 --- a/src/Components/Box.h +++ b/src/Components/BoxShape.h @@ -6,9 +6,9 @@ namespace Components { -struct Box : Component +struct BoxShape : Component { - Box() + BoxShape() : Width(1.f), Height(1.f), Depth(1.f){ } float Width; diff --git a/src/Components/Sphere.h b/src/Components/SphereShape.h similarity index 80% rename from src/Components/Sphere.h rename to src/Components/SphereShape.h index 2d089dd..afc717b 100644 --- a/src/Components/Sphere.h +++ b/src/Components/SphereShape.h @@ -6,9 +6,9 @@ namespace Components { -struct Sphere : Component +struct SphereShape : Component { - Sphere() + SphereShape() : Radius(1.f){ } float Radius; diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index 7926dcb..da3c1c8 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -21,7 +21,7 @@ void GameWorld::Initialize() transform->Orientation = glm::quat(glm::vec3(0.0f, 0.0f, 0.0f)); auto model = AddComponent(ground, "Model"); model->ModelFile = "Models/Placeholders/PhysicsTest/Cube.obj"; - auto box = AddComponent(ground, "Box"); + auto box = AddComponent(ground, "BoxShape"); box->Width = 200; box->Height = 5; box->Depth = 200; @@ -41,7 +41,7 @@ void GameWorld::Initialize() auto physics = AddComponent(jeep, "Physics"); physics->Mass = 1200; - auto box = AddComponent(jeep, "Box"); + auto box = AddComponent(jeep, "BoxShape"); box->Width = 1.487f; box->Height = 0.727f; box->Depth = 2.594f; @@ -239,7 +239,7 @@ void GameWorld::Initialize() auto physics = AddComponent(cube, "Physics"); physics->Mass = 100; - auto box = AddComponent(cube, "Box"); + auto box = AddComponent(cube, "BoxShape"); box->Width = 0.5f; box->Height = 0.5f; box->Depth = 0.5f; @@ -266,10 +266,6 @@ void GameWorld::RegisterComponents() { m_ComponentFactory.Register("Transform", []() { return new Components::Transform(); }); m_ComponentFactory.Register("Template", []() { return new Components::Template(); }); - m_ComponentFactory.Register("Sphere", []() { return new Components::Sphere(); }); - m_ComponentFactory.Register("Box", []() { return new Components::Box (); }); - m_ComponentFactory.Register("Vehicle", []() { return new Components::Vehicle(); }); - m_ComponentFactory.Register("Wheel", []() { return new Components::Wheel(); }); } void GameWorld::RegisterSystems() diff --git a/src/GameWorld.h b/src/GameWorld.h index 1e0f4a1..673358c 100755 --- a/src/GameWorld.h +++ b/src/GameWorld.h @@ -27,8 +27,8 @@ #include "Components/Transform.h" #include "Components/Physics.h" -#include "Components/Sphere.h" -#include "Components/Box.h" +#include "Components/SphereShape.h" +#include "Components/BoxShape.h" #include "Components/Vehicle.h" #include "Components/Wheel.h" diff --git a/src/Systems/PhysicsSystem.cpp b/src/Systems/PhysicsSystem.cpp index b4f8200..1f27e69 100644 --- a/src/Systems/PhysicsSystem.cpp +++ b/src/Systems/PhysicsSystem.cpp @@ -63,8 +63,8 @@ Systems::PhysicsSystem::PhysicsSystem(World* world) : System(world) void Systems::PhysicsSystem::RegisterComponents(ComponentFactory* cf) { cf->Register("Physics", []() { return new Components::Physics(); }); - cf->Register("Box", []() { return new Components::Box(); }); - cf->Register("Sphere", []() { return new Components::Sphere(); }); + cf->Register("BoxShape", []() { return new Components::BoxShape(); }); + cf->Register("SphereShape", []() { return new Components::SphereShape(); }); cf->Register("Vehicle", []() { return new Components::Vehicle(); }); cf->Register("Wheel", []() { return new Components::Wheel(); }); } @@ -181,8 +181,8 @@ void Systems::PhysicsSystem::OnEntityCommit( EntityID entity ) if (!physicsComponent) return; - auto sphereComponent = m_World->GetComponent(entity, "Sphere"); - auto boxComponent = m_World->GetComponent(entity, "Box"); + auto sphereComponent = m_World->GetComponent(entity, "SphereShape"); + auto boxComponent = m_World->GetComponent(entity, "BoxShape"); hkpConvexShape* shape; @@ -285,8 +285,8 @@ void Systems::PhysicsSystem::SetUpPhysicsState(EntityID entity, EntityID parent) if (!physicsComponent) return; - auto sphereComponent = m_World->GetComponent(entity, "Sphere"); - auto boxComponent = m_World->GetComponent(entity, "Box"); + auto sphereComponent = m_World->GetComponent(entity, "SphereShape"); + auto boxComponent = m_World->GetComponent(entity, "BoxShape"); hkpConvexShape* shape; diff --git a/src/Systems/PhysicsSystem.h b/src/Systems/PhysicsSystem.h index f5ca539..5d1af28 100644 --- a/src/Systems/PhysicsSystem.h +++ b/src/Systems/PhysicsSystem.h @@ -4,8 +4,8 @@ #include "System.h" #include "Components/Transform.h" #include "Components/Physics.h" -#include "Components/Sphere.h" -#include "Components/Box.h" +#include "Components/BoxShape.h" +#include "Components/SphereShape.h" #include "Components/Vehicle.h" #include "Components/Input.h" diff --git a/vs11/Returngeance/Returngeance.vcxproj b/vs11/Returngeance/Returngeance.vcxproj index 65ee872..8d90c02 100755 --- a/vs11/Returngeance/Returngeance.vcxproj +++ b/vs11/Returngeance/Returngeance.vcxproj @@ -121,7 +121,7 @@ - + @@ -131,7 +131,7 @@ - + diff --git a/vs11/Returngeance/Returngeance.vcxproj.filters b/vs11/Returngeance/Returngeance.vcxproj.filters index dfd85bb..9d5ff23 100755 --- a/vs11/Returngeance/Returngeance.vcxproj.filters +++ b/vs11/Returngeance/Returngeance.vcxproj.filters @@ -215,12 +215,6 @@ Audio - - Physics\Components - - - Physics\Components - Physics\Components @@ -230,6 +224,12 @@ Physics + + Physics\Components + + + Physics\Components + From 9c329145c4542818a89bb26283c8454d8a18569d Mon Sep 17 00:00:00 2001 From: Tleety Date: Fri, 25 Apr 2014 04:09:42 +0200 Subject: [PATCH 15/65] Deferred rendering base mostly complete. --- src/Renderer.cpp | 218 +++++++++++++++--------------- src/Renderer.h | 10 +- src/Shaders/First_pass.frag.glsl | 27 +++- src/Shaders/First_pass.vert.glsl | 34 ++++- src/Shaders/Second_pass.frag.glsl | 50 ++++--- src/Shaders/Second_pass.vert.glsl | 14 +- 6 files changed, 206 insertions(+), 147 deletions(-) diff --git a/src/Renderer.cpp b/src/Renderer.cpp index 50c820b..de9d6d3 100755 --- a/src/Renderer.cpp +++ b/src/Renderer.cpp @@ -115,8 +115,14 @@ void Renderer::LoadContent() m_FirstPassProgram.AddShader(std::shared_ptr(new VertexShader("Shaders/First_pass.vert.glsl"))); m_FirstPassProgram.AddShader(std::shared_ptr(new FragmentShader("Shaders/First_pass.frag.glsl"))); m_FirstPassProgram.Compile(); + BindFragDataLocation(); m_FirstPassProgram.Link(); + m_SecondPassProgram.AddShader(std::shared_ptr(new VertexShader("Shaders/Second_pass.vert.glsl"))); + m_SecondPassProgram.AddShader(std::shared_ptr(new FragmentShader("Shaders/Second_pass.frag.glsl"))); + m_SecondPassProgram.Compile(); + m_SecondPassProgram.Link(); + m_Skybox = std::make_shared("Textures/Skybox/Sunset", "jpg"); m_DebugAABB = CreateAABB(); @@ -538,137 +544,125 @@ void Renderer::ClearStuff() void Renderer::FrameBufferTextures() { m_fb = 0; - + m_fDepthBuffer = 0; + glGenFramebuffers(1, &m_fb); - GLERROR("GLERROR: Failed to generate frame buffer"); - glGenTextures(1, &m_fb_PositionTexture); - GLERROR("GLERROR: Failed to generate Position texture"); - glBindTexture(GL_TEXTURE_2D, m_fb_PositionTexture); - GLERROR("GLERROR: Failed to bind Position texture"); - glTexImage2D( - GL_TEXTURE_2D, - 0, - GL_RGB16F, - WIDTH, - HEIGHT, - 0, - GL_RGBA, - GL_UNSIGNED_BYTE, - NULL - ); - GLERROR("GLERROR: Failed to generate Position texture image"); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glGenRenderbuffers(1, &m_fDepthBuffer); + + glBindRenderbuffer(GL_RENDERBUFFER, m_fDepthBuffer); + glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, WIDTH, HEIGHT); + + //Generate and bind diffuse texture + glGenTextures(1, &m_fDiffuseTexture); + glBindTexture(GL_TEXTURE_2D, m_fDiffuseTexture); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, WIDTH, HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - GLERROR("GLERROR: Failed to generate Position Parameters"); - glGenTextures(1, &m_fb_NormalsTexture); - GLERROR("GLERROR: Failed to generate Normal texture"); - glBindTexture(GL_TEXTURE_2D, m_fb_NormalsTexture); - GLERROR("GLERROR: Failed to bind Normal texture"); - glTexImage2D( - GL_TEXTURE_2D, - 0, - GL_RGB16F, - WIDTH, - HEIGHT, - 0, - GL_RGBA, - GL_UNSIGNED_BYTE, - NULL - ); - GLERROR("GLERROR: Failed to generate Normal texture image"); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + //Generate and bind position texture + glGenTextures(1, &m_fPositionTexture); + glBindTexture(GL_TEXTURE_2D, m_fPositionTexture); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, WIDTH, HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - GLERROR("GLERROR: Failed to generate Normals Parameters"); + //Generate and bind normal texture + glGenTextures(1, &m_fNormalsTexture); + glBindTexture(GL_TEXTURE_2D, m_fNormalsTexture); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, WIDTH, HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + + //Generate and bind blend texture + glGenTextures(1, &m_fBlendTexture); + glBindTexture(GL_TEXTURE_2D, m_fBlendTexture); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, WIDTH, HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + + //Bind fb glBindFramebuffer(GL_FRAMEBUFFER, m_fb); - GLERROR("GLERROR: Failed to bind framebuffer"); - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_fb_PositionTexture, 0); - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, m_fb_NormalsTexture, 0); - GLERROR("GLERROR: Failed to FrameBufferTexture2D"); + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_fDepthBuffer); - m_rb = 0; - glGenRenderbuffers(1, &m_rb); - GLERROR("GLERROR: Failed to generate RenderBuffer"); - glBindRenderbuffer(GL_RENDERBUFFER, m_rb); - GLERROR("GLERROR: Failed to bind RenderBuffer"); - glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, WIDTH, HEIGHT); - glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_rb); - - draw_bufs[1] = GL_COLOR_ATTACHMENT0; - draw_bufs[2] = GL_COLOR_ATTACHMENT1; - + //Attach textures to the FB + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_fDiffuseTexture, 0); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, m_fPositionTexture, 0); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, m_fNormalsTexture, 0); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3, GL_TEXTURE_2D, m_fBlendTexture, 0); + GLenum fbStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER); + if(fbStatus != GL_FRAMEBUFFER_COMPLETE) + { + printf("DeferredLighting:Init: FrameBuffer incomplete: 0x%x\n", fbStatus); + exit(1); + } + + glBindFramebuffer(GL_FRAMEBUFFER, 0); } void Renderer::DrawFBO() { + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fb); + + GLenum windowBuffClear[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3 }; + glDrawBuffers(4, windowBuffClear); + glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - glBindFramebuffer(GL_FRAMEBUFFER, m_fb); - glEnable(GL_DEPTH_TEST); - glEnable(GL_CULL_FACE); - glCullFace(GL_BACK); -#ifdef DEBUG - glDisable(GL_CULL_FACE); - glPolygonMode(GL_BACK, GL_LINE); -#endif - // Draw models - glm::mat4 depthViewMatrix = glm::lookAt(m_SunPosition, m_SunTarget, glm::vec3(0, 1, 0)) * glm::translate(-m_Camera->Position() * glm::vec3(1, 0, 0)); - glm::mat4 depthCamera = m_SunProjection * depthViewMatrix; - glm::mat4 biasMatrix( - 0.5, 0.0, 0.0, 0.0, - 0.0, 0.5, 0.0, 0.0, - 0.0, 0.0, 0.5, 0.0, - 0.5, 0.5, 0.5, 1.0 - ); + // Execute the first render stage which will fill out the internal buffers with data(??) + //EnableRenderProgramStage1; + GLenum windowBuffOpaque[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_NONE }; + glDrawBuffers(4, windowBuffOpaque); + //DrawTheWorld(); - m_ShaderProgram.Bind(); - if (m_DrawWireframe) - { - glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); - } - glm::mat4 cameraMatrix = m_Camera->ProjectionMatrix() * m_Camera->ViewMatrix(); - glm::mat4 depthCameraMatrix = biasMatrix * depthCamera; - glm::mat4 MVP; - glm::mat4 depthMVP; - for (auto tuple : ModelsToRender) - { - Model* model; - glm::mat4 modelMatrix; - bool visible; - std::tie(model, modelMatrix, visible, std::ignore) = tuple; - if (!visible) - continue; + GLenum windowBuffTransp[] = { GL_NONE, GL_NONE, GL_NONE, GL_COLOR_ATTACHMENT3 }; + glDrawBuffers(4, windowBuffTransp); + glEnable(GL_BLEND); + glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + //Depth buffer shall not be updated + glDepthMask(GL_FALSE); + //DrawTransparent items + glDepthMask(GL_TRUE); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glDisable(GL_BLEND); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); - MVP = cameraMatrix * modelMatrix; - depthMVP = depthCameraMatrix * modelMatrix; - glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "M"), 1, GL_FALSE, glm::value_ptr(modelMatrix)); - glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "V"), 1, GL_FALSE, glm::value_ptr( m_Camera->ViewMatrix())); - glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "P"), 1, GL_FALSE, glm::value_ptr(m_Camera->ProjectionMatrix())); - glBindVertexArray(model->VAO); -// for (auto texGroup : model->TextureGroups) -// { -// glActiveTexture(GL_TEXTURE0); -// glBindTexture(GL_TEXTURE_2D, *texGroup.Texture); -// glDrawArrays(GL_TRIANGLES, texGroup.StartIndex, texGroup.EndIndex - texGroup.StartIndex + 1); -// } - } + //Probably means to use the second_pass shader + //EnableRenderProgramDeferredStage(); -#ifdef DEBUG - // Debug draw model normals - if (m_DrawNormals) - { - m_ShaderProgramNormals.Bind(); - glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); - DrawModels(m_ShaderProgramNormals); - } -#endif + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); + //SetupDefferedStageUniforms(); // Probably what we do in FrameBufferTextures(); + //glEnableVertexAttribArray(fVertexIndex); // VertexIndex? + glActiveTexture(GL_TEXTURE3); + glBindTexture(GL_TEXTURE_2D, m_fBlendTexture); + + glActiveTexture(GL_TEXTURE2); + glBindTexture(GL_TEXTURE_2D, m_fNormalsTexture); + + glActiveTexture(GL_TEXTURE1); + glBindTexture(GL_TEXTURE_2D, m_fPositionTexture); + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, m_fDiffuseTexture); + + //DrawSimpleSquare(); //I guess this draw a square and put the textures on it + + //glDisableVertexAttribArray(fVertexIndex); //VertexIndex? - //glDrawBuffers(2, draw_bufs); } +void Renderer::BindFragDataLocation() +{ + glBindFragDataLocation(m_FirstPassProgram.GetHandle(), 0, "diffuseOutput"); + glBindFragDataLocation(m_FirstPassProgram.GetHandle(), 1, "posOutput"); + glBindFragDataLocation(m_FirstPassProgram.GetHandle(), 2, "normOutput"); + glBindFragDataLocation(m_FirstPassProgram.GetHandle(), 3, "blendOutput"); +} diff --git a/src/Renderer.h b/src/Renderer.h index 3243eef..d915c9c 100755 --- a/src/Renderer.h +++ b/src/Renderer.h @@ -88,16 +88,19 @@ private: GLuint m_ShadowFrameBuffer; GLuint m_ShadowDepthTexture; - GLuint m_fb_PositionTexture; - GLuint m_fb_NormalsTexture; + GLuint m_fDiffuseTexture; + GLuint m_fPositionTexture; + GLuint m_fNormalsTexture; + GLuint m_fBlendTexture; GLuint m_fb; - GLuint m_rb; + GLuint m_fDepthBuffer; GLenum draw_bufs[2]; std::shared_ptr m_Camera; ShaderProgram m_ShaderProgram; ShaderProgram m_FirstPassProgram; + ShaderProgram m_SecondPassProgram; ShaderProgram m_ShaderProgramNormals; ShaderProgram m_ShaderProgramShadows; ShaderProgram m_ShaderProgramShadowsDrawDepth; @@ -111,6 +114,7 @@ private: void CreateShadowMap(int resolution); void FrameBufferTextures(); void DrawFBO(); + void BindFragDataLocation(); GLuint CreateQuad(); void DrawDebugShadowMap(); diff --git a/src/Shaders/First_pass.frag.glsl b/src/Shaders/First_pass.frag.glsl index df66547..2f3405b 100644 --- a/src/Shaders/First_pass.frag.glsl +++ b/src/Shaders/First_pass.frag.glsl @@ -1,4 +1,27 @@ -#version 400 +#version 130 +uniform sampler2D firstTexture; +in vec3 fragmentNormal; +in vec2 fragmentTexCoord; +in vec3 position; +layout (location = 0) out vec4 diffuseOutput; +layout (location = 1) out vec4 posOutput; +layout (location = 2) out vec4 normOutput; +layout (location = 3) out vec4 blendOutput; + +void main(void) +{ + posOutput.xyz = position; + normOutPut = vec4(fragmentNormal, 0); + vec4 clr = texture(firstTexture, fragmentTexCoord); + float alpha = clr.a; + if(alpha < 0.1) + discard; //Some optimizing + blendOutput.rgb = clr.rgb * clr.a; //Pre multiplied alpha + blendOutput.a = clr.a; + diffuseOutput = clr; +} + +/*#version 400 in vec3 p_eye; in vec3 n_eye; @@ -9,4 +32,4 @@ layout (location = 1) out vec4 def_n; // "go to GL_COLOR_ATTACHMENT1" void main () { def_p = vec4(p_eye, 1.0); def_n = vec4(n_eye, 1.0); -} \ No newline at end of file +}*/ \ No newline at end of file diff --git a/src/Shaders/First_pass.vert.glsl b/src/Shaders/First_pass.vert.glsl index f6cd49c..832c0d8 100644 --- a/src/Shaders/First_pass.vert.glsl +++ b/src/Shaders/First_pass.vert.glsl @@ -1,4 +1,34 @@ -#version 400 +#version 130 + +precision mediump float; +uniform mat4 projectionMatrix; +uniform mat4 modelMatrix; +uniform mat4 viewMatrix; + +in vec3 normal; +in vec2 texCoord; +in vec3 vertex; + +in float intensity; +in float ambientLight; + +out vec3 fragmentNormal; +out vec2 fragmentTexCoord; +out float extIntensity; +out float extAmbientLight; + +void main(void) +{ + fragmentTexCoord = texCoord; + fragmentNormal = normalize((modelMatrix*vec4(normal, 0.0).xyz); + gl_Position = vec3(modelMatrix * vertex); //Copy position to the fragment shader + extIntensity = intensity/255.0; + extAmbientLight = ambientLight/255.0; +} + + + +/*#version 400 layout(location = 0) in vec3 vp; layout(location = 1) in vec3 vn; @@ -13,4 +43,4 @@ void main () { p_eye = (V * M * vec4 (vp, 1.0)).xyz; n_eye = (V * M * vec4 (vn, 0.0)).xyz; gl_Position = P * vec4 (p_eye, 1.0); -} \ No newline at end of file +}*/ \ No newline at end of file diff --git a/src/Shaders/Second_pass.frag.glsl b/src/Shaders/Second_pass.frag.glsl index 5792748..3591f9b 100644 --- a/src/Shaders/Second_pass.frag.glsl +++ b/src/Shaders/Second_pass.frag.glsl @@ -1,24 +1,32 @@ -#version 430 +#version 130 -uniform sampler2D tDiffuse; -uniform sampler2D tPosition; -uniform sampler2D tNormals; -uniform vec3 cameraPosition; +uniform sampler2D diffuseTex; // The color information +uniform sampler2D posTex; // World position +uniform sampler2D normalTex; // Normals +uniform sampler2D blendTex; // A bitmap with colors to blend with. +uniform vec3 camera; // The coordinate of the camera +in vec2 position; // The world position +layout (location = 0) out vec4 fragColor; -void main( void ) +void main(void) { - vec4 image = texture2D( tDiffuse, gl_TexCoord[0].xy ); - vec4 position = texture2D( tPosition, gl_TexCoord[0].xy ); - vec4 normal = texture2D( tNormals, gl_TexCoord[0].xy ); - - vec3 light = vec3(50,100,50); - vec3 lightDir = light - position.xyz ; - - normal = normalize(normal); - lightDir = normalize(lightDir); - - vec3 eyeDir = normalize(cameraPosition-position.xyz); - vec3 vHalfVector = normalize(lightDir.xyz+eyeDir); - - gl_FragColor = max(dot(normal,lightDir),0) * image + pow(max(dot(normal,vHalfVector),0.0), 100) * 1.5; -} + // Load data, stored in textures, from the first stage rendering. + vec4 diffuse = texture2D(diffuseTex, position.xy); + vec4 blend = texture2D(blendTex, position.xy); + vec4 worldPos = texture2D(posTex, position.xy); + vec4 normal = texture2D(normalTex, position.xy); + // Use information about lamp coordinate (not shown here), the pixel + // coordinate (worldpos.xyz), the normal of this pixel (normal.xyz) + // to compute a lighting effect. + // Use this lighting effect to update 'diffuse' + vec4 preBlend = diffuse * lamp + specularGlare; + // manual blending, using premultiplied alpha. + fragColor = blend + preBlend*(1-blend.a); +// Some debug features. Enable any of them to get a visual representation +// of an internal buffer. +// fragColor = (normal+1)/2; +// fragColor = diffuse; +// fragColor = blend; +// fragColor = worldPos; // Scaling may be needed to range [0,1] +// fragColor = lamp*vec4(1,1,1,1); +} \ No newline at end of file diff --git a/src/Shaders/Second_pass.vert.glsl b/src/Shaders/Second_pass.vert.glsl index 23a3280..3845ced 100644 --- a/src/Shaders/Second_pass.vert.glsl +++ b/src/Shaders/Second_pass.vert.glsl @@ -1,9 +1,9 @@ -#version 430 +#version 130 +in vec4 vertex; out vec2 position; -void main( void ) +void main(void) { - gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; - gl_TexCoord[0] = gl_MultiTexCoord0; - - gl_FrontColor = vec4(1.0, 1.0, 1.0, 1.0); -} + gl_Position = vertex*2-1; + gl_Position.z = 0.0; + position = vertex.xy; +} \ No newline at end of file From 956e7cab7bf8b9b10926bec4be5151d2bf3bb5bc Mon Sep 17 00:00:00 2001 From: Stiffly Date: Fri, 25 Apr 2014 04:32:15 +0200 Subject: [PATCH 16/65] BUG FIX: Iterator not increased incorrectly -> No longer a particle stuck in emitter. --- src/GameWorld.cpp | 10 ++++---- src/Systems/ParticleSystem.cpp | 43 ++++++++++++++++++---------------- src/Systems/ParticleSystem.h | 4 ++-- 3 files changed, 30 insertions(+), 27 deletions(-) diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index be62e0a..17d1a0f 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -49,7 +49,7 @@ void GameWorld::Initialize() model->ModelFile = "Models/Placeholders/tank/Chassi.obj"; } - for(int i = 0; i < 2; i++) + /*for(int i = 0; i < 2; i++) { auto light = CreateEntity(); auto transform = AddComponent(light, "Transform"); @@ -65,7 +65,7 @@ void GameWorld::Initialize() auto model = AddComponent(light, "Model"); model->ModelFile = "Models/Placeholders/PhysicsTest/PointLight.obj"; - } + }*/ for(int i = 0; i < 3; i++) { @@ -92,7 +92,7 @@ void GameWorld::Initialize() }*/ { - for(int i = 0; i < 4 ; i++) + for(int i = 0; i < 1 ; i++) { // Particle emitter auto ent = CreateEntity(); @@ -100,9 +100,9 @@ void GameWorld::Initialize() transform->Position = glm::vec3(i * 10, 20, 0); auto emitter = AddComponent(ent, "ParticleEmitter"); emitter->LifeTime = 2; - emitter->SpawnCount = 1; + emitter->SpawnCount = 3; emitter->SpreadAngle = 35; - emitter->SpawnFrequency = 2; + emitter->SpawnFrequency = 0.2; auto model = AddComponent(ent, "Model"); model->ModelFile = "Models/Placeholders/PhysicsTest/PointLight.obj"; //emitter-> diff --git a/src/Systems/ParticleSystem.cpp b/src/Systems/ParticleSystem.cpp index 22075bc..30fb6c1 100644 --- a/src/Systems/ParticleSystem.cpp +++ b/src/Systems/ParticleSystem.cpp @@ -28,14 +28,21 @@ void Systems::ParticleSystem::UpdateEntity(double dt, EntityID entity, EntityID auto transformComponent = m_World->GetComponent(entity, "Transform"); if(emitterComponent->TimeSinceLastSpawn > emitterComponent->SpawnFrequency) { - SpawnParticles(entity, transformComponent->Position, emitterComponent->SpawnCount, emitterComponent->SpreadAngle); + SpawnParticles(entity, transformComponent->Position, emitterComponent->SpawnCount, emitterComponent->SpreadAngle, emitterComponent->LifeTime); emitterComponent->TimeSinceLastSpawn = 0; } - + std::cout<<"Number of particles in list for emitter "<::iterator it; for(it = m_ParticleEmitter[entity].begin(); it != m_ParticleEmitter[entity].end();) { - EntityID particleID = it->ParticleID; + EntityID particleID = (it)->ParticleID; + auto transformComponent = m_World->GetComponent(particleID, "Transform"); + float speed = 20 * dt; + //ERROR: Direction seems to be 0 for first particle in the list... + transformComponent->Position.x += it->Direction.x * speed; + transformComponent->Position.y += it->Direction.y * speed; + transformComponent->Position.z += it->Direction.z * speed; + auto particleComponent = m_World->GetComponent(particleID, "Particle"); double timeLived = glfwGetTime() - it->SpawnTime; if(timeLived > particleComponent->LifeTime) @@ -43,8 +50,6 @@ void Systems::ParticleSystem::UpdateEntity(double dt, EntityID entity, EntityID m_World->RemoveEntity(particleID); m_ParticleEmitter[entity].erase(it); - //std::cout<<"Removed dead particle..."<GetComponent(particleID, "Transform"); - float speed = 20 * dt; - transformComponent->Position.x += it->Direction.x * speed; - transformComponent->Position.y += it->Direction.y * speed; - transformComponent->Position.z += it->Direction.z * speed; + // Interpolates the color for each color channel by the start and end value. Decides how much the color should be interpolated based on time. @@ -91,7 +92,7 @@ void Systems::ParticleSystem::RegisterComponents(ComponentFactory* cf) cf->Register("Particle", []() { return new Components::Particle(); }); } -void Systems::ParticleSystem::SpawnParticles(EntityID emitterID, glm::vec3 pos, float spawnCount, float spreadAngle) +void Systems::ParticleSystem::SpawnParticles(EntityID emitterID, glm::vec3 pos, float spawnCount, float spreadAngle, double lifeTime) { for(int i = 0; i < spawnCount; i++) { @@ -104,7 +105,7 @@ void Systems::ParticleSystem::SpawnParticles(EntityID emitterID, glm::vec3 pos, transform->Scale = glm::vec3(1, 1, 0); auto particle = m_World->AddComponent(ent, "Particle"); - particle->LifeTime = 4; + particle->LifeTime = lifeTime; /*Color startColor = {.4f, .45f, .2f}; particle->ColorSpectrum.push_back(startColor); Color endColor = {0.f, 45.f, 23.f}; @@ -117,6 +118,15 @@ void Systems::ParticleSystem::SpawnParticles(EntityID emitterID, glm::vec3 pos, auto model = m_World->AddComponent(ent, "Model"); model->ModelFile = "Models/Placeholders/PhysicsTest/Cube.obj"; + auto light = m_World->AddComponent(ent, "PointLight"); + light->Specular = glm::vec3(0.1f, 0.1f, 0.1f); + light->Diffuse = glm::vec3(1.f, 1.f, 0.f); + light->constantAttenuation = 0.03f; + light->linearAttenuation = 0.00009f; + light->quadraticAttenuation = 0.07f; + light->spotExponent = 0.0f; + + /*auto physics = m_World->AddComponent(ent, "Physics"); physics->Mass = 1; @@ -130,17 +140,10 @@ void Systems::ParticleSystem::SpawnParticles(EntityID emitterID, glm::vec3 pos, data.SpawnTime = glfwGetTime(); // data.color = particle->ColorSpectrum[0]; // data.Scale = particle->ScaleSpectrum[0]; + //Random between [-1,1] on every axis data.Direction = glm::vec3(((double)rand() / ((double)RAND_MAX + 1) * 2) -1, ((double)rand() / ((double)RAND_MAX + 1) * 2) -1, ((double)rand() / ((double)RAND_MAX + 1) * 2) -1); data.Direction = glm::normalize(data.Direction); m_ParticleEmitter[emitterID].push_back(data); } } - - -// void Systems::ParticleSystem::Draw(double dt) -// { -// -// } - - diff --git a/src/Systems/ParticleSystem.h b/src/Systems/ParticleSystem.h index 484a212..5b0ae2e 100644 --- a/src/Systems/ParticleSystem.h +++ b/src/Systems/ParticleSystem.h @@ -8,6 +8,7 @@ #include "Components/Model.h" #include "Components/Physics.h" #include "Components/Box.h" +#include "Components/PointLight.h" #include "Color.h" #include @@ -32,9 +33,8 @@ public: void Update(double dt) override; void UpdateEntity(double dt, EntityID entity, EntityID parent) override; - void Draw(double dt); private: - void SpawnParticles(EntityID emitterID, glm::vec3 pos, float spawnCount, float spreadAngle); + void SpawnParticles(EntityID emitterID, glm::vec3 pos, float spawnCount, float spreadAngle, double lifeTime); std::map> m_ParticleEmitter; std::map m_TimeSinceLastSpawn; From 023f49b0ec1738611793f8a2ca70ef79785a8967 Mon Sep 17 00:00:00 2001 From: Stiffly Date: Sun, 27 Apr 2014 00:17:21 +0200 Subject: [PATCH 17/65] Implemented support for spread angle for particle emitter. --- src/GameWorld.cpp | 18 ++++++------ src/Systems/ParticleSystem.cpp | 52 +++++++++++++++++++--------------- src/Systems/ParticleSystem.h | 6 ++-- 3 files changed, 41 insertions(+), 35 deletions(-) diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index 17d1a0f..3edaf44 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -40,14 +40,14 @@ void GameWorld::Initialize() physics->Mass = 10; } - { + /*{ auto TankTest = CreateEntity(); auto transform = AddComponent(TankTest, "Transform"); transform->Position = glm::vec3(1.5f, 0.7f, 5.f); auto model = AddComponent(TankTest, "Model"); model->ModelFile = "Models/Placeholders/tank/Chassi.obj"; - } + }*/ /*for(int i = 0; i < 2; i++) { @@ -67,7 +67,7 @@ void GameWorld::Initialize() model->ModelFile = "Models/Placeholders/PhysicsTest/PointLight.obj"; }*/ - for(int i = 0; i < 3; i++) + /*for(int i = 0; i < 3; i++) { auto ball = CreateEntity(); auto transform = AddComponent(ball, "Transform"); @@ -80,7 +80,7 @@ void GameWorld::Initialize() sphere->Radius = 0.05; auto physics = AddComponent(ball, "Physics"); physics->Mass = 1; - } + }*/ /*{ auto entity = CreateEntity(); @@ -97,15 +97,15 @@ void GameWorld::Initialize() // Particle emitter auto ent = CreateEntity(); auto transform = AddComponent(ent, "Transform"); + transform->Orientation = glm::angleAxis(glm::pi()/4, glm::vec3(0,1,0)); transform->Position = glm::vec3(i * 10, 20, 0); auto emitter = AddComponent(ent, "ParticleEmitter"); - emitter->LifeTime = 2; - emitter->SpawnCount = 3; - emitter->SpreadAngle = 35; - emitter->SpawnFrequency = 0.2; + emitter->LifeTime = 4; + emitter->SpawnCount = 4; + emitter->SpreadAngle = glm::pi()/6; + emitter->SpawnFrequency = 0.08; auto model = AddComponent(ent, "Model"); model->ModelFile = "Models/Placeholders/PhysicsTest/PointLight.obj"; - //emitter-> } } } diff --git a/src/Systems/ParticleSystem.cpp b/src/Systems/ParticleSystem.cpp index 30fb6c1..a5479f2 100644 --- a/src/Systems/ParticleSystem.cpp +++ b/src/Systems/ParticleSystem.cpp @@ -28,21 +28,18 @@ void Systems::ParticleSystem::UpdateEntity(double dt, EntityID entity, EntityID auto transformComponent = m_World->GetComponent(entity, "Transform"); if(emitterComponent->TimeSinceLastSpawn > emitterComponent->SpawnFrequency) { - SpawnParticles(entity, transformComponent->Position, emitterComponent->SpawnCount, emitterComponent->SpreadAngle, emitterComponent->LifeTime); + SpawnParticles(entity, transformComponent->Position, emitterComponent->SpawnCount, emitterComponent->SpreadAngle, emitterComponent->LifeTime, dt); emitterComponent->TimeSinceLastSpawn = 0; } - std::cout<<"Number of particles in list for emitter "<::iterator it; for(it = m_ParticleEmitter[entity].begin(); it != m_ParticleEmitter[entity].end();) { EntityID particleID = (it)->ParticleID; auto transformComponent = m_World->GetComponent(particleID, "Transform"); - float speed = 20 * dt; - //ERROR: Direction seems to be 0 for first particle in the list... - transformComponent->Position.x += it->Direction.x * speed; - transformComponent->Position.y += it->Direction.y * speed; - transformComponent->Position.z += it->Direction.z * speed; + transformComponent->Position += transformComponent->Velocity; + auto particleComponent = m_World->GetComponent(particleID, "Particle"); double timeLived = glfwGetTime() - it->SpawnTime; if(timeLived > particleComponent->LifeTime) @@ -57,9 +54,6 @@ void Systems::ParticleSystem::UpdateEntity(double dt, EntityID entity, EntityID it++; } - - - // Interpolates the color for each color channel by the start and end value. Decides how much the color should be interpolated based on time. /*// How big fraction the color is multiplied with float timeProgress = timeLived / particleComponent->LifeTime; @@ -92,20 +86,30 @@ void Systems::ParticleSystem::RegisterComponents(ComponentFactory* cf) cf->Register("Particle", []() { return new Components::Particle(); }); } -void Systems::ParticleSystem::SpawnParticles(EntityID emitterID, glm::vec3 pos, float spawnCount, float spreadAngle, double lifeTime) +void Systems::ParticleSystem::SpawnParticles(EntityID emitterID, glm::vec3 pos, float spawnCount, float spreadAngle, double lifeTime, double dt) { + auto emitterTransform = m_World->GetComponent(emitterID, "Transform"); + glm::quat emitterOrientation = emitterTransform->Orientation; + float tempSpeed = 5 * dt; + glm::vec3 speed = glm::vec3(tempSpeed); for(int i = 0; i < spawnCount; i++) { auto ent = m_World->CreateEntity(); - auto transform = m_World->AddComponent(ent, "Transform"); - transform->Position.x = pos.x; - transform->Position.y = pos.y; - transform->Position.z = pos.z; - transform->Scale = glm::vec3(1, 1, 0); - + auto particleTransform = m_World->AddComponent(ent, "Transform"); + particleTransform->Position.x = pos.x; + particleTransform->Position.y = pos.y; + particleTransform->Position.z = pos.z; + particleTransform->Scale = glm::vec3(1, 1, 1); + //The emitter's orientation as "start value" times the default direction for quaternion. Times the speed, and then rotate on x and y axis with the randomized spread angle. + particleTransform->Velocity = emitterOrientation * glm::vec3(0, 0, -1) * speed * + glm::normalize(glm::angleAxis(RandomizeAngle(spreadAngle), glm::vec3(1, 0, 0))) * + glm::normalize(glm::angleAxis(RandomizeAngle(spreadAngle), glm::vec3(0, 1, 0))); + + auto particle = m_World->AddComponent(ent, "Particle"); particle->LifeTime = lifeTime; + /*Color startColor = {.4f, .45f, .2f}; particle->ColorSpectrum.push_back(startColor); Color endColor = {0.f, 45.f, 23.f}; @@ -116,15 +120,15 @@ void Systems::ParticleSystem::SpawnParticles(EntityID emitterID, glm::vec3 pos, particle->VelocitySpectrum.push_back(glm::vec3(0, -3, 0));*/ auto model = m_World->AddComponent(ent, "Model"); - model->ModelFile = "Models/Placeholders/PhysicsTest/Cube.obj"; + model->ModelFile = "Models/Placeholders/PhysicsTest/PointLight.obj"; - auto light = m_World->AddComponent(ent, "PointLight"); + /*auto light = m_World->AddComponent(ent, "PointLight"); light->Specular = glm::vec3(0.1f, 0.1f, 0.1f); light->Diffuse = glm::vec3(1.f, 1.f, 0.f); light->constantAttenuation = 0.03f; light->linearAttenuation = 0.00009f; light->quadraticAttenuation = 0.07f; - light->spotExponent = 0.0f; + light->spotExponent = 0.0f;*/ /*auto physics = m_World->AddComponent(ent, "Physics"); @@ -140,10 +144,12 @@ void Systems::ParticleSystem::SpawnParticles(EntityID emitterID, glm::vec3 pos, data.SpawnTime = glfwGetTime(); // data.color = particle->ColorSpectrum[0]; // data.Scale = particle->ScaleSpectrum[0]; - //Random between [-1,1] on every axis - data.Direction = glm::vec3(((double)rand() / ((double)RAND_MAX + 1) * 2) -1, ((double)rand() / ((double)RAND_MAX + 1) * 2) -1, ((double)rand() / ((double)RAND_MAX + 1) * 2) -1); - data.Direction = glm::normalize(data.Direction); m_ParticleEmitter[emitterID].push_back(data); } } + +float Systems::ParticleSystem::RandomizeAngle(float spreadAngle) +{ + return ((float)rand() / ((float)RAND_MAX + 1) * spreadAngle) - spreadAngle/2; +} \ No newline at end of file diff --git a/src/Systems/ParticleSystem.h b/src/Systems/ParticleSystem.h index 5b0ae2e..059eb2f 100644 --- a/src/Systems/ParticleSystem.h +++ b/src/Systems/ParticleSystem.h @@ -21,8 +21,6 @@ namespace Systems double SpawnTime; float Scale; Color color; - glm::vec3 Velocity; - glm::vec3 Direction; }; class ParticleSystem : public System @@ -34,9 +32,11 @@ public: void Update(double dt) override; void UpdateEntity(double dt, EntityID entity, EntityID parent) override; private: - void SpawnParticles(EntityID emitterID, glm::vec3 pos, float spawnCount, float spreadAngle, double lifeTime); + void SpawnParticles(EntityID emitterID, glm::vec3 pos, float spawnCount, float spreadAngle, double lifeTime, double dt); std::map> m_ParticleEmitter; std::map m_TimeSinceLastSpawn; + + float RandomizeAngle(float spreadAngle); }; From 87cac66cd8222b7417c71f74f7bd4a0a1877c625 Mon Sep 17 00:00:00 2001 From: Tleety Date: Sun, 27 Apr 2014 02:44:04 +0200 Subject: [PATCH 18/65] Basic working deferred rendering --- src/GameWorld.cpp | 2 +- src/Renderer.cpp | 277 ++++++++++++------ src/Renderer.h | 3 +- src/ShaderProgram.cpp | 7 +- src/ShaderProgram.h | 2 +- src/Shaders/First_pass.frag.glsl | 35 --- src/Shaders/First_pass.vert.glsl | 46 --- src/Shaders/Fragment.glsl | 107 +------ src/Shaders/Fragment2.glsl | 19 ++ src/Shaders/Second_pass.frag.glsl | 32 -- src/Shaders/Second_pass.vert.glsl | 9 - src/Shaders/Vertex.glsl | 11 +- src/Shaders/Vertex2.glsl | 17 ++ vs11/Returngeance.psess | 83 ++++++ vs11/Returngeance.sln | 3 + vs11/Returngeance/Returngeance.vcxproj | 2 + .../Returngeance/Returngeance.vcxproj.filters | 14 +- 17 files changed, 344 insertions(+), 325 deletions(-) delete mode 100644 src/Shaders/First_pass.frag.glsl delete mode 100644 src/Shaders/First_pass.vert.glsl create mode 100644 src/Shaders/Fragment2.glsl delete mode 100644 src/Shaders/Second_pass.frag.glsl delete mode 100644 src/Shaders/Second_pass.vert.glsl create mode 100644 src/Shaders/Vertex2.glsl create mode 100644 vs11/Returngeance.psess diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index 62e3980..f51cddf 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -67,7 +67,7 @@ void GameWorld::Initialize() model->ModelFile = "Models/Placeholders/PhysicsTest/PointLight.obj"; } - for(int i = 0; i < 500; i++) + for(int i = 0; i < 0; i++) { auto ball = CreateEntity(); auto transform = AddComponent(ball, "Transform"); diff --git a/src/Renderer.cpp b/src/Renderer.cpp index de9d6d3..44032b0 100755 --- a/src/Renderer.cpp +++ b/src/Renderer.cpp @@ -72,13 +72,11 @@ void Renderer::Initialize() glEnable(GL_DEPTH_TEST); LoadContent(); - - FrameBufferTextures(); } void Renderer::LoadContent() { - auto standardVS = std::shared_ptr(new VertexShader("Shaders/Vertex.glsl")); + /*auto standardVS = std::shared_ptr(new VertexShader("Shaders/Vertex.glsl")); auto standardFS = std::shared_ptr(new FragmentShader("Shaders/Fragment.glsl")); m_ShaderProgram.AddShader(standardVS); @@ -110,52 +108,26 @@ void Renderer::LoadContent() m_ShaderProgramSkybox.AddShader(std::shared_ptr(new VertexShader("Shaders/Skybox.vert.glsl"))); m_ShaderProgramSkybox.AddShader(std::shared_ptr(new FragmentShader("Shaders/Skybox.frag.glsl"))); m_ShaderProgramSkybox.Compile(); - m_ShaderProgramSkybox.Link(); + m_ShaderProgramSkybox.Link();*/ - m_FirstPassProgram.AddShader(std::shared_ptr(new VertexShader("Shaders/First_pass.vert.glsl"))); - m_FirstPassProgram.AddShader(std::shared_ptr(new FragmentShader("Shaders/First_pass.frag.glsl"))); + m_FirstPassProgram.AddShader(std::shared_ptr(new VertexShader("Shaders/Vertex.glsl"))); + m_FirstPassProgram.AddShader(std::shared_ptr(new FragmentShader("Shaders/Fragment.glsl"))); m_FirstPassProgram.Compile(); - BindFragDataLocation(); + glBindFragDataLocation(m_FirstPassProgram.GetHandle(), 0, "frag_Diffuse"); + glBindFragDataLocation(m_FirstPassProgram.GetHandle(), 1, "frag_Position"); + glBindFragDataLocation(m_FirstPassProgram.GetHandle(), 2, "frag_Normal"); m_FirstPassProgram.Link(); - m_SecondPassProgram.AddShader(std::shared_ptr(new VertexShader("Shaders/Second_pass.vert.glsl"))); - m_SecondPassProgram.AddShader(std::shared_ptr(new FragmentShader("Shaders/Second_pass.frag.glsl"))); + m_SecondPassProgram.AddShader(std::shared_ptr(new VertexShader("Shaders/Vertex2.glsl"))); + m_SecondPassProgram.AddShader(std::shared_ptr(new FragmentShader("Shaders/Fragment2.glsl"))); m_SecondPassProgram.Compile(); m_SecondPassProgram.Link(); - m_Skybox = std::make_shared("Textures/Skybox/Sunset", "jpg"); - - m_DebugAABB = CreateAABB(); m_ScreenQuad = CreateQuad(); - CreateShadowMap(m_ShadowMapRes); + + FrameBufferTextures(); } -void Renderer::CreateShadowMap(int resolution) -{ - glGenFramebuffers(1, &m_ShadowFrameBuffer); - glBindFramebuffer(GL_FRAMEBUFFER, m_ShadowFrameBuffer); - - // Depth texture - glGenTextures(1, &m_ShadowDepthTexture); - glBindTexture(GL_TEXTURE_2D, m_ShadowDepthTexture); - glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, resolution, resolution, 0, GL_DEPTH_COMPONENT, GL_FLOAT, 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); - - //glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE ); - //glTexParameteri( GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE, GL_INTENSITY ); - - glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, m_ShadowDepthTexture, 0); - glDrawBuffer(GL_NONE); - - if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) - { - LOG_ERROR("Framebuffer incomplete!"); - return; - } -} void Renderer::Draw(double dt) { glDisable(GL_BLEND); @@ -550,7 +522,7 @@ void Renderer::FrameBufferTextures() glGenRenderbuffers(1, &m_fDepthBuffer); glBindRenderbuffer(GL_RENDERBUFFER, m_fDepthBuffer); - glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, WIDTH, HEIGHT); + glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, WIDTH, HEIGHT); //Generate and bind diffuse texture glGenTextures(1, &m_fDiffuseTexture); @@ -579,15 +551,6 @@ void Renderer::FrameBufferTextures() glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - //Generate and bind blend texture - glGenTextures(1, &m_fBlendTexture); - glBindTexture(GL_TEXTURE_2D, m_fBlendTexture); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, WIDTH, HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - //Bind fb glBindFramebuffer(GL_FRAMEBUFFER, m_fb); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_fDepthBuffer); @@ -596,73 +559,201 @@ void Renderer::FrameBufferTextures() glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_fDiffuseTexture, 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, m_fPositionTexture, 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, m_fNormalsTexture, 0); - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3, GL_TEXTURE_2D, m_fBlendTexture, 0); GLenum fbStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER); if(fbStatus != GL_FRAMEBUFFER_COMPLETE) { - printf("DeferredLighting:Init: FrameBuffer incomplete: 0x%x\n", fbStatus); - exit(1); + LOG_ERROR("DeferredLighting:Init: FrameBuffer incomplete: 0x%x\n", fbStatus); + //exit(1); } - - glBindFramebuffer(GL_FRAMEBUFFER, 0); } +//void Renderer::FrameBufferTextures() +//{ +// m_fb = 0; +// m_fDepthBuffer = 0; +// +// glGenFramebuffers(1, &m_fb); +// glGenRenderbuffers(1, &m_fDepthBuffer); +// +// glBindRenderbuffer(GL_RENDERBUFFER, m_fDepthBuffer); +// glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, WIDTH, HEIGHT); +// +// //Generate and bind diffuse texture +// glGenTextures(1, &m_fDiffuseTexture); +// glBindTexture(GL_TEXTURE_2D, m_fDiffuseTexture); +// glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, WIDTH, HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); +// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); +// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); +// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); +// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); +// +// //Generate and bind position texture +// glGenTextures(1, &m_fPositionTexture); +// glBindTexture(GL_TEXTURE_2D, m_fPositionTexture); +// glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, WIDTH, HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); +// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); +// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); +// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); +// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); +// +// //Generate and bind normal texture +// glGenTextures(1, &m_fNormalsTexture); +// glBindTexture(GL_TEXTURE_2D, m_fNormalsTexture); +// glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, WIDTH, HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); +// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); +// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); +// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); +// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); +// +// //Generate and bind blend texture +// glGenTextures(1, &m_fBlendTexture); +// glBindTexture(GL_TEXTURE_2D, m_fBlendTexture); +// glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, WIDTH, HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); +// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); +// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); +// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); +// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); +// +// //Bind fb +// glBindFramebuffer(GL_FRAMEBUFFER, m_fb); +// glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_fDepthBuffer); +// +// //Attach textures to the FB +// glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_fDiffuseTexture, 0); +// glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, m_fPositionTexture, 0); +// glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, m_fNormalsTexture, 0); +// glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3, GL_TEXTURE_2D, m_fBlendTexture, 0); +// +// GLenum fbStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER); +// if(fbStatus != GL_FRAMEBUFFER_COMPLETE) +// { +// printf("DeferredLighting:Init: FrameBuffer incomplete: 0x%x\n", fbStatus); +// exit(1); +// } +// +// glBindFramebuffer(GL_FRAMEBUFFER, 0); +//} + void Renderer::DrawFBO() { glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fb); - GLenum windowBuffClear[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3 }; - glDrawBuffers(4, windowBuffClear); + // Clear G-buffer + GLenum windowBuffClear[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2 }; + glDrawBuffers(3, windowBuffClear); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Execute the first render stage which will fill out the internal buffers with data(??) - //EnableRenderProgramStage1; - GLenum windowBuffOpaque[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_NONE }; - glDrawBuffers(4, windowBuffOpaque); - //DrawTheWorld(); + m_FirstPassProgram.Bind(); + GLenum windowBuffOpaque[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2 }; + glDrawBuffers(3, windowBuffOpaque); + DrawFBOScene(); - GLenum windowBuffTransp[] = { GL_NONE, GL_NONE, GL_NONE, GL_COLOR_ATTACHMENT3 }; - glDrawBuffers(4, windowBuffTransp); - glEnable(GL_BLEND); - glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); - //Depth buffer shall not be updated - glDepthMask(GL_FALSE); - //DrawTransparent items - glDepthMask(GL_TRUE); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glDisable(GL_BLEND); + // Draw to screen glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); + m_SecondPassProgram.Bind(); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - //Probably means to use the second_pass shader - //EnableRenderProgramDeferredStage(); - - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); - //SetupDefferedStageUniforms(); // Probably what we do in FrameBufferTextures(); - //glEnableVertexAttribArray(fVertexIndex); // VertexIndex? - glActiveTexture(GL_TEXTURE3); - glBindTexture(GL_TEXTURE_2D, m_fBlendTexture); - - glActiveTexture(GL_TEXTURE2); - glBindTexture(GL_TEXTURE_2D, m_fNormalsTexture); + ////SetupDefferedStageUniforms(); // Probably what we do in FrameBufferTextures(); + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, m_fDiffuseTexture); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, m_fPositionTexture); - glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_2D, m_fDiffuseTexture); - - //DrawSimpleSquare(); //I guess this draw a square and put the textures on it - - //glDisableVertexAttribArray(fVertexIndex); //VertexIndex? + glActiveTexture(GL_TEXTURE2); + glBindTexture(GL_TEXTURE_2D, m_fNormalsTexture); + glBindVertexArray(m_ScreenQuad); + glEnableVertexAttribArray(0); + glEnableVertexAttribArray(2); + glDrawArrays(GL_TRIANGLES, 0, 6); } -void Renderer::BindFragDataLocation() -{ - glBindFragDataLocation(m_FirstPassProgram.GetHandle(), 0, "diffuseOutput"); - glBindFragDataLocation(m_FirstPassProgram.GetHandle(), 1, "posOutput"); - glBindFragDataLocation(m_FirstPassProgram.GetHandle(), 2, "normOutput"); - glBindFragDataLocation(m_FirstPassProgram.GetHandle(), 3, "blendOutput"); +//void Renderer::DrawFBO() +//{ +// glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fb); +// +// GLenum windowBuffClear[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3 }; +// glDrawBuffers(4, windowBuffClear); +// glClearColor(0.0f, 0.0f, 0.0f, 0.0f); +// glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); +// +// // Execute the first render stage which will fill out the internal buffers with data(??) +// //EnableRenderProgramStage1; +// m_FirstPassProgram.Bind(); +// GLenum windowBuffOpaque[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_NONE }; +// glDrawBuffers(4, windowBuffOpaque); +// DrawFBOScene(); +// +// GLenum windowBuffTransp[] = { GL_NONE, GL_NONE, GL_NONE, GL_COLOR_ATTACHMENT3 }; +// glDrawBuffers(4, windowBuffTransp); +// glEnable(GL_BLEND); +// glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); +// //Depth buffer shall not be updated +// glDepthMask(GL_FALSE); +// //DrawTransparent items +// glDepthMask(GL_TRUE); +// glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); +// glDisable(GL_BLEND); +// +// +// glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); +// //Probably means to use the second_pass shader +// //EnableRenderProgramDeferredStage(); +// m_SecondPassProgram.Bind(); +// glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); +// //SetupDefferedStageUniforms(); // Probably what we do in FrameBufferTextures(); +// glEnableVertexAttribArray(0); +// glActiveTexture(GL_TEXTURE0); +// glBindTexture(GL_TEXTURE_2D, m_fDiffuseTexture); +// +// glActiveTexture(GL_TEXTURE1); +// glBindTexture(GL_TEXTURE_2D, m_fPositionTexture); +// +// glActiveTexture(GL_TEXTURE2); +// glBindTexture(GL_TEXTURE_2D, m_fNormalsTexture); +// +// glActiveTexture(GL_TEXTURE3); +// glBindTexture(GL_TEXTURE_2D, m_fBlendTexture); +// +// +// +// +// +// +// +// //DrawSimpleSquare(); //I guess this draw a square and put the textures on it +// glBindVertexArray(m_ScreenQuad); +// glDrawArrays(GL_TRIANGLES, 0, 6); +// glDisableVertexAttribArray(0); +// +//} + +void Renderer::DrawFBOScene() +{ + glm::mat4 cameraMatrix = m_Camera->ProjectionMatrix() * m_Camera->ViewMatrix(); + glm::mat4 MVP; + for (auto tuple : ModelsToRender) + { + Model* model; + glm::mat4 modelMatrix; + bool visible; + std::tie(model, modelMatrix, visible, std::ignore) = tuple; + if (!visible) + continue; + + MVP = cameraMatrix * modelMatrix; + glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "MVP"), 1, GL_FALSE, glm::value_ptr(MVP)); + glBindVertexArray(model->VAO); + for (auto texGroup : model->TextureGroups) + { + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, *texGroup.Texture); + glDrawArrays(GL_TRIANGLES, texGroup.StartIndex, texGroup.EndIndex - texGroup.StartIndex + 1); + } + } } + diff --git a/src/Renderer.h b/src/Renderer.h index d915c9c..2d5eab0 100755 --- a/src/Renderer.h +++ b/src/Renderer.h @@ -84,7 +84,6 @@ private: glm::mat4 m_SunProjection; GLuint m_DebugAABB; - GLuint m_ScreenQuad; GLuint m_ShadowFrameBuffer; GLuint m_ShadowDepthTexture; @@ -95,6 +94,7 @@ private: GLuint m_fb; GLuint m_fDepthBuffer; GLenum draw_bufs[2]; + GLuint m_ScreenQuad; std::shared_ptr m_Camera; @@ -114,6 +114,7 @@ private: void CreateShadowMap(int resolution); void FrameBufferTextures(); void DrawFBO(); + void DrawFBOScene(); void BindFragDataLocation(); GLuint CreateQuad(); diff --git a/src/ShaderProgram.cpp b/src/ShaderProgram.cpp index e9bd864..bd67e90 100755 --- a/src/ShaderProgram.cpp +++ b/src/ShaderProgram.cpp @@ -103,6 +103,11 @@ void ShaderProgram::AddShader(std::shared_ptr shader) void ShaderProgram::Compile() { + if (m_ShaderProgramHandle == 0) + { + m_ShaderProgramHandle = glCreateProgram(); + } + for (auto &shader : m_Shaders) { if (!shader->IsCompiled()) @@ -121,7 +126,7 @@ GLuint ShaderProgram::Link() } LOG_INFO("Linking shader program"); - m_ShaderProgramHandle = glCreateProgram(); + for (auto &shader : m_Shaders) { glAttachShader(m_ShaderProgramHandle, shader->GetHandle()); diff --git a/src/ShaderProgram.h b/src/ShaderProgram.h index 07dbf9b..a27300c 100755 --- a/src/ShaderProgram.h +++ b/src/ShaderProgram.h @@ -61,7 +61,7 @@ class ShaderProgram { public: ShaderProgram() - : m_ShaderProgramHandle(0) { } + : m_ShaderProgramHandle(0) { } ~ShaderProgram(); void AddShader(std::shared_ptr shader); diff --git a/src/Shaders/First_pass.frag.glsl b/src/Shaders/First_pass.frag.glsl deleted file mode 100644 index 2f3405b..0000000 --- a/src/Shaders/First_pass.frag.glsl +++ /dev/null @@ -1,35 +0,0 @@ -#version 130 -uniform sampler2D firstTexture; -in vec3 fragmentNormal; -in vec2 fragmentTexCoord; -in vec3 position; -layout (location = 0) out vec4 diffuseOutput; -layout (location = 1) out vec4 posOutput; -layout (location = 2) out vec4 normOutput; -layout (location = 3) out vec4 blendOutput; - -void main(void) -{ - posOutput.xyz = position; - normOutPut = vec4(fragmentNormal, 0); - vec4 clr = texture(firstTexture, fragmentTexCoord); - float alpha = clr.a; - if(alpha < 0.1) - discard; //Some optimizing - blendOutput.rgb = clr.rgb * clr.a; //Pre multiplied alpha - blendOutput.a = clr.a; - diffuseOutput = clr; -} - -/*#version 400 - -in vec3 p_eye; -in vec3 n_eye; - -layout (location = 0) out vec4 def_p; // "go to GL_COLOR_ATTACHMENT0" -layout (location = 1) out vec4 def_n; // "go to GL_COLOR_ATTACHMENT1" - -void main () { - def_p = vec4(p_eye, 1.0); - def_n = vec4(n_eye, 1.0); -}*/ \ No newline at end of file diff --git a/src/Shaders/First_pass.vert.glsl b/src/Shaders/First_pass.vert.glsl deleted file mode 100644 index 832c0d8..0000000 --- a/src/Shaders/First_pass.vert.glsl +++ /dev/null @@ -1,46 +0,0 @@ -#version 130 - -precision mediump float; -uniform mat4 projectionMatrix; -uniform mat4 modelMatrix; -uniform mat4 viewMatrix; - -in vec3 normal; -in vec2 texCoord; -in vec3 vertex; - -in float intensity; -in float ambientLight; - -out vec3 fragmentNormal; -out vec2 fragmentTexCoord; -out float extIntensity; -out float extAmbientLight; - -void main(void) -{ - fragmentTexCoord = texCoord; - fragmentNormal = normalize((modelMatrix*vec4(normal, 0.0).xyz); - gl_Position = vec3(modelMatrix * vertex); //Copy position to the fragment shader - extIntensity = intensity/255.0; - extAmbientLight = ambientLight/255.0; -} - - - -/*#version 400 - -layout(location = 0) in vec3 vp; -layout(location = 1) in vec3 vn; -layout(location = 2) in vec2 TextureCoord; - -uniform mat4 P, V, M; - -out vec3 p_eye; -out vec3 n_eye; - -void main () { - p_eye = (V * M * vec4 (vp, 1.0)).xyz; - n_eye = (V * M * vec4 (vn, 0.0)).xyz; - gl_Position = P * vec4 (p_eye, 1.0); -}*/ \ No newline at end of file diff --git a/src/Shaders/Fragment.glsl b/src/Shaders/Fragment.glsl index 11a43ab..7aa72d7 100755 --- a/src/Shaders/Fragment.glsl +++ b/src/Shaders/Fragment.glsl @@ -1,113 +1,26 @@ #version 430 -uniform mat4 model; -uniform mat4 view; - -layout(binding=0) uniform sampler2D texture0; -layout(binding=1) uniform sampler2D shadowMap; - -const int maxNumberOfLights = 82; -uniform int numberOfLights; -uniform vec3 position[maxNumberOfLights]; -uniform vec3 specular[maxNumberOfLights]; -uniform vec3 diffuse[maxNumberOfLights]; -uniform float constantAttenuation[maxNumberOfLights]; -uniform float linearAttenuation[maxNumberOfLights]; -uniform float quadraticAttenuation[maxNumberOfLights]; -uniform float spotExponent[maxNumberOfLights]; +layout (binding=0) uniform sampler2D DiffuseTexture; in VertexData { vec3 Position; vec3 Normal; vec2 TextureCoord; - vec3 ShadowCoord; } Input; -vec3 scene_ambient = vec3(0.5, 0.5, 0.5); - -out vec4 fragmentColor; +out vec4 frag_Diffuse; +out vec4 frag_Position; +out vec4 frag_Normal; void main() { + // Diffuse Texture + frag_Diffuse = texture2D(DiffuseTexture, Input.TextureCoord); - // Texture - vec4 texel = texture2D(texture0, Input.TextureCoord); - //vec4 texel = (blend.x * texel0) + (blend.y * texel1) + (blend.z * texel2); + // G-buffer Position + frag_Position = vec4(Input.Position.xy, 0.0, 0.0); - // - // Phong shading - // - - // Ambient light - vec3 La = scene_ambient; // Ambient light - vec3 Ks = vec3(0.3, 0.3, 0.3); // Specular reflectance - vec3 Kd = vec3(1.0, 1.0, 1.0); // Diffuse reflectance - vec3 Ka = vec3(1.0, 1.0, 1.0); // Ambient reflectance - vec3 Is; - vec3 Id; - - // Shadows - //float cosTheta = clamp(dot(Input.Normal, vec3(0, 1, 0)), 0.0, 1.0); - //float bias = 0.001 * tan(acos(cosTheta)); // cosTheta is dot( n,l ), clamped between 0 and 1 - //bias = clamp(bias, 0.0, 0.01); - float visibility = 1.0; - if (Input.ShadowCoord.x >= 0.0 && Input.ShadowCoord.x <= 1.0 && Input.ShadowCoord.y >= 0.0 && Input.ShadowCoord.y <= 1.0) - { - float bias = 0.00005; - vec4 shadowMapValue = texture(shadowMap, Input.ShadowCoord.xy); - if (shadowMapValue.z < clamp(Input.ShadowCoord.z - bias, 0, 1)) - { - visibility = 0.3; - } - } - - vec3 totalLighting = La * Ka * visibility; - - float attenuation; - - for(int i = 0; i < numberOfLights && i < maxNumberOfLights; i++) - { - // Light - //vec3 lightPosition = vec3(0, 0, 2); - vec3 Ls = specular[i]; // Specular light - vec3 Ld = diffuse[i]; // Diffuse light - - vec3 lightPosView = vec3(view * vec4(position[i], 1.0)); - vec3 surfacePosition = vec3(model * vec4(Input.Position, 1.0)); - vec3 surfacePosView = vec3(view * vec4(surfacePosition, 1.0)); - vec3 surfaceToLight = normalize(lightPosView - surfacePosView); - mat3 normalMatrix = transpose(inverse(mat3(view * model))); - vec3 surfaceNormal = normalize(normalMatrix * Input.Normal); - - float dist = length(position[i] - surfacePosition); - - attenuation = 1.0 / (constantAttenuation[i] - + linearAttenuation[i] * dist - + quadraticAttenuation[i] * pow(dist, 2.0)); - //attenuation = attenuation * pow(clampedCosine, spotExponent[i]); - - // Diffuse light - float dotProd = dot(surfaceToLight, surfaceNormal); - dotProd = max(dotProd, 0.0); - - Id = Ld * Kd * abs(dotProd) * attenuation; - - // Specular light - vec3 reflection = reflect(-surfaceToLight, surfaceNormal); - float dotSpecular = dot(reflection, normalize(-surfacePosView)); - dotSpecular = max(dotSpecular, 0.0); - float specularFactor = pow(dotSpecular, 30.0); // Specular factor - - Is = attenuation * Ls * Ks * specularFactor; - - totalLighting = totalLighting + Id + Is; - } - - fragmentColor = vec4(totalLighting, 1.0) * texel; - - - //fragmentColor = vec4(Id, 1.0) * texel; - - //fragmentColor = texel; + // G-buffer Normal + frag_Normal = vec4(Input.Normal, 0.0); } \ No newline at end of file diff --git a/src/Shaders/Fragment2.glsl b/src/Shaders/Fragment2.glsl new file mode 100644 index 0000000..cbc905e --- /dev/null +++ b/src/Shaders/Fragment2.glsl @@ -0,0 +1,19 @@ +#version 430 + +layout (binding=0) uniform sampler2D DiffuseTexture; +layout (binding=1) uniform sampler2D PositionTexture; +layout (binding=2) uniform sampler2D NormalTexture; + +in VertexData +{ + vec3 Position; + vec3 Normal; + vec2 TextureCoord; +} Input; + +out vec4 FragColor; + +void main() +{ + FragColor = texture2D(DiffuseTexture, Input.TextureCoord); +} \ No newline at end of file diff --git a/src/Shaders/Second_pass.frag.glsl b/src/Shaders/Second_pass.frag.glsl deleted file mode 100644 index 3591f9b..0000000 --- a/src/Shaders/Second_pass.frag.glsl +++ /dev/null @@ -1,32 +0,0 @@ -#version 130 - -uniform sampler2D diffuseTex; // The color information -uniform sampler2D posTex; // World position -uniform sampler2D normalTex; // Normals -uniform sampler2D blendTex; // A bitmap with colors to blend with. -uniform vec3 camera; // The coordinate of the camera -in vec2 position; // The world position -layout (location = 0) out vec4 fragColor; - -void main(void) -{ - // Load data, stored in textures, from the first stage rendering. - vec4 diffuse = texture2D(diffuseTex, position.xy); - vec4 blend = texture2D(blendTex, position.xy); - vec4 worldPos = texture2D(posTex, position.xy); - vec4 normal = texture2D(normalTex, position.xy); - // Use information about lamp coordinate (not shown here), the pixel - // coordinate (worldpos.xyz), the normal of this pixel (normal.xyz) - // to compute a lighting effect. - // Use this lighting effect to update 'diffuse' - vec4 preBlend = diffuse * lamp + specularGlare; - // manual blending, using premultiplied alpha. - fragColor = blend + preBlend*(1-blend.a); -// Some debug features. Enable any of them to get a visual representation -// of an internal buffer. -// fragColor = (normal+1)/2; -// fragColor = diffuse; -// fragColor = blend; -// fragColor = worldPos; // Scaling may be needed to range [0,1] -// fragColor = lamp*vec4(1,1,1,1); -} \ No newline at end of file diff --git a/src/Shaders/Second_pass.vert.glsl b/src/Shaders/Second_pass.vert.glsl deleted file mode 100644 index 3845ced..0000000 --- a/src/Shaders/Second_pass.vert.glsl +++ /dev/null @@ -1,9 +0,0 @@ -#version 130 -in vec4 vertex; out vec2 position; - -void main(void) -{ - gl_Position = vertex*2-1; - gl_Position.z = 0.0; - position = vertex.xy; -} \ No newline at end of file diff --git a/src/Shaders/Vertex.glsl b/src/Shaders/Vertex.glsl index 295d523..6254b60 100755 --- a/src/Shaders/Vertex.glsl +++ b/src/Shaders/Vertex.glsl @@ -1,26 +1,23 @@ #version 430 uniform mat4 MVP; -uniform mat4 DepthMVP; -layout(location = 0) in vec3 Position; -layout(location = 1) in vec3 Normal; -layout(location = 2) in vec2 TextureCoord; +layout (location = 0) in vec3 Position; +layout (location = 1) in vec3 Normal; +layout (location = 2) in vec2 TextureCoord; out VertexData { vec3 Position; vec3 Normal; vec2 TextureCoord; - vec3 ShadowCoord; } Output; void main() { gl_Position = MVP * vec4(Position, 1.0); - Output.Position = Position; + Output.Position = gl_Position.xyz; Output.Normal = Normal; Output.TextureCoord = TextureCoord; - Output.ShadowCoord = vec3(DepthMVP * vec4(Position, 1.0)); } \ No newline at end of file diff --git a/src/Shaders/Vertex2.glsl b/src/Shaders/Vertex2.glsl new file mode 100644 index 0000000..e866f94 --- /dev/null +++ b/src/Shaders/Vertex2.glsl @@ -0,0 +1,17 @@ +#version 430 + +layout (location = 0) in vec3 Position; +layout (location = 2) in vec2 TextureCoord; + +out VertexData +{ + vec3 Position; + vec2 TextureCoord; +} Output; + +void main() +{ + gl_Position = vec4(Position, 1.0); + Output.Position = Position; + Output.TextureCoord = TextureCoord; +} \ No newline at end of file diff --git a/vs11/Returngeance.psess b/vs11/Returngeance.psess new file mode 100644 index 0000000..1912c4c --- /dev/null +++ b/vs11/Returngeance.psess @@ -0,0 +1,83 @@ + + + + Returngeance.sln + Sampling + None + true + true + Timestamp + Cycles + 10000000 + 10 + 10 + + false + + + + false + 500 + + \Memory\Pages/sec + \PhysicalDisk(_Total)\Avg. Disk Queue Length + \Processor(_Total)\% Processor Time + + + + true + false + false + + false + + + false + + + + bin\Debug\Returngeance.exe + 01/01/0001 00:00:00 + true + true + false + false + false + false + false + true + false + Executable + bin\Debug\Returngeance.exe + ..\bin\Debug + + + IIS + InternetExplorer + true + false + + false + + + false + + {E8B4A2A2-882B-402A-98A7-8B4F7233C8B3}|Returngeance\Returngeance.vcxproj + Returngeance\Returngeance.vcxproj + Returngeance + + + + + Returngeance140427.vsp + + + Returngeance140427(1).vsp + + + + + :PB:{E8B4A2A2-882B-402A-98A7-8B4F7233C8B3}|Returngeance\Returngeance.vcxproj + + + \ No newline at end of file diff --git a/vs11/Returngeance.sln b/vs11/Returngeance.sln index 10ce52b..8daf9b5 100644 --- a/vs11/Returngeance.sln +++ b/vs11/Returngeance.sln @@ -39,4 +39,7 @@ Global GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection + GlobalSection(Performance) = preSolution + HasPerformanceSessions = true + EndGlobalSection EndGlobal diff --git a/vs11/Returngeance/Returngeance.vcxproj b/vs11/Returngeance/Returngeance.vcxproj index 46c68eb..f84e662 100755 --- a/vs11/Returngeance/Returngeance.vcxproj +++ b/vs11/Returngeance/Returngeance.vcxproj @@ -175,6 +175,7 @@ + @@ -188,6 +189,7 @@ + diff --git a/vs11/Returngeance/Returngeance.vcxproj.filters b/vs11/Returngeance/Returngeance.vcxproj.filters index 0186e7f..7747f2d 100755 --- a/vs11/Returngeance/Returngeance.vcxproj.filters +++ b/vs11/Returngeance/Returngeance.vcxproj.filters @@ -4,7 +4,6 @@ - Rendering\Systems @@ -50,6 +49,9 @@ + + Rendering + @@ -129,7 +131,6 @@ - Rendering\Components @@ -217,6 +218,9 @@ Util + + Rendering + @@ -264,5 +268,11 @@ Shaders + + Shaders + + + Shaders + \ No newline at end of file From 28ac8980f2fdc0edc4daa295dd324745353cd657 Mon Sep 17 00:00:00 2001 From: Stiffly Date: Sun, 27 Apr 2014 03:20:14 +0200 Subject: [PATCH 19/65] tested and fixed scale and velocity interpolation. Fix: could not go from lesser value to larger. Added methods for interpolation. --- src/GameWorld.cpp | 4 +- src/Systems/ParticleSystem.cpp | 94 ++++++++++++++++++---------------- src/Systems/ParticleSystem.h | 3 +- 3 files changed, 53 insertions(+), 48 deletions(-) diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index 3edaf44..d4bba0f 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -97,12 +97,12 @@ void GameWorld::Initialize() // Particle emitter auto ent = CreateEntity(); auto transform = AddComponent(ent, "Transform"); - transform->Orientation = glm::angleAxis(glm::pi()/4, glm::vec3(0,1,0)); + transform->Orientation = glm::angleAxis(glm::pi()/2, glm::vec3(1,0,0)); transform->Position = glm::vec3(i * 10, 20, 0); auto emitter = AddComponent(ent, "ParticleEmitter"); emitter->LifeTime = 4; emitter->SpawnCount = 4; - emitter->SpreadAngle = glm::pi()/6; + emitter->SpreadAngle = glm::pi()/4; emitter->SpawnFrequency = 0.08; auto model = AddComponent(ent, "Model"); model->ModelFile = "Models/Placeholders/PhysicsTest/PointLight.obj"; diff --git a/src/Systems/ParticleSystem.cpp b/src/Systems/ParticleSystem.cpp index a5479f2..b833de5 100644 --- a/src/Systems/ParticleSystem.cpp +++ b/src/Systems/ParticleSystem.cpp @@ -37,10 +37,8 @@ void Systems::ParticleSystem::UpdateEntity(double dt, EntityID entity, EntityID { EntityID particleID = (it)->ParticleID; auto transformComponent = m_World->GetComponent(particleID, "Transform"); - - transformComponent->Position += transformComponent->Velocity; - auto particleComponent = m_World->GetComponent(particleID, "Particle"); + double timeLived = glfwGetTime() - it->SpawnTime; if(timeLived > particleComponent->LifeTime) { @@ -54,28 +52,20 @@ void Systems::ParticleSystem::UpdateEntity(double dt, EntityID entity, EntityID it++; } - // Interpolates the color for each color channel by the start and end value. Decides how much the color should be interpolated based on time. - /*// How big fraction the color is multiplied with float timeProgress = timeLived / particleComponent->LifeTime; // The difference between the start and end value - float deltaColor = glm::abs(particleComponent->ColorSpectrum[0].r - particleComponent->ColorSpectrum[1].r); + /*float deltaColor = glm::abs(particleComponent->ColorSpectrum[0].r - particleComponent->ColorSpectrum[1].r); it->color.r = particleComponent->ColorSpectrum[0].r + deltaColor * timeProgress; deltaColor = glm::abs(particleComponent->ColorSpectrum[0].g - particleComponent->ColorSpectrum[1].g); it->color.g = particleComponent->ColorSpectrum[0].g + deltaColor * timeProgress; deltaColor = glm::abs(particleComponent->ColorSpectrum[0].b - particleComponent->ColorSpectrum[1].b); - it->color.b = particleComponent->ColorSpectrum[0].b + deltaColor * timeProgress; + it->color.b = particleComponent->ColorSpectrum[0].b + deltaColor * timeProgress;*/ - //Interpolates the scale of the particle - float deltaScale = glm::abs(particleComponent->ScaleSpectrum[0] - particleComponent->ScaleSpectrum[1]); - it->Scale = particleComponent->ScaleSpectrum[0] + deltaScale * timeProgress; + + ScaleInterpolation(timeProgress, particleComponent->ScaleSpectrum, transformComponent->Scale); + VelocityInterpolation(timeProgress, particleComponent->VelocitySpectrum, transformComponent->Velocity); - //Interpolates the velocity of the particle - float deltaVelocity = glm::abs(particleComponent->VelocitySpectrum[0].x - particleComponent->VelocitySpectrum[1].x); - it->Velocity.x = particleComponent->VelocitySpectrum[0].x + deltaVelocity * timeProgress; - deltaVelocity = glm::abs(particleComponent->VelocitySpectrum[0].y - particleComponent->VelocitySpectrum[1].y); - it->Velocity.y = particleComponent->VelocitySpectrum[0].y + deltaVelocity * timeProgress; - deltaVelocity = glm::abs(particleComponent->VelocitySpectrum[0].z - particleComponent->VelocitySpectrum[1].z); - it->Velocity.z = particleComponent->VelocitySpectrum[0].z + deltaVelocity * timeProgress;*/ + transformComponent->Position += transformComponent->Velocity; } } } @@ -90,8 +80,10 @@ void Systems::ParticleSystem::SpawnParticles(EntityID emitterID, glm::vec3 pos, { auto emitterTransform = m_World->GetComponent(emitterID, "Transform"); glm::quat emitterOrientation = emitterTransform->Orientation; - float tempSpeed = 5 * dt; + + float tempSpeed = 4 * dt; glm::vec3 speed = glm::vec3(tempSpeed); + for(int i = 0; i < spawnCount; i++) { auto ent = m_World->CreateEntity(); @@ -104,41 +96,26 @@ void Systems::ParticleSystem::SpawnParticles(EntityID emitterID, glm::vec3 pos, //The emitter's orientation as "start value" times the default direction for quaternion. Times the speed, and then rotate on x and y axis with the randomized spread angle. particleTransform->Velocity = emitterOrientation * glm::vec3(0, 0, -1) * speed * glm::normalize(glm::angleAxis(RandomizeAngle(spreadAngle), glm::vec3(1, 0, 0))) * - glm::normalize(glm::angleAxis(RandomizeAngle(spreadAngle), glm::vec3(0, 1, 0))); + glm::normalize(glm::angleAxis(RandomizeAngle(spreadAngle), glm::vec3(0, 1, 0))) * + glm::normalize(glm::angleAxis(RandomizeAngle(spreadAngle), glm::vec3(0, 0, 1))); + glm::vec3 testVel = glm::vec3(particleTransform->Velocity.x, -particleTransform->Velocity.y * 1.5, particleTransform->Velocity.z); //TEMP auto particle = m_World->AddComponent(ent, "Particle"); particle->LifeTime = lifeTime; - - /*Color startColor = {.4f, .45f, .2f}; - particle->ColorSpectrum.push_back(startColor); - Color endColor = {0.f, 45.f, 23.f}; - particle->ColorSpectrum.push_back(endColor); - particle->ScaleSpectrum.push_back(1); - particle->ScaleSpectrum.push_back(30); - particle->VelocitySpectrum.push_back(glm::vec3(0, -.2, 0)); - particle->VelocitySpectrum.push_back(glm::vec3(0, -3, 0));*/ + particle->ScaleSpectrum.push_back(4); //TEMP + particle->ScaleSpectrum.push_back(1); //TEMP + particle->VelocitySpectrum.push_back(particleTransform->Velocity); //TEMP + particle->VelocitySpectrum.push_back(testVel); //TEMP + +// Color startColor = {.4f, .45f, .2f}; +// particle->ColorSpectrum.push_back(startColor); +// Color endColor = {0.f, 45.f, 23.f}; +// particle->ColorSpectrum.push_back(endColor); auto model = m_World->AddComponent(ent, "Model"); model->ModelFile = "Models/Placeholders/PhysicsTest/PointLight.obj"; - /*auto light = m_World->AddComponent(ent, "PointLight"); - light->Specular = glm::vec3(0.1f, 0.1f, 0.1f); - light->Diffuse = glm::vec3(1.f, 1.f, 0.f); - light->constantAttenuation = 0.03f; - light->linearAttenuation = 0.00009f; - light->quadraticAttenuation = 0.07f; - light->spotExponent = 0.0f;*/ - - - /*auto physics = m_World->AddComponent(ent, "Physics"); - physics->Mass = 1; - - auto physicShape = m_World->AddComponent(ent, "Box"); - physicShape->Width = 0.5; - physicShape->Height = 0.5; - physicShape->Depth = 0.5;*/ - ParticleData data; data.ParticleID = ent; data.SpawnTime = glfwGetTime(); @@ -149,7 +126,34 @@ void Systems::ParticleSystem::SpawnParticles(EntityID emitterID, glm::vec3 pos, } } +//Randomizes between -spreadAngle/2 and spreadAngle/2 float Systems::ParticleSystem::RandomizeAngle(float spreadAngle) { return ((float)rand() / ((float)RAND_MAX + 1) * spreadAngle) - spreadAngle/2; +} + +//Interpolates the scale of the particle +void Systems::ParticleSystem::ScaleInterpolation(double timeProgress, std::vector scaleSpectrum, glm::vec3 &scale) +{ + float deltaScale = glm::abs(scaleSpectrum[0] - scaleSpectrum[1]); + if(scaleSpectrum[0] > scaleSpectrum[1]) + deltaScale *= -1; + scale = glm::vec3(scaleSpectrum[0] + deltaScale * timeProgress); +} + +//Interpolates the velocity of the particle +void Systems::ParticleSystem::VelocityInterpolation(double timeProgress, std::vector velocitySpectrum, glm::vec3 &velocity) +{ + float deltaVelocity = glm::abs(velocitySpectrum[0].x - velocitySpectrum[1].x); + if(velocitySpectrum[0].x > velocitySpectrum[1].x) + deltaVelocity *= -1; + velocity.x = velocitySpectrum[0].x + deltaVelocity * timeProgress; + deltaVelocity = glm::abs(velocitySpectrum[0].y - velocitySpectrum[1].y); + if (velocitySpectrum[0].y > velocitySpectrum[1].y) + deltaVelocity *= -1; + velocity.y = velocitySpectrum[0].y + deltaVelocity * timeProgress; + deltaVelocity = glm::abs(velocitySpectrum[0].z - velocitySpectrum[1].z); + if(velocitySpectrum[0].z > velocitySpectrum[1].z) + deltaVelocity *= -1; + velocity.z = velocitySpectrum[0].z + deltaVelocity * timeProgress; } \ No newline at end of file diff --git a/src/Systems/ParticleSystem.h b/src/Systems/ParticleSystem.h index 059eb2f..8940794 100644 --- a/src/Systems/ParticleSystem.h +++ b/src/Systems/ParticleSystem.h @@ -37,7 +37,8 @@ private: std::map m_TimeSinceLastSpawn; float RandomizeAngle(float spreadAngle); - + void ScaleInterpolation(double timeProgress, std::vector scaleSpectrum, glm::vec3 &scale); + void VelocityInterpolation(double timeProgress, std::vector velocitySpectrum, glm::vec3 &velocity); }; } From a199e777bc0ee8e83e06ae84db660e32fafa75ac Mon Sep 17 00:00:00 2001 From: Tleety Date: Sun, 27 Apr 2014 03:59:41 +0200 Subject: [PATCH 20/65] Working Debug mode --- src/Renderer.cpp | 17 +++++----- src/Shaders/Fragment2-Debug.glsl | 33 +++++++++++++++++++ src/Shaders/Fragment2.glsl | 2 +- src/Shaders/Vertex.glsl | 3 +- vs11/Returngeance/Returngeance.vcxproj | 18 +--------- .../Returngeance/Returngeance.vcxproj.filters | 18 +++++++--- 6 files changed, 60 insertions(+), 31 deletions(-) create mode 100644 src/Shaders/Fragment2-Debug.glsl diff --git a/src/Renderer.cpp b/src/Renderer.cpp index 44032b0..17e3db6 100755 --- a/src/Renderer.cpp +++ b/src/Renderer.cpp @@ -119,7 +119,7 @@ void Renderer::LoadContent() m_FirstPassProgram.Link(); m_SecondPassProgram.AddShader(std::shared_ptr(new VertexShader("Shaders/Vertex2.glsl"))); - m_SecondPassProgram.AddShader(std::shared_ptr(new FragmentShader("Shaders/Fragment2.glsl"))); + m_SecondPassProgram.AddShader(std::shared_ptr(new FragmentShader("Shaders/Fragment2-Debug.glsl"))); m_SecondPassProgram.Compile(); m_SecondPassProgram.Link(); @@ -530,8 +530,8 @@ void Renderer::FrameBufferTextures() glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, WIDTH, HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); //Generate and bind position texture glGenTextures(1, &m_fPositionTexture); @@ -539,8 +539,8 @@ void Renderer::FrameBufferTextures() glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, WIDTH, HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); //Generate and bind normal texture glGenTextures(1, &m_fNormalsTexture); @@ -548,8 +548,8 @@ void Renderer::FrameBufferTextures() glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, WIDTH, HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); //Bind fb glBindFramebuffer(GL_FRAMEBUFFER, m_fb); @@ -668,7 +668,7 @@ void Renderer::DrawFBO() glBindVertexArray(m_ScreenQuad); glEnableVertexAttribArray(0); - glEnableVertexAttribArray(2); +/* glEnableVertexAttribArray(2);*/ glDrawArrays(GL_TRIANGLES, 0, 6); } @@ -747,6 +747,7 @@ void Renderer::DrawFBOScene() MVP = cameraMatrix * modelMatrix; glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "MVP"), 1, GL_FALSE, glm::value_ptr(MVP)); + glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "ModelMatrix"), 1, GL_FALSE, glm::value_ptr(modelMatrix)); glBindVertexArray(model->VAO); for (auto texGroup : model->TextureGroups) { diff --git a/src/Shaders/Fragment2-Debug.glsl b/src/Shaders/Fragment2-Debug.glsl new file mode 100644 index 0000000..dc258c8 --- /dev/null +++ b/src/Shaders/Fragment2-Debug.glsl @@ -0,0 +1,33 @@ +#version 430 + +layout (binding=0) uniform sampler2D DiffuseTexture; +layout (binding=1) uniform sampler2D PositionTexture; +layout (binding=2) uniform sampler2D NormalTexture; + +in VertexData +{ + vec3 Position; + vec3 Normal; + vec2 TextureCoord; +} Input; + +out vec4 FragColor; + +void DrawQuadrant(vec4 texel, vec2 quadrant) +{ + if (-quadrant.x * Input.Position.x < 0 && -quadrant.y * Input.Position.y < 0) + { + FragColor = texel; + } +} + +void main() +{ + //FragColor = texture2D(DiffuseTexture, Input.TextureCoord * 2 + vec2(0, -1)); + DrawQuadrant(texture2D(DiffuseTexture, Input.TextureCoord * 2), vec2(-1, 1)); + DrawQuadrant(texture2D(PositionTexture, Input.TextureCoord * 2), vec2(1, 1)); + DrawQuadrant(texture2D(NormalTexture, Input.TextureCoord * 2), vec2(-1, -1)); + vec4 AllTexel = texture2D(DiffuseTexture, Input.TextureCoord*2)*texture2D(PositionTexture, Input.TextureCoord*2)*texture2D(NormalTexture, Input.TextureCoord*2); + DrawQuadrant(AllTexel, vec2(1, -1)); +} + diff --git a/src/Shaders/Fragment2.glsl b/src/Shaders/Fragment2.glsl index cbc905e..42c3997 100644 --- a/src/Shaders/Fragment2.glsl +++ b/src/Shaders/Fragment2.glsl @@ -15,5 +15,5 @@ out vec4 FragColor; void main() { - FragColor = texture2D(DiffuseTexture, Input.TextureCoord); + FragColor = texture2D(NormalTexture, Input.TextureCoord); } \ No newline at end of file diff --git a/src/Shaders/Vertex.glsl b/src/Shaders/Vertex.glsl index 6254b60..aaa0857 100755 --- a/src/Shaders/Vertex.glsl +++ b/src/Shaders/Vertex.glsl @@ -1,6 +1,7 @@ #version 430 uniform mat4 MVP; +uniform mat4 ModelMatrix; layout (location = 0) in vec3 Position; layout (location = 1) in vec3 Normal; @@ -18,6 +19,6 @@ void main() gl_Position = MVP * vec4(Position, 1.0); Output.Position = gl_Position.xyz; - Output.Normal = Normal; + Output.Normal = normalize((ModelMatrix * vec4(Normal, 0.0)).xyz); Output.TextureCoord = TextureCoord; } \ No newline at end of file diff --git a/vs11/Returngeance/Returngeance.vcxproj b/vs11/Returngeance/Returngeance.vcxproj index a51c769..d8ca087 100755 --- a/vs11/Returngeance/Returngeance.vcxproj +++ b/vs11/Returngeance/Returngeance.vcxproj @@ -167,27 +167,11 @@ - - - - true - - - - - - - + - - true - - - true - diff --git a/vs11/Returngeance/Returngeance.vcxproj.filters b/vs11/Returngeance/Returngeance.vcxproj.filters index b8f30e6..1a05dbf 100755 --- a/vs11/Returngeance/Returngeance.vcxproj.filters +++ b/vs11/Returngeance/Returngeance.vcxproj.filters @@ -226,12 +226,10 @@ Physics\Components + - - Shaders - - + Shaders @@ -255,11 +253,23 @@ Shaders + + Shaders + Shaders Shaders + + Shaders + + + Shaders + + + Shaders + \ No newline at end of file From 4389f2db4c39e08210f67192b034ff4a7e4807f0 Mon Sep 17 00:00:00 2001 From: Tleety Date: Sun, 27 Apr 2014 04:59:11 +0200 Subject: [PATCH 21/65] Fixed being able to switch between Quad view and normal view. --- src/Renderer.cpp | 27 +++++++++++++++++++++++++-- src/Renderer.h | 3 +++ src/Shaders/Fragment2-Debug.glsl | 5 +++++ src/Shaders/Fragment2.glsl | 2 +- 4 files changed, 34 insertions(+), 3 deletions(-) diff --git a/src/Renderer.cpp b/src/Renderer.cpp index 17e3db6..1125dc0 100755 --- a/src/Renderer.cpp +++ b/src/Renderer.cpp @@ -119,10 +119,15 @@ void Renderer::LoadContent() m_FirstPassProgram.Link(); m_SecondPassProgram.AddShader(std::shared_ptr(new VertexShader("Shaders/Vertex2.glsl"))); - m_SecondPassProgram.AddShader(std::shared_ptr(new FragmentShader("Shaders/Fragment2-Debug.glsl"))); + m_SecondPassProgram.AddShader(std::shared_ptr(new FragmentShader("Shaders/Fragment2.glsl"))); m_SecondPassProgram.Compile(); m_SecondPassProgram.Link(); + m_SecondPassProgram_Debug.AddShader(std::shared_ptr(new VertexShader("Shaders/Vertex2.glsl"))); + m_SecondPassProgram_Debug.AddShader(std::shared_ptr(new FragmentShader("Shaders/Fragment2-Debug.glsl"))); + m_SecondPassProgram_Debug.Compile(); + m_SecondPassProgram_Debug.Link(); + m_ScreenQuad = CreateQuad(); FrameBufferTextures(); @@ -130,6 +135,16 @@ void Renderer::LoadContent() void Renderer::Draw(double dt) { + + if(glfwGetKey(m_Window, GLFW_KEY_F1)) + { + m_QuadView = false; + } + if(glfwGetKey(m_Window, GLFW_KEY_F2)) + { + m_QuadView = true; + } + glDisable(GL_BLEND); DrawFBO(); @@ -653,7 +668,14 @@ void Renderer::DrawFBO() // Draw to screen glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); - m_SecondPassProgram.Bind(); + if(!m_QuadView) + { + m_SecondPassProgram.Bind(); + } + else + { + m_SecondPassProgram_Debug.Bind(); + } glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); ////SetupDefferedStageUniforms(); // Probably what we do in FrameBufferTextures(); @@ -736,6 +758,7 @@ void Renderer::DrawFBOScene() { glm::mat4 cameraMatrix = m_Camera->ProjectionMatrix() * m_Camera->ViewMatrix(); glm::mat4 MVP; + for (auto tuple : ModelsToRender) { Model* model; diff --git a/src/Renderer.h b/src/Renderer.h index 2d5eab0..540be71 100755 --- a/src/Renderer.h +++ b/src/Renderer.h @@ -96,11 +96,14 @@ private: GLenum draw_bufs[2]; GLuint m_ScreenQuad; + bool m_QuadView; + std::shared_ptr m_Camera; ShaderProgram m_ShaderProgram; ShaderProgram m_FirstPassProgram; ShaderProgram m_SecondPassProgram; + ShaderProgram m_SecondPassProgram_Debug; ShaderProgram m_ShaderProgramNormals; ShaderProgram m_ShaderProgramShadows; ShaderProgram m_ShaderProgramShadowsDrawDepth; diff --git a/src/Shaders/Fragment2-Debug.glsl b/src/Shaders/Fragment2-Debug.glsl index dc258c8..db35d6e 100644 --- a/src/Shaders/Fragment2-Debug.glsl +++ b/src/Shaders/Fragment2-Debug.glsl @@ -23,10 +23,15 @@ void DrawQuadrant(vec4 texel, vec2 quadrant) void main() { + vec4 DiffuseTexel = texture2D(DiffuseTexture, Input.TextureCoord); + vec4 PositionTexel = texture2D(PositionTexture, Input.TextureCoord); + vec4 NormalTexel = texture2D(NormalTexture, Input.TextureCoord); + //FragColor = texture2D(DiffuseTexture, Input.TextureCoord * 2 + vec2(0, -1)); DrawQuadrant(texture2D(DiffuseTexture, Input.TextureCoord * 2), vec2(-1, 1)); DrawQuadrant(texture2D(PositionTexture, Input.TextureCoord * 2), vec2(1, 1)); DrawQuadrant(texture2D(NormalTexture, Input.TextureCoord * 2), vec2(-1, -1)); + vec4 AllTexel = texture2D(DiffuseTexture, Input.TextureCoord*2)*texture2D(PositionTexture, Input.TextureCoord*2)*texture2D(NormalTexture, Input.TextureCoord*2); DrawQuadrant(AllTexel, vec2(1, -1)); } diff --git a/src/Shaders/Fragment2.glsl b/src/Shaders/Fragment2.glsl index 42c3997..cbc905e 100644 --- a/src/Shaders/Fragment2.glsl +++ b/src/Shaders/Fragment2.glsl @@ -15,5 +15,5 @@ out vec4 FragColor; void main() { - FragColor = texture2D(NormalTexture, Input.TextureCoord); + FragColor = texture2D(DiffuseTexture, Input.TextureCoord); } \ No newline at end of file From 04cafc53e227c0bf26f1b278c8be44d407569477 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Sun, 27 Apr 2014 07:48:16 +0200 Subject: [PATCH 22/65] Implemented entity cloning --- src/Component.h | 2 + src/Components/Box.h | 2 + src/Components/Camera.h | 2 + src/Components/DirectionalLight.h | 2 + src/Components/FreeSteering.h | 2 + src/Components/Input.h | 2 + src/Components/Model.h | 2 + src/Components/Particle.h | 2 + src/Components/ParticleEmitter.h | 2 + src/Components/Physics.h | 2 + src/Components/PointLight.h | 2 + src/Components/SoundEmitter.h | 2 + src/Components/Sphere.h | 2 + src/Components/Sprite.h | 2 + src/Components/Template.h | 7 ++- src/Components/Transform.h | 4 +- src/World.cpp | 55 ++++++++++++++++++- src/World.h | 21 ++++--- .../Returngeance/Returngeance.vcxproj.filters | 8 ++- 19 files changed, 107 insertions(+), 16 deletions(-) diff --git a/src/Component.h b/src/Component.h index 21d59f6..05e0628 100755 --- a/src/Component.h +++ b/src/Component.h @@ -7,6 +7,8 @@ struct Component { EntityID Entity; + + virtual Component* Clone() const = 0; }; class ComponentFactory : public Factory { }; diff --git a/src/Components/Box.h b/src/Components/Box.h index b9ddea7..3fe3687 100644 --- a/src/Components/Box.h +++ b/src/Components/Box.h @@ -14,6 +14,8 @@ struct Box : Component float Width; float Height; float Depth; + + virtual Box* Clone() const override { return new Box(*this); } }; } diff --git a/src/Components/Camera.h b/src/Components/Camera.h index 2cd379d..91e55b5 100755 --- a/src/Components/Camera.h +++ b/src/Components/Camera.h @@ -13,6 +13,8 @@ struct Camera : Component float FOV; float NearClip; float FarClip; + + virtual Camera* Clone() const override { return new Camera(*this); } }; } diff --git a/src/Components/DirectionalLight.h b/src/Components/DirectionalLight.h index ee2dd72..1d7de1e 100755 --- a/src/Components/DirectionalLight.h +++ b/src/Components/DirectionalLight.h @@ -13,6 +13,8 @@ struct DirectionalLight : Component float MaxRange; float SpecularIntensity; Color Color; + + virtual DirectionalLight* Clone() const override { return new DirectionalLight(*this); } }; } diff --git a/src/Components/FreeSteering.h b/src/Components/FreeSteering.h index a972eaf..ba40534 100755 --- a/src/Components/FreeSteering.h +++ b/src/Components/FreeSteering.h @@ -9,6 +9,8 @@ struct FreeSteering : Component { FreeSteering() : Speed(35) { } float Speed; + + virtual FreeSteering* Clone() const override { return new FreeSteering(*this); } }; } diff --git a/src/Components/Input.h b/src/Components/Input.h index b1c11b5..15cb286 100755 --- a/src/Components/Input.h +++ b/src/Components/Input.h @@ -18,6 +18,8 @@ struct Input : Component std::array LastMouseState; float dX, dY; float WheelDelta; + + virtual Input* Clone() const override { return new Input(*this); } }; } diff --git a/src/Components/Model.h b/src/Components/Model.h index ad3b4f3..cacfe17 100755 --- a/src/Components/Model.h +++ b/src/Components/Model.h @@ -16,6 +16,8 @@ struct Model : Component Color Color; bool Visible; bool ShadowCaster; + + virtual Model* Clone() const override { return new Model(*this); } }; } diff --git a/src/Components/Particle.h b/src/Components/Particle.h index b169ee2..dfa3075 100644 --- a/src/Components/Particle.h +++ b/src/Components/Particle.h @@ -16,6 +16,8 @@ namespace Components double LifeTime; std::vector VelocitySpectrum; std::vector AngularVelocitySpectrum; + + virtual Particle* Clone() const override { return new Particle(*this); } }; } diff --git a/src/Components/ParticleEmitter.h b/src/Components/ParticleEmitter.h index 46ad8fb..5aafcdc 100755 --- a/src/Components/ParticleEmitter.h +++ b/src/Components/ParticleEmitter.h @@ -24,6 +24,8 @@ struct ParticleEmitter : Component std::vector VelocitySpectrum; std::vector AngularVelocitySpectrum; + virtual ParticleEmitter* Clone() const override { return new ParticleEmitter(*this); } + private: double TimeSinceLastSpawn; }; diff --git a/src/Components/Physics.h b/src/Components/Physics.h index 956ae7a..98a682f 100644 --- a/src/Components/Physics.h +++ b/src/Components/Physics.h @@ -12,6 +12,8 @@ struct Physics : Component : Mass(0.f) { } float Mass; + + virtual Physics* Clone() const override { return new Physics(*this); } }; } diff --git a/src/Components/PointLight.h b/src/Components/PointLight.h index a7a5d4a..248fec6 100755 --- a/src/Components/PointLight.h +++ b/src/Components/PointLight.h @@ -16,6 +16,8 @@ struct PointLight : Component float constantAttenuation, linearAttenuation, quadraticAttenuation; float spotExponent; Color color; + + virtual PointLight* Clone() const override { return new PointLight(*this); } }; } diff --git a/src/Components/SoundEmitter.h b/src/Components/SoundEmitter.h index b4c74ee..05c5f15 100755 --- a/src/Components/SoundEmitter.h +++ b/src/Components/SoundEmitter.h @@ -17,6 +17,8 @@ struct SoundEmitter : Component float Pitch; bool Loop; std::string Path; + + virtual SoundEmitter* Clone() const override { return new SoundEmitter(*this); } }; } diff --git a/src/Components/Sphere.h b/src/Components/Sphere.h index 2d089dd..f92e418 100644 --- a/src/Components/Sphere.h +++ b/src/Components/Sphere.h @@ -12,6 +12,8 @@ struct Sphere : Component : Radius(1.f){ } float Radius; + + virtual Sphere* Clone() const override { return new Sphere(*this); } }; } diff --git a/src/Components/Sprite.h b/src/Components/Sprite.h index f54d3d0..29c930f 100755 --- a/src/Components/Sprite.h +++ b/src/Components/Sprite.h @@ -13,6 +13,8 @@ struct Sprite : Component { std::string SpriteFile; Color Color; + + virtual Sprite* Clone() const override { return new Sprite(*this); } }; } diff --git a/src/Components/Template.h b/src/Components/Template.h index 4bcb25c..613622c 100755 --- a/src/Components/Template.h +++ b/src/Components/Template.h @@ -6,7 +6,12 @@ namespace Components { -struct Template : Component { }; +struct Template + : public Component +{ + virtual Template* Clone() const override { return nullptr; } +}; } + #endif // !Components_Template_h__ \ No newline at end of file diff --git a/src/Components/Transform.h b/src/Components/Transform.h index 2bfd58d..26b701e 100755 --- a/src/Components/Transform.h +++ b/src/Components/Transform.h @@ -6,7 +6,7 @@ namespace Components { -struct Transform : Component +struct Transform : public Component { Transform() : Scale(glm::vec3(1.f)) { } @@ -15,6 +15,8 @@ struct Transform : Component glm::quat Orientation; glm::vec3 Velocity; glm::vec3 Scale; + + virtual Transform* Clone() const override { return new Transform(*this); } }; } diff --git a/src/World.cpp b/src/World.cpp index 78b297d..ef9d236 100755 --- a/src/World.cpp +++ b/src/World.cpp @@ -93,6 +93,7 @@ void World::ProcessEntityRemovals() for (auto entity : m_EntitiesToRemove) { m_EntityParents.erase(entity); + m_EntityChildren.erase(entity); // Remove components for (auto pair : m_EntityComponents[entity]) { @@ -116,7 +117,8 @@ void World::ProcessEntityRemovals() EntityID World::CreateEntity(EntityID parent /*= 0*/) { EntityID newEntity = GenerateEntityID(); - m_EntityParents.insert(std::pair(newEntity, parent)); + m_EntityParents[newEntity] = parent; + m_EntityChildren[parent].push_back(newEntity); return newEntity; } @@ -148,7 +150,58 @@ std::shared_ptr World::AddComponent(EntityID entity, std::string comp return AddComponent(entity, componentType); } +void World::AddComponent(EntityID entity, std::string componentType, std::shared_ptr component) +{ + component->Entity = entity; + m_ComponentsOfType[componentType].push_back(component); + m_EntityComponents[entity][componentType] = component; + for (auto pair : m_Systems) + { + auto system = pair.second; + system->OnComponentCreated(componentType, component); + } +} + void World::AddSystem(std::string systemType) { m_Systems[systemType] = std::shared_ptr(m_SystemFactory.Create(systemType)); } + +EntityID World::CloneEntity(EntityID entity, EntityID parent /* = 0 */) +{ + int clone = CreateEntity(parent); + + for (auto pair : m_EntityComponents[entity]) + { + auto type = pair.first; + auto component = std::shared_ptr(pair.second->Clone()); + if (component != nullptr) + { + AddComponent(clone, type, component); + } + } + + auto itChildren = m_EntityChildren.find(entity); + if (itChildren != m_EntityChildren.end()) + { + for (EntityID child : itChildren->second) + { + CloneEntity(child, clone); + } + } + + return clone; +} + +std::list World::GetEntityChildren(EntityID entity) +{ + auto it = m_EntityChildren.find(entity); + if (it == m_EntityChildren.end()) + { + return std::list(); + } + else + { + return it->second; + } +} diff --git a/src/World.h b/src/World.h index 9deeab9..d0c0692 100755 --- a/src/World.h +++ b/src/World.h @@ -34,6 +34,7 @@ public: std::shared_ptr GetSystem(std::string systemType); EntityID CreateEntity(EntityID parent = 0); + EntityID CloneEntity(EntityID entity, EntityID parent = 0); void RemoveEntity(EntityID entity); @@ -41,6 +42,7 @@ public: EntityID GetEntityParent(EntityID entity); EntityID GetEntityBaseParent(EntityID entity); + std::list GetEntityChildren(EntityID entity); template T GetProperty(EntityID entity, std::string property) @@ -83,13 +85,16 @@ protected: EntityID m_LastEntityID; std::stack m_RecycledEntityIDs; - // A bottom to top tree. A map of child entities to parent entities. - std::unordered_map m_EntityParents; - std::unordered_map> m_EntityProperties; + std::unordered_map m_EntityParents; // child -> parent + std::unordered_map> m_EntityChildren; // parent -> child + std::unordered_map> m_EntityProperties; std::unordered_map>> m_ComponentsOfType; std::unordered_map>> m_EntityComponents; + // Internal: Add a component to an entity + void AddComponent(EntityID entity, std::string componentType, std::shared_ptr component); + std::list m_EntitiesToRemove; void ProcessEntityRemovals(); @@ -121,14 +126,8 @@ std::shared_ptr World::AddComponent(EntityID entity, std::string componentTyp return nullptr; } - component->Entity = entity; - m_ComponentsOfType[componentType].push_back(component); - m_EntityComponents[entity][componentType] = component; - for (auto pair : m_Systems) - { - auto system = pair.second; - system->OnComponentCreated(componentType, component); - } + AddComponent(entity, componentType, component); + return component; } diff --git a/vs11/Returngeance/Returngeance.vcxproj.filters b/vs11/Returngeance/Returngeance.vcxproj.filters index 35f6ce6..2e7f203 100755 --- a/vs11/Returngeance/Returngeance.vcxproj.filters +++ b/vs11/Returngeance/Returngeance.vcxproj.filters @@ -215,14 +215,18 @@ Audio - - Particle System\Systems Particle System\Components + + Physics\Components + + + Physics\Components + From cb6b0a58d8787dcb35fe2a2b797280d0752f5b85 Mon Sep 17 00:00:00 2001 From: ViktorLjung Date: Sun, 27 Apr 2014 08:07:18 +0200 Subject: [PATCH 23/65] Resource manager OBJ vs Model conflict fixed --- src/Model.cpp | 2 +- src/Model.h | 2 +- src/OBJ.cpp | 2 +- src/OBJ.h | 4 +++- src/ResourceManager.cpp | 8 ++++---- src/ResourceManager.h | 9 +++++---- src/Util/UnorderedMapPair.h | 20 ++++++++++++++++++++ 7 files changed, 35 insertions(+), 12 deletions(-) create mode 100644 src/Util/UnorderedMapPair.h diff --git a/src/Model.cpp b/src/Model.cpp index 547e940..753ec65 100755 --- a/src/Model.cpp +++ b/src/Model.cpp @@ -1,7 +1,7 @@ #include "PrecompiledHeader.h" #include "Model.h" -Model::Model(OBJ &obj, ResourceManager* rm) +Model::Model(ResourceManager* rm, OBJ &obj) { OBJ::MaterialInfo* currentMaterial = nullptr; TextureGroup* currentTexGroup = nullptr; diff --git a/src/Model.h b/src/Model.h index 8d94a7d..dcf41d9 100755 --- a/src/Model.h +++ b/src/Model.h @@ -17,7 +17,7 @@ class Model : public Resource { public: - Model(OBJ &obj, ResourceManager* rm); + Model(ResourceManager* rm, OBJ &obj); struct TextureGroup { diff --git a/src/OBJ.cpp b/src/OBJ.cpp index a8b9f03..d8f91bf 100755 --- a/src/OBJ.cpp +++ b/src/OBJ.cpp @@ -9,7 +9,7 @@ bool OBJ::LoadFromFile(std::string filename) std::ifstream file(m_Path.string()); if (!file.is_open()) { - LOG_ERROR("Failed to open .obj \"%s\"", m_Path.string().c_str()); + LOG_ERROR("Failed to open .obj \"%s\": %s", m_Path.string().c_str(), strerror(errno)); return false; } diff --git a/src/OBJ.h b/src/OBJ.h index 2ef10e0..8ae9a32 100755 --- a/src/OBJ.h +++ b/src/OBJ.h @@ -12,7 +12,9 @@ #include #include -class OBJ +#include "ResourceManager.h" + +class OBJ : public Resource { public: struct MaterialInfo diff --git a/src/ResourceManager.cpp b/src/ResourceManager.cpp index 1361c11..b4ff9bd 100644 --- a/src/ResourceManager.cpp +++ b/src/ResourceManager.cpp @@ -16,7 +16,7 @@ Resource* ResourceManager::CreateResource(std::string resourceType, std::string resource->TypeID = GetTypeID(resourceType); resource->ResourceID = GetNewResourceID(resource->TypeID); // Cache - m_ResourceCache[resourceName] = resource; + m_ResourceCache[std::make_pair(resourceType, resourceName)] = resource; return resource; } @@ -28,7 +28,7 @@ void ResourceManager::RegisterType(std::string resourceType, std::function #include +#include "Util/UnorderedMapPair.h" #include "Factory.h" class Resource @@ -28,7 +29,7 @@ public: void Preload(std::string resourceType, std::string resourceName); // Checks if a resource is in cache - bool IsResourceLoaded(std::string resourceName); + bool IsResourceLoaded(std::string resourceType, std::string resourceName); template // Hot-loads a resource and caches it for future use @@ -40,7 +41,7 @@ public: private: std::unordered_map> m_FactoryFunctions; // type -> factory function - std::unordered_map m_ResourceCache; // name -> resource + std::unordered_map, Resource*> m_ResourceCache; // (type, name) -> resource // TODO: Getters for IDs unsigned int m_CurrentResourceTypeID; @@ -60,7 +61,7 @@ private: template T* ResourceManager::Load(std::string resourceType, std::string resourceName) { - auto it = m_ResourceCache.find(resourceName); + auto it = m_ResourceCache.find(std::make_pair(resourceType, resourceName)); if (it != m_ResourceCache.end()) return static_cast(it->second); @@ -79,7 +80,7 @@ T* ResourceManager::Load(std::string resourceType, std::string resourceName) template T* ResourceManager::Fetch(std::string resourceName) const { - auto it = m_ResourceCache.find(resourceName); + auto it = m_ResourceCache.find(std::make_pair(resourceType, resourceName)); if (it == m_ResourceCache.end()) { LOG_ERROR("Failed to fetch resource \"%s\": Resource not loaded!", resourceName.c_str()); diff --git a/src/Util/UnorderedMapPair.h b/src/Util/UnorderedMapPair.h new file mode 100644 index 0000000..68d2355 --- /dev/null +++ b/src/Util/UnorderedMapPair.h @@ -0,0 +1,20 @@ +#ifndef Util_UnorderedMapPair_h__ +#define Util_UnorderedMapPair_h__ + +#include + +namespace std +{ + template struct hash> + { + inline size_t operator()(const pair & v) const + { + size_t seed = 0; + boost::hash_combine(seed, v.first); + boost::hash_combine(seed, v.second); + return seed; + } + }; +} + +#endif // Util_UnorderedMapPair_h__ \ No newline at end of file From 720cf3aa8745094c917c10109f4efa126d5aeb5b Mon Sep 17 00:00:00 2001 From: ViktorLjung Date: Sun, 27 Apr 2014 08:08:00 +0200 Subject: [PATCH 24/65] Added support for HkpExtendedMeshShape. --- src/Components/MeshShape.h | 17 ++ src/Components/Vehicle.h | 2 +- src/GameWorld.cpp | 135 ++++--------- src/Systems/PhysicsSystem.cpp | 177 ++++++++---------- src/Systems/PhysicsSystem.h | 16 ++ src/Systems/RenderSystem.cpp | 3 +- vs11/Returngeance/Returngeance.vcxproj | 4 +- .../Returngeance/Returngeance.vcxproj.filters | 6 + 8 files changed, 153 insertions(+), 207 deletions(-) create mode 100644 src/Components/MeshShape.h diff --git a/src/Components/MeshShape.h b/src/Components/MeshShape.h new file mode 100644 index 0000000..64084ab --- /dev/null +++ b/src/Components/MeshShape.h @@ -0,0 +1,17 @@ +#ifndef Components_MeshShape_h__ +#define Components_MeshShape_h__ + +#include + +#include "Component.h" + +namespace Components +{ + +struct MeshShape : Component +{ + std::string ResourceName; +}; + +} +#endif // !Components_MeshShape_h__ \ No newline at end of file diff --git a/src/Components/Vehicle.h b/src/Components/Vehicle.h index e61c713..9e4a59e 100644 --- a/src/Components/Vehicle.h +++ b/src/Components/Vehicle.h @@ -10,7 +10,7 @@ namespace Components struct Vehicle : Component { Vehicle() - : MaxTorque(500.0f), MinRPM(1000.0f), OptimalRPM(5500.0f), MaxRPM(7500.0f), MaxSteeringAngle(35), TopSpeed(50.0f) { } + : MaxTorque(500.0f), MinRPM(800.0f), OptimalRPM(4000.0f), MaxRPM(6000.0f), MaxSteeringAngle(35), TopSpeed(50.0f) { } float MaxTorque; float MinRPM; diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index 7926dcb..4ca0ac7 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -16,15 +16,14 @@ void GameWorld::Initialize() { auto ground = CreateEntity(); auto transform = AddComponent(ground, "Transform"); - transform->Position = glm::vec3(0, -5, 0); - transform->Scale = glm::vec3(400.0f, 10.0f, 400.0f); + transform->Position = glm::vec3(0, 0, 0); + //transform->Scale = glm::vec3(400.0f, 10.0f, 400.0f); transform->Orientation = glm::quat(glm::vec3(0.0f, 0.0f, 0.0f)); auto model = AddComponent(ground, "Model"); - model->ModelFile = "Models/Placeholders/PhysicsTest/Cube.obj"; - auto box = AddComponent(ground, "Box"); - box->Width = 200; - box->Height = 5; - box->Depth = 200; + model->ModelFile = "Models/Placeholders/Terrain/Terrain.obj"; + auto meshShape = AddComponent(ground, "MeshShape"); + meshShape->ResourceName = "Models/Placeholders/Terrain/Terrain.obj"; + auto physics = AddComponent(ground, "Physics"); physics->Mass = 10; @@ -37,16 +36,28 @@ void GameWorld::Initialize() { auto jeep = CreateEntity(); auto transform = AddComponent(jeep, "Transform"); - transform->Position = glm::vec3(0, 2, 0); + transform->Position = glm::vec3(0, 10, 0); auto physics = AddComponent(jeep, "Physics"); - physics->Mass = 1200; - auto box = AddComponent(jeep, "Box"); - box->Width = 1.487f; - box->Height = 0.727f; - box->Depth = 2.594f; + physics->Mass = 800; + + +// auto box = AddComponent(jeep, "Box"); +// box->Width = 1.487f; +// box->Height = 0.727f; +// box->Depth = 2.594f; + + auto meshShape = AddComponent(jeep, "MeshShape"); + meshShape->ResourceName = "Models/JeepV2/Chassi/chassi.OBJ"; + auto vehicle = AddComponent(jeep, "Vehicle"); + auto light = AddComponent(jeep, "PointLight"); + light->Diffuse = glm::vec3(0, 1, 0); + light->constantAttenuation = 0.0005f; + light->linearAttenuation = 0.001f; + light->quadraticAttenuation = 0.001f; + AddComponent(jeep, "Input"); @@ -69,7 +80,6 @@ void GameWorld::Initialize() transform->Position = glm::vec3(0, -0.6577f, 0); auto model = AddComponent(chassis, "Model"); model->ModelFile = "Models/JeepV2/Chassi/chassi.OBJ"; - } { @@ -86,7 +96,7 @@ void GameWorld::Initialize() Wheel->Radius = 0.837f; Wheel->Steering = true; Wheel->SuspensionStrength = 40.f; - Wheel->Friction = 4.0f; + Wheel->Friction = 3.0f; Wheel->ConnectedToHandbrake = true; CommitEntity(wheel); } @@ -106,7 +116,7 @@ void GameWorld::Initialize() Wheel->Radius = 0.837f; Wheel->Steering = true; Wheel->SuspensionStrength = 40.f; - Wheel->Friction = 4.0f; + Wheel->Friction = 3.0f; Wheel->ConnectedToHandbrake = true; CommitEntity(wheel); } @@ -123,8 +133,9 @@ void GameWorld::Initialize() Wheel->Mass = 10; Wheel->Radius = 0.737f; Wheel->Steering = false; - Wheel->SuspensionStrength = 50.f; - Wheel->Friction = 4.0f; + Wheel->SuspensionStrength = 20.f; + Wheel->Friction = 3.0f; + Wheel->ConnectedToHandbrake = true; CommitEntity(wheel); } @@ -141,93 +152,15 @@ void GameWorld::Initialize() Wheel->Mass = 10; Wheel->Radius = 0.737f; Wheel->Steering = false; - Wheel->SuspensionStrength = 50.f; - Wheel->Friction = 4.0f; + Wheel->SuspensionStrength = 20.f; + Wheel->Friction = 3.0f; + Wheel->ConnectedToHandbrake = true; CommitEntity(wheel); } CommitEntity(jeep); } -/* - - { - // Front Right Wheel - auto ent = CreateEntity(car); - auto transform = AddComponent(ent, "Transform"); - transform->Scale = glm::vec3(1)/glm::vec3(3, 1, 5); - transform->Position = glm::vec3(1.1f, -1.5f, -1.3f); - auto Wheel = AddComponent(ent, "Wheel"); - Wheel->Hardpoint = glm::vec3(1.1f, 0.f, -1.3f);// HACK: make into component - Wheel->AxleID = 0; - Wheel->Mass = 10; - Wheel->Radius = 0.5f; - Wheel->Steering = true; - Wheel->SuspensionStrength = 20.f; - auto model = AddComponent(ent, "Model"); - model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; - CommitEntity(ent); - } - { - // Front Left Wheel - auto ent = CreateEntity(car); - auto transform = AddComponent(ent, "Transform"); - transform->Scale = glm::vec3(1)/glm::vec3(3, 1, 5); - transform->Position = glm::vec3(-1.1f, -1.5f, -1.3f); - auto Wheel = AddComponent(ent, "Wheel"); - Wheel->Hardpoint = glm::vec3(-1.1f, 0.f, -1.3f); - Wheel->AxleID = 0; - Wheel->Mass = 10; - Wheel->Radius = 0.5f; - Wheel->Steering = true; - Wheel->SuspensionStrength = 20.f; - auto model = AddComponent(ent, "Model"); - model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; - CommitEntity(ent); - } - { - // Back Right Wheel - auto ent = CreateEntity(car); - auto transform = AddComponent(ent, "Transform"); - transform->Scale = glm::vec3(1)/glm::vec3(3, 1, 5); - transform->Position = glm::vec3(1.1f, -1.5f, 1.3f); - auto Wheel = AddComponent(ent, "Wheel"); - Wheel->Hardpoint = glm::vec3(1.1f, 0.f, 1.3f); - Wheel->AxleID = 1; - Wheel->Mass = 10; - Wheel->Radius = 0.5f; - Wheel->Steering = false; - Wheel->ConnectedToHandbrake = true; - Wheel->SuspensionStrength = 20.f; - auto model = AddComponent(ent, "Model"); - model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; - CommitEntity(ent); - } - { - // Back Left Wheel - auto ent = CreateEntity(car); - auto transform = AddComponent(ent, "Transform"); - transform->Scale = glm::vec3(1)/glm::vec3(3, 1, 5); - transform->Position = glm::vec3(-1.1f, -1.5f, 1.3f); - auto Wheel = AddComponent(ent, "Wheel"); - Wheel->Hardpoint = glm::vec3(-1.1f, 0.f, 1.3f); - Wheel->AxleID = 1; - Wheel->Mass = 10; - Wheel->Radius = 0.5f; - Wheel->Steering = false; - Wheel->ConnectedToHandbrake = true; - Wheel->SuspensionStrength = 20.f; - auto model = AddComponent(ent, "Model"); - model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; - CommitEntity(ent); - } - - CommitEntity(car); - } -*/ - - - - for(int i = 0; i < 10; i++) + for(int i = 0; i < 0; i++) { auto cube = CreateEntity(); auto transform = AddComponent(cube, "Transform"); @@ -235,7 +168,7 @@ void GameWorld::Initialize() transform->Scale = glm::vec3(1); transform->Orientation = glm::quat(glm::vec3(0.0f, 0.0f, 0.0f)); auto model = AddComponent(cube, "Model"); - model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; + model->ModelFile = "Models/cardboardBox/BoxFixed.obj"; auto physics = AddComponent(cube, "Physics"); physics->Mass = 100; diff --git a/src/Systems/PhysicsSystem.cpp b/src/Systems/PhysicsSystem.cpp index b4f8200..059629c 100644 --- a/src/Systems/PhysicsSystem.cpp +++ b/src/Systems/PhysicsSystem.cpp @@ -67,6 +67,7 @@ void Systems::PhysicsSystem::RegisterComponents(ComponentFactory* cf) cf->Register("Sphere", []() { return new Components::Sphere(); }); cf->Register("Vehicle", []() { return new Components::Vehicle(); }); cf->Register("Wheel", []() { return new Components::Wheel(); }); + cf->Register("MeshShape", []() { return new Components::MeshShape(); }); } void Systems::PhysicsSystem::Update(double dt) @@ -183,11 +184,12 @@ void Systems::PhysicsSystem::OnEntityCommit( EntityID entity ) auto sphereComponent = m_World->GetComponent(entity, "Sphere"); auto boxComponent = m_World->GetComponent(entity, "Box"); + auto meshShapeComponent = m_World->GetComponent(entity, "MeshShape"); - - hkpConvexShape* shape; + hkpShape* shape = nullptr; hkpRigidBodyCinfo rigidBodyInfo; hkMassProperties massProperties; + if (sphereComponent) { @@ -220,16 +222,83 @@ void Systems::PhysicsSystem::OnEntityCommit( EntityID entity ) rigidBodyInfo.m_motionType = hkpMotion::MOTION_BOX_INERTIA; } hkpInertiaTensorComputer::computeBoxSurfaceMassProperties(hkVector4(boxComponent->Width - thickness, boxComponent->Height - thickness, boxComponent->Depth - thickness), physicsComponent->Mass, thickness, massProperties); + + } + else if(meshShapeComponent) + { + std::vector* vertices = new std::vector; + std::vector* vertexIndices = new std::vector; + auto meshShape = m_World->GetResourceManager()->Load("OBJ", meshShapeComponent->ResourceName); + + for (auto &vertex : meshShape->Vertices) + { + hkReal x, y, z; + std::tie(x, y, z) = vertex; + vertices->push_back(x); + vertices->push_back(y); + vertices->push_back(z); + } + + int i = 0; + for (auto &face : meshShape->Faces) + { + for (auto &faceDef : face.Definitions) + { + /*hkReal x, y, z; + std::tie(x, y, z) = meshShape->Vertices.at(faceDef.VertexIndex - 1); + vertices.push_back(x); + vertices.push_back(y); + vertices.push_back(z);*/ + vertexIndices->push_back(faceDef.VertexIndex - 1); + //vertexIndices.push_back(i++); + } + } + + hkpExtendedMeshShape* mesh = new hkpExtendedMeshShape(); + mesh->setRadius( 0.05f); + { + hkpExtendedMeshShape::TrianglesSubpart part; + part.m_numTriangleShapes = meshShape->Faces.size(); + part.m_indexBase = vertexIndices->data(); + part.m_indexStriding = sizeof(hkUint16) * 3; + + part.m_numVertices = vertices->size() / 3; + part.m_vertexBase = vertices->data(); + part.m_vertexStriding = sizeof(hkReal) * 3; + + part.m_stridingType = hkpExtendedMeshShape::INDICES_INT16; + + + + mesh->addTrianglesSubpart(part); + } + + if (physicsComponent->Static) + { + rigidBodyInfo.m_motionType = hkpMotion::MOTION_FIXED; + } + else + { + rigidBodyInfo.m_motionType = hkpMotion::MOTION_BOX_INERTIA; + } + hkpInertiaTensorComputer::computeShapeVolumeMassProperties(mesh, physicsComponent->Mass, massProperties); + rigidBodyInfo.m_shape = mesh; + m_hkpExtendedMeshShapes[entity].ExtendedMeshShape = mesh; + m_hkpExtendedMeshShapes[entity].VertexIndices = vertexIndices; + m_hkpExtendedMeshShapes[entity].Vertices = vertices; + shape = mesh; } else { return; } + rigidBodyInfo.m_position.set(transformComponent->Position.x, transformComponent->Position.y, transformComponent->Position.z); rigidBodyInfo.m_inertiaTensor = massProperties.m_inertiaTensor; - rigidBodyInfo.m_centerOfMass = massProperties.m_centerOfMass; + //rigidBodyInfo.m_centerOfMass = massProperties.m_centerOfMass; rigidBodyInfo.m_mass = massProperties.m_mass; + // Create RigidBody hkpRigidBody* rigidBody = new hkpRigidBody(rigidBodyInfo); @@ -271,108 +340,10 @@ void Systems::PhysicsSystem::OnEntityCommit( EntityID entity ) shape->removeReference(); rigidBody->removeReference(); + + } } -/* - -void Systems::PhysicsSystem::SetUpPhysicsState(EntityID entity, EntityID parent) -{ - auto transformComponent = m_World->GetComponent(entity, "Transform"); - if (!transformComponent) - return; - - auto physicsComponent = m_World->GetComponent(entity, "Physics"); - if (!physicsComponent) - return; - - auto sphereComponent = m_World->GetComponent(entity, "Sphere"); - auto boxComponent = m_World->GetComponent(entity, "Box"); - - - hkpConvexShape* shape; - hkpRigidBodyCinfo rigidBodyInfo; - hkMassProperties massProperties; - - - if (sphereComponent) - { - shape = new hkpSphereShape(sphereComponent->Radius); - rigidBodyInfo.m_shape = shape; - - if (physicsComponent->Static) - { - rigidBodyInfo.m_motionType = hkpMotion::MOTION_FIXED; - } - else - { - rigidBodyInfo.m_motionType = hkpMotion::MOTION_SPHERE_INERTIA; - } - - hkpInertiaTensorComputer::computeSphereVolumeMassProperties(sphereComponent->Radius, physicsComponent->Mass, massProperties); - - } - else if (boxComponent) - { - hkReal thickness = 0.05; - shape = new hkpBoxShape(hkVector4(boxComponent->Width - thickness, boxComponent->Height - thickness, boxComponent->Depth - thickness)); - rigidBodyInfo.m_shape = shape; - if (physicsComponent->Static) - { - rigidBodyInfo.m_motionType = hkpMotion::MOTION_FIXED; - } - else - { - rigidBodyInfo.m_motionType = hkpMotion::MOTION_BOX_INERTIA; - } - hkpInertiaTensorComputer::computeBoxSurfaceMassProperties(hkVector4(boxComponent->Width - thickness, boxComponent->Height - thickness, boxComponent->Depth - thickness), physicsComponent->Mass, thickness, massProperties); - } - else - { - return; - } - - rigidBodyInfo.m_position.set(transformComponent->Position.x, transformComponent->Position.y, transformComponent->Position.z); - rigidBodyInfo.m_inertiaTensor = massProperties.m_inertiaTensor; - rigidBodyInfo.m_centerOfMass = massProperties.m_centerOfMass; - rigidBodyInfo.m_mass = massProperties.m_mass; - - // Create RigidBody - hkpRigidBody* rigidBody = new hkpRigidBody(rigidBodyInfo); - - - auto vehicleComponent = m_World->GetComponent(entity, "Vehicle"); - if (vehicleComponent && m_Vehicles.find(entity) == m_Vehicles.end()) - { - VehicleSetup vehicleSetup; - - // Create the basic vehicle. - m_Vehicles[entity] = new hkpVehicleInstance(rigidBody); - vehicleSetup.buildVehicle(m_PhysicsWorld, *m_Vehicles[entity]); - // Add the vehicle's entities and phantoms to the world - m_Vehicles[entity]->addToWorld(m_PhysicsWorld); - - m_RigidBodies[entity] = rigidBody; - - // The vehicle is an action - m_PhysicsWorld->addAction(m_Vehicles[entity]); - - //m_Vehicles[entity]->m_rpm = 0.0f; // Not sure why this one should be here - - shape->removeReference(); - rigidBody->removeReference(); - } - else - { - m_PhysicsWorld->addEntity(rigidBody); - m_RigidBodies[entity] = rigidBody; - shape->removeReference(); - rigidBody->removeReference(); - } -} -*/ - - - void Systems::PhysicsSystem::TearDownPhysicsState(EntityID entity, EntityID parent) { diff --git a/src/Systems/PhysicsSystem.h b/src/Systems/PhysicsSystem.h index f5ca539..e69a38c 100644 --- a/src/Systems/PhysicsSystem.h +++ b/src/Systems/PhysicsSystem.h @@ -8,6 +8,8 @@ #include "Components/Box.h" #include "Components/Vehicle.h" #include "Components/Input.h" +#include "Components/MeshShape.h" +#include "OBJ.h" // Math and base include #include @@ -34,6 +36,8 @@ #include #include +#include + #include "Physics/VehicleSetup.h" #include @@ -66,10 +70,22 @@ private: void SetupPhysics(hkpWorld* physicsWorld); std::unordered_map m_RigidBodies; + + std::unordered_map m_Vehicles; std::vector m_Wheels; hkpVehicleInstance* Systems::PhysicsSystem::createVehicle(VehicleSetup& vehicleSetup, hkpRigidBody* chassis); + + + + struct ExtendedShapeData + { + hkpExtendedMeshShape* ExtendedMeshShape; + std::vector* Vertices; + std::vector* VertexIndices; + }; + std::unordered_map m_hkpExtendedMeshShapes; }; } diff --git a/src/Systems/RenderSystem.cpp b/src/Systems/RenderSystem.cpp index fe254f4..60044f8 100755 --- a/src/Systems/RenderSystem.cpp +++ b/src/Systems/RenderSystem.cpp @@ -72,7 +72,8 @@ void Systems::RenderSystem::RegisterComponents(ComponentFactory* cf) void Systems::RenderSystem::RegisterResourceTypes(ResourceManager* rm) { - rm->RegisterType("Model", [rm](std::string resourceName) { return new Model(OBJ(resourceName), rm); }); + rm->RegisterType("Model", [rm](std::string resourceName) { return new Model(rm, *rm->Load("OBJ", resourceName)); }); + rm->RegisterType("OBJ", [](std::string resourceName) { return new OBJ(resourceName); }); rm->RegisterType("Texture", [](std::string resourceName) { return new Texture(resourceName); }); } diff --git a/vs11/Returngeance/Returngeance.vcxproj b/vs11/Returngeance/Returngeance.vcxproj index 65ee872..3702a27 100755 --- a/vs11/Returngeance/Returngeance.vcxproj +++ b/vs11/Returngeance/Returngeance.vcxproj @@ -80,7 +80,7 @@ true true true - _CRT_SECURE_NO_WARNINGS;_MBCS;%(PreprocessorDefinitions) + _CRT_SECURE_NO_WARNINGS;_MBCS;HK_CONFIG_SIMD=1;%(PreprocessorDefinitions) Create PrecompiledHeader.h StreamingSIMDExtensions2 @@ -126,6 +126,7 @@ + @@ -162,6 +163,7 @@ + diff --git a/vs11/Returngeance/Returngeance.vcxproj.filters b/vs11/Returngeance/Returngeance.vcxproj.filters index dfd85bb..5117384 100755 --- a/vs11/Returngeance/Returngeance.vcxproj.filters +++ b/vs11/Returngeance/Returngeance.vcxproj.filters @@ -230,6 +230,12 @@ Physics + + Physics\Components + + + Util + From 00d27f0058cbb6873a41d66ebfe89501651cc792 Mon Sep 17 00:00:00 2001 From: ViktorLjung Date: Mon, 28 Apr 2014 02:06:08 +0200 Subject: [PATCH 25/65] Physics now running on multiple threads --- src/GameWorld.cpp | 86 +++++++++++++--------- src/Systems/PhysicsSystem.cpp | 130 ++++++++++++++++++++++++---------- src/Systems/PhysicsSystem.h | 8 +++ 3 files changed, 156 insertions(+), 68 deletions(-) diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index fe71de6..bdf3f29 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -32,6 +32,18 @@ void GameWorld::Initialize() CommitEntity(ground); } + { + auto camera = CreateEntity(); + auto transform = AddComponent(camera, "Transform"); + transform->Position.z = 20.f; + transform->Position.y = 10.f; + transform->Orientation = glm::quat(glm::vec3(-glm::pi() / 8.f, 0.f, 0.f)); + auto cameraComp = AddComponent(camera, "Camera"); + cameraComp->FarClip = 2000.f; + AddComponent(camera, "Input"); + auto freeSteering = AddComponent(camera, "FreeSteering"); + CommitEntity(camera); + } { auto jeep = CreateEntity(); @@ -60,20 +72,6 @@ void GameWorld::Initialize() AddComponent(jeep, "Input"); - - { - auto camera = CreateEntity(); - auto transform = AddComponent(camera, "Transform"); - transform->Position.z = 20.f; - transform->Position.y = 10.f; - transform->Orientation = glm::quat(glm::vec3(-glm::pi() / 8.f, 0.f, 0.f)); - auto cameraComp = AddComponent(camera, "Camera"); - cameraComp->FarClip = 2000.f; - AddComponent(camera, "Input"); - auto freeSteering = AddComponent(camera, "FreeSteering"); - CommitEntity(camera); - } - { auto chassis = CreateEntity(jeep); auto transform = AddComponent(chassis, "Transform"); @@ -160,24 +158,48 @@ void GameWorld::Initialize() CommitEntity(jeep); } - for(int i = 0; i < 0; i++) - { - auto cube = CreateEntity(); - auto transform = AddComponent(cube, "Transform"); - transform->Position = glm::vec3(20, 10 + i*2, 0); - transform->Scale = glm::vec3(1); - transform->Orientation = glm::quat(glm::vec3(0.0f, 0.0f, 0.0f)); - auto model = AddComponent(cube, "Model"); - model->ModelFile = "Models/cardboardBox/BoxFixed.obj"; - - auto physics = AddComponent(cube, "Physics"); - physics->Mass = 100; - auto box = AddComponent(cube, "BoxShape"); - box->Width = 0.5f; - box->Height = 0.5f; - box->Depth = 0.5f; - CommitEntity(cube); - } + + for (int x = 0; x < 5; x++) + for (int y = 0; y < 5; y++) + { + auto cube = CreateEntity(); + auto transform = AddComponent(cube, "Transform"); + transform->Position = glm::vec3(3 * x + 0.1f + 20.f, 3 * y + 0.1f + 1.f, 0); + transform->Scale = glm::vec3(3); + transform->Orientation = glm::quat(glm::vec3(0.0f, 0.0f, 0.0f)); + auto model = AddComponent(cube, "Model"); + model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; + + auto physics = AddComponent(cube, "Physics"); + physics->Mass = 100; + auto box = AddComponent(cube, "BoxShape"); + box->Width = 1.5f; + box->Height = 1.5f; + box->Depth = 1.5f; + CommitEntity(cube); + } + + /*for (int x = 0; x < 5; x++) + for (int y = 0; y < 5; y++) + { + auto cube = CreateEntity(); + auto transform = AddComponent(cube, "Transform"); + transform->Position = glm::vec3(3 * x + 0.1f + -20.f, 3 * y + 0.1f + 1.f, 0); + transform->Scale = glm::vec3(3); + transform->Orientation = glm::quat(glm::vec3(0.0f, 0.0f, 0.0f)); + auto model = AddComponent(cube, "Model"); + model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; + + auto physics = AddComponent(cube, "Physics"); + physics->Mass = 100; + auto box = AddComponent(cube, "BoxShape"); + box->Width = 1.5f; + box->Height = 1.5f; + box->Depth = 1.5f; + CommitEntity(cube); + } +*/ + /*{ auto entity = CreateEntity(); diff --git a/src/Systems/PhysicsSystem.cpp b/src/Systems/PhysicsSystem.cpp index 2554d1d..ab19101 100644 --- a/src/Systems/PhysicsSystem.cpp +++ b/src/Systems/PhysicsSystem.cpp @@ -28,36 +28,81 @@ Systems::PhysicsSystem::PhysicsSystem(World* world) : System(world) { m_Accumulator = 0; + + hkMemorySystem::FrameInfo finfo(500 * 1024); // Allocate 500KB of Physics solver buffer + hkMemoryRouter* memoryRouter = hkMemoryInitUtil::initDefault(hkMallocAllocator::m_defaultMallocAllocator, finfo); + hkBaseSystem::init(memoryRouter, HavokErrorReport); + + + // Get the number of physical threads available on the system + hkHardwareInfo hwInfo; + hkGetHardwareInfo(hwInfo); + m_TotalNumThreadsUsed = hwInfo.m_numThreads; + + // We use one less than this for our thread pool, because we must also use this thread for our simulation + hkCpuJobThreadPoolCinfo threadPoolCinfo; + threadPoolCinfo.m_numThreads = m_TotalNumThreadsUsed - 1; + + // This line enables timers collection, by allocating 200 Kb per thread. If you leave this at its default (0), + // timer collection will not be enabled. + threadPoolCinfo.m_timerBufferPerThreadAllocation = 200000; + m_ThreadPool = new hkCpuJobThreadPool(threadPoolCinfo); + + hkJobQueueCinfo info; + info.m_jobQueueHwSetup.m_numCpuThreads = m_TotalNumThreadsUsed; + m_JobQueue = new hkJobQueue(info); + + // + // Enable monitors for this thread. + // + + // Monitors have been enabled for thread pool threads already (see above comment). + hkMonitorStream::getInstance().resize(200000); + { - hkMemorySystem::FrameInfo finfo(500 * 1024); // Allocate 500KB of Physics solver buffer - hkMemoryRouter* memoryRouter = hkMemoryInitUtil::initDefault(hkMallocAllocator::m_defaultMallocAllocator, finfo); - hkBaseSystem::init(memoryRouter, HavokErrorReport); - - hkpWorldCinfo worldInfo; + + // Set the simulation type of the world to multi-threaded. + worldInfo.m_simulationType = hkpWorldCinfo::SIMULATION_TYPE_MULTITHREADED; + worldInfo.setupSolverInfo(hkpWorldCinfo::SOLVER_TYPE_4ITERS_MEDIUM); - worldInfo.m_gravity = hkVector4(0.0f, -9.8f, 0.0f); - worldInfo.m_broadPhaseBorderBehaviour = hkpWorldCinfo::BROADPHASE_BORDER_FIX_ENTITY; // just fix the entity if the object falls off too far + worldInfo.m_gravity = hkVector4(0.0f, -9.82f, 0.0f); + worldInfo.m_broadPhaseBorderBehaviour = hkpWorldCinfo::BROADPHASE_BORDER_REMOVE_ENTITY; // just fix the entity if the object falls off too far // You must specify the size of the broad phase - objects should not be simulated outside this region worldInfo.setBroadPhaseWorldSize(1000.0f); m_PhysicsWorld = new hkpWorld(worldInfo); - } - // Register all collision agents, even though only box - box will be used in this particular example. - // It's important to register collision agents before adding any entities to the world. - hkpAgentRegisterUtil::registerAllAgents(m_PhysicsWorld->getCollisionDispatcher()); - - // - // Initialize the visual debugger so we can connect remotely to the simulation - // The context must exist beyond the use of the VDB instance, and you can make - // whatever contexts you like for your own viewer types. - // - hkpPhysicsContext* context = new hkpPhysicsContext; - hkpPhysicsContext::registerAllPhysicsProcesses(); // all the physics viewers - context->addWorld(m_PhysicsWorld); // add the physics world so the viewers can see it - SetupVisualDebugger(context); - //SetupPhysics(m_PhysicsWorld); + + + + // When the simulation type is SIMULATION_TYPE_MULTITHREADED, in the debug build, the sdk performs checks + // to make sure only one thread is modifying the world at once to prevent multithreaded bugs. Each thread + // must call markForRead / markForWrite before it modifies the world to enable these checks. + m_PhysicsWorld->markForWrite(); + + // Register all collision agents, even though only box - box will be used in this particular example. + // It's important to register collision agents before adding any entities to the world. + hkpAgentRegisterUtil::registerAllAgents(m_PhysicsWorld->getCollisionDispatcher()); + + // We need to register all modules we will be running multi-threaded with the job queue + m_PhysicsWorld->registerWithJobQueue(m_JobQueue); + + + // + // Initialize the visual debugger so we can connect remotely to the simulation + // The context must exist beyond the use of the VDB instance, and you can make + // whatever contexts you like for your own viewer types. + // + m_Context = new hkpPhysicsContext; + hkpPhysicsContext::registerAllPhysicsProcesses(); // all the physics viewers + m_Context->addWorld(m_PhysicsWorld); // add the physics world so the viewers can see it + + SetupVisualDebugger(m_Context); + + m_PhysicsWorld->unmarkForWrite(); + } + } void Systems::PhysicsSystem::RegisterComponents(ComponentFactory* cf) @@ -86,9 +131,11 @@ void Systems::PhysicsSystem::Update(double dt) if(m_RigidBodies[entity]->isActive()) { + m_PhysicsWorld->markForWrite(); hkVector4 position(transformComponent->Position.x, transformComponent->Position.y, transformComponent->Position.z); hkQuaternion rotation(transformComponent->Orientation.x, transformComponent->Orientation.y, transformComponent->Orientation.z, transformComponent->Orientation.w); m_RigidBodies[entity]->setPositionAndRotation(position, rotation); + m_PhysicsWorld->unmarkForWrite(); } } @@ -100,12 +147,18 @@ void Systems::PhysicsSystem::Update(double dt) m_Accumulator += dt; while (m_Accumulator >= timestep) { - m_PhysicsWorld->stepDeltaTime(timestep); + m_PhysicsWorld->stepMultithreaded(m_JobQueue, m_ThreadPool, timestep); m_Accumulator -= timestep; - } - // Step the visual debugger - StepVisualDebugger(); + m_Context->syncTimers(m_ThreadPool); + // Step the visual debugger + StepVisualDebugger(); + } + + + // Clear accumulated timer data in this thread and all slave threads + hkMonitorStream::getInstance().reset(); + m_ThreadPool->clearTimerData(); } void Systems::PhysicsSystem::UpdateEntity(double dt, EntityID entity, EntityID parent) @@ -120,6 +173,7 @@ void Systems::PhysicsSystem::UpdateEntity(double dt, EntityID entity, EntityID p EntityID car = m_World->GetEntityParent(entity); if(m_Vehicles.find(car) != m_Vehicles.end()) { + m_PhysicsWorld->markForWrite(); m_Vehicles[car]->getChassis()->activate(); hkVector4 hardPoint = m_Vehicles[car]->m_suspension->m_wheelParams[wheelComponent->ID].m_hardpointChassisSpace; @@ -132,22 +186,26 @@ void Systems::PhysicsSystem::UpdateEntity(double dt, EntityID entity, EntityID p hkReal spinAngle = -m_Vehicles[car]->m_wheelsInfo[wheelComponent->ID].m_spinAngle; glm::quat orientation = glm::quat(steeringOrientation(3), steeringOrientation(0), steeringOrientation(1), steeringOrientation(2)) * glm::angleAxis(spinAngle, glm::vec3(1, 0, 0)); transformComponent->Orientation = orientation * wheelComponent->OriginalOrientation; + m_PhysicsWorld->unmarkForWrite(); } } else if(m_Vehicles.find(entity) != m_Vehicles.end()) { + m_PhysicsWorld->markForWrite(); hkVector4 position = m_RigidBodies[entity]->getPosition(); transformComponent->Position = glm::vec3(position(0), position(1), position(2)); hkQuaternion orientation = m_RigidBodies[entity]->getRotation(); - transformComponent->Orientation = glm::quat(orientation(3),orientation(0), orientation(1), orientation(2)); - + transformComponent->Orientation = glm::quat(orientation(3), orientation(0), orientation(1), orientation(2)); + m_PhysicsWorld->unmarkForWrite(); } else if(m_RigidBodies.find(entity) != m_RigidBodies.end()) { + m_PhysicsWorld->markForWrite(); hkVector4 position = m_RigidBodies[entity]->getPosition(); transformComponent->Position = glm::vec3(position(0), position(1), position(2)); hkQuaternion orientation = m_RigidBodies[entity]->getRotation(); transformComponent->Orientation = glm::quat(orientation(3),orientation(0), orientation(1), orientation(2)); + m_PhysicsWorld->unmarkForWrite(); } @@ -156,10 +214,12 @@ void Systems::PhysicsSystem::UpdateEntity(double dt, EntityID entity, EntityID p auto inputComponent = m_World->GetComponent(entity, "Input"); if (vehicleComponent && inputComponent) { + m_PhysicsWorld->markForWrite(); hkpVehicleDriverInputAnalogStatus* deviceStatus = (hkpVehicleDriverInputAnalogStatus*)m_Vehicles[entity]->m_deviceStatus; deviceStatus->m_positionY = inputComponent->KeyState[GLFW_KEY_UP] * -1 + inputComponent->KeyState[GLFW_KEY_DOWN] * 1; deviceStatus->m_positionX = inputComponent->KeyState[GLFW_KEY_LEFT] * -1 + inputComponent->KeyState[GLFW_KEY_RIGHT] * 1; deviceStatus->m_handbrakeButtonPressed = inputComponent->KeyState[GLFW_KEY_RIGHT_CONTROL]; + m_PhysicsWorld->unmarkForWrite(); } } @@ -244,13 +304,7 @@ void Systems::PhysicsSystem::OnEntityCommit( EntityID entity ) { for (auto &faceDef : face.Definitions) { - /*hkReal x, y, z; - std::tie(x, y, z) = meshShape->Vertices.at(faceDef.VertexIndex - 1); - vertices.push_back(x); - vertices.push_back(y); - vertices.push_back(z);*/ vertexIndices->push_back(faceDef.VertexIndex - 1); - //vertexIndices.push_back(i++); } } @@ -315,8 +369,9 @@ void Systems::PhysicsSystem::OnEntityCommit( EntityID entity ) i--; } } - VehicleSetup vehicleSetup; + m_PhysicsWorld->markForWrite(); + VehicleSetup vehicleSetup; // Create the basic vehicle. m_Vehicles[entity] = new hkpVehicleInstance(rigidBody); vehicleSetup.buildVehicle(m_World, m_PhysicsWorld, *m_Vehicles[entity], entity, m_Wheels); @@ -327,6 +382,7 @@ void Systems::PhysicsSystem::OnEntityCommit( EntityID entity ) // The vehicle is an action m_PhysicsWorld->addAction(m_Vehicles[entity]); + m_PhysicsWorld->unmarkForWrite(); //m_Vehicles[entity]->m_rpm = 0.0f; // Not sure why this one should be here m_Wheels.clear(); @@ -335,9 +391,11 @@ void Systems::PhysicsSystem::OnEntityCommit( EntityID entity ) } else { + m_PhysicsWorld->markForWrite(); m_PhysicsWorld->addEntity(rigidBody); m_RigidBodies[entity] = rigidBody; - + m_PhysicsWorld->unmarkForWrite(); + shape->removeReference(); rigidBody->removeReference(); diff --git a/src/Systems/PhysicsSystem.h b/src/Systems/PhysicsSystem.h index cd02d1d..82a0222 100644 --- a/src/Systems/PhysicsSystem.h +++ b/src/Systems/PhysicsSystem.h @@ -38,6 +38,10 @@ #include +#include +#include +#include + #include "Physics/VehicleSetup.h" #include @@ -71,6 +75,10 @@ private: std::unordered_map m_RigidBodies; + hkJobThreadPool* m_ThreadPool; + hkJobQueue* m_JobQueue; + int m_TotalNumThreadsUsed; + hkpPhysicsContext* m_Context; std::unordered_map m_Vehicles; std::vector m_Wheels; From 7e32946173f0151eb912a69cc7d234754e3f7ae8 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Mon, 28 Apr 2014 04:00:53 +0200 Subject: [PATCH 26/65] Optimizations --- src/Systems/RenderSystem.cpp | 7 ++++--- src/Systems/TransformSystem.cpp | 31 +++++++++++++++++++++++++++++++ src/Systems/TransformSystem.h | 3 ++- src/World.cpp | 9 +++------ 4 files changed, 40 insertions(+), 10 deletions(-) diff --git a/src/Systems/RenderSystem.cpp b/src/Systems/RenderSystem.cpp index 60044f8..23c8274 100755 --- a/src/Systems/RenderSystem.cpp +++ b/src/Systems/RenderSystem.cpp @@ -23,10 +23,11 @@ void Systems::RenderSystem::UpdateEntity(double dt, EntityID entity, EntityID pa auto model = m_World->GetResourceManager()->Load("Model", modelComponent->ModelFile); if (model != nullptr) { - glm::vec3 position = m_TransformSystem->AbsolutePosition(entity); + /*glm::vec3 position = m_TransformSystem->AbsolutePosition(entity); glm::quat orientation = m_TransformSystem->AbsoluteOrientation(entity); - glm::vec3 scale = m_TransformSystem->AbsoluteScale(entity); - m_Renderer->AddModelToDraw(model, position, orientation, scale, modelComponent->Visible, modelComponent->ShadowCaster); + glm::vec3 scale = m_TransformSystem->AbsoluteScale(entity);*/ + Components::Transform absoluteTransform = m_TransformSystem->AbsoluteTransform(entity); + m_Renderer->AddModelToDraw(model, absoluteTransform.Position, absoluteTransform.Orientation, absoluteTransform.Scale, modelComponent->Visible, modelComponent->ShadowCaster); } } diff --git a/src/Systems/TransformSystem.cpp b/src/Systems/TransformSystem.cpp index 494acd0..383c123 100755 --- a/src/Systems/TransformSystem.cpp +++ b/src/Systems/TransformSystem.cpp @@ -60,3 +60,34 @@ glm::vec3 Systems::TransformSystem::AbsoluteScale(EntityID entity) return absScale; } + +Components::Transform Systems::TransformSystem::AbsoluteTransform(EntityID entity) +{ + glm::vec3 absPosition; + glm::quat absOrientation; + glm::vec3 absScale(1); + + do + { + auto transform = m_World->GetComponent(entity, "Transform"); + entity = m_World->GetEntityParent(entity); + auto transform2 = m_World->GetComponent(entity, "Transform"); + + // Position + if (entity != 0) + absPosition += transform2->Orientation * transform->Position; + else + absPosition += transform->Position; + // Orientation + absOrientation = transform->Orientation * absOrientation; + // Scale + absScale *= transform->Scale; + } while (entity != 0); + + Components::Transform transform; + transform.Position = absPosition; + transform.Orientation = absOrientation; + transform.Scale = absScale; + + return transform; +} diff --git a/src/Systems/TransformSystem.h b/src/Systems/TransformSystem.h index 542000d..754a567 100755 --- a/src/Systems/TransformSystem.h +++ b/src/Systems/TransformSystem.h @@ -15,7 +15,8 @@ public: //void Update(double dt) override; //void UpdateEntity(double dt, EntityID entity, EntityID parent) override; - + + Components::Transform AbsoluteTransform(EntityID entity); glm::vec3 AbsolutePosition(EntityID entity); glm::quat AbsoluteOrientation(EntityID entity); glm::vec3 AbsoluteScale(EntityID entity); diff --git a/src/World.cpp b/src/World.cpp index 0b6a245..6e168c2 100755 --- a/src/World.cpp +++ b/src/World.cpp @@ -22,16 +22,13 @@ EntityID World::GenerateEntityID() void World::RecursiveUpdate(std::shared_ptr system, double dt, EntityID parentEntity) { - for (auto pair : m_EntityParents) + for (auto &pair : m_EntityParents) { EntityID child = pair.first; EntityID parent = pair.second; - if (parent == parentEntity) - { - system->UpdateEntity(dt, child, parent); - RecursiveUpdate(system, dt, child); - } + system->UpdateEntity(dt, child, parent); + //RecursiveUpdate(system, dt, child); } } From 55059c05fed94c1140cde989bca9d1ecb5282960 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Mon, 28 Apr 2014 04:56:37 +0200 Subject: [PATCH 27/65] Debugging Optimizations Removed Basic Runtime Checks flag /RTC1 Added Maximize Speed flag /O2 Changed Debug Information Format flag /ZI -> /Zi Added Enable Intrinsic Functions flag /Oi --- vs11/Returngeance/Returngeance.vcxproj | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/vs11/Returngeance/Returngeance.vcxproj b/vs11/Returngeance/Returngeance.vcxproj index 77e653e..b78075c 100755 --- a/vs11/Returngeance/Returngeance.vcxproj +++ b/vs11/Returngeance/Returngeance.vcxproj @@ -53,15 +53,15 @@ Level3 - Disabled - true _WINDOWS;WIN32;_WIN32;_DEBUG;HK_DEBUG;HK_DEBUG_SLOW;_XT_STATICLINK;_CONSOLE;_ALLOW_ITERATOR_DEBUG_LEVEL_MISMATCH;HK_CONFIG_SIMD=1;DEBUG;_CRT_SECURE_NO_WARNINGS;_MBCS;%(PreprocessorDefinitions) Create PrecompiledHeader.h - true MultiThreadedDebugDLL - StreamingSIMDExtensions2 false + Default + ProgramDatabase + MaxSpeed + true true From 0b8a3230c308aed83c307ffcd15dfebe130e2a6e Mon Sep 17 00:00:00 2001 From: Stiffly Date: Mon, 28 Apr 2014 16:18:08 +0200 Subject: [PATCH 28/65] Fixed GetComponent bug which would create invalid components if the entity didn't have the requested component --- src/World.h | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/World.h b/src/World.h index d0c0692..8829933 100755 --- a/src/World.h +++ b/src/World.h @@ -135,7 +135,16 @@ std::shared_ptr World::AddComponent(EntityID entity, std::string componentTyp template T* World::GetComponent(EntityID entity, std::string componentType) { - return (T*)m_EntityComponents[entity][componentType].get(); + auto components = m_EntityComponents[entity]; + auto it = components.find(componentType); + if (it != components.end()) + { + return static_cast(it->second.get()); + } + else + { + return nullptr; + } } #endif // World_h__ \ No newline at end of file From 5e1355f3fe4c0aeb099c51cd1cf2883c398e6473 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Mon, 28 Apr 2014 04:00:53 +0200 Subject: [PATCH 29/65] Optimizations (cherry picked from commit 7e32946173f0151eb912a69cc7d234754e3f7ae8) --- src/Systems/RenderSystem.cpp | 7 ++++--- src/Systems/TransformSystem.cpp | 31 +++++++++++++++++++++++++++++++ src/Systems/TransformSystem.h | 3 ++- src/World.cpp | 9 +++------ 4 files changed, 40 insertions(+), 10 deletions(-) diff --git a/src/Systems/RenderSystem.cpp b/src/Systems/RenderSystem.cpp index d8c3c19..9e2b426 100755 --- a/src/Systems/RenderSystem.cpp +++ b/src/Systems/RenderSystem.cpp @@ -23,10 +23,11 @@ void Systems::RenderSystem::UpdateEntity(double dt, EntityID entity, EntityID pa auto model = m_World->GetResourceManager()->Load("Model", modelComponent->ModelFile); if (model != nullptr) { - glm::vec3 position = m_TransformSystem->AbsolutePosition(entity); + /*glm::vec3 position = m_TransformSystem->AbsolutePosition(entity); glm::quat orientation = m_TransformSystem->AbsoluteOrientation(entity); - glm::vec3 scale = m_TransformSystem->AbsoluteScale(entity); - m_Renderer->AddModelToDraw(model, position, orientation, scale, modelComponent->Visible, modelComponent->ShadowCaster); + glm::vec3 scale = m_TransformSystem->AbsoluteScale(entity);*/ + Components::Transform absoluteTransform = m_TransformSystem->AbsoluteTransform(entity); + m_Renderer->AddModelToDraw(model, absoluteTransform.Position, absoluteTransform.Orientation, absoluteTransform.Scale, modelComponent->Visible, modelComponent->ShadowCaster); } } diff --git a/src/Systems/TransformSystem.cpp b/src/Systems/TransformSystem.cpp index a23d92b..0d1767d 100755 --- a/src/Systems/TransformSystem.cpp +++ b/src/Systems/TransformSystem.cpp @@ -60,3 +60,34 @@ glm::vec3 Systems::TransformSystem::AbsoluteScale(EntityID entity) return absScale; } + +Components::Transform Systems::TransformSystem::AbsoluteTransform(EntityID entity) +{ + glm::vec3 absPosition; + glm::quat absOrientation; + glm::vec3 absScale(1); + + do + { + auto transform = m_World->GetComponent(entity, "Transform"); + entity = m_World->GetEntityParent(entity); + auto transform2 = m_World->GetComponent(entity, "Transform"); + + // Position + if (entity != 0) + absPosition += transform2->Orientation * transform->Position; + else + absPosition += transform->Position; + // Orientation + absOrientation = transform->Orientation * absOrientation; + // Scale + absScale *= transform->Scale; + } while (entity != 0); + + Components::Transform transform; + transform.Position = absPosition; + transform.Orientation = absOrientation; + transform.Scale = absScale; + + return transform; +} diff --git a/src/Systems/TransformSystem.h b/src/Systems/TransformSystem.h index 542000d..754a567 100755 --- a/src/Systems/TransformSystem.h +++ b/src/Systems/TransformSystem.h @@ -15,7 +15,8 @@ public: //void Update(double dt) override; //void UpdateEntity(double dt, EntityID entity, EntityID parent) override; - + + Components::Transform AbsoluteTransform(EntityID entity); glm::vec3 AbsolutePosition(EntityID entity); glm::quat AbsoluteOrientation(EntityID entity); glm::vec3 AbsoluteScale(EntityID entity); diff --git a/src/World.cpp b/src/World.cpp index ef9d236..e6a10b8 100755 --- a/src/World.cpp +++ b/src/World.cpp @@ -22,16 +22,13 @@ EntityID World::GenerateEntityID() void World::RecursiveUpdate(std::shared_ptr system, double dt, EntityID parentEntity) { - for (auto pair : m_EntityParents) + for (auto &pair : m_EntityParents) { EntityID child = pair.first; EntityID parent = pair.second; - if (parent == parentEntity) - { - system->UpdateEntity(dt, child, parent); - RecursiveUpdate(system, dt, child); - } + system->UpdateEntity(dt, child, parent); + //RecursiveUpdate(system, dt, child); } } From d917be0135d951745ff8b8a7119f9b11b2c1ca1f Mon Sep 17 00:00:00 2001 From: Stiffly Date: Mon, 28 Apr 2014 17:55:51 +0200 Subject: [PATCH 30/65] Default values for ParticleEmitter.h --- src/Components/ParticleEmitter.h | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/Components/ParticleEmitter.h b/src/Components/ParticleEmitter.h index 5aafcdc..afb5622 100755 --- a/src/Components/ParticleEmitter.h +++ b/src/Components/ParticleEmitter.h @@ -14,6 +14,13 @@ struct ParticleEmitter : Component { friend class Systems::ParticleSystem; + ParticleEmitter() + : SpawnFrequency(0) + , SpawnCount(0) + , SpreadAngle(0) + , LifeTime(0) + , TimeSinceLastSpawn(0) { } + EntityID ParticleTemplate; float SpawnFrequency; int SpawnCount; From ea4b7b005e160d441a2a4f9e6072f1b5e513c07a Mon Sep 17 00:00:00 2001 From: Stiffly Date: Mon, 28 Apr 2014 17:56:05 +0200 Subject: [PATCH 31/65] Now use the CloneEntity() function to spawn new particles. --- src/GameWorld.cpp | 7 ++++ src/Systems/ParticleSystem.cpp | 63 +++++++++++++++++----------------- src/Systems/ParticleSystem.h | 11 +++--- src/World.h | 7 ++++ 4 files changed, 52 insertions(+), 36 deletions(-) diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index d4bba0f..8d75f10 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -106,6 +106,13 @@ void GameWorld::Initialize() emitter->SpawnFrequency = 0.08; auto model = AddComponent(ent, "Model"); model->ModelFile = "Models/Placeholders/PhysicsTest/PointLight.obj"; + + auto particleEnt = CreateEntity(); + AddComponent(particleEnt, "Transform"); + model = AddComponent(particleEnt, "Model"); + model->ModelFile = "Models/Placeholders/PhysicsTest/PointLight.obj"; + + emitter->ParticleTemplate = particleEnt; } } } diff --git a/src/Systems/ParticleSystem.cpp b/src/Systems/ParticleSystem.cpp index b833de5..e274e3f 100644 --- a/src/Systems/ParticleSystem.cpp +++ b/src/Systems/ParticleSystem.cpp @@ -28,7 +28,7 @@ void Systems::ParticleSystem::UpdateEntity(double dt, EntityID entity, EntityID auto transformComponent = m_World->GetComponent(entity, "Transform"); if(emitterComponent->TimeSinceLastSpawn > emitterComponent->SpawnFrequency) { - SpawnParticles(entity, transformComponent->Position, emitterComponent->SpawnCount, emitterComponent->SpreadAngle, emitterComponent->LifeTime, dt); + SpawnParticles(entity); emitterComponent->TimeSinceLastSpawn = 0; } @@ -42,30 +42,28 @@ void Systems::ParticleSystem::UpdateEntity(double dt, EntityID entity, EntityID double timeLived = glfwGetTime() - it->SpawnTime; if(timeLived > particleComponent->LifeTime) { - m_World->RemoveEntity(particleID); - m_ParticleEmitter[entity].erase(it); - break; + it = m_ParticleEmitter[entity].erase(it); } else { - it++; - } - - float timeProgress = timeLived / particleComponent->LifeTime; - // The difference between the start and end value - /*float deltaColor = glm::abs(particleComponent->ColorSpectrum[0].r - particleComponent->ColorSpectrum[1].r); - it->color.r = particleComponent->ColorSpectrum[0].r + deltaColor * timeProgress; - deltaColor = glm::abs(particleComponent->ColorSpectrum[0].g - particleComponent->ColorSpectrum[1].g); - it->color.g = particleComponent->ColorSpectrum[0].g + deltaColor * timeProgress; - deltaColor = glm::abs(particleComponent->ColorSpectrum[0].b - particleComponent->ColorSpectrum[1].b); - it->color.b = particleComponent->ColorSpectrum[0].b + deltaColor * timeProgress;*/ + float timeProgress = timeLived / particleComponent->LifeTime; + // The difference between the start and end value + /*float deltaColor = glm::abs(particleComponent->ColorSpectrum[0].r - particleComponent->ColorSpectrum[1].r); + it->color.r = particleComponent->ColorSpectrum[0].r + deltaColor * timeProgress; + deltaColor = glm::abs(particleComponent->ColorSpectrum[0].g - particleComponent->ColorSpectrum[1].g); + it->color.g = particleComponent->ColorSpectrum[0].g + deltaColor * timeProgress; + deltaColor = glm::abs(particleComponent->ColorSpectrum[0].b - particleComponent->ColorSpectrum[1].b); + it->color.b = particleComponent->ColorSpectrum[0].b + deltaColor * timeProgress;*/ - ScaleInterpolation(timeProgress, particleComponent->ScaleSpectrum, transformComponent->Scale); - VelocityInterpolation(timeProgress, particleComponent->VelocitySpectrum, transformComponent->Velocity); + ScaleInterpolation(timeProgress, particleComponent->ScaleSpectrum, transformComponent->Scale); + VelocityInterpolation(timeProgress, particleComponent->VelocitySpectrum, transformComponent->Velocity); - transformComponent->Position += transformComponent->Velocity; + transformComponent->Position += transformComponent->Velocity * (float)dt; + + it++; + } } } } @@ -76,24 +74,26 @@ void Systems::ParticleSystem::RegisterComponents(ComponentFactory* cf) cf->Register("Particle", []() { return new Components::Particle(); }); } -void Systems::ParticleSystem::SpawnParticles(EntityID emitterID, glm::vec3 pos, float spawnCount, float spreadAngle, double lifeTime, double dt) + +void Systems::ParticleSystem::SpawnParticles(EntityID emitterID) { + auto emitterComponent = m_World->GetComponent(emitterID, "ParticleEmitter"); auto emitterTransform = m_World->GetComponent(emitterID, "Transform"); glm::quat emitterOrientation = emitterTransform->Orientation; - float tempSpeed = 4 * dt; + float tempSpeed = 4; glm::vec3 speed = glm::vec3(tempSpeed); - for(int i = 0; i < spawnCount; i++) + for(int i = 0; i < emitterComponent->SpawnCount; i++) { - auto ent = m_World->CreateEntity(); - - auto particleTransform = m_World->AddComponent(ent, "Transform"); - particleTransform->Position.x = pos.x; - particleTransform->Position.y = pos.y; - particleTransform->Position.z = pos.z; + auto ent = m_World->CloneEntity(emitterComponent->ParticleTemplate); + + auto particleTransform = m_World->GetComponent(ent, "Transform"); + particleTransform->Position = emitterTransform->Position; particleTransform->Scale = glm::vec3(1, 1, 1); + //The emitter's orientation as "start value" times the default direction for quaternion. Times the speed, and then rotate on x and y axis with the randomized spread angle. + float spreadAngle = emitterComponent->SpreadAngle; particleTransform->Velocity = emitterOrientation * glm::vec3(0, 0, -1) * speed * glm::normalize(glm::angleAxis(RandomizeAngle(spreadAngle), glm::vec3(1, 0, 0))) * glm::normalize(glm::angleAxis(RandomizeAngle(spreadAngle), glm::vec3(0, 1, 0))) * @@ -102,19 +102,20 @@ void Systems::ParticleSystem::SpawnParticles(EntityID emitterID, glm::vec3 pos, glm::vec3 testVel = glm::vec3(particleTransform->Velocity.x, -particleTransform->Velocity.y * 1.5, particleTransform->Velocity.z); //TEMP auto particle = m_World->AddComponent(ent, "Particle"); - particle->LifeTime = lifeTime; + particle->LifeTime = emitterComponent->LifeTime; particle->ScaleSpectrum.push_back(4); //TEMP - particle->ScaleSpectrum.push_back(1); //TEMP + particle->ScaleSpectrum.push_back(0); //TEMP particle->VelocitySpectrum.push_back(particleTransform->Velocity); //TEMP particle->VelocitySpectrum.push_back(testVel); //TEMP +// particle->AngularVelocitySpectrum.push_back(); +// particle->AngularVelocitySpectrum.push_back(); // Color startColor = {.4f, .45f, .2f}; // particle->ColorSpectrum.push_back(startColor); // Color endColor = {0.f, 45.f, 23.f}; // particle->ColorSpectrum.push_back(endColor); - auto model = m_World->AddComponent(ent, "Model"); - model->ModelFile = "Models/Placeholders/PhysicsTest/PointLight.obj"; + ParticleData data; data.ParticleID = ent; diff --git a/src/Systems/ParticleSystem.h b/src/Systems/ParticleSystem.h index 8940794..33d14ae 100644 --- a/src/Systems/ParticleSystem.h +++ b/src/Systems/ParticleSystem.h @@ -28,17 +28,18 @@ class ParticleSystem : public System public: ParticleSystem(World* world); void RegisterComponents(ComponentFactory* cf) override; - void Update(double dt) override; void UpdateEntity(double dt, EntityID entity, EntityID parent) override; private: - void SpawnParticles(EntityID emitterID, glm::vec3 pos, float spawnCount, float spreadAngle, double lifeTime, double dt); - std::map> m_ParticleEmitter; - std::map m_TimeSinceLastSpawn; - + void SpawnParticles(EntityID emitterID); float RandomizeAngle(float spreadAngle); void ScaleInterpolation(double timeProgress, std::vector scaleSpectrum, glm::vec3 &scale); void VelocityInterpolation(double timeProgress, std::vector velocitySpectrum, glm::vec3 &velocity); + void Billboard(); + std::map> m_ParticleEmitter; + std::map m_TimeSinceLastSpawn; + + }; } diff --git a/src/World.h b/src/World.h index 8829933..c8c55c4 100755 --- a/src/World.h +++ b/src/World.h @@ -135,7 +135,14 @@ std::shared_ptr World::AddComponent(EntityID entity, std::string componentTyp template T* World::GetComponent(EntityID entity, std::string componentType) { + + /*auto it0 = m_EntityComponents.find(entity); + + if (it0 == m_EntityComponents.end()) + return nullptr;*/ + auto components = m_EntityComponents[entity]; + auto it = components.find(componentType); if (it != components.end()) { From 68761c9291359dd830a58b929aaa862cf717dc84 Mon Sep 17 00:00:00 2001 From: Stiffly Date: Mon, 28 Apr 2014 19:12:51 +0200 Subject: [PATCH 32/65] Angular velocity support --- src/Components/Particle.h | 2 +- src/Components/ParticleEmitter.h | 2 +- src/GameWorld.cpp | 6 ++-- src/Systems/ParticleSystem.cpp | 53 +++++++++++++++++++++----------- src/Systems/ParticleSystem.h | 3 ++ 5 files changed, 43 insertions(+), 23 deletions(-) diff --git a/src/Components/Particle.h b/src/Components/Particle.h index dfa3075..a4725b3 100644 --- a/src/Components/Particle.h +++ b/src/Components/Particle.h @@ -15,7 +15,7 @@ namespace Components std::vector ScaleSpectrum; double LifeTime; std::vector VelocitySpectrum; - std::vector AngularVelocitySpectrum; + std::vector AngularVelocitySpectrum; virtual Particle* Clone() const override { return new Particle(*this); } }; diff --git a/src/Components/ParticleEmitter.h b/src/Components/ParticleEmitter.h index afb5622..6ddd302 100755 --- a/src/Components/ParticleEmitter.h +++ b/src/Components/ParticleEmitter.h @@ -29,7 +29,7 @@ struct ParticleEmitter : Component float SpreadAngle; double LifeTime; std::vector VelocitySpectrum; - std::vector AngularVelocitySpectrum; + std::vector AngularVelocitySpectrum; virtual ParticleEmitter* Clone() const override { return new ParticleEmitter(*this); } diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index 8d75f10..f63c86a 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -101,9 +101,9 @@ void GameWorld::Initialize() transform->Position = glm::vec3(i * 10, 20, 0); auto emitter = AddComponent(ent, "ParticleEmitter"); emitter->LifeTime = 4; - emitter->SpawnCount = 4; - emitter->SpreadAngle = glm::pi()/4; - emitter->SpawnFrequency = 0.08; + emitter->SpawnCount = 1; + emitter->SpreadAngle = glm::pi()/20; + emitter->SpawnFrequency = 0.008; auto model = AddComponent(ent, "Model"); model->ModelFile = "Models/Placeholders/PhysicsTest/PointLight.obj"; diff --git a/src/Systems/ParticleSystem.cpp b/src/Systems/ParticleSystem.cpp index e274e3f..5ee695c 100644 --- a/src/Systems/ParticleSystem.cpp +++ b/src/Systems/ParticleSystem.cpp @@ -47,19 +47,18 @@ void Systems::ParticleSystem::UpdateEntity(double dt, EntityID entity, EntityID } else { - float timeProgress = timeLived / particleComponent->LifeTime; - // The difference between the start and end value - /*float deltaColor = glm::abs(particleComponent->ColorSpectrum[0].r - particleComponent->ColorSpectrum[1].r); - it->color.r = particleComponent->ColorSpectrum[0].r + deltaColor * timeProgress; - deltaColor = glm::abs(particleComponent->ColorSpectrum[0].g - particleComponent->ColorSpectrum[1].g); - it->color.g = particleComponent->ColorSpectrum[0].g + deltaColor * timeProgress; - deltaColor = glm::abs(particleComponent->ColorSpectrum[0].b - particleComponent->ColorSpectrum[1].b); - it->color.b = particleComponent->ColorSpectrum[0].b + deltaColor * timeProgress;*/ - - ScaleInterpolation(timeProgress, particleComponent->ScaleSpectrum, transformComponent->Scale); - VelocityInterpolation(timeProgress, particleComponent->VelocitySpectrum, transformComponent->Velocity); - + //FIX: calculate once + float timeProgress = timeLived / particleComponent->LifeTime; + //ColorInterpolation(timeProgress, particleComponent->ColorSpectrum, color); + if(particleComponent->ScaleSpectrum.size() > 1) + ScaleInterpolation(timeProgress, particleComponent->ScaleSpectrum, transformComponent->Scale); + if(particleComponent->VelocitySpectrum.size() > 1) + VelocityInterpolation(timeProgress, particleComponent->VelocitySpectrum, transformComponent->Velocity); + if(particleComponent->AngularVelocitySpectrum.size() > 1) + AngularVelocityInterpolation(timeProgress, particleComponent->AngularVelocitySpectrum, it->AngularVelocity); + + transformComponent->Orientation *= glm::angleAxis(it->AngularVelocity, glm::vec3(0, 0, 1)); transformComponent->Position += transformComponent->Velocity * (float)dt; it++; @@ -103,12 +102,12 @@ void Systems::ParticleSystem::SpawnParticles(EntityID emitterID) auto particle = m_World->AddComponent(ent, "Particle"); particle->LifeTime = emitterComponent->LifeTime; - particle->ScaleSpectrum.push_back(4); //TEMP - particle->ScaleSpectrum.push_back(0); //TEMP + particle->ScaleSpectrum.push_back(1); //TEMP + particle->ScaleSpectrum.push_back(1); //TEMP particle->VelocitySpectrum.push_back(particleTransform->Velocity); //TEMP particle->VelocitySpectrum.push_back(testVel); //TEMP -// particle->AngularVelocitySpectrum.push_back(); -// particle->AngularVelocitySpectrum.push_back(); + //particle->AngularVelocitySpectrum.push_back(0.f); + particle->AngularVelocitySpectrum.push_back(-glm::pi()/10); // Color startColor = {.4f, .45f, .2f}; // particle->ColorSpectrum.push_back(startColor); @@ -120,8 +119,7 @@ void Systems::ParticleSystem::SpawnParticles(EntityID emitterID) ParticleData data; data.ParticleID = ent; data.SpawnTime = glfwGetTime(); -// data.color = particle->ColorSpectrum[0]; -// data.Scale = particle->ScaleSpectrum[0]; + data.AngularVelocity = particle->AngularVelocitySpectrum[0]; m_ParticleEmitter[emitterID].push_back(data); } @@ -157,4 +155,23 @@ void Systems::ParticleSystem::VelocityInterpolation(double timeProgress, std::ve if(velocitySpectrum[0].z > velocitySpectrum[1].z) deltaVelocity *= -1; velocity.z = velocitySpectrum[0].z + deltaVelocity * timeProgress; +} + +void Systems::ParticleSystem::ColorInterpolation(double timeProgress, std::vector colorSpectrum, Color &color) +{ + float deltaColor = glm::abs(colorSpectrum[0].r - colorSpectrum[1].r); + color.r = colorSpectrum[0].r + deltaColor * timeProgress; + deltaColor = glm::abs(colorSpectrum[0].g - colorSpectrum[1].g); + color.g = colorSpectrum[0].g + deltaColor * timeProgress; + deltaColor = glm::abs(colorSpectrum[0].b - colorSpectrum[1].b); + color.b = colorSpectrum[0].b + deltaColor * timeProgress; +} + +void Systems::ParticleSystem::AngularVelocityInterpolation(double timeProgress, std::vector spectrum, float &angularVelocity) +{ + float deltaAngularVelocity = glm::abs(spectrum[0] - spectrum[1]); + if(spectrum[0] > spectrum[1]) + deltaAngularVelocity *= -1; + angularVelocity = spectrum[0] + deltaAngularVelocity * timeProgress; + } \ No newline at end of file diff --git a/src/Systems/ParticleSystem.h b/src/Systems/ParticleSystem.h index 33d14ae..9e10b99 100644 --- a/src/Systems/ParticleSystem.h +++ b/src/Systems/ParticleSystem.h @@ -20,6 +20,7 @@ namespace Systems EntityID ParticleID; double SpawnTime; float Scale; + float AngularVelocity; Color color; }; @@ -35,6 +36,8 @@ private: float RandomizeAngle(float spreadAngle); void ScaleInterpolation(double timeProgress, std::vector scaleSpectrum, glm::vec3 &scale); void VelocityInterpolation(double timeProgress, std::vector velocitySpectrum, glm::vec3 &velocity); + void ColorInterpolation(double timeProgress, std::vector colorSpectrum, Color &color); + void AngularVelocityInterpolation(double timeProgress, std::vector spectrum, float &angularVelocity); void Billboard(); std::map> m_ParticleEmitter; std::map m_TimeSinceLastSpawn; From ed1df6dc60edb0378f6e84e85c83ed4c9879089d Mon Sep 17 00:00:00 2001 From: ViktorLjung Date: Mon, 28 Apr 2014 19:51:13 +0200 Subject: [PATCH 33/65] Proper rotation of child physics objects --- src/Components/Vehicle.h | 4 +- src/GameWorld.cpp | 123 +++++++++++++++++++++++----------- src/Physics/VehicleSetup.cpp | 8 +-- src/Renderer.cpp | 2 +- src/Systems/PhysicsSystem.cpp | 89 ++++++++++++++++++------ src/Systems/PhysicsSystem.h | 1 + src/Texture.cpp | 3 + vs11/Returngeance.sln | 3 + 8 files changed, 166 insertions(+), 67 deletions(-) diff --git a/src/Components/Vehicle.h b/src/Components/Vehicle.h index 9e4a59e..3892e8f 100644 --- a/src/Components/Vehicle.h +++ b/src/Components/Vehicle.h @@ -10,7 +10,8 @@ namespace Components struct Vehicle : Component { Vehicle() - : MaxTorque(500.0f), MinRPM(800.0f), OptimalRPM(4000.0f), MaxRPM(6000.0f), MaxSteeringAngle(35), TopSpeed(50.0f) { } + : MaxTorque(1000.0f), MinRPM(1000.0f), OptimalRPM(3000.0f), MaxRPM(4000.0f), MaxSteeringAngle(35), TopSpeed(130.0f), + MaxSpeedFullSteeringAngle(40.0f){ } float MaxTorque; float MinRPM; @@ -19,6 +20,7 @@ struct Vehicle : Component // Degrees float MaxSteeringAngle; float TopSpeed; + float MaxSpeedFullSteeringAngle; }; } diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index bdf3f29..a120fb8 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -64,37 +64,46 @@ void GameWorld::Initialize() auto vehicle = AddComponent(jeep, "Vehicle"); - auto light = AddComponent(jeep, "PointLight"); - light->Diffuse = glm::vec3(0, 1, 0); - light->constantAttenuation = 0.0005f; - light->linearAttenuation = 0.001f; - light->quadraticAttenuation = 0.001f; - AddComponent(jeep, "Input"); { auto chassis = CreateEntity(jeep); auto transform = AddComponent(chassis, "Transform"); - transform->Position = glm::vec3(0, -0.6577f, 0); + transform->Position = glm::vec3(0, 0, 0); // 0.6577f auto model = AddComponent(chassis, "Model"); model->ModelFile = "Models/JeepV2/Chassi/chassi.OBJ"; } + { + auto lightentity = CreateEntity(jeep); + auto transform = AddComponent(lightentity, "Transform"); + transform->Position = glm::vec3(0, 15, 0); + auto light = AddComponent(lightentity, "PointLight"); + light->Diffuse = glm::vec3(128.f/255.f, 172.f/255.f, 242.f/255.f); + light->Specular = glm::vec3(1.f); + light->constantAttenuation = 0.3f; + light->linearAttenuation = 0.003f; + light->quadraticAttenuation = 0.002f; + } + + float wheelOffset = -0.2f; + float hardPointOffset = 0.0f; + { auto wheel = CreateEntity(jeep); auto transform = AddComponent(wheel, "Transform"); - transform->Position = glm::vec3(1.4f, 0.5546f - 0.6577f - 0.2, -0.9242f); + transform->Position = glm::vec3(1.9f, 0.5546f - 0.2 + wheelOffset, -0.9242f); transform->Scale = glm::vec3(1.0f); auto model = AddComponent(wheel, "Model"); model->ModelFile = "Models/JeepV2/WheelFront/wheelFront.obj"; auto Wheel = AddComponent(wheel, "Wheel"); - Wheel->Hardpoint = transform->Position + glm::vec3(0.f, 1.f, 0.f); + Wheel->Hardpoint = transform->Position + glm::vec3(0.f, 1.f - hardPointOffset, 0.f); Wheel->AxleID = 0; Wheel->Mass = 50; Wheel->Radius = 0.837f; Wheel->Steering = true; - Wheel->SuspensionStrength = 40.f; - Wheel->Friction = 3.0f; + Wheel->SuspensionStrength = 50.f; + Wheel->Friction = 3.5f; Wheel->ConnectedToHandbrake = true; CommitEntity(wheel); } @@ -102,19 +111,19 @@ void GameWorld::Initialize() { auto wheel = CreateEntity(jeep); auto transform = AddComponent(wheel, "Transform"); - transform->Position = glm::vec3(-1.4f, 0.5546f - 0.6577f - 0.2, -0.9242f); + transform->Position = glm::vec3(-1.9f, 0.5546f - 0.2 + wheelOffset, -0.9242f); transform->Scale = glm::vec3(1.0f); transform->Orientation = glm::angleAxis(glm::pi(), glm::vec3(0, 0, 1)); auto model = AddComponent(wheel, "Model"); model->ModelFile = "Models/JeepV2/WheelFront/wheelFront.obj"; auto Wheel = AddComponent(wheel, "Wheel"); - Wheel->Hardpoint = transform->Position + glm::vec3(0.f, 1.f, 0.f); + Wheel->Hardpoint = transform->Position + glm::vec3(0.f, 1.f - hardPointOffset, 0.f); Wheel->AxleID = 0; Wheel->Mass = 50; Wheel->Radius = 0.837f; Wheel->Steering = true; - Wheel->SuspensionStrength = 40.f; - Wheel->Friction = 3.0f; + Wheel->SuspensionStrength = 50.f; + Wheel->Friction = 3.5f; Wheel->ConnectedToHandbrake = true; CommitEntity(wheel); } @@ -122,17 +131,17 @@ void GameWorld::Initialize() { auto wheel = CreateEntity(jeep); auto transform = AddComponent(wheel, "Transform"); - transform->Position = glm::vec3(0.2726f, 0.2805f - 0.6577f, 1.9307f); + transform->Position = glm::vec3(0.2726f, 0.2805f + wheelOffset, 1.9307f); auto model = AddComponent(wheel, "Model"); model->ModelFile = "Models/JeepV2/WheelBack/wheelBack.obj"; auto Wheel = AddComponent(wheel, "Wheel"); - Wheel->Hardpoint = transform->Position + glm::vec3(0.f, 1.f, 0.f); + Wheel->Hardpoint = transform->Position + glm::vec3(0.f, 1.f - hardPointOffset, 0.f); Wheel->AxleID = 1; - Wheel->Mass = 10; + Wheel->Mass = 50; Wheel->Radius = 0.737f; Wheel->Steering = false; - Wheel->SuspensionStrength = 20.f; - Wheel->Friction = 3.0f; + Wheel->SuspensionStrength = 40.f; + Wheel->Friction = 3.5f; Wheel->ConnectedToHandbrake = true; CommitEntity(wheel); } @@ -140,44 +149,78 @@ void GameWorld::Initialize() { auto wheel = CreateEntity(jeep); auto transform = AddComponent(wheel, "Transform"); - transform->Position = glm::vec3(-0.2726f, 0.2805f - 0.6577f, 1.9307f); + transform->Position = glm::vec3(-0.2726f, 0.2805f + wheelOffset, 1.9307f); transform->Orientation = glm::angleAxis(glm::pi(), glm::vec3(0, 0, 1)); auto model = AddComponent(wheel, "Model"); model->ModelFile = "Models/JeepV2/WheelBack/wheelBack.obj"; auto Wheel = AddComponent(wheel, "Wheel"); - Wheel->Hardpoint = transform->Position + glm::vec3(0.f, 1.f, 0.f); + Wheel->Hardpoint = transform->Position + glm::vec3(0.f, 1.f - hardPointOffset, 0.f); Wheel->AxleID = 1; - Wheel->Mass = 10; + Wheel->Mass = 50; Wheel->Radius = 0.737f; Wheel->Steering = false; - Wheel->SuspensionStrength = 20.f; - Wheel->Friction = 3.0f; + Wheel->SuspensionStrength = 40.f; + Wheel->Friction = 3.5f; Wheel->ConnectedToHandbrake = true; CommitEntity(wheel); } CommitEntity(jeep); } - - for (int x = 0; x < 5; x++) - for (int y = 0; y < 5; y++) + /* + for(int i = 0; i < 10; i++) { - auto cube = CreateEntity(); - auto transform = AddComponent(cube, "Transform"); - transform->Position = glm::vec3(3 * x + 0.1f + 20.f, 3 * y + 0.1f + 1.f, 0); - transform->Scale = glm::vec3(3); + auto entity = CreateEntity(); + auto transform = AddComponent(entity, "Transform"); + transform->Position = glm::vec3(30 + i*0.1f, 0 + i*0.1f, 10 + i*0.1f); + transform->Scale = glm::vec3(0); transform->Orientation = glm::quat(glm::vec3(0.0f, 0.0f, 0.0f)); - auto model = AddComponent(cube, "Model"); - model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; + + std::stringstream ss; + ss << "Models/Placeholders/ShatterTest/" << i+1 << ".obj"; - auto physics = AddComponent(cube, "Physics"); + auto model = AddComponent(entity, "Model"); + model->ModelFile = ss.str(); + + auto physics = AddComponent(entity, "Physics"); physics->Mass = 100; - auto box = AddComponent(cube, "BoxShape"); - box->Width = 1.5f; - box->Height = 1.5f; - box->Depth = 1.5f; - CommitEntity(cube); + physics->Static = true; + auto meshShape = AddComponent(entity, "MeshShape"); + meshShape->ResourceName = ss.str(); + + CommitEntity(entity); + }*/ + + { + auto wall = CreateEntity(); + auto transform = AddComponent(wall, "Transform"); + transform->Position = glm::vec3(10, 0, -20); + transform->Orientation = glm::angleAxis(glm::pi()/2.f, glm::vec3(0, 1, 0)); + + for (int y = 0; y < 10; y++) + { + for (int x = -5; x < 5; x++) + { + auto brick = CreateEntity(wall); + auto transform = AddComponent(brick, "Transform"); + transform->Position = glm::vec3(x + 0.01f, y*0.3f + 0.01f, 0); + transform->Position.x += (y % 2)*0.5f; + transform->Scale = glm::vec3(1, 0.3f, 0.6f); + transform->Orientation = glm::quat(glm::vec3(0.0f, 0.0f, 0.0f)); + auto model = AddComponent(brick, "Model"); + model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; + + auto physics = AddComponent(brick, "Physics"); + physics->Mass = 1; + auto box = AddComponent(brick, "BoxShape"); + box->Width = 0.5f; + box->Height = 0.15f; + box->Depth = 0.3f; + CommitEntity(brick); + } } + CommitEntity(wall); + } /*for (int x = 0; x < 5; x++) for (int y = 0; y < 5; y++) diff --git a/src/Physics/VehicleSetup.cpp b/src/Physics/VehicleSetup.cpp index 1768b1e..5041b9d 100644 --- a/src/Physics/VehicleSetup.cpp +++ b/src/Physics/VehicleSetup.cpp @@ -165,7 +165,7 @@ void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultS // [mph/h] The steering angle decreases linearly // based on your overall max speed of the vehicle. - steering.m_maxSpeedFullSteeringAngle = 70.0f * (1.605f / 3.6f); //MPH???! + steering.m_maxSpeedFullSteeringAngle = vehicleComponent.MaxSpeedFullSteeringAngle; // * (1.605f / 3.6f); //MPH???! for (int i = 0; i < m_Wheels.size(); i++) { @@ -198,8 +198,8 @@ void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultT transmission.m_gearsRatio.setSize(numberOfGears); transmission.m_wheelsTorqueRatio.setSize(data.m_numWheels); - transmission.m_downshiftRPM = 3500.0f; - transmission.m_upshiftRPM = 6500.0f; + transmission.m_downshiftRPM = 1500.0f; + transmission.m_upshiftRPM = 3500.0f; transmission.m_clutchDelayTime = 0.0f; transmission.m_reverseGearRatio = 1.0f; @@ -267,7 +267,7 @@ void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultA aerodynamics.m_liftCoefficient = -0.3f; // Extra gavity applies in world space (independent of m_chassisCoordinateSystem). - aerodynamics.m_extraGravityws.set(0.0f, -5.0f, 0.0f); + aerodynamics.m_extraGravityws.set(0.0f, -0.982f, 0.0f); // fuck this shit } void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultVelocityDamper& velocityDamper, Components::Vehicle vehicleComponent) diff --git a/src/Renderer.cpp b/src/Renderer.cpp index e7dfed6..6cc7dc2 100755 --- a/src/Renderer.cpp +++ b/src/Renderer.cpp @@ -191,7 +191,7 @@ void Renderer::DrawSkybox() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_ShaderProgramSkybox.Bind(); - glm::mat4 cameraMatrix = m_Camera->ProjectionMatrix() * glm::toMat4(m_Camera->Orientation()); + glm::mat4 cameraMatrix = m_Camera->ProjectionMatrix() * glm::toMat4(glm::inverse(m_Camera->Orientation())); glUniformMatrix4fv(glGetUniformLocation(m_ShaderProgramSkybox.GetHandle(), "MVP"), 1, GL_FALSE, glm::value_ptr(cameraMatrix)); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); m_Skybox->Draw(); diff --git a/src/Systems/PhysicsSystem.cpp b/src/Systems/PhysicsSystem.cpp index ab19101..1b8bc81 100644 --- a/src/Systems/PhysicsSystem.cpp +++ b/src/Systems/PhysicsSystem.cpp @@ -129,21 +129,21 @@ void Systems::PhysicsSystem::Update(double dt) continue; - if(m_RigidBodies[entity]->isActive()) + /*if(m_RigidBodies[entity]->isActive()) { m_PhysicsWorld->markForWrite(); hkVector4 position(transformComponent->Position.x, transformComponent->Position.y, transformComponent->Position.z); hkQuaternion rotation(transformComponent->Orientation.x, transformComponent->Orientation.y, transformComponent->Orientation.z, transformComponent->Orientation.w); m_RigidBodies[entity]->setPositionAndRotation(position, rotation); m_PhysicsWorld->unmarkForWrite(); - } + }*/ } - static const double timestep = 1 / 30.0; + static const double timestep = 1 / 60.0; m_Accumulator += dt; while (m_Accumulator >= timestep) { @@ -189,36 +189,84 @@ void Systems::PhysicsSystem::UpdateEntity(double dt, EntityID entity, EntityID p m_PhysicsWorld->unmarkForWrite(); } } - else if(m_Vehicles.find(entity) != m_Vehicles.end()) - { - m_PhysicsWorld->markForWrite(); - hkVector4 position = m_RigidBodies[entity]->getPosition(); - transformComponent->Position = glm::vec3(position(0), position(1), position(2)); - hkQuaternion orientation = m_RigidBodies[entity]->getRotation(); - transformComponent->Orientation = glm::quat(orientation(3), orientation(0), orientation(1), orientation(2)); - m_PhysicsWorld->unmarkForWrite(); - } else if(m_RigidBodies.find(entity) != m_RigidBodies.end()) { - m_PhysicsWorld->markForWrite(); + auto transformComponentParent = m_World->GetComponent(parent, "Transform"); + //m_PhysicsWorld->markForWrite(); hkVector4 position = m_RigidBodies[entity]->getPosition(); transformComponent->Position = glm::vec3(position(0), position(1), position(2)); + if (transformComponentParent) + { + transformComponent->Position -= transformComponentParent->Position; + transformComponent->Position = transformComponent->Position * transformComponentParent->Orientation; + } hkQuaternion orientation = m_RigidBodies[entity]->getRotation(); transformComponent->Orientation = glm::quat(orientation(3),orientation(0), orientation(1), orientation(2)); - m_PhysicsWorld->unmarkForWrite(); + if (transformComponentParent) + { + transformComponent->Orientation = transformComponent->Orientation * glm::inverse(transformComponentParent->Orientation); + } + //m_PhysicsWorld->unmarkForWrite(); } // HACK: Vehicle test-controls auto vehicleComponent = m_World->GetComponent(entity, "Vehicle"); auto inputComponent = m_World->GetComponent(entity, "Input"); - if (vehicleComponent && inputComponent) + if (vehicleComponent && inputComponent && m_Vehicles.find(entity) != m_Vehicles.end() && m_RigidBodies.find(entity) != m_RigidBodies.end()) { m_PhysicsWorld->markForWrite(); hkpVehicleDriverInputAnalogStatus* deviceStatus = (hkpVehicleDriverInputAnalogStatus*)m_Vehicles[entity]->m_deviceStatus; - deviceStatus->m_positionY = inputComponent->KeyState[GLFW_KEY_UP] * -1 + inputComponent->KeyState[GLFW_KEY_DOWN] * 1; - deviceStatus->m_positionX = inputComponent->KeyState[GLFW_KEY_LEFT] * -1 + inputComponent->KeyState[GLFW_KEY_RIGHT] * 1; + + + if(inputComponent->KeyState[GLFW_KEY_UP] != 0 || inputComponent->KeyState[GLFW_KEY_DOWN] != 0) + { + deviceStatus->m_positionY += inputComponent->KeyState[GLFW_KEY_UP] * -1 * 0.05f + inputComponent->KeyState[GLFW_KEY_DOWN] * 1 * 0.05f; + } + else + { + deviceStatus->m_positionY = 0; + } + + if(deviceStatus->m_positionY > 1) + deviceStatus->m_positionY = 1; + else if(deviceStatus->m_positionY < -1) + deviceStatus->m_positionY = -1; + + + + if(inputComponent->KeyState[GLFW_KEY_LEFT] != 0 || inputComponent->KeyState[GLFW_KEY_RIGHT] != 0) + { + deviceStatus->m_positionX += inputComponent->KeyState[GLFW_KEY_LEFT] * -1 * 0.01f + inputComponent->KeyState[GLFW_KEY_RIGHT] * 1 * 0.01f; + } + else + { + if(deviceStatus->m_positionX > 0) + { + deviceStatus->m_positionX += -1 * 0.01f; + } + else if(deviceStatus->m_positionX < 0) + { + deviceStatus->m_positionX += 1 * 0.01f; + } + } + + if(deviceStatus->m_positionX > 1) + deviceStatus->m_positionX = 1; + else if(deviceStatus->m_positionX < -1) + deviceStatus->m_positionX = -1; + + deviceStatus->m_handbrakeButtonPressed = inputComponent->KeyState[GLFW_KEY_RIGHT_CONTROL]; + + if(inputComponent->KeyState[GLFW_KEY_R]) + { + transformComponent->Position = glm::vec3(0, 10, 0); + transformComponent->Orientation = glm::quat(glm::vec3(0.0f, 0.0f, 0.0f)); + m_RigidBodies[entity]->setLinearVelocity(hkVector4(0, 0, 0)); + m_RigidBodies[entity]->setAngularVelocity(hkVector4(0, 0, 0)); + } + m_PhysicsWorld->unmarkForWrite(); } } @@ -322,8 +370,6 @@ void Systems::PhysicsSystem::OnEntityCommit( EntityID entity ) part.m_stridingType = hkpExtendedMeshShape::INDICES_INT16; - - mesh->addTrianglesSubpart(part); } @@ -347,8 +393,9 @@ void Systems::PhysicsSystem::OnEntityCommit( EntityID entity ) return; } - - rigidBodyInfo.m_position.set(transformComponent->Position.x, transformComponent->Position.y, transformComponent->Position.z); + auto absoluteTransform = m_World->GetSystem("TransformSystem")->AbsoluteTransform(entity); + rigidBodyInfo.m_position.set(absoluteTransform.Position.x, absoluteTransform.Position.y, absoluteTransform.Position.z); + rigidBodyInfo.m_rotation.set(absoluteTransform.Orientation.x, absoluteTransform.Orientation.y, absoluteTransform.Orientation.z, absoluteTransform.Orientation.w); rigidBodyInfo.m_inertiaTensor = massProperties.m_inertiaTensor; //rigidBodyInfo.m_centerOfMass = massProperties.m_centerOfMass; rigidBodyInfo.m_mass = massProperties.m_mass; diff --git a/src/Systems/PhysicsSystem.h b/src/Systems/PhysicsSystem.h index 82a0222..bee1039 100644 --- a/src/Systems/PhysicsSystem.h +++ b/src/Systems/PhysicsSystem.h @@ -2,6 +2,7 @@ #define PhysicsSystem_h__ #include "System.h" +#include "Systems/TransformSystem.h" #include "Components/Transform.h" #include "Components/Physics.h" #include "Components/BoxShape.h" diff --git a/src/Texture.cpp b/src/Texture.cpp index 49256da..373db0d 100755 --- a/src/Texture.cpp +++ b/src/Texture.cpp @@ -15,6 +15,9 @@ void Texture::Load(std::string path) } m_Texture = m_TextureCache[path]; + glBindTexture(GL_TEXTURE_2D, m_Texture); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); } void Texture::Bind() diff --git a/vs11/Returngeance.sln b/vs11/Returngeance.sln index 10ce52b..8daf9b5 100644 --- a/vs11/Returngeance.sln +++ b/vs11/Returngeance.sln @@ -39,4 +39,7 @@ Global GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection + GlobalSection(Performance) = preSolution + HasPerformanceSessions = true + EndGlobalSection EndGlobal From 0feb9832778ed09f5acffcce850519d3e0bb271a Mon Sep 17 00:00:00 2001 From: Stiffly Date: Mon, 28 Apr 2014 19:56:18 +0200 Subject: [PATCH 34/65] Made Interpolation functions look nicer --- src/Systems/ParticleSystem.cpp | 60 ++++++++++++++++------------------ 1 file changed, 29 insertions(+), 31 deletions(-) diff --git a/src/Systems/ParticleSystem.cpp b/src/Systems/ParticleSystem.cpp index 5ee695c..2fd1cfe 100644 --- a/src/Systems/ParticleSystem.cpp +++ b/src/Systems/ParticleSystem.cpp @@ -24,7 +24,6 @@ void Systems::ParticleSystem::UpdateEntity(double dt, EntityID entity, EntityID if(emitterComponent) { emitterComponent->TimeSinceLastSpawn += dt; - auto transformComponent = m_World->GetComponent(entity, "Transform"); if(emitterComponent->TimeSinceLastSpawn > emitterComponent->SpawnFrequency) { @@ -47,7 +46,6 @@ void Systems::ParticleSystem::UpdateEntity(double dt, EntityID entity, EntityID } else { - //FIX: calculate once float timeProgress = timeLived / particleComponent->LifeTime; //ColorInterpolation(timeProgress, particleComponent->ColorSpectrum, color); @@ -132,46 +130,46 @@ float Systems::ParticleSystem::RandomizeAngle(float spreadAngle) } //Interpolates the scale of the particle -void Systems::ParticleSystem::ScaleInterpolation(double timeProgress, std::vector scaleSpectrum, glm::vec3 &scale) +void Systems::ParticleSystem::ScaleInterpolation(double timeProgress, std::vector spectrum, glm::vec3 &s) { - float deltaScale = glm::abs(scaleSpectrum[0] - scaleSpectrum[1]); - if(scaleSpectrum[0] > scaleSpectrum[1]) - deltaScale *= -1; - scale = glm::vec3(scaleSpectrum[0] + deltaScale * timeProgress); + float dScale = glm::abs(spectrum[0] - spectrum[1]); + if(spectrum[0] > spectrum[1]) + dScale *= -1; + s = glm::vec3(spectrum[0] + dScale * timeProgress); } //Interpolates the velocity of the particle -void Systems::ParticleSystem::VelocityInterpolation(double timeProgress, std::vector velocitySpectrum, glm::vec3 &velocity) +void Systems::ParticleSystem::VelocityInterpolation(double timeProgress, std::vector spectrum, glm::vec3 &v) { - float deltaVelocity = glm::abs(velocitySpectrum[0].x - velocitySpectrum[1].x); - if(velocitySpectrum[0].x > velocitySpectrum[1].x) - deltaVelocity *= -1; - velocity.x = velocitySpectrum[0].x + deltaVelocity * timeProgress; - deltaVelocity = glm::abs(velocitySpectrum[0].y - velocitySpectrum[1].y); - if (velocitySpectrum[0].y > velocitySpectrum[1].y) - deltaVelocity *= -1; - velocity.y = velocitySpectrum[0].y + deltaVelocity * timeProgress; - deltaVelocity = glm::abs(velocitySpectrum[0].z - velocitySpectrum[1].z); - if(velocitySpectrum[0].z > velocitySpectrum[1].z) - deltaVelocity *= -1; - velocity.z = velocitySpectrum[0].z + deltaVelocity * timeProgress; + float dVelocity = glm::abs(spectrum[0].x - spectrum[1].x); + if(spectrum[0].x > spectrum[1].x) + dVelocity *= -1; + v.x = spectrum[0].x + dVelocity * timeProgress; + dVelocity = glm::abs(spectrum[0].y - spectrum[1].y); + if (spectrum[0].y > spectrum[1].y) + dVelocity *= -1; + v.y = spectrum[0].y + dVelocity * timeProgress; + dVelocity = glm::abs(spectrum[0].z - spectrum[1].z); + if(spectrum[0].z > spectrum[1].z) + dVelocity *= -1; + v.z = spectrum[0].z + dVelocity * timeProgress; } -void Systems::ParticleSystem::ColorInterpolation(double timeProgress, std::vector colorSpectrum, Color &color) +void Systems::ParticleSystem::ColorInterpolation(double timeProgress, std::vector spectrum, Color &c) { - float deltaColor = glm::abs(colorSpectrum[0].r - colorSpectrum[1].r); - color.r = colorSpectrum[0].r + deltaColor * timeProgress; - deltaColor = glm::abs(colorSpectrum[0].g - colorSpectrum[1].g); - color.g = colorSpectrum[0].g + deltaColor * timeProgress; - deltaColor = glm::abs(colorSpectrum[0].b - colorSpectrum[1].b); - color.b = colorSpectrum[0].b + deltaColor * timeProgress; + float dColor = glm::abs(spectrum[0].r - spectrum[1].r); + c.r = spectrum[0].r + dColor * timeProgress; + dColor = glm::abs(spectrum[0].g - spectrum[1].g); + c.g = spectrum[0].g + dColor * timeProgress; + dColor = glm::abs(spectrum[0].b - spectrum[1].b); + c.b = spectrum[0].b + dColor * timeProgress; } -void Systems::ParticleSystem::AngularVelocityInterpolation(double timeProgress, std::vector spectrum, float &angularVelocity) +void Systems::ParticleSystem::AngularVelocityInterpolation(double timeProgress, std::vector spectrum, float &alpha) { - float deltaAngularVelocity = glm::abs(spectrum[0] - spectrum[1]); + float dAlpha = glm::abs(spectrum[0] - spectrum[1]); if(spectrum[0] > spectrum[1]) - deltaAngularVelocity *= -1; - angularVelocity = spectrum[0] + deltaAngularVelocity * timeProgress; + dAlpha *= -1; + alpha = spectrum[0] + dAlpha * timeProgress; } \ No newline at end of file From f471d7732f541cc9746ed931cab4f5506ffec3b1 Mon Sep 17 00:00:00 2001 From: ViktorLjung Date: Tue, 29 Apr 2014 03:47:09 +0200 Subject: [PATCH 35/65] Vehicle tuning --- src/Components/Vehicle.h | 1 + src/GameWorld.cpp | 58 +++++++++++++++++++---------------- src/Physics/VehicleSetup.cpp | 2 +- src/Systems/PhysicsSystem.cpp | 28 ++++++++++------- vs11/Returngeance.sln | 4 ++- 5 files changed, 53 insertions(+), 40 deletions(-) diff --git a/src/Components/Vehicle.h b/src/Components/Vehicle.h index 3892e8f..388d9f2 100644 --- a/src/Components/Vehicle.h +++ b/src/Components/Vehicle.h @@ -19,6 +19,7 @@ struct Vehicle : Component float MaxRPM; // Degrees float MaxSteeringAngle; + //TopSpeed not working fully yet float TopSpeed; float MaxSpeedFullSteeringAngle; }; diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index a120fb8..3388729 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -20,10 +20,11 @@ void GameWorld::Initialize() //transform->Scale = glm::vec3(400.0f, 10.0f, 400.0f); transform->Orientation = glm::quat(glm::vec3(0.0f, 0.0f, 0.0f)); auto model = AddComponent(ground, "Model"); - model->ModelFile = "Models/Placeholders/Terrain/Terrain.obj"; + model->ModelFile = "Models/TestScene/testScene.obj"; + //model->ModelFile = "Models/Placeholders/Terrain/Terrain.obj"; auto meshShape = AddComponent(ground, "MeshShape"); - meshShape->ResourceName = "Models/Placeholders/Terrain/Terrain.obj"; - + //meshShape->ResourceName = "Models/Placeholders/Terrain/Terrain.obj"; + meshShape->ResourceName = "Models/TestScene/testScene.obj"; auto physics = AddComponent(ground, "Physics"); physics->Mass = 10; @@ -86,24 +87,26 @@ void GameWorld::Initialize() light->quadraticAttenuation = 0.002f; } - float wheelOffset = -0.2f; - float hardPointOffset = 0.0f; + //Create wheels + float wheelOffset = 0.4f; + float springLength = 0.3f; + float suspensionStrength = 20.f; { auto wheel = CreateEntity(jeep); auto transform = AddComponent(wheel, "Transform"); - transform->Position = glm::vec3(1.9f, 0.5546f - 0.2 + wheelOffset, -0.9242f); + transform->Position = glm::vec3(1.9f, 0.5546f - wheelOffset, -0.9242f); transform->Scale = glm::vec3(1.0f); auto model = AddComponent(wheel, "Model"); model->ModelFile = "Models/JeepV2/WheelFront/wheelFront.obj"; auto Wheel = AddComponent(wheel, "Wheel"); - Wheel->Hardpoint = transform->Position + glm::vec3(0.f, 1.f - hardPointOffset, 0.f); + Wheel->Hardpoint = transform->Position + glm::vec3(0.f, springLength, 0.f); Wheel->AxleID = 0; Wheel->Mass = 50; Wheel->Radius = 0.837f; Wheel->Steering = true; - Wheel->SuspensionStrength = 50.f; - Wheel->Friction = 3.5f; + Wheel->SuspensionStrength = suspensionStrength; + Wheel->Friction = 4.f; Wheel->ConnectedToHandbrake = true; CommitEntity(wheel); } @@ -111,19 +114,19 @@ void GameWorld::Initialize() { auto wheel = CreateEntity(jeep); auto transform = AddComponent(wheel, "Transform"); - transform->Position = glm::vec3(-1.9f, 0.5546f - 0.2 + wheelOffset, -0.9242f); + transform->Position = glm::vec3(-1.9f, 0.5546f - wheelOffset, -0.9242f); transform->Scale = glm::vec3(1.0f); transform->Orientation = glm::angleAxis(glm::pi(), glm::vec3(0, 0, 1)); auto model = AddComponent(wheel, "Model"); model->ModelFile = "Models/JeepV2/WheelFront/wheelFront.obj"; auto Wheel = AddComponent(wheel, "Wheel"); - Wheel->Hardpoint = transform->Position + glm::vec3(0.f, 1.f - hardPointOffset, 0.f); + Wheel->Hardpoint = transform->Position + glm::vec3(0.f, springLength, 0.f); Wheel->AxleID = 0; Wheel->Mass = 50; Wheel->Radius = 0.837f; Wheel->Steering = true; - Wheel->SuspensionStrength = 50.f; - Wheel->Friction = 3.5f; + Wheel->SuspensionStrength = suspensionStrength; + Wheel->Friction = 4.f; Wheel->ConnectedToHandbrake = true; CommitEntity(wheel); } @@ -131,17 +134,17 @@ void GameWorld::Initialize() { auto wheel = CreateEntity(jeep); auto transform = AddComponent(wheel, "Transform"); - transform->Position = glm::vec3(0.2726f, 0.2805f + wheelOffset, 1.9307f); + transform->Position = glm::vec3(0.2726f, 0.2805f - wheelOffset, 1.9307f); auto model = AddComponent(wheel, "Model"); model->ModelFile = "Models/JeepV2/WheelBack/wheelBack.obj"; auto Wheel = AddComponent(wheel, "Wheel"); - Wheel->Hardpoint = transform->Position + glm::vec3(0.f, 1.f - hardPointOffset, 0.f); + Wheel->Hardpoint = transform->Position + glm::vec3(0.f, springLength, 0.f); Wheel->AxleID = 1; Wheel->Mass = 50; Wheel->Radius = 0.737f; Wheel->Steering = false; - Wheel->SuspensionStrength = 40.f; - Wheel->Friction = 3.5f; + Wheel->SuspensionStrength = suspensionStrength; + Wheel->Friction = 4.f; Wheel->ConnectedToHandbrake = true; CommitEntity(wheel); } @@ -149,18 +152,18 @@ void GameWorld::Initialize() { auto wheel = CreateEntity(jeep); auto transform = AddComponent(wheel, "Transform"); - transform->Position = glm::vec3(-0.2726f, 0.2805f + wheelOffset, 1.9307f); + transform->Position = glm::vec3(-0.2726f, 0.2805f - wheelOffset, 1.9307f); transform->Orientation = glm::angleAxis(glm::pi(), glm::vec3(0, 0, 1)); auto model = AddComponent(wheel, "Model"); model->ModelFile = "Models/JeepV2/WheelBack/wheelBack.obj"; auto Wheel = AddComponent(wheel, "Wheel"); - Wheel->Hardpoint = transform->Position + glm::vec3(0.f, 1.f - hardPointOffset, 0.f); + Wheel->Hardpoint = transform->Position + glm::vec3(0.f, springLength, 0.f); Wheel->AxleID = 1; Wheel->Mass = 50; Wheel->Radius = 0.737f; Wheel->Steering = false; - Wheel->SuspensionStrength = 40.f; - Wheel->Friction = 3.5f; + Wheel->SuspensionStrength = suspensionStrength; + Wheel->Friction = 4.f; Wheel->ConnectedToHandbrake = true; CommitEntity(wheel); } @@ -191,27 +194,28 @@ void GameWorld::Initialize() CommitEntity(entity); }*/ + for(int i = 0; i < 0; i++) { auto wall = CreateEntity(); auto transform = AddComponent(wall, "Transform"); - transform->Position = glm::vec3(10, 0, -20); - transform->Orientation = glm::angleAxis(glm::pi()/2.f, glm::vec3(0, 1, 0)); + transform->Position = glm::vec3(10, 0, -20 + (-10 * i)); + //transform->Orientation = glm::angleAxis(glm::pi()/2.f, glm::vec3(0, 1, 0)); - for (int y = 0; y < 10; y++) + for (int y = 0; y < 15; y++) { for (int x = -5; x < 5; x++) { auto brick = CreateEntity(wall); auto transform = AddComponent(brick, "Transform"); - transform->Position = glm::vec3(x + 0.01f, y*0.3f + 0.01f, 0); + transform->Position = glm::vec3(x + 0.01f, y * 0.3f + 0.01f, 0); transform->Position.x += (y % 2)*0.5f; - transform->Scale = glm::vec3(1, 0.3f, 0.6f); + transform->Scale = glm::vec3(1, 0.3f, 0.4f); transform->Orientation = glm::quat(glm::vec3(0.0f, 0.0f, 0.0f)); auto model = AddComponent(brick, "Model"); model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; auto physics = AddComponent(brick, "Physics"); - physics->Mass = 1; + physics->Mass = 3; auto box = AddComponent(brick, "BoxShape"); box->Width = 0.5f; box->Height = 0.15f; diff --git a/src/Physics/VehicleSetup.cpp b/src/Physics/VehicleSetup.cpp index 5041b9d..2995fd1 100644 --- a/src/Physics/VehicleSetup.cpp +++ b/src/Physics/VehicleSetup.cpp @@ -267,7 +267,7 @@ void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultA aerodynamics.m_liftCoefficient = -0.3f; // Extra gavity applies in world space (independent of m_chassisCoordinateSystem). - aerodynamics.m_extraGravityws.set(0.0f, -0.982f, 0.0f); // fuck this shit + aerodynamics.m_extraGravityws.set(0.0f, -8.0f, 0.0f); // fuck this shit } void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultVelocityDamper& velocityDamper, Components::Vehicle vehicleComponent) diff --git a/src/Systems/PhysicsSystem.cpp b/src/Systems/PhysicsSystem.cpp index 1b8bc81..b1d93cd 100644 --- a/src/Systems/PhysicsSystem.cpp +++ b/src/Systems/PhysicsSystem.cpp @@ -29,7 +29,7 @@ Systems::PhysicsSystem::PhysicsSystem(World* world) : System(world) { m_Accumulator = 0; - hkMemorySystem::FrameInfo finfo(500 * 1024); // Allocate 500KB of Physics solver buffer + hkMemorySystem::FrameInfo finfo(6000 * 1024); // Allocate 6MB of Physics solver buffer hkMemoryRouter* memoryRouter = hkMemoryInitUtil::initDefault(hkMallocAllocator::m_defaultMallocAllocator, finfo); hkBaseSystem::init(memoryRouter, HavokErrorReport); @@ -143,7 +143,7 @@ void Systems::PhysicsSystem::Update(double dt) - static const double timestep = 1 / 60.0; + static const double timestep = 1 / 30.0; m_Accumulator += dt; while (m_Accumulator >= timestep) { @@ -153,12 +153,14 @@ void Systems::PhysicsSystem::Update(double dt) m_Context->syncTimers(m_ThreadPool); // Step the visual debugger StepVisualDebugger(); + + // Clear accumulated timer data in this thread and all slave threads + hkMonitorStream::getInstance().reset(); + m_ThreadPool->clearTimerData(); } - // Clear accumulated timer data in this thread and all slave threads - hkMonitorStream::getInstance().reset(); - m_ThreadPool->clearTimerData(); + } void Systems::PhysicsSystem::UpdateEntity(double dt, EntityID entity, EntityID parent) @@ -218,10 +220,9 @@ void Systems::PhysicsSystem::UpdateEntity(double dt, EntityID entity, EntityID p m_PhysicsWorld->markForWrite(); hkpVehicleDriverInputAnalogStatus* deviceStatus = (hkpVehicleDriverInputAnalogStatus*)m_Vehicles[entity]->m_deviceStatus; - if(inputComponent->KeyState[GLFW_KEY_UP] != 0 || inputComponent->KeyState[GLFW_KEY_DOWN] != 0) { - deviceStatus->m_positionY += inputComponent->KeyState[GLFW_KEY_UP] * -1 * 0.05f + inputComponent->KeyState[GLFW_KEY_DOWN] * 1 * 0.05f; + deviceStatus->m_positionY += inputComponent->KeyState[GLFW_KEY_UP] * -1 * 0.1f + inputComponent->KeyState[GLFW_KEY_DOWN] * 1 * 0.1f; } else { @@ -233,21 +234,26 @@ void Systems::PhysicsSystem::UpdateEntity(double dt, EntityID entity, EntityID p else if(deviceStatus->m_positionY < -1) deviceStatus->m_positionY = -1; - + float turningSpeed = 0.02f; if(inputComponent->KeyState[GLFW_KEY_LEFT] != 0 || inputComponent->KeyState[GLFW_KEY_RIGHT] != 0) { - deviceStatus->m_positionX += inputComponent->KeyState[GLFW_KEY_LEFT] * -1 * 0.01f + inputComponent->KeyState[GLFW_KEY_RIGHT] * 1 * 0.01f; + deviceStatus->m_positionX += inputComponent->KeyState[GLFW_KEY_LEFT] * -1 * turningSpeed + inputComponent->KeyState[GLFW_KEY_RIGHT] * 1 * turningSpeed; } else { if(deviceStatus->m_positionX > 0) { - deviceStatus->m_positionX += -1 * 0.01f; + deviceStatus->m_positionX += -1 * turningSpeed; } else if(deviceStatus->m_positionX < 0) { - deviceStatus->m_positionX += 1 * 0.01f; + deviceStatus->m_positionX += 1 * turningSpeed; + } + + if (deviceStatus->m_positionX > -turningSpeed && deviceStatus->m_positionX < turningSpeed) + { + deviceStatus->m_positionX = 0.f; } } diff --git a/vs11/Returngeance.sln b/vs11/Returngeance.sln index 8daf9b5..f834d6d 100644 --- a/vs11/Returngeance.sln +++ b/vs11/Returngeance.sln @@ -1,6 +1,8 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2012 +# Visual Studio 2013 +VisualStudioVersion = 12.0.30110.0 +MinimumVisualStudioVersion = 10.0.40219.1 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Returngeance", "Returngeance\Returngeance.vcxproj", "{E8B4A2A2-882B-402A-98A7-8B4F7233C8B3}" EndProject Project("{F088123C-0E9E-452A-89E6-6BA2F21D5CAC}") = "ModelingProject1", "ModelingProject1\ModelingProject1.modelproj", "{B35F204C-3377-457E-AC9E-D9606F421191}" From a13e9d32ec791a83f9bfb35b0d56ff0336cc1000 Mon Sep 17 00:00:00 2001 From: Stiffly Date: Tue, 29 Apr 2014 11:51:57 +0200 Subject: [PATCH 36/65] Generalized interpolation functions. (orientation spectrum not working properly (quaterions...)) --- src/Components/Particle.h | 3 +- src/Components/ParticleEmitter.h | 3 +- src/GameWorld.cpp | 2 +- src/Systems/ParticleSystem.cpp | 93 +++++++++++++++++--------------- src/Systems/ParticleSystem.h | 9 ++-- 5 files changed, 61 insertions(+), 49 deletions(-) diff --git a/src/Components/Particle.h b/src/Components/Particle.h index a4725b3..d08b1a7 100644 --- a/src/Components/Particle.h +++ b/src/Components/Particle.h @@ -12,10 +12,11 @@ namespace Components struct Particle : Component { std::vector ColorSpectrum; - std::vector ScaleSpectrum; + std::vector ScaleSpectrum; double LifeTime; std::vector VelocitySpectrum; std::vector AngularVelocitySpectrum; + std::vector OrientationSpectrum; //Keep? virtual Particle* Clone() const override { return new Particle(*this); } }; diff --git a/src/Components/ParticleEmitter.h b/src/Components/ParticleEmitter.h index 6ddd302..ae66fca 100755 --- a/src/Components/ParticleEmitter.h +++ b/src/Components/ParticleEmitter.h @@ -25,11 +25,12 @@ struct ParticleEmitter : Component float SpawnFrequency; int SpawnCount; std::vector ColorSpectrum; - std::vector ScaleSpectrum; + std::vector ScaleSpectrum; float SpreadAngle; double LifeTime; std::vector VelocitySpectrum; std::vector AngularVelocitySpectrum; + std::vector OrientationSpectrum; //Keep? virtual ParticleEmitter* Clone() const override { return new ParticleEmitter(*this); } diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index f63c86a..7d25c46 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -103,7 +103,7 @@ void GameWorld::Initialize() emitter->LifeTime = 4; emitter->SpawnCount = 1; emitter->SpreadAngle = glm::pi()/20; - emitter->SpawnFrequency = 0.008; + emitter->SpawnFrequency = 1.008; auto model = AddComponent(ent, "Model"); model->ModelFile = "Models/Placeholders/PhysicsTest/PointLight.obj"; diff --git a/src/Systems/ParticleSystem.cpp b/src/Systems/ParticleSystem.cpp index 2fd1cfe..06b2397 100644 --- a/src/Systems/ParticleSystem.cpp +++ b/src/Systems/ParticleSystem.cpp @@ -46,17 +46,34 @@ void Systems::ParticleSystem::UpdateEntity(double dt, EntityID entity, EntityID } else { - //FIX: calculate once + // FIX: calculate once float timeProgress = timeLived / particleComponent->LifeTime; - //ColorInterpolation(timeProgress, particleComponent->ColorSpectrum, color); + // ColorInterpolation(timeProgress, particleComponent->ColorSpectrum, color); + // Scale interpolation if(particleComponent->ScaleSpectrum.size() > 1) - ScaleInterpolation(timeProgress, particleComponent->ScaleSpectrum, transformComponent->Scale); + VectorInterpolation(timeProgress, particleComponent->ScaleSpectrum, transformComponent->Scale); + // Velocity interpolation if(particleComponent->VelocitySpectrum.size() > 1) - VelocityInterpolation(timeProgress, particleComponent->VelocitySpectrum, transformComponent->Velocity); + VectorInterpolation(timeProgress, particleComponent->VelocitySpectrum, transformComponent->Velocity); + // Angular velocity interpolation if(particleComponent->AngularVelocitySpectrum.size() > 1) - AngularVelocityInterpolation(timeProgress, particleComponent->AngularVelocitySpectrum, it->AngularVelocity); + ScalarInterpolation(timeProgress, particleComponent->AngularVelocitySpectrum, it->AngularVelocity); + //Angular velocity interpolation + if(particleComponent->OrientationSpectrum.size() > 1) + VectorInterpolation(timeProgress, particleComponent->OrientationSpectrum, it->Orientation); - transformComponent->Orientation *= glm::angleAxis(it->AngularVelocity, glm::vec3(0, 0, 1)); +// glm::vec3 v1 = particleComponent->OrientationSpectrum[0]; +// glm::vec3 v2 = it->Orientation; +// glm::vec3 v3 = glm::normalize(glm::cross(v1,v2)); +// float angle = glm::acos(glm::dot(v1, v2) / glm::length(v1) * glm::length(v2)); +// float s = sin(angle / 2); +// transformComponent->Orientation.x = v3.x * s; +// transformComponent->Orientation.y = v3.y * s; +// transformComponent->Orientation.z = v3.z * s; +// transformComponent->Orientation.w = glm::cos(angle/2); + + //float alpha = it->AngularVelocity * dt; + //transformComponent->Orientation = transformComponent->Orientation * it->Orientation; transformComponent->Position += transformComponent->Velocity * (float)dt; it++; @@ -89,7 +106,7 @@ void Systems::ParticleSystem::SpawnParticles(EntityID emitterID) particleTransform->Position = emitterTransform->Position; particleTransform->Scale = glm::vec3(1, 1, 1); - //The emitter's orientation as "start value" times the default direction for quaternion. Times the speed, and then rotate on x and y axis with the randomized spread angle. + //The emitter's orientation as "start value" times the default direction for emitter. Times the speed, and then rotate on x and y axis with the randomized spread angle. float spreadAngle = emitterComponent->SpreadAngle; particleTransform->Velocity = emitterOrientation * glm::vec3(0, 0, -1) * speed * glm::normalize(glm::angleAxis(RandomizeAngle(spreadAngle), glm::vec3(1, 0, 0))) * @@ -100,12 +117,13 @@ void Systems::ParticleSystem::SpawnParticles(EntityID emitterID) auto particle = m_World->AddComponent(ent, "Particle"); particle->LifeTime = emitterComponent->LifeTime; - particle->ScaleSpectrum.push_back(1); //TEMP - particle->ScaleSpectrum.push_back(1); //TEMP + particle->ScaleSpectrum.push_back(glm::vec3(1)); //TEMP + //particle->ScaleSpectrum.push_back(glm::vec3(1,4,1)); //TEMP particle->VelocitySpectrum.push_back(particleTransform->Velocity); //TEMP particle->VelocitySpectrum.push_back(testVel); //TEMP - //particle->AngularVelocitySpectrum.push_back(0.f); - particle->AngularVelocitySpectrum.push_back(-glm::pi()/10); +// particle->AngularVelocitySpectrum.push_back(0.f); +// particle->AngularVelocitySpectrum.push_back(-glm::pi()); + particle->OrientationSpectrum = particle->VelocitySpectrum; // Color startColor = {.4f, .45f, .2f}; // particle->ColorSpectrum.push_back(startColor); @@ -117,7 +135,8 @@ void Systems::ParticleSystem::SpawnParticles(EntityID emitterID) ParticleData data; data.ParticleID = ent; data.SpawnTime = glfwGetTime(); - data.AngularVelocity = particle->AngularVelocitySpectrum[0]; + //data.AngularVelocity = particle->AngularVelocitySpectrum[0]; + data.Orientation = particle->OrientationSpectrum[0]; m_ParticleEmitter[emitterID].push_back(data); } @@ -129,47 +148,37 @@ float Systems::ParticleSystem::RandomizeAngle(float spreadAngle) return ((float)rand() / ((float)RAND_MAX + 1) * spreadAngle) - spreadAngle/2; } -//Interpolates the scale of the particle -void Systems::ParticleSystem::ScaleInterpolation(double timeProgress, std::vector spectrum, glm::vec3 &s) -{ - float dScale = glm::abs(spectrum[0] - spectrum[1]); - if(spectrum[0] > spectrum[1]) - dScale *= -1; - s = glm::vec3(spectrum[0] + dScale * timeProgress); -} - //Interpolates the velocity of the particle -void Systems::ParticleSystem::VelocityInterpolation(double timeProgress, std::vector spectrum, glm::vec3 &v) +void Systems::ParticleSystem::VectorInterpolation(double timeProgress, std::vector spectrum, glm::vec3 &v) { - float dVelocity = glm::abs(spectrum[0].x - spectrum[1].x); + float dAxisValue = glm::abs(spectrum[0].x - spectrum[1].x); if(spectrum[0].x > spectrum[1].x) - dVelocity *= -1; - v.x = spectrum[0].x + dVelocity * timeProgress; - dVelocity = glm::abs(spectrum[0].y - spectrum[1].y); + dAxisValue *= -1; + v.x = spectrum[0].x + dAxisValue * timeProgress; + dAxisValue = glm::abs(spectrum[0].y - spectrum[1].y); if (spectrum[0].y > spectrum[1].y) - dVelocity *= -1; - v.y = spectrum[0].y + dVelocity * timeProgress; - dVelocity = glm::abs(spectrum[0].z - spectrum[1].z); + dAxisValue *= -1; + v.y = spectrum[0].y + dAxisValue * timeProgress; + dAxisValue = glm::abs(spectrum[0].z - spectrum[1].z); if(spectrum[0].z > spectrum[1].z) - dVelocity *= -1; - v.z = spectrum[0].z + dVelocity * timeProgress; + dAxisValue *= -1; + v.z = spectrum[0].z + dAxisValue * timeProgress; } -void Systems::ParticleSystem::ColorInterpolation(double timeProgress, std::vector spectrum, Color &c) -{ - float dColor = glm::abs(spectrum[0].r - spectrum[1].r); - c.r = spectrum[0].r + dColor * timeProgress; - dColor = glm::abs(spectrum[0].g - spectrum[1].g); - c.g = spectrum[0].g + dColor * timeProgress; - dColor = glm::abs(spectrum[0].b - spectrum[1].b); - c.b = spectrum[0].b + dColor * timeProgress; -} +// void Systems::ParticleSystem::ColorInterpolation(double timeProgress, std::vector spectrum, Color &c) +// { +// float dColor = glm::abs(spectrum[0].r - spectrum[1].r); +// c.r = spectrum[0].r + dColor * timeProgress; +// dColor = glm::abs(spectrum[0].g - spectrum[1].g); +// c.g = spectrum[0].g + dColor * timeProgress; +// dColor = glm::abs(spectrum[0].b - spectrum[1].b); +// c.b = spectrum[0].b + dColor * timeProgress; +// } -void Systems::ParticleSystem::AngularVelocityInterpolation(double timeProgress, std::vector spectrum, float &alpha) +void Systems::ParticleSystem::ScalarInterpolation(double timeProgress, std::vector spectrum, float &alpha) { float dAlpha = glm::abs(spectrum[0] - spectrum[1]); if(spectrum[0] > spectrum[1]) dAlpha *= -1; alpha = spectrum[0] + dAlpha * timeProgress; - } \ No newline at end of file diff --git a/src/Systems/ParticleSystem.h b/src/Systems/ParticleSystem.h index 9e10b99..4dff51e 100644 --- a/src/Systems/ParticleSystem.h +++ b/src/Systems/ParticleSystem.h @@ -21,6 +21,7 @@ namespace Systems double SpawnTime; float Scale; float AngularVelocity; + glm::vec3 Orientation; Color color; }; @@ -34,10 +35,10 @@ public: private: void SpawnParticles(EntityID emitterID); float RandomizeAngle(float spreadAngle); - void ScaleInterpolation(double timeProgress, std::vector scaleSpectrum, glm::vec3 &scale); - void VelocityInterpolation(double timeProgress, std::vector velocitySpectrum, glm::vec3 &velocity); - void ColorInterpolation(double timeProgress, std::vector colorSpectrum, Color &color); - void AngularVelocityInterpolation(double timeProgress, std::vector spectrum, float &angularVelocity); + //void ScaleInterpolation(double timeProgress, std::vector spectrum, glm::vec3 &scale); + void VectorInterpolation(double timeProgress, std::vector spectrum, glm::vec3 &velocity); + //void ColorInterpolation(double timeProgress, std::vector spectrum, Color &color); + void ScalarInterpolation(double timeProgress, std::vector spectrum, float &alpha); void Billboard(); std::map> m_ParticleEmitter; std::map m_TimeSinceLastSpawn; From dc32316bd744faf8a1fe45ed21ce9f45eea50736 Mon Sep 17 00:00:00 2001 From: ViktorLjung Date: Tue, 29 Apr 2014 14:21:14 +0200 Subject: [PATCH 37/65] Fixing suspension and car collision shape --- src/GameWorld.cpp | 18 +++++------ src/Systems/PhysicsSystem.cpp | 60 ++++++++++++++++++++++++----------- src/Systems/PhysicsSystem.h | 6 +++- vs11/Returngeance.sln | 7 +--- 4 files changed, 57 insertions(+), 34 deletions(-) diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index 3388729..fc83950 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -20,11 +20,11 @@ void GameWorld::Initialize() //transform->Scale = glm::vec3(400.0f, 10.0f, 400.0f); transform->Orientation = glm::quat(glm::vec3(0.0f, 0.0f, 0.0f)); auto model = AddComponent(ground, "Model"); - model->ModelFile = "Models/TestScene/testScene.obj"; - //model->ModelFile = "Models/Placeholders/Terrain/Terrain.obj"; + //model->ModelFile = "Models/TestScene/testScene.obj"; + model->ModelFile = "Models/Placeholders/Terrain/Terrain.obj"; auto meshShape = AddComponent(ground, "MeshShape"); - //meshShape->ResourceName = "Models/Placeholders/Terrain/Terrain.obj"; - meshShape->ResourceName = "Models/TestScene/testScene.obj"; + meshShape->ResourceName = "Models/Placeholders/Terrain/Terrain.obj"; + //meshShape->ResourceName = "Models/TestScene/testScene.obj"; auto physics = AddComponent(ground, "Physics"); physics->Mass = 10; @@ -49,7 +49,7 @@ void GameWorld::Initialize() { auto jeep = CreateEntity(); auto transform = AddComponent(jeep, "Transform"); - transform->Position = glm::vec3(0, 10, 0); + transform->Position = glm::vec3(0, 15, 0); auto physics = AddComponent(jeep, "Physics"); physics->Mass = 800; @@ -61,7 +61,7 @@ void GameWorld::Initialize() // box->Depth = 2.594f; auto meshShape = AddComponent(jeep, "MeshShape"); - meshShape->ResourceName = "Models/JeepV2/Chassi/chassi.OBJ"; + meshShape->ResourceName = "Models/JeepV2/Chassi/ChassiCollision.obj"; auto vehicle = AddComponent(jeep, "Vehicle"); @@ -72,7 +72,7 @@ void GameWorld::Initialize() auto transform = AddComponent(chassis, "Transform"); transform->Position = glm::vec3(0, 0, 0); // 0.6577f auto model = AddComponent(chassis, "Model"); - model->ModelFile = "Models/JeepV2/Chassi/chassi.OBJ"; + model->ModelFile = "Models/JeepV2/Chassi/ChassiCollision.obj"; } { @@ -91,7 +91,7 @@ void GameWorld::Initialize() //Create wheels float wheelOffset = 0.4f; float springLength = 0.3f; - float suspensionStrength = 20.f; + float suspensionStrength = 35.f; { auto wheel = CreateEntity(jeep); auto transform = AddComponent(wheel, "Transform"); @@ -194,7 +194,7 @@ void GameWorld::Initialize() CommitEntity(entity); }*/ - for(int i = 0; i < 0; i++) + for(int i = 0; i < 5; i++) { auto wall = CreateEntity(); auto transform = AddComponent(wall, "Transform"); diff --git a/src/Systems/PhysicsSystem.cpp b/src/Systems/PhysicsSystem.cpp index b1d93cd..d59e09d 100644 --- a/src/Systems/PhysicsSystem.cpp +++ b/src/Systems/PhysicsSystem.cpp @@ -120,6 +120,7 @@ void Systems::PhysicsSystem::Update(double dt) for (auto pair : *m_World->GetEntities()) { EntityID entity = pair.first; + EntityID parent = pair.second; if (m_RigidBodies.find(entity) == m_RigidBodies.end()) continue; @@ -128,22 +129,35 @@ void Systems::PhysicsSystem::Update(double dt) if (!transformComponent) continue; - - /*if(m_RigidBodies[entity]->isActive()) + if(m_RigidBodies[entity]->isActive()) { + + hkVector4 position; + hkQuaternion rotation; + + if (parent) + { + auto absoluteTransform = m_World->GetSystem("TransformSystem")->AbsoluteTransform(entity); + position = hkVector4(absoluteTransform.Position.x, absoluteTransform.Position.y, absoluteTransform.Position.z); + rotation = hkQuaternion(absoluteTransform.Orientation.x, absoluteTransform.Orientation.y, absoluteTransform.Orientation.z, absoluteTransform.Orientation.w); + } + else + { + position = hkVector4(transformComponent->Position.x, transformComponent->Position.y, transformComponent->Position.z); + rotation = hkQuaternion(transformComponent->Orientation.x, transformComponent->Orientation.y, transformComponent->Orientation.z, transformComponent->Orientation.w); + } m_PhysicsWorld->markForWrite(); - hkVector4 position(transformComponent->Position.x, transformComponent->Position.y, transformComponent->Position.z); - hkQuaternion rotation(transformComponent->Orientation.x, transformComponent->Orientation.y, transformComponent->Orientation.z, transformComponent->Orientation.w); m_RigidBodies[entity]->setPositionAndRotation(position, rotation); m_PhysicsWorld->unmarkForWrite(); - }*/ + + } } - static const double timestep = 1 / 30.0; + static const double timestep = 1 / 60.0; m_Accumulator += dt; while (m_Accumulator >= timestep) { @@ -222,7 +236,7 @@ void Systems::PhysicsSystem::UpdateEntity(double dt, EntityID entity, EntityID p if(inputComponent->KeyState[GLFW_KEY_UP] != 0 || inputComponent->KeyState[GLFW_KEY_DOWN] != 0) { - deviceStatus->m_positionY += inputComponent->KeyState[GLFW_KEY_UP] * -1 * 0.1f + inputComponent->KeyState[GLFW_KEY_DOWN] * 1 * 0.1f; + deviceStatus->m_positionY += inputComponent->KeyState[GLFW_KEY_UP] * -1 * 1.f * dt + inputComponent->KeyState[GLFW_KEY_DOWN] * 1 * 1.f * dt; } else { @@ -234,24 +248,24 @@ void Systems::PhysicsSystem::UpdateEntity(double dt, EntityID entity, EntityID p else if(deviceStatus->m_positionY < -1) deviceStatus->m_positionY = -1; - float turningSpeed = 0.02f; + float turningSpeed = 3.f; if(inputComponent->KeyState[GLFW_KEY_LEFT] != 0 || inputComponent->KeyState[GLFW_KEY_RIGHT] != 0) { - deviceStatus->m_positionX += inputComponent->KeyState[GLFW_KEY_LEFT] * -1 * turningSpeed + inputComponent->KeyState[GLFW_KEY_RIGHT] * 1 * turningSpeed; + deviceStatus->m_positionX += inputComponent->KeyState[GLFW_KEY_LEFT] * -1 * turningSpeed * dt + inputComponent->KeyState[GLFW_KEY_RIGHT] * 1 * turningSpeed * dt; } else { if(deviceStatus->m_positionX > 0) { - deviceStatus->m_positionX += -1 * turningSpeed; + deviceStatus->m_positionX += -1 * (turningSpeed*2) *dt; } else if(deviceStatus->m_positionX < 0) { - deviceStatus->m_positionX += 1 * turningSpeed; + deviceStatus->m_positionX += 1 * (turningSpeed*2) * dt; } - if (deviceStatus->m_positionX > -turningSpeed && deviceStatus->m_positionX < turningSpeed) + if (deviceStatus->m_positionX > -0.1 && deviceStatus->m_positionX < 0.1) { deviceStatus->m_positionX = 0.f; } @@ -265,9 +279,9 @@ void Systems::PhysicsSystem::UpdateEntity(double dt, EntityID entity, EntityID p deviceStatus->m_handbrakeButtonPressed = inputComponent->KeyState[GLFW_KEY_RIGHT_CONTROL]; - if(inputComponent->KeyState[GLFW_KEY_R]) + if(inputComponent->KeyState[GLFW_KEY_R] && !inputComponent->LastKeyState[GLFW_KEY_R]) { - transformComponent->Position = glm::vec3(0, 10, 0); + transformComponent->Position = transformComponent->Position + glm::vec3(0, 5, 0); transformComponent->Orientation = glm::quat(glm::vec3(0.0f, 0.0f, 0.0f)); m_RigidBodies[entity]->setLinearVelocity(hkVector4(0, 0, 0)); m_RigidBodies[entity]->setAngularVelocity(hkVector4(0, 0, 0)); @@ -389,9 +403,18 @@ void Systems::PhysicsSystem::OnEntityCommit( EntityID entity ) } hkpInertiaTensorComputer::computeShapeVolumeMassProperties(mesh, physicsComponent->Mass, massProperties); rigidBodyInfo.m_shape = mesh; - m_hkpExtendedMeshShapes[entity].ExtendedMeshShape = mesh; - m_hkpExtendedMeshShapes[entity].VertexIndices = vertexIndices; - m_hkpExtendedMeshShapes[entity].Vertices = vertices; + m_ExtendedMeshShapes[entity].ExtendedMeshShape = mesh; + m_ExtendedMeshShapes[entity].VertexIndices = vertexIndices; + m_ExtendedMeshShapes[entity].Vertices = vertices; + + hkpMoppCompilerInput mci; + hkpMoppCode* code = hkpMoppUtility::buildCode( mesh, mci ); + hkpMoppBvTreeShape* moppShape = new hkpMoppBvTreeShape(mesh, code); + + m_ExtendedMeshShapes[entity].Code = code; + m_ExtendedMeshShapes[entity].MoppShape = moppShape; + shape = moppShape; + shape = mesh; } else @@ -422,11 +445,12 @@ void Systems::PhysicsSystem::OnEntityCommit( EntityID entity ) i--; } } - m_PhysicsWorld->markForWrite(); + VehicleSetup vehicleSetup; // Create the basic vehicle. m_Vehicles[entity] = new hkpVehicleInstance(rigidBody); + m_PhysicsWorld->markForWrite(); vehicleSetup.buildVehicle(m_World, m_PhysicsWorld, *m_Vehicles[entity], entity, m_Wheels); // Add the vehicle's entities and phantoms to the world m_Vehicles[entity]->addToWorld(m_PhysicsWorld); diff --git a/src/Systems/PhysicsSystem.h b/src/Systems/PhysicsSystem.h index bee1039..6981f3a 100644 --- a/src/Systems/PhysicsSystem.h +++ b/src/Systems/PhysicsSystem.h @@ -38,6 +38,8 @@ #include #include +#include +#include #include #include @@ -93,8 +95,10 @@ private: hkpExtendedMeshShape* ExtendedMeshShape; std::vector* Vertices; std::vector* VertexIndices; + hkpMoppCode* Code; + hkpMoppBvTreeShape* MoppShape; }; - std::unordered_map m_hkpExtendedMeshShapes; + std::unordered_map m_ExtendedMeshShapes; }; } diff --git a/vs11/Returngeance.sln b/vs11/Returngeance.sln index f834d6d..10ce52b 100644 --- a/vs11/Returngeance.sln +++ b/vs11/Returngeance.sln @@ -1,8 +1,6 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2013 -VisualStudioVersion = 12.0.30110.0 -MinimumVisualStudioVersion = 10.0.40219.1 +# Visual Studio 2012 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Returngeance", "Returngeance\Returngeance.vcxproj", "{E8B4A2A2-882B-402A-98A7-8B4F7233C8B3}" EndProject Project("{F088123C-0E9E-452A-89E6-6BA2F21D5CAC}") = "ModelingProject1", "ModelingProject1\ModelingProject1.modelproj", "{B35F204C-3377-457E-AC9E-D9606F421191}" @@ -41,7 +39,4 @@ Global GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection - GlobalSection(Performance) = preSolution - HasPerformanceSessions = true - EndGlobalSection EndGlobal From fa9a610353ddc1dad62cf0c178b28936755da862 Mon Sep 17 00:00:00 2001 From: Stiffly Date: Tue, 29 Apr 2014 14:21:52 +0200 Subject: [PATCH 38/65] Almost correct Orientation calculation... --- src/Systems/ParticleSystem.cpp | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/src/Systems/ParticleSystem.cpp b/src/Systems/ParticleSystem.cpp index 06b2397..6aa3d97 100644 --- a/src/Systems/ParticleSystem.cpp +++ b/src/Systems/ParticleSystem.cpp @@ -59,18 +59,16 @@ void Systems::ParticleSystem::UpdateEntity(double dt, EntityID entity, EntityID if(particleComponent->AngularVelocitySpectrum.size() > 1) ScalarInterpolation(timeProgress, particleComponent->AngularVelocitySpectrum, it->AngularVelocity); //Angular velocity interpolation + if(particleComponent->OrientationSpectrum.size() > 1) VectorInterpolation(timeProgress, particleComponent->OrientationSpectrum, it->Orientation); -// glm::vec3 v1 = particleComponent->OrientationSpectrum[0]; -// glm::vec3 v2 = it->Orientation; -// glm::vec3 v3 = glm::normalize(glm::cross(v1,v2)); -// float angle = glm::acos(glm::dot(v1, v2) / glm::length(v1) * glm::length(v2)); -// float s = sin(angle / 2); -// transformComponent->Orientation.x = v3.x * s; -// transformComponent->Orientation.y = v3.y * s; -// transformComponent->Orientation.z = v3.z * s; -// transformComponent->Orientation.w = glm::cos(angle/2); + glm::vec3 v1 = glm::normalize(particleComponent->OrientationSpectrum[0]); + glm::vec3 v2 = glm::normalize(it->Orientation); + glm::vec3 v3 = glm::cross(v1,v2); + float angle = glm::abs(glm::acos(glm::dot(v1, v2) / (v1.length() * v2.length()))); + transformComponent->Orientation = glm::angleAxis(angle, v3); + //float alpha = it->AngularVelocity * dt; //transformComponent->Orientation = transformComponent->Orientation * it->Orientation; From 262d2596811a79aa96ace7825aef0699b63054c7 Mon Sep 17 00:00:00 2001 From: Stiffly Date: Thu, 1 May 2014 02:00:10 +0200 Subject: [PATCH 39/65] Orientation interpolation complete (v.length() != glm::length(v), the latter is correct) --- src/Systems/ParticleSystem.cpp | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/src/Systems/ParticleSystem.cpp b/src/Systems/ParticleSystem.cpp index 6aa3d97..48a1a91 100644 --- a/src/Systems/ParticleSystem.cpp +++ b/src/Systems/ParticleSystem.cpp @@ -59,19 +59,15 @@ void Systems::ParticleSystem::UpdateEntity(double dt, EntityID entity, EntityID if(particleComponent->AngularVelocitySpectrum.size() > 1) ScalarInterpolation(timeProgress, particleComponent->AngularVelocitySpectrum, it->AngularVelocity); //Angular velocity interpolation - if(particleComponent->OrientationSpectrum.size() > 1) VectorInterpolation(timeProgress, particleComponent->OrientationSpectrum, it->Orientation); - glm::vec3 v1 = glm::normalize(particleComponent->OrientationSpectrum[0]); - glm::vec3 v2 = glm::normalize(it->Orientation); - glm::vec3 v3 = glm::cross(v1,v2); - float angle = glm::abs(glm::acos(glm::dot(v1, v2) / (v1.length() * v2.length()))); + glm::vec3 v1 = (particleComponent->OrientationSpectrum[0]); + glm::vec3 v2 = (it->Orientation); + glm::vec3 v3 = glm::normalize(glm::cross(v1,v2)); + float angle = glm::acos(glm::dot(v1, v2) / (glm::length(v1) * glm::length(v2))); + transformComponent->Orientation = glm::angleAxis(angle, v3); - - - //float alpha = it->AngularVelocity * dt; - //transformComponent->Orientation = transformComponent->Orientation * it->Orientation; transformComponent->Position += transformComponent->Velocity * (float)dt; it++; @@ -122,6 +118,8 @@ void Systems::ParticleSystem::SpawnParticles(EntityID emitterID) // particle->AngularVelocitySpectrum.push_back(0.f); // particle->AngularVelocitySpectrum.push_back(-glm::pi()); particle->OrientationSpectrum = particle->VelocitySpectrum; +// particle->OrientationSpectrum.push_back(glm::vec3(0,1,0)); +// particle->OrientationSpectrum.push_back(glm::vec3(0,-1,0)); // Color startColor = {.4f, .45f, .2f}; // particle->ColorSpectrum.push_back(startColor); From 469b53c14d18422cbade43fafd50f2484e09e4da Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Tue, 6 May 2014 04:46:22 +0200 Subject: [PATCH 40/65] Updated model paths --- src/GameWorld.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index fc83950..8b56f75 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -61,7 +61,7 @@ void GameWorld::Initialize() // box->Depth = 2.594f; auto meshShape = AddComponent(jeep, "MeshShape"); - meshShape->ResourceName = "Models/JeepV2/Chassi/ChassiCollision.obj"; + meshShape->ResourceName = "Models/Jeep/Chassi/ChassiCollision.obj"; auto vehicle = AddComponent(jeep, "Vehicle"); @@ -72,7 +72,7 @@ void GameWorld::Initialize() auto transform = AddComponent(chassis, "Transform"); transform->Position = glm::vec3(0, 0, 0); // 0.6577f auto model = AddComponent(chassis, "Model"); - model->ModelFile = "Models/JeepV2/Chassi/ChassiCollision.obj"; + model->ModelFile = "Models/Jeep/Chassi/ChassiCollision.obj"; } { @@ -98,7 +98,7 @@ void GameWorld::Initialize() transform->Position = glm::vec3(1.9f, 0.5546f - wheelOffset, -0.9242f); transform->Scale = glm::vec3(1.0f); auto model = AddComponent(wheel, "Model"); - model->ModelFile = "Models/JeepV2/WheelFront/wheelFront.obj"; + model->ModelFile = "Models/Jeep/WheelFront/wheelFront.obj"; auto Wheel = AddComponent(wheel, "Wheel"); Wheel->Hardpoint = transform->Position + glm::vec3(0.f, springLength, 0.f); Wheel->AxleID = 0; @@ -118,7 +118,7 @@ void GameWorld::Initialize() transform->Scale = glm::vec3(1.0f); transform->Orientation = glm::angleAxis(glm::pi(), glm::vec3(0, 0, 1)); auto model = AddComponent(wheel, "Model"); - model->ModelFile = "Models/JeepV2/WheelFront/wheelFront.obj"; + model->ModelFile = "Models/Jeep/WheelFront/wheelFront.obj"; auto Wheel = AddComponent(wheel, "Wheel"); Wheel->Hardpoint = transform->Position + glm::vec3(0.f, springLength, 0.f); Wheel->AxleID = 0; @@ -136,7 +136,7 @@ void GameWorld::Initialize() auto transform = AddComponent(wheel, "Transform"); transform->Position = glm::vec3(0.2726f, 0.2805f - wheelOffset, 1.9307f); auto model = AddComponent(wheel, "Model"); - model->ModelFile = "Models/JeepV2/WheelBack/wheelBack.obj"; + model->ModelFile = "Models/Jeep/WheelBack/wheelBack.obj"; auto Wheel = AddComponent(wheel, "Wheel"); Wheel->Hardpoint = transform->Position + glm::vec3(0.f, springLength, 0.f); Wheel->AxleID = 1; @@ -155,7 +155,7 @@ void GameWorld::Initialize() transform->Position = glm::vec3(-0.2726f, 0.2805f - wheelOffset, 1.9307f); transform->Orientation = glm::angleAxis(glm::pi(), glm::vec3(0, 0, 1)); auto model = AddComponent(wheel, "Model"); - model->ModelFile = "Models/JeepV2/WheelBack/wheelBack.obj"; + model->ModelFile = "Models/Jeep/WheelBack/wheelBack.obj"; auto Wheel = AddComponent(wheel, "Wheel"); Wheel->Hardpoint = transform->Position + glm::vec3(0.f, springLength, 0.f); Wheel->AxleID = 1; From 398b157b893d9eb52cee2b543f60f17e9f253790 Mon Sep 17 00:00:00 2001 From: Stiffly Date: Tue, 6 May 2014 13:52:34 +0200 Subject: [PATCH 41/65] Rendering sprites --- src/GameWorld.cpp | 9 ++++++--- src/Renderer.cpp | 32 ++++++++++++++++++++++++++++++++ src/Renderer.h | 2 ++ src/Systems/ParticleSystem.cpp | 2 +- src/Systems/RenderSystem.cpp | 11 +++++++++++ 5 files changed, 52 insertions(+), 4 deletions(-) diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index 7d25c46..801cd6e 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -104,14 +104,17 @@ void GameWorld::Initialize() emitter->SpawnCount = 1; emitter->SpreadAngle = glm::pi()/20; emitter->SpawnFrequency = 1.008; + emitter->ScaleSpectrum.push_back(glm::vec3(1)); + emitter->ScaleSpectrum.push_back(glm::vec3(0)); auto model = AddComponent(ent, "Model"); model->ModelFile = "Models/Placeholders/PhysicsTest/PointLight.obj"; auto particleEnt = CreateEntity(); AddComponent(particleEnt, "Transform"); - model = AddComponent(particleEnt, "Model"); - model->ModelFile = "Models/Placeholders/PhysicsTest/PointLight.obj"; - +// model = AddComponent(particleEnt, "Model"); +// model->ModelFile = "Models/Placeholders/PhysicsTest/PointLight.obj"; + auto spriteComponent = AddComponent(particleEnt, "Sprite"); + spriteComponent->SpriteFile = "Textures/Sprites/SeriousParticle.png"; emitter->ParticleTemplate = particleEnt; } } diff --git a/src/Renderer.cpp b/src/Renderer.cpp index e7dfed6..c8cf06e 100755 --- a/src/Renderer.cpp +++ b/src/Renderer.cpp @@ -267,6 +267,29 @@ void Renderer::DrawScene() } } + for (auto tuple : TexturesToRender) + { + Texture* texture; + glm::mat4 modelMatrix; + std::tie(texture, modelMatrix) = tuple; + + //MVP = m_Camera->ProjectionMatrix() * glm::translate(glm::mat4(), m_Camera->Position()) * modelMatrix; + MVP = cameraMatrix * glm::inverse(glm::toMat4(m_Camera->Orientation())) * modelMatrix ; + depthMVP = depthCameraMatrix * modelMatrix; + glUniformMatrix4fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "MVP"), 1, GL_FALSE, glm::value_ptr(MVP)); + glUniformMatrix4fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "DepthMVP"), 1, GL_FALSE, glm::value_ptr(depthMVP)); + glUniformMatrix4fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "model"), 1, GL_FALSE, glm::value_ptr(modelMatrix)); + glUniformMatrix4fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "view"), 1, GL_FALSE, glm::value_ptr(m_Camera->ViewMatrix())); + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, *texture); + glBindVertexArray(m_ScreenQuad); + glDrawArrays(GL_TRIANGLES, 0, 6); + } + + + + #ifdef DEBUG // Debug draw model normals if (m_DrawNormals) @@ -318,6 +341,8 @@ void Renderer::DrawShadowMap() glDrawArrays(GL_TRIANGLES, texGroup.StartIndex, texGroup.EndIndex - texGroup.StartIndex + 1); } } + + } void Renderer::DrawDebugShadowMap() @@ -376,6 +401,12 @@ void Renderer::AddModelToDraw(Model* model, glm::vec3 position, glm::quat orient ModelsToRender.push_back(std::make_tuple(model, modelMatrix, visible, shadowCaster)); } +void Renderer::AddTextureToDraw(Texture* texture, glm::vec3 position, glm::quat orientation, glm::vec3 scale) +{ + glm::mat4 modelMatrix = glm::translate(glm::mat4(), position) * glm::toMat4(orientation) * glm::scale(scale); + TexturesToRender.push_back(std::make_tuple(texture, modelMatrix)); +} + void Renderer::AddPointLightToDraw( glm::vec3 _position, glm::vec3 _specular, @@ -536,6 +567,7 @@ void Renderer::ClearStuff() { AABBsToRender.clear(); ModelsToRender.clear(); + TexturesToRender.clear(); Light_position.clear(); Light_specular.clear(); Light_diffuse.clear(); diff --git a/src/Renderer.h b/src/Renderer.h index 8d0da1f..7d00b13 100755 --- a/src/Renderer.h +++ b/src/Renderer.h @@ -23,6 +23,7 @@ public: int HEIGHT, WIDTH; std::list> ModelsToRender; + std::list> TexturesToRender; int Lights; std::vector Light_position; std::vector Light_specular; @@ -40,6 +41,7 @@ public: void DrawText(); void AddModelToDraw(Model* model, glm::vec3 position, glm::quat orientation, glm::vec3 scale, bool visible, bool shadowCaster); + void AddTextureToDraw(Texture* texture, glm::vec3 position, glm::quat orientation, glm::vec3 scale); void AddTextToDraw(); void AddPointLightToDraw( glm::vec3 _position, diff --git a/src/Systems/ParticleSystem.cpp b/src/Systems/ParticleSystem.cpp index 48a1a91..660e39c 100644 --- a/src/Systems/ParticleSystem.cpp +++ b/src/Systems/ParticleSystem.cpp @@ -111,7 +111,7 @@ void Systems::ParticleSystem::SpawnParticles(EntityID emitterID) auto particle = m_World->AddComponent(ent, "Particle"); particle->LifeTime = emitterComponent->LifeTime; - particle->ScaleSpectrum.push_back(glm::vec3(1)); //TEMP + particle->ScaleSpectrum = emitterComponent->ScaleSpectrum; //TEMP //particle->ScaleSpectrum.push_back(glm::vec3(1,4,1)); //TEMP particle->VelocitySpectrum.push_back(particleTransform->Velocity); //TEMP particle->VelocitySpectrum.push_back(testVel); //TEMP diff --git a/src/Systems/RenderSystem.cpp b/src/Systems/RenderSystem.cpp index 9e2b426..d2102d1 100755 --- a/src/Systems/RenderSystem.cpp +++ b/src/Systems/RenderSystem.cpp @@ -55,6 +55,17 @@ void Systems::RenderSystem::UpdateEntity(double dt, EntityID entity, EntityID pa m_Renderer->GetCamera()->NearClip(cameraComponent->NearClip); m_Renderer->GetCamera()->FarClip(cameraComponent->FarClip); } + + auto spriteComponent = m_World->GetComponent(entity, "Sprite"); + if(spriteComponent != nullptr) + { + //TEMP + Texture* texture = m_World->GetResourceManager()->Load("Texture", spriteComponent->SpriteFile); + //glBindTexture(GL_TEXTURE_2D, texture); + auto transform = m_World->GetComponent(spriteComponent->Entity, "Transform"); + glm::quat orientation2D = glm::angleAxis(glm::eulerAngles(transform->Orientation).z, glm::vec3(0, 0, -1)); + m_Renderer->AddTextureToDraw(texture, transform->Position, orientation2D, transform->Scale); + } } void Systems::RenderSystem::Initialize() From b1b60bce6186fd4b647cc5373d87e9b413fcdc75 Mon Sep 17 00:00:00 2001 From: Tleety Date: Wed, 7 May 2014 14:23:01 +0000 Subject: [PATCH 42/65] WIP --- src/Components/PointLight.h | 6 +- src/GameWorld.cpp | 15 ++++- src/Renderer.cpp | 112 +++++++++++++++++++++++-------- src/Renderer.h | 28 +++++--- src/Shaders/Fragment2-Debug.glsl | 2 +- src/Shaders/Fragment2.glsl | 77 ++++++++++++++++++++- src/Shaders/Vertex2.glsl | 4 +- src/Systems/RenderSystem.cpp | 8 +-- 8 files changed, 203 insertions(+), 49 deletions(-) diff --git a/src/Components/PointLight.h b/src/Components/PointLight.h index a7a5d4a..29da989 100755 --- a/src/Components/PointLight.h +++ b/src/Components/PointLight.h @@ -11,11 +11,13 @@ struct PointLight : Component { float Intensity; float MaxRange; - glm::vec3 Specular; - glm::vec3 Diffuse; float constantAttenuation, linearAttenuation, quadraticAttenuation; float spotExponent; Color color; + + glm::vec3 Specular; + glm::vec3 Diffuse; + float specularExponent; }; } diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index 7926dcb..bb01e03 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -58,6 +58,7 @@ void GameWorld::Initialize() transform->Orientation = glm::quat(glm::vec3(-glm::pi() / 8.f, 0.f, 0.f)); auto cameraComp = AddComponent(camera, "Camera"); cameraComp->FarClip = 2000.f; + cameraComp->FOV = glm::radians(90.f); AddComponent(camera, "Input"); auto freeSteering = AddComponent(camera, "FreeSteering"); CommitEntity(camera); @@ -149,7 +150,6 @@ void GameWorld::Initialize() } /* - { // Front Right Wheel auto ent = CreateEntity(car); @@ -224,7 +224,18 @@ void GameWorld::Initialize() CommitEntity(car); } */ - + for(int i = 0; i < 5; i++) + { + auto Light = CreateEntity(); + auto transform = AddComponent(Light, "Transform"); + transform->Position = glm::vec3(20+ 10*cos(i), 3, 0 + 10*sin(i)); + auto light = AddComponent(Light, "PointLight"); + light->Diffuse = glm::vec3(94.f/255.f, 227.f/255.f, 230.f/255.f); + light->Specular = glm::vec3(94.f/255.f, 227.f/255.f, 230.f/255.f); + light->specularExponent = 1.0f; + auto model = AddComponent(Light, "Model"); + model->ModelFile = "Models/Placeholders/PhysicsTest/PointLight.obj"; + } for(int i = 0; i < 10; i++) diff --git a/src/Renderer.cpp b/src/Renderer.cpp index 1125dc0..bf6241b 100755 --- a/src/Renderer.cpp +++ b/src/Renderer.cpp @@ -155,9 +155,6 @@ void Renderer::Draw(double dt) #pragma region TempRegion - - - void Renderer::DrawSkybox() { glBindFramebuffer(GL_FRAMEBUFFER, 0); @@ -199,9 +196,9 @@ void Renderer::DrawScene() m_ShaderProgram.Bind(); glUniform1i(glGetUniformLocation(m_ShaderProgram.GetHandle(), "numberOfLights"), Lights); - glUniform3fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "position"), Lights, Light_position.data()); - glUniform3fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "specular"), Lights, Light_specular.data()); - glUniform3fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "diffuse"), Lights, Light_diffuse.data()); +// glUniform3fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "position"), Lights, Light_position.data()); +// glUniform3fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "specular"), Lights, Light_specular.data()); +// glUniform3fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "diffuse"), Lights, Light_diffuse.data()); glUniform1fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "constantAttenuation"), Lights, Light_constantAttenuation.data()); glUniform1fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "linearAttenuation"), Lights, Light_linearAttenuation.data()); glUniform1fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "quadraticAttenuation"), Lights, Light_quadraticAttenuation.data()); @@ -359,26 +356,30 @@ void Renderer::AddPointLightToDraw( glm::vec3 _position, glm::vec3 _specular, glm::vec3 _diffuse, - float _constantAttenuation, - float _linearAttenuation, - float _quadraticAttenuation, - float _spotExponent + float _specularExponent ) { - Light_position.push_back(_position.x); - Light_position.push_back(_position.y); - Light_position.push_back(_position.z); - Light_specular.push_back(_specular.x); - Light_specular.push_back(_specular.y); - Light_specular.push_back(_specular.z); - Light_diffuse.push_back(_diffuse.x); - Light_diffuse.push_back(_diffuse.y); - Light_diffuse.push_back(_diffuse.z); - Light_constantAttenuation.push_back(_constantAttenuation); - Light_linearAttenuation.push_back(_linearAttenuation); - Light_quadraticAttenuation.push_back(_quadraticAttenuation); - Light_spotExponent.push_back(_spotExponent); - Lights = Light_constantAttenuation.size(); + Light_position.push_back(_position); + Light_specular.push_back(_specular); + Light_diffuse.push_back(_diffuse); + Light_specularExponent.push_back(_specularExponent); + Lights = Light_position.size(); + CreateLightMatrix(); + +// Light_position.push_back(_position.x); +// Light_position.push_back(_position.y); +// Light_position.push_back(_position.z); +// Light_specular.push_back(_specular.x); +// Light_specular.push_back(_specular.y); +// Light_specular.push_back(_specular.z); +// Light_diffuse.push_back(_diffuse.x); +// Light_diffuse.push_back(_diffuse.y); +// Light_diffuse.push_back(_diffuse.z); +// Light_constantAttenuation.push_back(_constantAttenuation); +// Light_linearAttenuation.push_back(_linearAttenuation); +// Light_quadraticAttenuation.push_back(_quadraticAttenuation); +// Light_spotExponent.push_back(_spotExponent); +// Lights = Light_constantAttenuation.size(); } void Renderer::AddAABBToDraw(glm::vec3 origin, glm::vec3 volumeVector, bool colliding) @@ -523,6 +524,7 @@ void Renderer::ClearStuff() Light_linearAttenuation.clear(); Light_quadraticAttenuation.clear(); Light_spotExponent.clear(); + Light_specularExponent.clear(); Lights = 0; } @@ -657,13 +659,14 @@ void Renderer::DrawFBO() // Clear G-buffer GLenum windowBuffClear[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2 }; glDrawBuffers(3, windowBuffClear); - glClearColor(0.0f, 0.0f, 0.0f, 0.0f); + glClearColor(0.2f, 0.2f, 0.2f, 0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Execute the first render stage which will fill out the internal buffers with data(??) m_FirstPassProgram.Bind(); GLenum windowBuffOpaque[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2 }; glDrawBuffers(3, windowBuffOpaque); + DrawFBOScene(); // Draw to screen @@ -678,7 +681,7 @@ void Renderer::DrawFBO() } glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - ////SetupDefferedStageUniforms(); // Probably what we do in FrameBufferTextures(); + glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_fDiffuseTexture); @@ -688,9 +691,11 @@ void Renderer::DrawFBO() glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, m_fNormalsTexture); + DrawLightScene(); + glBindVertexArray(m_ScreenQuad); glEnableVertexAttribArray(0); -/* glEnableVertexAttribArray(2);*/ + glEnableVertexAttribArray(2); glDrawArrays(GL_TRIANGLES, 0, 6); } @@ -721,7 +726,6 @@ void Renderer::DrawFBO() // glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // glDisable(GL_BLEND); // -// // glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); // //Probably means to use the second_pass shader // //EnableRenderProgramDeferredStage(); @@ -781,3 +785,55 @@ void Renderer::DrawFBOScene() } } + + +void Renderer::DrawLightScene() +{ + glEnable(GL_BLEND); + glBlendEquation (GL_FUNC_ADD); + glBlendFunc(GL_ONE,GL_ONE); + + glDisable (GL_DEPTH_TEST); + glDepthMask (GL_FALSE); + glBindVertexArray(m_sphereModel->VAO); + + glm::mat4 cameraMatrix = m_Camera->ProjectionMatrix() * m_Camera->ViewMatrix(); + glm::mat4 MVP; + + for(int i = 0; i < Lights; i++) + { + glm::mat4 MVP = m_Camera->ProjectionMatrix() * m_Camera->ViewMatrix() * lM[i]; + + glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "MVP"), 1, GL_FALSE, glm::value_ptr(MVP)); + glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "V"), 1, GL_FALSE, glm::value_ptr(m_Camera->ViewMatrix())); + glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "P"), 1, GL_FALSE, glm::value_ptr(m_Camera->ProjectionMatrix())); + glUniformMatrix4fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "M"), 1, GL_FALSE, glm::value_ptr(lM[i])); + glUniform3f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "ls"), Light_specular[i].x, Light_specular[i].y, Light_specular[i].z); + glUniform3f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "ld"), Light_diffuse[i].x, Light_diffuse[i].y, Light_diffuse[i].z); + glUniform3f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "lp"), Light_position[i].x, Light_position[i].y, Light_position[i].z); + glUniform3f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "CameraPosition"), m_Camera->Position().x, m_Camera->Position().y, m_Camera->Position().z); + //glUniform1f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "speculatExponent"), Light_specularExponent[i]); + glDrawArrays(GL_TRIANGLES, 0, m_sphereModel->Vertices.size()); + }; + glEnable (GL_DEPTH_TEST); + glDepthMask (GL_TRUE); + glDisable (GL_BLEND); +} + +void Renderer::SetSphereModel( Model* _model ) +{ + m_sphereModel = _model; +} + +void Renderer::CreateLightMatrix() +{ + for(int i = 0; i < Lights; i++) + { + const float radius = 5.0f; + lM[i] = glm::scale(glm::mat4(1.0), glm::vec3(radius, radius, radius)); + lM[i] = glm::translate(lM[i], Light_position[i]); + lM[i] = m_Camera->ProjectionMatrix() * m_Camera->ViewMatrix() * lM[i]; + } + +} + diff --git a/src/Renderer.h b/src/Renderer.h index 540be71..1c73d49 100755 --- a/src/Renderer.h +++ b/src/Renderer.h @@ -12,6 +12,7 @@ #include "Model.h" #include "Components/PointLight.h" #include "Skybox.h" +#include "ResourceManager.h" class Renderer { @@ -24,13 +25,17 @@ public: std::list> ModelsToRender; int Lights; - std::vector Light_position; - std::vector Light_specular; - std::vector Light_diffuse; - std::vector Light_constantAttenuation; - std::vector Light_linearAttenuation; - std::vector Light_quadraticAttenuation; + std::vector Light_position; + std::vector Light_specular; + std::vector Light_diffuse; + std::vector Light_specularExponent; + + + std::vector Light_constantAttenuation; + std::vector Light_linearAttenuation; + std::vector Light_quadraticAttenuation; std::vector Light_spotExponent; + std::list> AABBsToRender; Renderer(); @@ -45,10 +50,7 @@ public: glm::vec3 _position, glm::vec3 _specular, glm::vec3 _diffuse, - float _constantAttenuation, - float _linearAttenuation, - float _quadraticAttenuation, - float _spotExponent + float _specularExponent ); void AddAABBToDraw(glm::vec3 origin, glm::vec3 volumeVector, bool colliding); @@ -65,6 +67,8 @@ public: void DrawBounds(bool val) { m_DrawBounds = val; } void DrawSkybox(); + void SetSphereModel(Model* _model); + private: @@ -94,7 +98,9 @@ private: GLuint m_fb; GLuint m_fDepthBuffer; GLenum draw_bufs[2]; + glm::mat4 lM[5]; GLuint m_ScreenQuad; + Model* m_sphereModel; bool m_QuadView; @@ -118,7 +124,9 @@ private: void FrameBufferTextures(); void DrawFBO(); void DrawFBOScene(); + void DrawLightScene(); void BindFragDataLocation(); + void CreateLightMatrix(); GLuint CreateQuad(); void DrawDebugShadowMap(); diff --git a/src/Shaders/Fragment2-Debug.glsl b/src/Shaders/Fragment2-Debug.glsl index db35d6e..0ab00d4 100644 --- a/src/Shaders/Fragment2-Debug.glsl +++ b/src/Shaders/Fragment2-Debug.glsl @@ -30,7 +30,7 @@ void main() //FragColor = texture2D(DiffuseTexture, Input.TextureCoord * 2 + vec2(0, -1)); DrawQuadrant(texture2D(DiffuseTexture, Input.TextureCoord * 2), vec2(-1, 1)); DrawQuadrant(texture2D(PositionTexture, Input.TextureCoord * 2), vec2(1, 1)); - DrawQuadrant(texture2D(NormalTexture, Input.TextureCoord * 2), vec2(-1, -1)); + DrawQuadrant((texture2D(NormalTexture, Input.TextureCoord * 2)+1)/2, vec2(-1, -1)); vec4 AllTexel = texture2D(DiffuseTexture, Input.TextureCoord*2)*texture2D(PositionTexture, Input.TextureCoord*2)*texture2D(NormalTexture, Input.TextureCoord*2); DrawQuadrant(AllTexel, vec2(1, -1)); diff --git a/src/Shaders/Fragment2.glsl b/src/Shaders/Fragment2.glsl index cbc905e..aff7665 100644 --- a/src/Shaders/Fragment2.glsl +++ b/src/Shaders/Fragment2.glsl @@ -4,6 +4,20 @@ layout (binding=0) uniform sampler2D DiffuseTexture; layout (binding=1) uniform sampler2D PositionTexture; layout (binding=2) uniform sampler2D NormalTexture; +uniform mat4 MVP; +uniform mat4 M; +uniform mat4 V; +uniform mat4 P; +uniform vec3 ls; +uniform vec3 ld; +uniform vec3 lp; +const float specularExponent = 20.0; +uniform vec3 CameraPosition; + +const vec3 kd = vec3(1.0, 1.0, 1.0); +const vec3 ks = vec3(1.0, 1.0, 1.0); +const float kshine = 1.0; + in VertexData { vec3 Position; @@ -13,7 +27,68 @@ in VertexData out vec4 FragColor; +vec3 phong (vec3 PositionTexel, vec3 NormalTexel) +{ + vec3 lightPosition = vec3( M * vec4( lp, 1.0 ) ); + vec3 distToLight = lightPosition - PositionTexel; + vec3 directionToLight = normalize(distToLight); + + //Diffuse light + float dotProdDiffuse = max(dot(directionToLight, NormalTexel), 0.0); + vec3 Id = ld * kd * dotProdDiffuse; //Final diffuse intensity + + //Specular light + vec3 reflection = reflect(-directionToLight, NormalTexel); + vec3 surfaceToCamera = normalize(PositionTexel); + vec3 HalfWay = normalize(surfaceToCamera + directionToLight); + float dotProdSpecular = dot(HalfWay, NormalTexel); + dotProdSpecular = max(dotProdSpecular, 0.0); + float specularFactor = pow(dotProdSpecular, specularExponent); + vec3 Is = ls * ks * specularFactor; //Final specular intensity + + //Attenuation + float dist2D = distance(lightPosition, PositionTexel); + float attenuationFactor = -log(min(1.0, dist2D / 5.0)); + + //vec3 FinalOut = (Id + Is) * attenuationFactor; + vec3 FinalOut = Id + Is; + return FinalOut; +} + + +vec3 phong2 (vec3 PositionTexel, vec3 NormalTexel) +{ + vec3 LightVector = lp - PositionTexel; + vec3 ViewVector = normalize(PositionTexel); + + //diffuse + vec3 Id = max(0.0, dot(LightVector, NormalTexel)) * ld; + + vec3 FinalOut = Id; + return FinalOut; +} + +vec3 phong3 (vec3 PositionTexel, vec3 NormalTexel) +{ + vec3 lightDir = lp - PositionTexel; + lightDir = normalize(lightDir); + + vec3 eyeDir = normalize(CameraPosition-PositionTexel); + vec3 vHalfVector = normalize(lightDir.xyz+eyeDir); + vec3 Id = max(0.0, dot(NormalTexel, lightDir)) * ld; + vec3 Is = pow(max(0.0, dot(NormalTexel, vHalfVector)), 100.0) * ls; + vec3 FinalFrag = Id + Is; + return FinalFrag; +} + void main() { - FragColor = texture2D(DiffuseTexture, Input.TextureCoord); + vec4 DiffuseTexel = texture2D(DiffuseTexture, Input.TextureCoord); + vec4 PositionTexel = texture2D(PositionTexture, Input.TextureCoord); + vec4 NormalTexel = texture2D(NormalTexture, Input.TextureCoord); + + vec4 Frag_color; + Frag_color.rgb = phong((MVP * PositionTexel).rgb, normalize(NormalTexel).rgb); + Frag_color.a = 1.0; + FragColor = Frag_color * DiffuseTexel; } \ No newline at end of file diff --git a/src/Shaders/Vertex2.glsl b/src/Shaders/Vertex2.glsl index e866f94..f341840 100644 --- a/src/Shaders/Vertex2.glsl +++ b/src/Shaders/Vertex2.glsl @@ -3,6 +3,8 @@ layout (location = 0) in vec3 Position; layout (location = 2) in vec2 TextureCoord; + + out VertexData { vec3 Position; @@ -11,7 +13,7 @@ out VertexData void main() { - gl_Position = vec4(Position, 1.0); + gl_Position = vec4(Position, 1.0); Output.Position = Position; Output.TextureCoord = TextureCoord; } \ No newline at end of file diff --git a/src/Systems/RenderSystem.cpp b/src/Systems/RenderSystem.cpp index fe254f4..2dc4116 100755 --- a/src/Systems/RenderSystem.cpp +++ b/src/Systems/RenderSystem.cpp @@ -38,10 +38,8 @@ void Systems::RenderSystem::UpdateEntity(double dt, EntityID entity, EntityID pa position, pointLightComponent->Specular, pointLightComponent->Diffuse, - pointLightComponent->constantAttenuation, - pointLightComponent->linearAttenuation, - pointLightComponent->quadraticAttenuation, - pointLightComponent->spotExponent); + pointLightComponent->specularExponent + ); } auto cameraComponent = m_World->GetComponent(entity, "Camera"); @@ -59,6 +57,8 @@ void Systems::RenderSystem::UpdateEntity(double dt, EntityID entity, EntityID pa void Systems::RenderSystem::Initialize() { m_TransformSystem = m_World->GetSystem("TransformSystem"); + + m_Renderer->SetSphereModel(m_World->GetResourceManager()->Load("Model", "Models/Placeholders/PhysicsTest/Sphere.obj")); } void Systems::RenderSystem::RegisterComponents(ComponentFactory* cf) From 1a365bf06990a0276834820e70a4e656d4def2d0 Mon Sep 17 00:00:00 2001 From: Stiffly Date: Wed, 7 May 2014 21:34:19 +0200 Subject: [PATCH 43/65] Billboarding on sprites --- src/Components/ParticleEmitter.h | 3 +- src/GameWorld.cpp | 17 ++++--- src/Renderer.cpp | 24 +++++++-- src/Renderer.h | 2 +- src/Systems/ParticleSystem.cpp | 86 +++++++++++++++++++++----------- src/Systems/ParticleSystem.h | 1 - 6 files changed, 90 insertions(+), 43 deletions(-) diff --git a/src/Components/ParticleEmitter.h b/src/Components/ParticleEmitter.h index ae66fca..1b30c8d 100755 --- a/src/Components/ParticleEmitter.h +++ b/src/Components/ParticleEmitter.h @@ -28,7 +28,8 @@ struct ParticleEmitter : Component std::vector ScaleSpectrum; float SpreadAngle; double LifeTime; - std::vector VelocitySpectrum; + bool UseGoalVelocity; + glm::vec3 GoalVelocity; std::vector AngularVelocitySpectrum; std::vector OrientationSpectrum; //Keep? diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index 801cd6e..0b19842 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -99,20 +99,23 @@ void GameWorld::Initialize() auto transform = AddComponent(ent, "Transform"); transform->Orientation = glm::angleAxis(glm::pi()/2, glm::vec3(1,0,0)); transform->Position = glm::vec3(i * 10, 20, 0); + auto emitter = AddComponent(ent, "ParticleEmitter"); - emitter->LifeTime = 4; + emitter->LifeTime = 0.3; emitter->SpawnCount = 1; - emitter->SpreadAngle = glm::pi()/20; - emitter->SpawnFrequency = 1.008; - emitter->ScaleSpectrum.push_back(glm::vec3(1)); - emitter->ScaleSpectrum.push_back(glm::vec3(0)); + emitter->SpreadAngle = glm::pi()/4; + emitter->SpawnFrequency = 0.0008; + emitter->ScaleSpectrum.push_back(glm::vec3(0.05f)); + emitter->UseGoalVelocity = false; + emitter->GoalVelocity = glm::vec3(4, -4, 0); +// emitter->OrientationSpectrum.push_back(glm::vec3(0, 1, 0)); +// emitter->OrientationSpectrum.push_back(glm::vec3(0, -1, 0)); + emitter->AngularVelocitySpectrum.push_back(glm::pi() / 100); auto model = AddComponent(ent, "Model"); model->ModelFile = "Models/Placeholders/PhysicsTest/PointLight.obj"; auto particleEnt = CreateEntity(); AddComponent(particleEnt, "Transform"); -// model = AddComponent(particleEnt, "Model"); -// model->ModelFile = "Models/Placeholders/PhysicsTest/PointLight.obj"; auto spriteComponent = AddComponent(particleEnt, "Sprite"); spriteComponent->SpriteFile = "Textures/Sprites/SeriousParticle.png"; emitter->ParticleTemplate = particleEnt; diff --git a/src/Renderer.cpp b/src/Renderer.cpp index c8cf06e..f7960d5 100755 --- a/src/Renderer.cpp +++ b/src/Renderer.cpp @@ -271,10 +271,13 @@ void Renderer::DrawScene() { Texture* texture; glm::mat4 modelMatrix; - std::tie(texture, modelMatrix) = tuple; - - //MVP = m_Camera->ProjectionMatrix() * glm::translate(glm::mat4(), m_Camera->Position()) * modelMatrix; - MVP = cameraMatrix * glm::inverse(glm::toMat4(m_Camera->Orientation())) * modelMatrix ; + glm::mat4 billboardMatrix; + std::tie(texture, modelMatrix, billboardMatrix) = tuple; + + + //MVP = cameraMatrix * glm::inverse(glm::toMat4(m_Camera->Orientation()) * modelMatrix ); + MVP = cameraMatrix * billboardMatrix * modelMatrix; + depthMVP = depthCameraMatrix * modelMatrix; glUniformMatrix4fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "MVP"), 1, GL_FALSE, glm::value_ptr(MVP)); glUniformMatrix4fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "DepthMVP"), 1, GL_FALSE, glm::value_ptr(depthMVP)); @@ -404,7 +407,18 @@ void Renderer::AddModelToDraw(Model* model, glm::vec3 position, glm::quat orient void Renderer::AddTextureToDraw(Texture* texture, glm::vec3 position, glm::quat orientation, glm::vec3 scale) { glm::mat4 modelMatrix = glm::translate(glm::mat4(), position) * glm::toMat4(orientation) * glm::scale(scale); - TexturesToRender.push_back(std::make_tuple(texture, modelMatrix)); + + glm::vec3 camToParticle = glm::normalize(m_Camera->Position() - position); + glm::vec3 up = glm::vec3(0,1,0); + glm::vec3 rightVec = glm::cross(up, camToParticle); + + glm::mat4 billboardMatrix; + billboardMatrix[0] = glm::vec4(rightVec, 0); + billboardMatrix[1] = glm::vec4(up, 0); + billboardMatrix[2] = glm::vec4(camToParticle, 0); + //billboardMatrix[3] = glm::vec4(position, 0); + + TexturesToRender.push_back(std::make_tuple(texture, modelMatrix, billboardMatrix)); } void Renderer::AddPointLightToDraw( diff --git a/src/Renderer.h b/src/Renderer.h index 7d00b13..17485aa 100755 --- a/src/Renderer.h +++ b/src/Renderer.h @@ -23,7 +23,7 @@ public: int HEIGHT, WIDTH; std::list> ModelsToRender; - std::list> TexturesToRender; + std::list> TexturesToRender; int Lights; std::vector Light_position; std::vector Light_specular; diff --git a/src/Systems/ParticleSystem.cpp b/src/Systems/ParticleSystem.cpp index 660e39c..8e384c5 100644 --- a/src/Systems/ParticleSystem.cpp +++ b/src/Systems/ParticleSystem.cpp @@ -31,6 +31,9 @@ void Systems::ParticleSystem::UpdateEntity(double dt, EntityID entity, EntityID emitterComponent->TimeSinceLastSpawn = 0; } + + + std::list::iterator it; for(it = m_ParticleEmitter[entity].begin(); it != m_ParticleEmitter[entity].end();) { @@ -55,19 +58,35 @@ void Systems::ParticleSystem::UpdateEntity(double dt, EntityID entity, EntityID // Velocity interpolation if(particleComponent->VelocitySpectrum.size() > 1) VectorInterpolation(timeProgress, particleComponent->VelocitySpectrum, transformComponent->Velocity); + // Angular velocity interpolation - if(particleComponent->AngularVelocitySpectrum.size() > 1) - ScalarInterpolation(timeProgress, particleComponent->AngularVelocitySpectrum, it->AngularVelocity); + if (particleComponent->AngularVelocitySpectrum.size() != 0) + { + if(particleComponent->AngularVelocitySpectrum.size() > 1) + { + ScalarInterpolation(timeProgress, particleComponent->AngularVelocitySpectrum, it->AngularVelocity); + transformComponent->Orientation = glm::angleAxis(it->AngularVelocity, it->Orientation); + } + else + { + transformComponent->Orientation *= glm::angleAxis(it->AngularVelocity, it->Orientation); + //it->Orientation = glm::angleAxis(it->AngularVelocity, it->Orientation); + } + } + //Angular velocity interpolation if(particleComponent->OrientationSpectrum.size() > 1) + { VectorInterpolation(timeProgress, particleComponent->OrientationSpectrum, it->Orientation); + glm::vec3 v1 = (particleComponent->OrientationSpectrum[0]); + glm::vec3 v2 = (it->Orientation); + glm::vec3 v3 = glm::normalize(glm::cross(v1,v2)); + float angle = glm::acos(glm::dot(v1, v2) / (glm::length(v1) * glm::length(v2))); + + transformComponent->Orientation = glm::angleAxis(angle, v3); + } - glm::vec3 v1 = (particleComponent->OrientationSpectrum[0]); - glm::vec3 v2 = (it->Orientation); - glm::vec3 v3 = glm::normalize(glm::cross(v1,v2)); - float angle = glm::acos(glm::dot(v1, v2) / (glm::length(v1) * glm::length(v2))); - transformComponent->Orientation = glm::angleAxis(angle, v3); transformComponent->Position += transformComponent->Velocity * (float)dt; it++; @@ -98,8 +117,8 @@ void Systems::ParticleSystem::SpawnParticles(EntityID emitterID) auto particleTransform = m_World->GetComponent(ent, "Transform"); particleTransform->Position = emitterTransform->Position; - particleTransform->Scale = glm::vec3(1, 1, 1); + particleTransform->Orientation = emitterOrientation; //The emitter's orientation as "start value" times the default direction for emitter. Times the speed, and then rotate on x and y axis with the randomized spread angle. float spreadAngle = emitterComponent->SpreadAngle; particleTransform->Velocity = emitterOrientation * glm::vec3(0, 0, -1) * speed * @@ -107,33 +126,44 @@ void Systems::ParticleSystem::SpawnParticles(EntityID emitterID) glm::normalize(glm::angleAxis(RandomizeAngle(spreadAngle), glm::vec3(0, 1, 0))) * glm::normalize(glm::angleAxis(RandomizeAngle(spreadAngle), glm::vec3(0, 0, 1))); - glm::vec3 testVel = glm::vec3(particleTransform->Velocity.x, -particleTransform->Velocity.y * 1.5, particleTransform->Velocity.z); //TEMP - auto particle = m_World->AddComponent(ent, "Particle"); particle->LifeTime = emitterComponent->LifeTime; - particle->ScaleSpectrum = emitterComponent->ScaleSpectrum; //TEMP - //particle->ScaleSpectrum.push_back(glm::vec3(1,4,1)); //TEMP - particle->VelocitySpectrum.push_back(particleTransform->Velocity); //TEMP - particle->VelocitySpectrum.push_back(testVel); //TEMP -// particle->AngularVelocitySpectrum.push_back(0.f); -// particle->AngularVelocitySpectrum.push_back(-glm::pi()); - particle->OrientationSpectrum = particle->VelocitySpectrum; -// particle->OrientationSpectrum.push_back(glm::vec3(0,1,0)); -// particle->OrientationSpectrum.push_back(glm::vec3(0,-1,0)); - -// Color startColor = {.4f, .45f, .2f}; -// particle->ColorSpectrum.push_back(startColor); -// Color endColor = {0.f, 45.f, 23.f}; -// particle->ColorSpectrum.push_back(endColor); - + particle->ScaleSpectrum = emitterComponent->ScaleSpectrum; + particle->VelocitySpectrum.push_back(particleTransform->Velocity); + + if (emitterComponent->ScaleSpectrum.size() > 0) + { + if (emitterComponent->ScaleSpectrum.size() > 1) + { + particle->ScaleSpectrum = emitterComponent->ScaleSpectrum; + } + else + { + particleTransform->Scale = emitterComponent->ScaleSpectrum[0]; + } + } + else + { + particleTransform->Scale = glm::vec3(1, 1, 1); + } + + if(emitterComponent->UseGoalVelocity) + particle->VelocitySpectrum.push_back(emitterComponent->GoalVelocity); + particle->OrientationSpectrum = emitterComponent->OrientationSpectrum; + if(particle->OrientationSpectrum.size() != 0) + particleTransform->Orientation = glm::angleAxis(0.f, particle->OrientationSpectrum[0]); + particle->AngularVelocitySpectrum = emitterComponent->AngularVelocitySpectrum; ParticleData data; data.ParticleID = ent; data.SpawnTime = glfwGetTime(); - //data.AngularVelocity = particle->AngularVelocitySpectrum[0]; - data.Orientation = particle->OrientationSpectrum[0]; - + if (particle->AngularVelocitySpectrum.size() != 0) + data.AngularVelocity = particle->AngularVelocitySpectrum[0]; + if (particle->OrientationSpectrum.size() != 0) + data.Orientation = particle->OrientationSpectrum[0]; + else data.Orientation = emitterOrientation * glm::vec3(0,0,-1); + m_ParticleEmitter[emitterID].push_back(data); } } diff --git a/src/Systems/ParticleSystem.h b/src/Systems/ParticleSystem.h index 4dff51e..082c957 100644 --- a/src/Systems/ParticleSystem.h +++ b/src/Systems/ParticleSystem.h @@ -19,7 +19,6 @@ namespace Systems { EntityID ParticleID; double SpawnTime; - float Scale; float AngularVelocity; glm::vec3 Orientation; Color color; From ea69a9345d0230184d23ee45e8ef77f1229de30e Mon Sep 17 00:00:00 2001 From: ViktorLjung Date: Wed, 7 May 2014 16:21:47 +0200 Subject: [PATCH 44/65] PhysicsSystem redesigned, more work is needed. --- src/Components/ExtendedMeshShape.h | 0 src/Components/HingeConstraint.h | 18 + src/GameWorld.cpp | 46 +- src/GameWorld.h | 1 + src/Physics/VehicleSetup.cpp | 4 +- src/Systems/PhysicsSystem.cpp | 408 ++++++++++-------- src/Systems/PhysicsSystem.h | 34 +- vs11/Returngeance/Returngeance.vcxproj | 2 + .../Returngeance/Returngeance.vcxproj.filters | 6 + 9 files changed, 325 insertions(+), 194 deletions(-) create mode 100644 src/Components/ExtendedMeshShape.h create mode 100644 src/Components/HingeConstraint.h diff --git a/src/Components/ExtendedMeshShape.h b/src/Components/ExtendedMeshShape.h new file mode 100644 index 0000000..e69de29 diff --git a/src/Components/HingeConstraint.h b/src/Components/HingeConstraint.h new file mode 100644 index 0000000..96f0db3 --- /dev/null +++ b/src/Components/HingeConstraint.h @@ -0,0 +1,18 @@ +#ifndef Components_HingeConstraint_h__ +#define Components_HingeConstraint_h__ + +#include "Component.h" + +namespace Components +{ + + struct HingeConstraint : Component + { + EntityID LinkedEntity; + glm::vec3 Pivot; + glm::vec3 Axis; + }; + +} + +#endif // Components_HingeConstraint_h__ diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index fc83950..8c36206 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -22,14 +22,20 @@ void GameWorld::Initialize() auto model = AddComponent(ground, "Model"); //model->ModelFile = "Models/TestScene/testScene.obj"; model->ModelFile = "Models/Placeholders/Terrain/Terrain.obj"; - auto meshShape = AddComponent(ground, "MeshShape"); - meshShape->ResourceName = "Models/Placeholders/Terrain/Terrain.obj"; - //meshShape->ResourceName = "Models/TestScene/testScene.obj"; - + auto physics = AddComponent(ground, "Physics"); physics->Mass = 10; physics->Static = true; + + auto groundshape = CreateEntity(ground); + auto transformshape = AddComponent(groundshape, "Transform"); + auto meshShape = AddComponent(groundshape, "MeshShape"); + meshShape->ResourceName = "Models/Placeholders/Terrain/Terrain.obj"; + //meshShape->ResourceName = "Models/TestScene/testScene.obj"; + + + CommitEntity(groundshape); CommitEntity(ground); } @@ -49,11 +55,10 @@ void GameWorld::Initialize() { auto jeep = CreateEntity(); auto transform = AddComponent(jeep, "Transform"); - transform->Position = glm::vec3(0, 15, 0); - + transform->Position = glm::vec3(0, 5, 0); + transform->Orientation = glm::angleAxis(glm::pi()/2, glm::vec3(0, 1, 0)); auto physics = AddComponent(jeep, "Physics"); - physics->Mass = 800; - + physics->Mass = 1800; // auto box = AddComponent(jeep, "Box"); // box->Width = 1.487f; @@ -61,7 +66,7 @@ void GameWorld::Initialize() // box->Depth = 2.594f; auto meshShape = AddComponent(jeep, "MeshShape"); - meshShape->ResourceName = "Models/JeepV2/Chassi/ChassiCollision.obj"; + meshShape->ResourceName = "Models/Jeep/Chassi/ChassiCollision.obj"; auto vehicle = AddComponent(jeep, "Vehicle"); @@ -72,7 +77,7 @@ void GameWorld::Initialize() auto transform = AddComponent(chassis, "Transform"); transform->Position = glm::vec3(0, 0, 0); // 0.6577f auto model = AddComponent(chassis, "Model"); - model->ModelFile = "Models/JeepV2/Chassi/ChassiCollision.obj"; + model->ModelFile = "Models/Jeep/Chassi/chassi.obj"; } { @@ -98,7 +103,7 @@ void GameWorld::Initialize() transform->Position = glm::vec3(1.9f, 0.5546f - wheelOffset, -0.9242f); transform->Scale = glm::vec3(1.0f); auto model = AddComponent(wheel, "Model"); - model->ModelFile = "Models/JeepV2/WheelFront/wheelFront.obj"; + model->ModelFile = "Models/Jeep/WheelFront/wheelFront.obj"; auto Wheel = AddComponent(wheel, "Wheel"); Wheel->Hardpoint = transform->Position + glm::vec3(0.f, springLength, 0.f); Wheel->AxleID = 0; @@ -118,7 +123,7 @@ void GameWorld::Initialize() transform->Scale = glm::vec3(1.0f); transform->Orientation = glm::angleAxis(glm::pi(), glm::vec3(0, 0, 1)); auto model = AddComponent(wheel, "Model"); - model->ModelFile = "Models/JeepV2/WheelFront/wheelFront.obj"; + model->ModelFile = "Models/Jeep/WheelFront/wheelFront.obj"; auto Wheel = AddComponent(wheel, "Wheel"); Wheel->Hardpoint = transform->Position + glm::vec3(0.f, springLength, 0.f); Wheel->AxleID = 0; @@ -136,7 +141,7 @@ void GameWorld::Initialize() auto transform = AddComponent(wheel, "Transform"); transform->Position = glm::vec3(0.2726f, 0.2805f - wheelOffset, 1.9307f); auto model = AddComponent(wheel, "Model"); - model->ModelFile = "Models/JeepV2/WheelBack/wheelBack.obj"; + model->ModelFile = "Models/Jeep/WheelBack/wheelBack.obj"; auto Wheel = AddComponent(wheel, "Wheel"); Wheel->Hardpoint = transform->Position + glm::vec3(0.f, springLength, 0.f); Wheel->AxleID = 1; @@ -155,7 +160,7 @@ void GameWorld::Initialize() transform->Position = glm::vec3(-0.2726f, 0.2805f - wheelOffset, 1.9307f); transform->Orientation = glm::angleAxis(glm::pi(), glm::vec3(0, 0, 1)); auto model = AddComponent(wheel, "Model"); - model->ModelFile = "Models/JeepV2/WheelBack/wheelBack.obj"; + model->ModelFile = "Models/Jeep/WheelBack/wheelBack.obj"; auto Wheel = AddComponent(wheel, "Wheel"); Wheel->Hardpoint = transform->Position + glm::vec3(0.f, springLength, 0.f); Wheel->AxleID = 1; @@ -167,6 +172,7 @@ void GameWorld::Initialize() Wheel->ConnectedToHandbrake = true; CommitEntity(wheel); } + CommitEntity(jeep); } @@ -194,7 +200,7 @@ void GameWorld::Initialize() CommitEntity(entity); }*/ - for(int i = 0; i < 5; i++) + for(int i = 0; i < 1; i++) { auto wall = CreateEntity(); auto transform = AddComponent(wall, "Transform"); @@ -205,7 +211,7 @@ void GameWorld::Initialize() { for (int x = -5; x < 5; x++) { - auto brick = CreateEntity(wall); + auto brick = CreateEntity(); auto transform = AddComponent(brick, "Transform"); transform->Position = glm::vec3(x + 0.01f, y * 0.3f + 0.01f, 0); transform->Position.x += (y % 2)*0.5f; @@ -216,10 +222,16 @@ void GameWorld::Initialize() auto physics = AddComponent(brick, "Physics"); physics->Mass = 3; - auto box = AddComponent(brick, "BoxShape"); + + + + auto shape = CreateEntity(brick); + auto transformshape = AddComponent(shape, "Transform"); + auto box = AddComponent(shape, "BoxShape"); box->Width = 0.5f; box->Height = 0.15f; box->Depth = 0.3f; + CommitEntity(shape); CommitEntity(brick); } } diff --git a/src/GameWorld.h b/src/GameWorld.h index 673358c..cda5836 100755 --- a/src/GameWorld.h +++ b/src/GameWorld.h @@ -31,6 +31,7 @@ #include "Components/BoxShape.h" #include "Components/Vehicle.h" #include "Components/Wheel.h" +#include "Components/HingeConstraint.h" class GameWorld : public World { diff --git a/src/Physics/VehicleSetup.cpp b/src/Physics/VehicleSetup.cpp index 2995fd1..a309824 100644 --- a/src/Physics/VehicleSetup.cpp +++ b/src/Physics/VehicleSetup.cpp @@ -48,7 +48,6 @@ void VehicleSetup::buildVehicle(World *world, const hkpWorld* physicsWorld, hkpV setupWheelCollide(physicsWorld, vehicle, *static_cast(vehicle.m_wheelCollide)); - // // Check that all components are present. // @@ -212,6 +211,9 @@ void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultT transmission.m_wheelsTorqueRatio[2] = 0.3f; transmission.m_wheelsTorqueRatio[3] = 0.3f; + //transmission.m_wheelsTorqueRatio[4] = 0.1f; + //transmission.m_wheelsTorqueRatio[5] = 0.1f; + // HACK: fix support for more than 4 wheels, m_wheelsTorqueRatio must equal 1 for all wheels transmission.m_primaryTransmissionRatio = hkpVehicleDefaultTransmission::calculatePrimaryTransmissionRatio( vehicleComponent.TopSpeed, diff --git a/src/Systems/PhysicsSystem.cpp b/src/Systems/PhysicsSystem.cpp index d59e09d..fb54b87 100644 --- a/src/Systems/PhysicsSystem.cpp +++ b/src/Systems/PhysicsSystem.cpp @@ -67,15 +67,12 @@ Systems::PhysicsSystem::PhysicsSystem(World* world) : System(world) worldInfo.setupSolverInfo(hkpWorldCinfo::SOLVER_TYPE_4ITERS_MEDIUM); worldInfo.m_gravity = hkVector4(0.0f, -9.82f, 0.0f); - worldInfo.m_broadPhaseBorderBehaviour = hkpWorldCinfo::BROADPHASE_BORDER_REMOVE_ENTITY; // just fix the entity if the object falls off too far + worldInfo.m_broadPhaseBorderBehaviour = hkpWorldCinfo::BROADPHASE_BORDER_FIX_ENTITY; // just fix the entity if the object falls off too far // You must specify the size of the broad phase - objects should not be simulated outside this region worldInfo.setBroadPhaseWorldSize(1000.0f); m_PhysicsWorld = new hkpWorld(worldInfo); - - - // When the simulation type is SIMULATION_TYPE_MULTITHREADED, in the debug build, the sdk performs checks // to make sure only one thread is modifying the world at once to prevent multithreaded bugs. Each thread // must call markForRead / markForWrite before it modifies the world to enable these checks. @@ -113,6 +110,7 @@ void Systems::PhysicsSystem::RegisterComponents(ComponentFactory* cf) cf->Register("Vehicle", []() { return new Components::Vehicle(); }); cf->Register("Wheel", []() { return new Components::Wheel(); }); cf->Register("MeshShape", []() { return new Components::MeshShape(); }); + cf->Register("HingeConstraint", []() { return new Components::HingeConstraint(); }); } void Systems::PhysicsSystem::Update(double dt) @@ -131,20 +129,19 @@ void Systems::PhysicsSystem::Update(double dt) if(m_RigidBodies[entity]->isActive()) { - hkVector4 position; hkQuaternion rotation; if (parent) { auto absoluteTransform = m_World->GetSystem("TransformSystem")->AbsoluteTransform(entity); - position = hkVector4(absoluteTransform.Position.x, absoluteTransform.Position.y, absoluteTransform.Position.z); - rotation = hkQuaternion(absoluteTransform.Orientation.x, absoluteTransform.Orientation.y, absoluteTransform.Orientation.z, absoluteTransform.Orientation.w); + position = ConvertPosition(absoluteTransform.Position); + rotation = ConvertRotation(absoluteTransform.Orientation); } else { - position = hkVector4(transformComponent->Position.x, transformComponent->Position.y, transformComponent->Position.z); - rotation = hkQuaternion(transformComponent->Orientation.x, transformComponent->Orientation.y, transformComponent->Orientation.z, transformComponent->Orientation.w); + position = ConvertPosition(transformComponent->Position); + rotation = ConvertRotation(transformComponent->Orientation); } m_PhysicsWorld->markForWrite(); m_RigidBodies[entity]->setPositionAndRotation(position, rotation); @@ -154,14 +151,13 @@ void Systems::PhysicsSystem::Update(double dt) } - - - static const double timestep = 1 / 60.0; m_Accumulator += dt; while (m_Accumulator >= timestep) { m_PhysicsWorld->stepMultithreaded(m_JobQueue, m_ThreadPool, timestep); + //m_PhysicsWorld->stepDeltaTime(timestep); + m_Accumulator -= timestep; m_Context->syncTimers(m_ThreadPool); @@ -200,7 +196,7 @@ void Systems::PhysicsSystem::UpdateEntity(double dt, EntityID entity, EntityID p hkQuaternion steeringOrientation = m_Vehicles[car]->m_wheelsInfo[wheelComponent->ID].m_steeringOrientationChassisSpace; hkReal spinAngle = -m_Vehicles[car]->m_wheelsInfo[wheelComponent->ID].m_spinAngle; - glm::quat orientation = glm::quat(steeringOrientation(3), steeringOrientation(0), steeringOrientation(1), steeringOrientation(2)) * glm::angleAxis(spinAngle, glm::vec3(1, 0, 0)); + glm::quat orientation = ConvertRotation(steeringOrientation) * glm::angleAxis(spinAngle, glm::vec3(1, 0, 0)); transformComponent->Orientation = orientation * wheelComponent->OriginalOrientation; m_PhysicsWorld->unmarkForWrite(); } @@ -208,23 +204,18 @@ void Systems::PhysicsSystem::UpdateEntity(double dt, EntityID entity, EntityID p else if(m_RigidBodies.find(entity) != m_RigidBodies.end()) { auto transformComponentParent = m_World->GetComponent(parent, "Transform"); - //m_PhysicsWorld->markForWrite(); - hkVector4 position = m_RigidBodies[entity]->getPosition(); - transformComponent->Position = glm::vec3(position(0), position(1), position(2)); + + transformComponent->Position = ConvertPosition(m_RigidBodies[entity]->getPosition()); + transformComponent->Orientation = ConvertRotation(m_RigidBodies[entity]->getRotation()); + // TODO: No support for Scale, MIGHT be possible + if (transformComponentParent) { transformComponent->Position -= transformComponentParent->Position; transformComponent->Position = transformComponent->Position * transformComponentParent->Orientation; - } - hkQuaternion orientation = m_RigidBodies[entity]->getRotation(); - transformComponent->Orientation = glm::quat(orientation(3),orientation(0), orientation(1), orientation(2)); - if (transformComponentParent) - { transformComponent->Orientation = transformComponent->Orientation * glm::inverse(transformComponentParent->Orientation); } - //m_PhysicsWorld->unmarkForWrite(); } - // HACK: Vehicle test-controls auto vehicleComponent = m_World->GetComponent(entity, "Vehicle"); @@ -276,7 +267,6 @@ void Systems::PhysicsSystem::UpdateEntity(double dt, EntityID entity, EntityID p else if(deviceStatus->m_positionX < -1) deviceStatus->m_positionX = -1; - deviceStatus->m_handbrakeButtonPressed = inputComponent->KeyState[GLFW_KEY_RIGHT_CONTROL]; if(inputComponent->KeyState[GLFW_KEY_R] && !inputComponent->LastKeyState[GLFW_KEY_R]) @@ -297,7 +287,6 @@ void Systems::PhysicsSystem::OnEntityCommit( EntityID entity ) if (!transformComponent) return; - auto wheelComponent = m_World->GetComponent(entity, "Wheel"); if (wheelComponent) { @@ -306,178 +295,216 @@ void Systems::PhysicsSystem::OnEntityCommit( EntityID entity ) m_Wheels.push_back(entity); } - auto physicsComponent = m_World->GetComponent(entity, "Physics"); - if (!physicsComponent) - return; + EntityID entityParent = m_World->GetEntityBaseParent(entity); auto sphereComponent = m_World->GetComponent(entity, "SphereShape"); auto boxComponent = m_World->GetComponent(entity, "BoxShape"); auto meshShapeComponent = m_World->GetComponent(entity, "MeshShape"); - - hkpShape* shape = nullptr; - hkpRigidBodyCinfo rigidBodyInfo; - hkMassProperties massProperties; - - if (sphereComponent) - { - shape = new hkpSphereShape(sphereComponent->Radius); - rigidBodyInfo.m_shape = shape; - - if (physicsComponent->Static) - { - rigidBodyInfo.m_motionType = hkpMotion::MOTION_FIXED; - } - else - { - rigidBodyInfo.m_motionType = hkpMotion::MOTION_SPHERE_INERTIA; - } - - hkpInertiaTensorComputer::computeSphereVolumeMassProperties(sphereComponent->Radius, physicsComponent->Mass, massProperties); - - } - else if (boxComponent) - { - hkReal thickness = 0.05; - shape = new hkpBoxShape(hkVector4(boxComponent->Width - thickness, boxComponent->Height - thickness, boxComponent->Depth - thickness)); - rigidBodyInfo.m_shape = shape; - if (physicsComponent->Static) - { - rigidBodyInfo.m_motionType = hkpMotion::MOTION_FIXED; - } - else - { - rigidBodyInfo.m_motionType = hkpMotion::MOTION_BOX_INERTIA; - } - hkpInertiaTensorComputer::computeBoxSurfaceMassProperties(hkVector4(boxComponent->Width - thickness, boxComponent->Height - thickness, boxComponent->Depth - thickness), physicsComponent->Mass, thickness, massProperties); - - } - else if(meshShapeComponent) - { - std::vector* vertices = new std::vector; - std::vector* vertexIndices = new std::vector; - auto meshShape = m_World->GetResourceManager()->Load("OBJ", meshShapeComponent->ResourceName); - - for (auto &vertex : meshShape->Vertices) - { - hkReal x, y, z; - std::tie(x, y, z) = vertex; - vertices->push_back(x); - vertices->push_back(y); - vertices->push_back(z); - } - - int i = 0; - for (auto &face : meshShape->Faces) - { - for (auto &faceDef : face.Definitions) - { - vertexIndices->push_back(faceDef.VertexIndex - 1); - } - } - - hkpExtendedMeshShape* mesh = new hkpExtendedMeshShape(); - mesh->setRadius( 0.05f); - { - hkpExtendedMeshShape::TrianglesSubpart part; - part.m_numTriangleShapes = meshShape->Faces.size(); - part.m_indexBase = vertexIndices->data(); - part.m_indexStriding = sizeof(hkUint16) * 3; - - part.m_numVertices = vertices->size() / 3; - part.m_vertexBase = vertices->data(); - part.m_vertexStriding = sizeof(hkReal) * 3; - - part.m_stridingType = hkpExtendedMeshShape::INDICES_INT16; - - mesh->addTrianglesSubpart(part); - } - - if (physicsComponent->Static) - { - rigidBodyInfo.m_motionType = hkpMotion::MOTION_FIXED; - } - else - { - rigidBodyInfo.m_motionType = hkpMotion::MOTION_BOX_INERTIA; - } - hkpInertiaTensorComputer::computeShapeVolumeMassProperties(mesh, physicsComponent->Mass, massProperties); - rigidBodyInfo.m_shape = mesh; - m_ExtendedMeshShapes[entity].ExtendedMeshShape = mesh; - m_ExtendedMeshShapes[entity].VertexIndices = vertexIndices; - m_ExtendedMeshShapes[entity].Vertices = vertices; - - hkpMoppCompilerInput mci; - hkpMoppCode* code = hkpMoppUtility::buildCode( mesh, mci ); - hkpMoppBvTreeShape* moppShape = new hkpMoppBvTreeShape(mesh, code); - - m_ExtendedMeshShapes[entity].Code = code; - m_ExtendedMeshShapes[entity].MoppShape = moppShape; - shape = moppShape; - - shape = mesh; - } - else + if(entityParent == entity && (sphereComponent || boxComponent || meshShapeComponent)) { + LOG_ERROR("Entity: %i , Only the children can have a shapeComponent", entity); return; } - auto absoluteTransform = m_World->GetSystem("TransformSystem")->AbsoluteTransform(entity); - rigidBodyInfo.m_position.set(absoluteTransform.Position.x, absoluteTransform.Position.y, absoluteTransform.Position.z); - rigidBodyInfo.m_rotation.set(absoluteTransform.Orientation.x, absoluteTransform.Orientation.y, absoluteTransform.Orientation.z, absoluteTransform.Orientation.w); - rigidBodyInfo.m_inertiaTensor = massProperties.m_inertiaTensor; - //rigidBodyInfo.m_centerOfMass = massProperties.m_centerOfMass; - rigidBodyInfo.m_mass = massProperties.m_mass; - - - // Create RigidBody - hkpRigidBody* rigidBody = new hkpRigidBody(rigidBodyInfo); - - - auto vehicleComponent = m_World->GetComponent(entity, "Vehicle"); - if (vehicleComponent && m_Vehicles.find(entity) == m_Vehicles.end()) + auto physicsComponent = m_World->GetComponent(entity, "Physics"); + if (physicsComponent) { - for (int i = 0; i < m_Wheels.size(); i++) - { - if(m_World->GetEntityParent(m_Wheels[i]) != entity) - { - m_Wheels.erase(m_Wheels.begin() + i); - i--; - } - } + if(entityParent != entity) + { + LOG_ERROR("Entity: %i , Only the baseparent can have a PhysicsComponent", entity); + return; + } - VehicleSetup vehicleSetup; - // Create the basic vehicle. - m_Vehicles[entity] = new hkpVehicleInstance(rigidBody); - m_PhysicsWorld->markForWrite(); - vehicleSetup.buildVehicle(m_World, m_PhysicsWorld, *m_Vehicles[entity], entity, m_Wheels); - // Add the vehicle's entities and phantoms to the world - m_Vehicles[entity]->addToWorld(m_PhysicsWorld); + if(! physicsComponent->Static) // Not static + { + hkArray shapeArray; + for (auto &shapeData : m_Shapes[entity]) + { + shapeArray.pushBack(shapeData.Shape); + } - m_RigidBodies[entity] = rigidBody; - // The vehicle is an action - m_PhysicsWorld->addAction(m_Vehicles[entity]); - m_PhysicsWorld->unmarkForWrite(); + // Create a hkpListShape* of all the childEntities collected in m_ShapeArrays + hkpListShape* listShape = new hkpListShape(shapeArray.begin(), shapeArray.getSize(), hkpShapeContainer::REFERENCE_POLICY_INCREMENT); + // Save the listShape for further use + m_ListShapes[entity] = listShape; + + + ////////////////////////////////// + //******************************// + // Add a hkpBvShape // + //******************************// + ////////////////////////////////// + + // Clean up for less memory usage + m_Shapes.erase(entity); + + hkMassProperties massProperties; + hkpInertiaTensorComputer::computeShapeVolumeMassProperties(listShape, physicsComponent->Mass, massProperties); + + hkpRigidBodyCinfo rigidBodyInfo; + { + rigidBodyInfo.m_shape = listShape; + rigidBodyInfo.m_motionType = hkpMotion::MOTION_DYNAMIC; + auto absoluteTransform = m_World->GetSystem("TransformSystem")->AbsoluteTransform(entity); + hkVector4 position = ConvertPosition(absoluteTransform.Position); + hkQuaternion rotation = ConvertRotation(absoluteTransform.Orientation); + rigidBodyInfo.m_position.set(position(0), position(1), position(2), position(3)); + rigidBodyInfo.m_rotation.set(rotation(0), rotation(1), rotation(2), rotation(3)); + + rigidBodyInfo.m_inertiaTensor = massProperties.m_inertiaTensor; + //rigidBodyInfo.m_centerOfMass = massProperties.m_centerOfMass; //HACK: CENTER OF MASS ALWAYS IN THE CENTER + rigidBodyInfo.m_mass = massProperties.m_mass; + } + // Create RigidBody + hkpRigidBody* rigidBody = new hkpRigidBody(rigidBodyInfo); + + m_PhysicsWorld->markForWrite(); + m_PhysicsWorld->addEntity(rigidBody); + m_RigidBodies[entity] = rigidBody; + m_PhysicsWorld->unmarkForWrite(); + + listShape->removeReference(); + rigidBody->removeReference(); + } + else // Static + { + // Create the hkpStaticCompoundShape and add the instances. + // "meshShape" should not be modified by the user in any way after adding it as an instance. + hkpStaticCompoundShape* staticCompoundShape = new hkpStaticCompoundShape(); + + for (auto &shapeData : m_Shapes[entity]) + { + + auto childTransformComponent = m_World->GetComponent(shapeData.Entity, "Transform"); + + hkVector4 position = ConvertPosition(childTransformComponent->Position); + hkQuaternion rotation = ConvertRotation(childTransformComponent->Orientation); + hkVector4 scale = ConvertScale(childTransformComponent->Scale); + hkQsTransform transform(position, rotation, scale); + + staticCompoundShape->addInstance(shapeData.Shape, transform); + } + + // This must be called after adding the instances and before using the shape. + staticCompoundShape->bake(); + + m_Shapes.erase(entity); + hkMassProperties massProperties; + hkpInertiaTensorComputer::computeShapeVolumeMassProperties(staticCompoundShape, physicsComponent->Mass, massProperties); + + hkpRigidBodyCinfo rigidBodyInfo; + { + rigidBodyInfo.m_shape = staticCompoundShape; + rigidBodyInfo.m_motionType = hkpMotion::MOTION_FIXED; + auto absoluteTransform = m_World->GetSystem("TransformSystem")->AbsoluteTransform(entity); + hkVector4 position = ConvertPosition(absoluteTransform.Position); + hkQuaternion rotation = ConvertRotation(absoluteTransform.Orientation); + rigidBodyInfo.m_position.set(position(0), position(1), position(2), position(3)); + rigidBodyInfo.m_rotation.set(rotation(0), rotation(1), rotation(2), rotation(3)); + + rigidBodyInfo.m_inertiaTensor = massProperties.m_inertiaTensor; + //rigidBodyInfo.m_centerOfMass = massProperties.m_centerOfMass; //HACK: CENTER OF MASS ALWAYS IN THE CENTER + rigidBodyInfo.m_mass = massProperties.m_mass; + } + // Create RigidBody + hkpRigidBody* rigidBody = new hkpRigidBody(rigidBodyInfo); + + m_PhysicsWorld->markForWrite(); + m_PhysicsWorld->addEntity(rigidBody); + m_RigidBodies[entity] = rigidBody; + m_PhysicsWorld->unmarkForWrite(); + + staticCompoundShape->removeReference(); + rigidBody->removeReference(); + } - //m_Vehicles[entity]->m_rpm = 0.0f; // Not sure why this one should be here - m_Wheels.clear(); - shape->removeReference(); - rigidBody->removeReference(); } else { - m_PhysicsWorld->markForWrite(); - m_PhysicsWorld->addEntity(rigidBody); - m_RigidBodies[entity] = rigidBody; - m_PhysicsWorld->unmarkForWrite(); + + //TODO: COMMENT THIS SECTION + if(sphereComponent) + { + hkpSphereShape* sphereShape = new hkpSphereShape(sphereComponent->Radius); + + hkQsTransform transform( ConvertPosition(transformComponent->Position), ConvertRotation(transformComponent->Orientation), ConvertScale(transformComponent->Scale)); + hkpConvexTransformShape* transformedSphereShape = new hkpConvexTransformShape( sphereShape, transform ); + + m_Shapes[entityParent].push_back(ShapeArrayData(entity, transformedSphereShape)); - shape->removeReference(); - rigidBody->removeReference(); + sphereShape->removeReference(); + } + //TODO: COMMENT THIS SECTION + else if(boxComponent) + { + hkReal thickness = 0.05; + hkpBoxShape* boxShape = new hkpBoxShape(hkVector4(boxComponent->Width, boxComponent->Height, boxComponent->Depth), thickness); + + hkpShapeShrinker* shapeShrinker = new hkpShapeShrinker(); + boxShape = shapeShrinker->shrinkBoxShape(boxShape, thickness, 0); // HACK: Unsure about the 3rd argument + delete shapeShrinker; + + hkQsTransform transform( ConvertPosition(transformComponent->Position), ConvertRotation(transformComponent->Orientation), ConvertScale(transformComponent->Scale)); + hkpConvexTransformShape* transformedBoxShape = new hkpConvexTransformShape( boxShape, transform ); + m_Shapes[entityParent].push_back(ShapeArrayData(entity, transformedBoxShape)); + boxShape->removeReference(); + } + else if(meshShapeComponent) + { + std::vector* vertices = new std::vector; + std::vector* vertexIndices = new std::vector; + auto meshShape = m_World->GetResourceManager()->Load("OBJ", meshShapeComponent->ResourceName); + for (auto &vertex : meshShape->Vertices) + { + hkReal x, y, z; + std::tie(x, y, z) = vertex; + vertices->push_back(x); + vertices->push_back(y); + vertices->push_back(z); + } + int i = 0; + for (auto &face : meshShape->Faces) + { + for (auto &faceDef : face.Definitions) + { + vertexIndices->push_back(faceDef.VertexIndex - 1); + } + } + + hkpExtendedMeshShape* mesh = new hkpExtendedMeshShape(); + hkReal thickness = 0.00f; // HACK: Convex radius should be 0 for static shapes and 0.05 for dynamic shapes. + mesh->setRadius(thickness); + { + hkpExtendedMeshShape::TrianglesSubpart part; + part.m_numTriangleShapes = meshShape->Faces.size(); + part.m_indexBase = vertexIndices->data(); + part.m_indexStriding = sizeof(hkUint16) * 3; + + part.m_numVertices = vertices->size() / 3; + part.m_vertexBase = vertices->data(); + part.m_vertexStriding = sizeof(hkReal) * 3; + + part.m_stridingType = hkpExtendedMeshShape::INDICES_INT16; + + mesh->addTrianglesSubpart(part); + } + hkpMoppCompilerInput mci; + hkpMoppCode* code = hkpMoppUtility::buildCode( mesh, mci ); + hkpMoppBvTreeShape* moppShape = new hkpMoppBvTreeShape(mesh, code); + + m_ExtendedMeshShapes[entity].Code = code; + m_ExtendedMeshShapes[entity].MoppShape = moppShape; + m_Shapes[entityParent].push_back(ShapeArrayData(entity, moppShape)); //HACK: Should maybe have transform, not sure yet + } } + + + } void Systems::PhysicsSystem::TearDownPhysicsState(EntityID entity, EntityID parent) @@ -527,3 +554,34 @@ void HK_CALL Systems::PhysicsSystem::HavokErrorReport(const char* msg, void*) LOG_INFO("%s", msg); } + +glm::vec3 Systems::PhysicsSystem::ConvertPosition(const hkVector4 &hkPosition) +{ + return glm::vec3(hkPosition(0), hkPosition(1), hkPosition(2)); +} + +const hkVector4& Systems::PhysicsSystem::ConvertPosition(glm::vec3 glmPosition) +{ + return hkVector4( glmPosition.x, glmPosition.y, glmPosition.z ); +} + +glm::quat Systems::PhysicsSystem::ConvertRotation(const hkQuaternion &hkRotation) +{ + return glm::quat(hkRotation(3), hkRotation(0), hkRotation(1), hkRotation(2)); +} + +const hkQuaternion& Systems::PhysicsSystem::ConvertRotation(glm::quat glmRotation) +{ + return hkQuaternion(glmRotation.x, glmRotation.y, glmRotation.z, glmRotation.w ); +} + +glm::vec3 Systems::PhysicsSystem::ConvertScale(const hkVector4 &hkScale) +{ + return glm::vec3(hkScale(0), hkScale(1), hkScale(2)); +} + +const hkVector4& Systems::PhysicsSystem::ConvertScale(glm::vec3 glmScale) +{ + return hkVector4(glmScale.x, glmScale.y, glmScale.z); +} + diff --git a/src/Systems/PhysicsSystem.h b/src/Systems/PhysicsSystem.h index 6981f3a..c74a5ec 100644 --- a/src/Systems/PhysicsSystem.h +++ b/src/Systems/PhysicsSystem.h @@ -10,6 +10,7 @@ #include "Components/Vehicle.h" #include "Components/Input.h" #include "Components/MeshShape.h" +#include "Components/HingeConstraint.h" #include "OBJ.h" // Math and base include @@ -44,6 +45,13 @@ #include #include #include +#include +#include + +#include +#include +#include +#include #include "Physics/VehicleSetup.h" @@ -75,6 +83,16 @@ private: void StepVisualDebugger(); static void HK_CALL HavokErrorReport(const char* msg, void*); void SetupPhysics(hkpWorld* physicsWorld); + + // Converterfunctions + glm::vec3 ConvertPosition(const hkVector4 &hkPosition); + const hkVector4& ConvertPosition(glm::vec3 glmPosition); + + glm::quat ConvertRotation(const hkQuaternion &hkRotation); + const hkQuaternion& ConvertRotation(glm::quat glmRotation); + + glm::vec3 ConvertScale(const hkVector4 &hkScale); + const hkVector4&ConvertScale(glm::vec3 glmScale); std::unordered_map m_RigidBodies; @@ -88,7 +106,21 @@ private: hkpVehicleInstance* Systems::PhysicsSystem::createVehicle(VehicleSetup& vehicleSetup, hkpRigidBody* chassis); - + + struct ShapeArrayData + { + ShapeArrayData(EntityID entity, hkpShape* shape) + { + Entity = entity; + Shape = shape; + } + EntityID Entity; + hkpShape* Shape; + }; + std::unordered_map> m_Shapes; + std::unordered_map m_ListShapes; + + struct ExtendedShapeData { diff --git a/vs11/Returngeance/Returngeance.vcxproj b/vs11/Returngeance/Returngeance.vcxproj index b78075c..6e66309 100755 --- a/vs11/Returngeance/Returngeance.vcxproj +++ b/vs11/Returngeance/Returngeance.vcxproj @@ -124,7 +124,9 @@ + + diff --git a/vs11/Returngeance/Returngeance.vcxproj.filters b/vs11/Returngeance/Returngeance.vcxproj.filters index 4e41278..cf6f009 100755 --- a/vs11/Returngeance/Returngeance.vcxproj.filters +++ b/vs11/Returngeance/Returngeance.vcxproj.filters @@ -236,6 +236,12 @@ Util + + Physics\Components + + + Physics\Components + From 62ca923821ef0ee7fab83feaea9ccd55b8464cff Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Wed, 7 May 2014 22:34:38 +0200 Subject: [PATCH 45/65] Defucked defucked rendering --- src/GameWorld.cpp | 6 +- src/Renderer.cpp | 130 +++++++++++++----- src/Renderer.h | 9 +- src/Shaders/FinalPass.frag.glsl | 22 +++ src/Shaders/FinalPass.vert.glsl | 16 +++ src/Shaders/Fragment.glsl | 2 +- src/Shaders/Fragment2-Debug.glsl | 2 +- src/Shaders/Fragment2.glsl | 106 +++++++------- src/Shaders/Vertex.glsl | 8 +- src/Shaders/Vertex2.glsl | 8 +- vs11/Returngeance.sln | 3 - vs11/Returngeance/Returngeance.vcxproj | 2 + .../Returngeance/Returngeance.vcxproj.filters | 6 + 13 files changed, 207 insertions(+), 113 deletions(-) create mode 100644 src/Shaders/FinalPass.frag.glsl create mode 100644 src/Shaders/FinalPass.vert.glsl diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index bb01e03..6e78089 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -230,8 +230,8 @@ void GameWorld::Initialize() auto transform = AddComponent(Light, "Transform"); transform->Position = glm::vec3(20+ 10*cos(i), 3, 0 + 10*sin(i)); auto light = AddComponent(Light, "PointLight"); - light->Diffuse = glm::vec3(94.f/255.f, 227.f/255.f, 230.f/255.f); - light->Specular = glm::vec3(94.f/255.f, 227.f/255.f, 230.f/255.f); + light->Diffuse = glm::vec3(0.5f, 0.5f, 1.0f); + light->Specular = glm::vec3(1.0f, 1.0f, 1.0f); light->specularExponent = 1.0f; auto model = AddComponent(Light, "Model"); model->ModelFile = "Models/Placeholders/PhysicsTest/PointLight.obj"; @@ -243,7 +243,7 @@ void GameWorld::Initialize() auto cube = CreateEntity(); auto transform = AddComponent(cube, "Transform"); transform->Position = glm::vec3(20, 10 + i*2, 0); - transform->Scale = glm::vec3(1); + //transform->Scale = glm::vec3(1); transform->Orientation = glm::quat(glm::vec3(0.0f, 0.0f, 0.0f)); auto model = AddComponent(cube, "Model"); model->ModelFile = "Models/Placeholders/PhysicsTest/Cube2.obj"; diff --git a/src/Renderer.cpp b/src/Renderer.cpp index bf6241b..27820a9 100755 --- a/src/Renderer.cpp +++ b/src/Renderer.cpp @@ -128,6 +128,11 @@ void Renderer::LoadContent() m_SecondPassProgram_Debug.Compile(); m_SecondPassProgram_Debug.Link(); + m_FinalPassProgram.AddShader(std::shared_ptr(new VertexShader("Shaders/FinalPass.vert.glsl"))); + m_FinalPassProgram.AddShader(std::shared_ptr(new FragmentShader("Shaders/FinalPass.frag.glsl"))); + m_FinalPassProgram.Compile(); + m_FinalPassProgram.Link(); + m_ScreenQuad = CreateQuad(); FrameBufferTextures(); @@ -532,10 +537,10 @@ void Renderer::ClearStuff() void Renderer::FrameBufferTextures() { - m_fb = 0; + m_fbBasePass = 0; m_fDepthBuffer = 0; - glGenFramebuffers(1, &m_fb); + glGenFramebuffers(1, &m_fbBasePass); glGenRenderbuffers(1, &m_fDepthBuffer); glBindRenderbuffer(GL_RENDERBUFFER, m_fDepthBuffer); @@ -562,14 +567,14 @@ void Renderer::FrameBufferTextures() //Generate and bind normal texture glGenTextures(1, &m_fNormalsTexture); glBindTexture(GL_TEXTURE_2D, m_fNormalsTexture); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, WIDTH, HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB10_A2, WIDTH, HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); //Bind fb - glBindFramebuffer(GL_FRAMEBUFFER, m_fb); + glBindFramebuffer(GL_FRAMEBUFFER, m_fbBasePass); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_fDepthBuffer); //Attach textures to the FB @@ -583,6 +588,29 @@ void Renderer::FrameBufferTextures() LOG_ERROR("DeferredLighting:Init: FrameBuffer incomplete: 0x%x\n", fbStatus); //exit(1); } + + m_fbLightingPass = 0; + glGenFramebuffers(1, &m_fbLightingPass); + + glGenTextures(1, &m_fLightingTexture); + glBindTexture(GL_TEXTURE_2D, m_fLightingTexture); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, WIDTH, HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + + glBindFramebuffer(GL_FRAMEBUFFER, m_fbLightingPass); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_fLightingTexture, 0); + + fbStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER); + if(fbStatus != GL_FRAMEBUFFER_COMPLETE) + { + LOG_ERROR("DeferredLighting:Init: FrameBuffer incomplete: 0x%x\n", fbStatus); + //exit(1); + } + + } //void Renderer::FrameBufferTextures() @@ -654,12 +682,15 @@ void Renderer::FrameBufferTextures() void Renderer::DrawFBO() { - glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fb); + /* + Base pass + */ + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbBasePass); // Clear G-buffer GLenum windowBuffClear[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2 }; glDrawBuffers(3, windowBuffClear); - glClearColor(0.2f, 0.2f, 0.2f, 0.0f); + glClearColor(0.f, 0.f, 0.f, 0.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Execute the first render stage which will fill out the internal buffers with data(??) @@ -667,35 +698,54 @@ void Renderer::DrawFBO() GLenum windowBuffOpaque[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2 }; glDrawBuffers(3, windowBuffOpaque); + glCullFace(GL_BACK); DrawFBOScene(); - // Draw to screen - glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); - if(!m_QuadView) - { - m_SecondPassProgram.Bind(); - } - else - { - m_SecondPassProgram_Debug.Bind(); - } - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + /* + Lighting pass + */ + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbLightingPass); + GLenum lightingPassAttachments[] = { GL_COLOR_ATTACHMENT0 }; + glDrawBuffers(1, lightingPassAttachments); - + glClearColor(0.f, 0.f, 0.f, 0.f); + glClear(GL_COLOR_BUFFER_BIT); + + m_SecondPassProgram.Bind(); glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_2D, m_fDiffuseTexture); - - glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, m_fPositionTexture); - - glActiveTexture(GL_TEXTURE2); + glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, m_fNormalsTexture); + glCullFace(GL_FRONT); DrawLightScene(); + /* + Final pass + */ + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + + //if(!m_QuadView) + //{ + m_FinalPassProgram.Bind(); + //} + //else + //{ + // m_SecondPassProgram_Debug.Bind(); + //} + + // Ambient light + glUniform3fv(glGetUniformLocation(m_FinalPassProgram.GetHandle(), "La"), 1, glm::value_ptr(glm::vec3(0.3f, 0.3f, 0.3f))); + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, m_fDiffuseTexture); + glActiveTexture(GL_TEXTURE1); + glBindTexture(GL_TEXTURE_2D, m_fLightingTexture); + + glCullFace(GL_BACK); glBindVertexArray(m_ScreenQuad); glEnableVertexAttribArray(0); - glEnableVertexAttribArray(2); glDrawArrays(GL_TRIANGLES, 0, 6); } @@ -774,7 +824,9 @@ void Renderer::DrawFBOScene() MVP = cameraMatrix * modelMatrix; glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "MVP"), 1, GL_FALSE, glm::value_ptr(MVP)); - glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "ModelMatrix"), 1, GL_FALSE, glm::value_ptr(modelMatrix)); + glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "M"), 1, GL_FALSE, glm::value_ptr(modelMatrix)); + glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "V"), 1, GL_FALSE, glm::value_ptr(m_Camera->ViewMatrix())); + glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "P"), 1, GL_FALSE, glm::value_ptr(m_Camera->ProjectionMatrix())); glBindVertexArray(model->VAO); for (auto texGroup : model->TextureGroups) { @@ -792,7 +844,7 @@ void Renderer::DrawLightScene() glEnable(GL_BLEND); glBlendEquation (GL_FUNC_ADD); glBlendFunc(GL_ONE,GL_ONE); - + glDisable (GL_DEPTH_TEST); glDepthMask (GL_FALSE); glBindVertexArray(m_sphereModel->VAO); @@ -802,15 +854,18 @@ void Renderer::DrawLightScene() for(int i = 0; i < Lights; i++) { - glm::mat4 MVP = m_Camera->ProjectionMatrix() * m_Camera->ViewMatrix() * lM[i]; + MVP = cameraMatrix * lM[i]; - glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "MVP"), 1, GL_FALSE, glm::value_ptr(MVP)); - glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "V"), 1, GL_FALSE, glm::value_ptr(m_Camera->ViewMatrix())); - glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "P"), 1, GL_FALSE, glm::value_ptr(m_Camera->ProjectionMatrix())); + glUniform2fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "ViewportSize"), 1,glm::value_ptr(glm::vec2(WIDTH, HEIGHT))); + glUniformMatrix4fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "MVP"), 1, GL_FALSE, glm::value_ptr(MVP)); + glUniformMatrix4fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "V"), 1, GL_FALSE, glm::value_ptr(m_Camera->ViewMatrix())); + glUniformMatrix4fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "P"), 1, GL_FALSE, glm::value_ptr(m_Camera->ProjectionMatrix())); glUniformMatrix4fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "M"), 1, GL_FALSE, glm::value_ptr(lM[i])); - glUniform3f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "ls"), Light_specular[i].x, Light_specular[i].y, Light_specular[i].z); - glUniform3f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "ld"), Light_diffuse[i].x, Light_diffuse[i].y, Light_diffuse[i].z); - glUniform3f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "lp"), Light_position[i].x, Light_position[i].y, Light_position[i].z); + glUniform3fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "la"), 1, glm::value_ptr(glm::vec3(0.3f, 0.3f, 0.3f))); + glUniform3fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "ls"), 1, glm::value_ptr(Light_specular[i])); + glUniform3fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "ld"), 1, glm::value_ptr(Light_diffuse[i])); + glUniform3fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "lp"), 1, glm::value_ptr(Light_position[i])); + glUniform1f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "LightRadius"), 5.0f); glUniform3f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "CameraPosition"), m_Camera->Position().x, m_Camera->Position().y, m_Camera->Position().z); //glUniform1f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "speculatExponent"), Light_specularExponent[i]); glDrawArrays(GL_TRIANGLES, 0, m_sphereModel->Vertices.size()); @@ -829,10 +884,11 @@ void Renderer::CreateLightMatrix() { for(int i = 0; i < Lights; i++) { - const float radius = 5.0f; - lM[i] = glm::scale(glm::mat4(1.0), glm::vec3(radius, radius, radius)); - lM[i] = glm::translate(lM[i], Light_position[i]); - lM[i] = m_Camera->ProjectionMatrix() * m_Camera->ViewMatrix() * lM[i]; + const float scale = 10.0f; + glm::mat4 model; + model *= glm::translate(Light_position[i]); + model *= glm::scale(glm::vec3(scale)); + lM[i] = model; } } diff --git a/src/Renderer.h b/src/Renderer.h index 1c73d49..6754701 100755 --- a/src/Renderer.h +++ b/src/Renderer.h @@ -91,11 +91,14 @@ private: GLuint m_ShadowFrameBuffer; GLuint m_ShadowDepthTexture; + GLuint m_fbBasePass; GLuint m_fDiffuseTexture; GLuint m_fPositionTexture; GLuint m_fNormalsTexture; GLuint m_fBlendTexture; - GLuint m_fb; + GLuint m_fbLightingPass; + GLuint m_fLightingTexture; + GLuint m_fDepthBuffer; GLenum draw_bufs[2]; glm::mat4 lM[5]; @@ -110,12 +113,16 @@ private: ShaderProgram m_FirstPassProgram; ShaderProgram m_SecondPassProgram; ShaderProgram m_SecondPassProgram_Debug; + ShaderProgram m_FinalPassProgram; + ShaderProgram m_ShaderProgramNormals; ShaderProgram m_ShaderProgramShadows; ShaderProgram m_ShaderProgramShadowsDrawDepth; ShaderProgram m_ShaderProgramDebugAABB; ShaderProgram m_ShaderProgramSkybox; + + void ClearStuff(); void DrawScene(); void DrawModels(ShaderProgram &shader); diff --git a/src/Shaders/FinalPass.frag.glsl b/src/Shaders/FinalPass.frag.glsl new file mode 100644 index 0000000..8509ea8 --- /dev/null +++ b/src/Shaders/FinalPass.frag.glsl @@ -0,0 +1,22 @@ +#version 430 + +uniform vec3 La; + +layout (binding=0) uniform sampler2D DiffuseTexture; +layout (binding=1) uniform sampler2D LightingTexture; + +in VertexData +{ + vec3 Position; + vec2 TextureCoord; +} Input; + +out vec4 FragmentColor; + +void main() +{ + vec4 DiffuseTexel = texture(DiffuseTexture, Input.TextureCoord); + vec4 LightingTexel = texture(LightingTexture, Input.TextureCoord); + + FragmentColor = DiffuseTexel * vec4(La, 1.0) + LightingTexel; +} \ No newline at end of file diff --git a/src/Shaders/FinalPass.vert.glsl b/src/Shaders/FinalPass.vert.glsl new file mode 100644 index 0000000..05deece --- /dev/null +++ b/src/Shaders/FinalPass.vert.glsl @@ -0,0 +1,16 @@ +#version 430 + +layout(location = 0) in vec3 Position; + +out VertexData +{ + vec3 Position; + vec2 TextureCoord; +} Output; + +void main() +{ + gl_Position = vec4(Position, 1.0); + Output.Position = Position; + Output.TextureCoord = (vec2(Position) + 1) / 2; +} \ No newline at end of file diff --git a/src/Shaders/Fragment.glsl b/src/Shaders/Fragment.glsl index 7aa72d7..64d4a59 100755 --- a/src/Shaders/Fragment.glsl +++ b/src/Shaders/Fragment.glsl @@ -19,7 +19,7 @@ void main() frag_Diffuse = texture2D(DiffuseTexture, Input.TextureCoord); // G-buffer Position - frag_Position = vec4(Input.Position.xy, 0.0, 0.0); + frag_Position = vec4(Input.Position.xyz, 0.0); // G-buffer Normal frag_Normal = vec4(Input.Normal, 0.0); diff --git a/src/Shaders/Fragment2-Debug.glsl b/src/Shaders/Fragment2-Debug.glsl index 0ab00d4..db35d6e 100644 --- a/src/Shaders/Fragment2-Debug.glsl +++ b/src/Shaders/Fragment2-Debug.glsl @@ -30,7 +30,7 @@ void main() //FragColor = texture2D(DiffuseTexture, Input.TextureCoord * 2 + vec2(0, -1)); DrawQuadrant(texture2D(DiffuseTexture, Input.TextureCoord * 2), vec2(-1, 1)); DrawQuadrant(texture2D(PositionTexture, Input.TextureCoord * 2), vec2(1, 1)); - DrawQuadrant((texture2D(NormalTexture, Input.TextureCoord * 2)+1)/2, vec2(-1, -1)); + DrawQuadrant(texture2D(NormalTexture, Input.TextureCoord * 2), vec2(-1, -1)); vec4 AllTexel = texture2D(DiffuseTexture, Input.TextureCoord*2)*texture2D(PositionTexture, Input.TextureCoord*2)*texture2D(NormalTexture, Input.TextureCoord*2); DrawQuadrant(AllTexel, vec2(1, -1)); diff --git a/src/Shaders/Fragment2.glsl b/src/Shaders/Fragment2.glsl index aff7665..a27a268 100644 --- a/src/Shaders/Fragment2.glsl +++ b/src/Shaders/Fragment2.glsl @@ -1,94 +1,80 @@ #version 430 -layout (binding=0) uniform sampler2D DiffuseTexture; -layout (binding=1) uniform sampler2D PositionTexture; -layout (binding=2) uniform sampler2D NormalTexture; +layout (binding=0) uniform sampler2D PositionTexture; +layout (binding=1) uniform sampler2D NormalsTexture; +uniform vec2 ViewportSize; uniform mat4 MVP; uniform mat4 M; uniform mat4 V; uniform mat4 P; +uniform vec3 la; uniform vec3 ls; uniform vec3 ld; -uniform vec3 lp; -const float specularExponent = 20.0; +uniform vec3 lp; +uniform float LightRadius; +const float specularExponent = 50.0; uniform vec3 CameraPosition; -const vec3 kd = vec3(1.0, 1.0, 1.0); -const vec3 ks = vec3(1.0, 1.0, 1.0); +const vec3 ks = vec3(1.0, 0.0, 0.0); +const vec3 kd = vec3(0.8, 0.8, 0.8); +const vec3 ka = vec3(1.0, 1.0, 1.0); const float kshine = 1.0; in VertexData { vec3 Position; - vec3 Normal; vec2 TextureCoord; } Input; out vec4 FragColor; -vec3 phong (vec3 PositionTexel, vec3 NormalTexel) +vec4 phong4(vec3 position, vec3 normal) { - vec3 lightPosition = vec3( M * vec4( lp, 1.0 ) ); - vec3 distToLight = lightPosition - PositionTexel; - vec3 directionToLight = normalize(distToLight); + // Diffuse + vec3 lightPos = vec3(V * vec4(lp, 1.0)); + vec3 distanceToLight = lightPos - position; + vec3 directionToLight = normalize(distanceToLight); + float dotProd = dot(directionToLight, normal); + dotProd = max(dotProd, 0.0); + vec3 Id = kd * ld * dotProd; - //Diffuse light - float dotProdDiffuse = max(dot(directionToLight, NormalTexel), 0.0); - vec3 Id = ld * kd * dotProdDiffuse; //Final diffuse intensity - - //Specular light - vec3 reflection = reflect(-directionToLight, NormalTexel); - vec3 surfaceToCamera = normalize(PositionTexel); - vec3 HalfWay = normalize(surfaceToCamera + directionToLight); - float dotProdSpecular = dot(HalfWay, NormalTexel); - dotProdSpecular = max(dotProdSpecular, 0.0); - float specularFactor = pow(dotProdSpecular, specularExponent); - vec3 Is = ls * ks * specularFactor; //Final specular intensity + // Specular + //vec3 reflection = reflect(-directionToLight, normal); + vec3 surfaceToViewer = normalize(-position); + vec3 halfWay = normalize(surfaceToViewer + directionToLight); + float dotSpecular = max(dot(halfWay, normal), 0.0); + float specularFactor = pow(dotSpecular, specularExponent * 2); + vec3 Is = ks * ls * specularFactor; //Attenuation - float dist2D = distance(lightPosition, PositionTexel); - float attenuationFactor = -log(min(1.0, dist2D / 5.0)); + float dist = distance(lightPos, position); + float attenuation = -log(min(1.0, dist / LightRadius)); + //float attenuation = 1.0 / (1.0 - 0.0001 * pow(dist, 2)); - //vec3 FinalOut = (Id + Is) * attenuationFactor; - vec3 FinalOut = Id + Is; - return FinalOut; -} + //float attenuation = clamp(0.0, 1.0, 1.0 / (0.001 + (0.001 * dist) + (0.001 * dist * dist))); + + //float attenuation = 1.0 / dot(directionToLight, directionToLight); + + //float att_s = 5; + //float attenuation = pow(dist, 2) / pow(5.0, 2); + //attenuation = 1.0 / (1.0 + attenuation * att_s); + //att_s = 1.0 / (1.0 + att_s); + //attenuation = attenuation / (1.0 - att_s); + + float radius = 5.0; + float alpha = dist / radius; + float dampingFactor = 1.0 - pow(alpha, 3); -vec3 phong2 (vec3 PositionTexel, vec3 NormalTexel) -{ - vec3 LightVector = lp - PositionTexel; - vec3 ViewVector = normalize(PositionTexel); - - //diffuse - vec3 Id = max(0.0, dot(LightVector, NormalTexel)) * ld; - - vec3 FinalOut = Id; - return FinalOut; -} - -vec3 phong3 (vec3 PositionTexel, vec3 NormalTexel) -{ - vec3 lightDir = lp - PositionTexel; - lightDir = normalize(lightDir); - - vec3 eyeDir = normalize(CameraPosition-PositionTexel); - vec3 vHalfVector = normalize(lightDir.xyz+eyeDir); - vec3 Id = max(0.0, dot(NormalTexel, lightDir)) * ld; - vec3 Is = pow(max(0.0, dot(NormalTexel, vHalfVector)), 100.0) * ls; - vec3 FinalFrag = Id + Is; - return FinalFrag; + return vec4((Id + Is) * attenuation, 1.0); } void main() { - vec4 DiffuseTexel = texture2D(DiffuseTexture, Input.TextureCoord); - vec4 PositionTexel = texture2D(PositionTexture, Input.TextureCoord); - vec4 NormalTexel = texture2D(NormalTexture, Input.TextureCoord); + vec2 TextureCoord = gl_FragCoord.xy / ViewportSize; + vec4 PositionTexel = texture(PositionTexture, TextureCoord); + vec4 NormalTexel = texture(NormalsTexture, TextureCoord); - vec4 Frag_color; - Frag_color.rgb = phong((MVP * PositionTexel).rgb, normalize(NormalTexel).rgb); - Frag_color.a = 1.0; - FragColor = Frag_color * DiffuseTexel; + FragColor = phong4(vec3(PositionTexel), vec3(NormalTexel)); } \ No newline at end of file diff --git a/src/Shaders/Vertex.glsl b/src/Shaders/Vertex.glsl index aaa0857..ea38b24 100755 --- a/src/Shaders/Vertex.glsl +++ b/src/Shaders/Vertex.glsl @@ -1,7 +1,9 @@ #version 430 uniform mat4 MVP; -uniform mat4 ModelMatrix; +uniform mat4 M; +uniform mat4 V; +uniform mat4 P; layout (location = 0) in vec3 Position; layout (location = 1) in vec3 Normal; @@ -18,7 +20,7 @@ void main() { gl_Position = MVP * vec4(Position, 1.0); - Output.Position = gl_Position.xyz; - Output.Normal = normalize((ModelMatrix * vec4(Normal, 0.0)).xyz); + Output.Position = vec3(V * M * vec4(Position, 1.0)); + Output.Normal = normalize(vec3(inverse(transpose(V * M)) * vec4(Normal, 0.0))); Output.TextureCoord = TextureCoord; } \ No newline at end of file diff --git a/src/Shaders/Vertex2.glsl b/src/Shaders/Vertex2.glsl index f341840..3156821 100644 --- a/src/Shaders/Vertex2.glsl +++ b/src/Shaders/Vertex2.glsl @@ -1,10 +1,10 @@ #version 430 +uniform mat4 MVP; + layout (location = 0) in vec3 Position; layout (location = 2) in vec2 TextureCoord; - - out VertexData { vec3 Position; @@ -13,7 +13,7 @@ out VertexData void main() { - gl_Position = vec4(Position, 1.0); + gl_Position = MVP * vec4(Position, 1.0); Output.Position = Position; - Output.TextureCoord = TextureCoord; + Output.TextureCoord = (vec2(Position) + 1) / 2; } \ No newline at end of file diff --git a/vs11/Returngeance.sln b/vs11/Returngeance.sln index 8daf9b5..10ce52b 100644 --- a/vs11/Returngeance.sln +++ b/vs11/Returngeance.sln @@ -39,7 +39,4 @@ Global GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection - GlobalSection(Performance) = preSolution - HasPerformanceSessions = true - EndGlobalSection EndGlobal diff --git a/vs11/Returngeance/Returngeance.vcxproj b/vs11/Returngeance/Returngeance.vcxproj index d8ca087..b079859 100755 --- a/vs11/Returngeance/Returngeance.vcxproj +++ b/vs11/Returngeance/Returngeance.vcxproj @@ -167,6 +167,8 @@ + + diff --git a/vs11/Returngeance/Returngeance.vcxproj.filters b/vs11/Returngeance/Returngeance.vcxproj.filters index 1a05dbf..e416604 100755 --- a/vs11/Returngeance/Returngeance.vcxproj.filters +++ b/vs11/Returngeance/Returngeance.vcxproj.filters @@ -271,5 +271,11 @@ Shaders + + Shaders + + + Shaders + \ No newline at end of file From 1268b3d8fd7a5a4176686a88f96e19270cedf2d5 Mon Sep 17 00:00:00 2001 From: Tleety Date: Sat, 10 May 2014 17:44:55 +0200 Subject: [PATCH 46/65] Removed Unused code in renderer --- src/GameWorld.cpp | 2 +- src/Renderer.cpp | 137 +------------------------------------ src/Shaders/Fragment2.glsl | 4 +- 3 files changed, 5 insertions(+), 138 deletions(-) diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index 6e78089..3002e6b 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -224,7 +224,7 @@ void GameWorld::Initialize() CommitEntity(car); } */ - for(int i = 0; i < 5; i++) + for(int i = 0; i < 6; i++) { auto Light = CreateEntity(); auto transform = AddComponent(Light, "Transform"); diff --git a/src/Renderer.cpp b/src/Renderer.cpp index 27820a9..64a0064 100755 --- a/src/Renderer.cpp +++ b/src/Renderer.cpp @@ -613,73 +613,6 @@ void Renderer::FrameBufferTextures() } -//void Renderer::FrameBufferTextures() -//{ -// m_fb = 0; -// m_fDepthBuffer = 0; -// -// glGenFramebuffers(1, &m_fb); -// glGenRenderbuffers(1, &m_fDepthBuffer); -// -// glBindRenderbuffer(GL_RENDERBUFFER, m_fDepthBuffer); -// glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, WIDTH, HEIGHT); -// -// //Generate and bind diffuse texture -// glGenTextures(1, &m_fDiffuseTexture); -// glBindTexture(GL_TEXTURE_2D, m_fDiffuseTexture); -// glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, WIDTH, HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); -// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); -// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); -// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); -// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); -// -// //Generate and bind position texture -// glGenTextures(1, &m_fPositionTexture); -// glBindTexture(GL_TEXTURE_2D, m_fPositionTexture); -// glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, WIDTH, HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); -// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); -// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); -// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); -// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); -// -// //Generate and bind normal texture -// glGenTextures(1, &m_fNormalsTexture); -// glBindTexture(GL_TEXTURE_2D, m_fNormalsTexture); -// glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, WIDTH, HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); -// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); -// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); -// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); -// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); -// -// //Generate and bind blend texture -// glGenTextures(1, &m_fBlendTexture); -// glBindTexture(GL_TEXTURE_2D, m_fBlendTexture); -// glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, WIDTH, HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); -// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); -// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); -// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); -// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); -// -// //Bind fb -// glBindFramebuffer(GL_FRAMEBUFFER, m_fb); -// glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_fDepthBuffer); -// -// //Attach textures to the FB -// glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_fDiffuseTexture, 0); -// glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, m_fPositionTexture, 0); -// glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, m_fNormalsTexture, 0); -// glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3, GL_TEXTURE_2D, m_fBlendTexture, 0); -// -// GLenum fbStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER); -// if(fbStatus != GL_FRAMEBUFFER_COMPLETE) -// { -// printf("DeferredLighting:Init: FrameBuffer incomplete: 0x%x\n", fbStatus); -// exit(1); -// } -// -// glBindFramebuffer(GL_FRAMEBUFFER, 0); -//} - void Renderer::DrawFBO() { /* @@ -725,15 +658,8 @@ void Renderer::DrawFBO() */ glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - - //if(!m_QuadView) - //{ - m_FinalPassProgram.Bind(); - //} - //else - //{ - // m_SecondPassProgram_Debug.Bind(); - //} + + m_FinalPassProgram.Bind(); // Ambient light glUniform3fv(glGetUniformLocation(m_FinalPassProgram.GetHandle(), "La"), 1, glm::value_ptr(glm::vec3(0.3f, 0.3f, 0.3f))); @@ -749,65 +675,6 @@ void Renderer::DrawFBO() glDrawArrays(GL_TRIANGLES, 0, 6); } -//void Renderer::DrawFBO() -//{ -// glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fb); -// -// GLenum windowBuffClear[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3 }; -// glDrawBuffers(4, windowBuffClear); -// glClearColor(0.0f, 0.0f, 0.0f, 0.0f); -// glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); -// -// // Execute the first render stage which will fill out the internal buffers with data(??) -// //EnableRenderProgramStage1; -// m_FirstPassProgram.Bind(); -// GLenum windowBuffOpaque[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_NONE }; -// glDrawBuffers(4, windowBuffOpaque); -// DrawFBOScene(); -// -// GLenum windowBuffTransp[] = { GL_NONE, GL_NONE, GL_NONE, GL_COLOR_ATTACHMENT3 }; -// glDrawBuffers(4, windowBuffTransp); -// glEnable(GL_BLEND); -// glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); -// //Depth buffer shall not be updated -// glDepthMask(GL_FALSE); -// //DrawTransparent items -// glDepthMask(GL_TRUE); -// glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); -// glDisable(GL_BLEND); -// -// glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); -// //Probably means to use the second_pass shader -// //EnableRenderProgramDeferredStage(); -// m_SecondPassProgram.Bind(); -// glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); -// //SetupDefferedStageUniforms(); // Probably what we do in FrameBufferTextures(); -// glEnableVertexAttribArray(0); -// glActiveTexture(GL_TEXTURE0); -// glBindTexture(GL_TEXTURE_2D, m_fDiffuseTexture); -// -// glActiveTexture(GL_TEXTURE1); -// glBindTexture(GL_TEXTURE_2D, m_fPositionTexture); -// -// glActiveTexture(GL_TEXTURE2); -// glBindTexture(GL_TEXTURE_2D, m_fNormalsTexture); -// -// glActiveTexture(GL_TEXTURE3); -// glBindTexture(GL_TEXTURE_2D, m_fBlendTexture); -// -// -// -// -// -// -// -// //DrawSimpleSquare(); //I guess this draw a square and put the textures on it -// glBindVertexArray(m_ScreenQuad); -// glDrawArrays(GL_TRIANGLES, 0, 6); -// glDisableVertexAttribArray(0); -// -//} - void Renderer::DrawFBOScene() { glm::mat4 cameraMatrix = m_Camera->ProjectionMatrix() * m_Camera->ViewMatrix(); diff --git a/src/Shaders/Fragment2.glsl b/src/Shaders/Fragment2.glsl index a27a268..4dde49f 100644 --- a/src/Shaders/Fragment2.glsl +++ b/src/Shaders/Fragment2.glsl @@ -29,7 +29,7 @@ in VertexData out vec4 FragColor; -vec4 phong4(vec3 position, vec3 normal) +vec4 phong(vec3 position, vec3 normal) { // Diffuse vec3 lightPos = vec3(V * vec4(lp, 1.0)); @@ -76,5 +76,5 @@ void main() vec4 PositionTexel = texture(PositionTexture, TextureCoord); vec4 NormalTexel = texture(NormalsTexture, TextureCoord); - FragColor = phong4(vec3(PositionTexel), vec3(NormalTexel)); + FragColor = phong(vec3(PositionTexel), vec3(NormalTexel)); } \ No newline at end of file From 4c0b465c7f3b9f6287d62179ab0ab2a68ea81aa3 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Sat, 10 May 2014 19:13:41 +0200 Subject: [PATCH 47/65] Assets now as Git submodule! (cherry picked from commit 6e6a115ac3ad18184b6bb8d5e0b87ade9e0cd39f) --- .gitignore | 1 - .gitmodules | 4 ++++ assets | 1 + 3 files changed, 5 insertions(+), 1 deletion(-) create mode 100644 .gitmodules create mode 160000 assets diff --git a/.gitignore b/.gitignore index 4f30c2a..c1454f6 100755 --- a/.gitignore +++ b/.gitignore @@ -30,5 +30,4 @@ ipch/ [Rr]elease*/ Ankh.NoLoad -assets/ !libs/*.lib \ No newline at end of file diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..185a1f9 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,4 @@ +[submodule "assets"] + path = assets + url = returngeance@shard.imon.nu:Assets + branch = master diff --git a/assets b/assets new file mode 160000 index 0000000..672e8a2 --- /dev/null +++ b/assets @@ -0,0 +1 @@ +Subproject commit 672e8a2b11ecaafc95a5b0286b5ec310c62438ad From d00ff3c2ed448555f0624ef45365b7222c195a4f Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Sat, 10 May 2014 19:13:41 +0200 Subject: [PATCH 48/65] Assets now as Git submodule! (cherry picked from commit 6e6a115ac3ad18184b6bb8d5e0b87ade9e0cd39f) --- .gitignore | 1 - .gitmodules | 4 ++++ assets | 1 + 3 files changed, 5 insertions(+), 1 deletion(-) create mode 100644 .gitmodules create mode 160000 assets diff --git a/.gitignore b/.gitignore index 3b5dc2e..5982b10 100755 --- a/.gitignore +++ b/.gitignore @@ -31,5 +31,4 @@ ipch/ Ankh.NoLoad *.orig -assets/ !libs/*.lib \ No newline at end of file diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..185a1f9 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,4 @@ +[submodule "assets"] + path = assets + url = returngeance@shard.imon.nu:Assets + branch = master diff --git a/assets b/assets new file mode 160000 index 0000000..672e8a2 --- /dev/null +++ b/assets @@ -0,0 +1 @@ +Subproject commit 672e8a2b11ecaafc95a5b0286b5ec310c62438ad From c1c30b00197c8a692b8b0ab4f63abbd921e6c393 Mon Sep 17 00:00:00 2001 From: Tleety Date: Sat, 10 May 2014 19:51:48 +0200 Subject: [PATCH 49/65] Fixed lights and added a bad gamma correction --- src/Components/PointLight.h | 11 +++- src/GameWorld.cpp | 8 +-- src/Renderer.cpp | 100 ++++++++++++++------------------ src/Renderer.h | 29 +++++---- src/Shaders/FinalPass.frag.glsl | 4 +- src/Shaders/Fragment2.glsl | 6 +- src/Systems/RenderSystem.cpp | 3 +- 7 files changed, 81 insertions(+), 80 deletions(-) diff --git a/src/Components/PointLight.h b/src/Components/PointLight.h index 29da989..ef6eec5 100755 --- a/src/Components/PointLight.h +++ b/src/Components/PointLight.h @@ -9,15 +9,20 @@ namespace Components struct PointLight : Component { - float Intensity; - float MaxRange; + PointLight() + : Specular(1.0f, 1.0f, 1.0f) + , Diffuse(0.4f, 0.4f, 0.4f) + , specularExponent(50.0f) + , Scale(10.0f) + { } + float constantAttenuation, linearAttenuation, quadraticAttenuation; - float spotExponent; Color color; glm::vec3 Specular; glm::vec3 Diffuse; float specularExponent; + float Scale; }; } diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index 3002e6b..f703c76 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -224,15 +224,13 @@ void GameWorld::Initialize() CommitEntity(car); } */ - for(int i = 0; i < 6; i++) + for(int i = 0; i < 20; i++) { auto Light = CreateEntity(); auto transform = AddComponent(Light, "Transform"); - transform->Position = glm::vec3(20+ 10*cos(i), 3, 0 + 10*sin(i)); + transform->Position = glm::vec3(i*cos(i), 3, 0 + i*sin(i)); auto light = AddComponent(Light, "PointLight"); - light->Diffuse = glm::vec3(0.5f, 0.5f, 1.0f); - light->Specular = glm::vec3(1.0f, 1.0f, 1.0f); - light->specularExponent = 1.0f; + //light->Specular = glm::vec3(1.0f, 1.0f, 1.0f); auto model = AddComponent(Light, "Model"); model->ModelFile = "Models/Placeholders/PhysicsTest/PointLight.obj"; } diff --git a/src/Renderer.cpp b/src/Renderer.cpp index 8e6c999..82ac29a 100755 --- a/src/Renderer.cpp +++ b/src/Renderer.cpp @@ -18,7 +18,7 @@ Renderer::Renderer() m_SunPosition = glm::vec3(0, 3.5f, 10); m_SunTarget = glm::vec3(0, 0, 0); m_SunProjection = glm::ortho(-100, 100, -100, 100, -100, 100); - Lights = 0; +/* Lights = 0;*/ } void Renderer::Initialize() @@ -132,7 +132,7 @@ void Renderer::LoadContent() m_FinalPassProgram.AddShader(std::shared_ptr(new FragmentShader("Shaders/FinalPass.frag.glsl"))); m_FinalPassProgram.Compile(); m_FinalPassProgram.Link(); - + Gamma = 1; m_ScreenQuad = CreateQuad(); FrameBufferTextures(); @@ -150,6 +150,17 @@ void Renderer::Draw(double dt) m_QuadView = true; } + if(glfwGetKey(m_Window, GLFW_KEY_KP_1)) + { + Gamma -= 0.3f * dt; + LOG_INFO("Gamma_UP: %f", Gamma); + } + if(glfwGetKey(m_Window, GLFW_KEY_KP_4)) + { + Gamma += 0.3f * dt; + LOG_INFO("Gamma_DOWN: %f", Gamma); + } + glDisable(GL_BLEND); DrawFBO(); @@ -200,14 +211,14 @@ void Renderer::DrawScene() ); m_ShaderProgram.Bind(); - glUniform1i(glGetUniformLocation(m_ShaderProgram.GetHandle(), "numberOfLights"), Lights); + glUniform1i(glGetUniformLocation(m_ShaderProgram.GetHandle(), "numberOfLights"), Lights.size()); // glUniform3fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "position"), Lights, Light_position.data()); // glUniform3fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "specular"), Lights, Light_specular.data()); // glUniform3fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "diffuse"), Lights, Light_diffuse.data()); - glUniform1fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "constantAttenuation"), Lights, Light_constantAttenuation.data()); - glUniform1fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "linearAttenuation"), Lights, Light_linearAttenuation.data()); - glUniform1fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "quadraticAttenuation"), Lights, Light_quadraticAttenuation.data()); - glUniform1fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "spotExponent"), Lights, Light_spotExponent.data()); + glUniform1fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "constantAttenuation"), Lights.size(), Light_constantAttenuation.data()); + glUniform1fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "linearAttenuation"), Lights.size(), Light_linearAttenuation.data()); + glUniform1fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "quadraticAttenuation"), Lights.size(), Light_quadraticAttenuation.data()); + glUniform1fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "spotExponent"), Lights.size(), Light_spotExponent.data()); if (m_DrawWireframe) { glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); @@ -361,30 +372,18 @@ void Renderer::AddPointLightToDraw( glm::vec3 _position, glm::vec3 _specular, glm::vec3 _diffuse, - float _specularExponent + float _specularExponent, + float _scale ) { - Light_position.push_back(_position); - Light_specular.push_back(_specular); - Light_diffuse.push_back(_diffuse); - Light_specularExponent.push_back(_specularExponent); - Lights = Light_position.size(); - CreateLightMatrix(); - -// Light_position.push_back(_position.x); -// Light_position.push_back(_position.y); -// Light_position.push_back(_position.z); -// Light_specular.push_back(_specular.x); -// Light_specular.push_back(_specular.y); -// Light_specular.push_back(_specular.z); -// Light_diffuse.push_back(_diffuse.x); -// Light_diffuse.push_back(_diffuse.y); -// Light_diffuse.push_back(_diffuse.z); -// Light_constantAttenuation.push_back(_constantAttenuation); -// Light_linearAttenuation.push_back(_linearAttenuation); -// Light_quadraticAttenuation.push_back(_quadraticAttenuation); -// Light_spotExponent.push_back(_spotExponent); -// Lights = Light_constantAttenuation.size(); + Light light; + light.Position = _position; + light.Diffuse = _diffuse; + light.Specular = _specular; + light.Scale = _scale; + light.SpecularExponent = _specularExponent; + light.SphereModelMatrix = CreateLightMatrix(light); + Lights.push_back(light); } void Renderer::AddAABBToDraw(glm::vec3 origin, glm::vec3 volumeVector, bool colliding) @@ -522,15 +521,7 @@ void Renderer::ClearStuff() { AABBsToRender.clear(); ModelsToRender.clear(); - Light_position.clear(); - Light_specular.clear(); - Light_diffuse.clear(); - Light_constantAttenuation.clear(); - Light_linearAttenuation.clear(); - Light_quadraticAttenuation.clear(); - Light_spotExponent.clear(); - Light_specularExponent.clear(); - Lights = 0; + Lights.clear(); } #pragma endregion @@ -663,6 +654,7 @@ void Renderer::DrawFBO() // Ambient light glUniform3fv(glGetUniformLocation(m_FinalPassProgram.GetHandle(), "La"), 1, glm::value_ptr(glm::vec3(0.3f, 0.3f, 0.3f))); + glUniform1f(glGetUniformLocation(m_FinalPassProgram.GetHandle(), "Gamma"), Gamma); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_fDiffuseTexture); @@ -719,22 +711,21 @@ void Renderer::DrawLightScene() glm::mat4 cameraMatrix = m_Camera->ProjectionMatrix() * m_Camera->ViewMatrix(); glm::mat4 MVP; - for(int i = 0; i < Lights; i++) + for (auto &light : Lights) { - MVP = cameraMatrix * lM[i]; + MVP = cameraMatrix * light.SphereModelMatrix; glUniform2fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "ViewportSize"), 1,glm::value_ptr(glm::vec2(WIDTH, HEIGHT))); glUniformMatrix4fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "MVP"), 1, GL_FALSE, glm::value_ptr(MVP)); glUniformMatrix4fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "V"), 1, GL_FALSE, glm::value_ptr(m_Camera->ViewMatrix())); glUniformMatrix4fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "P"), 1, GL_FALSE, glm::value_ptr(m_Camera->ProjectionMatrix())); - glUniformMatrix4fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "M"), 1, GL_FALSE, glm::value_ptr(lM[i])); - glUniform3fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "la"), 1, glm::value_ptr(glm::vec3(0.3f, 0.3f, 0.3f))); - glUniform3fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "ls"), 1, glm::value_ptr(Light_specular[i])); - glUniform3fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "ld"), 1, glm::value_ptr(Light_diffuse[i])); - glUniform3fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "lp"), 1, glm::value_ptr(Light_position[i])); - glUniform1f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "LightRadius"), 5.0f); + glUniformMatrix4fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "M"), 1, GL_FALSE, glm::value_ptr(light.SphereModelMatrix)); + glUniform3fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "ls"), 1, glm::value_ptr(light.Specular)); + glUniform3fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "ld"), 1, glm::value_ptr(light.Diffuse)); + glUniform3fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "lp"), 1, glm::value_ptr(light.Position)); + glUniform1f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "LightRadius"), light.Scale/2.f); glUniform3f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "CameraPosition"), m_Camera->Position().x, m_Camera->Position().y, m_Camera->Position().z); - //glUniform1f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "speculatExponent"), Light_specularExponent[i]); + glUniform1f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "specularExponent"), light.SpecularExponent); glDrawArrays(GL_TRIANGLES, 0, m_sphereModel->Vertices.size()); }; glEnable (GL_DEPTH_TEST); @@ -747,16 +738,11 @@ void Renderer::SetSphereModel( Model* _model ) m_sphereModel = _model; } -void Renderer::CreateLightMatrix() +glm::mat4 Renderer::CreateLightMatrix(Light &_light) { - for(int i = 0; i < Lights; i++) - { - const float scale = 10.0f; - glm::mat4 model; - model *= glm::translate(Light_position[i]); - model *= glm::scale(glm::vec3(scale)); - lM[i] = model; - } - + glm::mat4 model; + model *= glm::translate(_light.Position); + model *= glm::scale(glm::vec3(_light.Scale)); + return model; } diff --git a/src/Renderer.h b/src/Renderer.h index 6754701..0a8bc12 100755 --- a/src/Renderer.h +++ b/src/Renderer.h @@ -24,13 +24,7 @@ public: int HEIGHT, WIDTH; std::list> ModelsToRender; - int Lights; - std::vector Light_position; - std::vector Light_specular; - std::vector Light_diffuse; - std::vector Light_specularExponent; - - + std::vector Light_constantAttenuation; std::vector Light_linearAttenuation; std::vector Light_quadraticAttenuation; @@ -50,7 +44,8 @@ public: glm::vec3 _position, glm::vec3 _specular, glm::vec3 _diffuse, - float _specularExponent + float _specularExponent, + float _scale ); void AddAABBToDraw(glm::vec3 origin, glm::vec3 volumeVector, bool colliding); @@ -72,6 +67,21 @@ public: private: + + struct Light + { + glm::vec3 Position; + glm::vec3 Specular; + glm::vec3 Diffuse; + float SpecularExponent; + float Scale; + glm::mat4 SphereModelMatrix; + }; + + float Gamma; + + std::list Lights; + GLFWwindow* m_Window; GLint m_glVersion[2]; GLchar* m_glVendor; @@ -101,7 +111,6 @@ private: GLuint m_fDepthBuffer; GLenum draw_bufs[2]; - glm::mat4 lM[5]; GLuint m_ScreenQuad; Model* m_sphereModel; @@ -133,7 +142,7 @@ private: void DrawFBOScene(); void DrawLightScene(); void BindFragDataLocation(); - void CreateLightMatrix(); + glm::mat4 CreateLightMatrix(Light &_light); GLuint CreateQuad(); void DrawDebugShadowMap(); diff --git a/src/Shaders/FinalPass.frag.glsl b/src/Shaders/FinalPass.frag.glsl index 8509ea8..c6b9257 100644 --- a/src/Shaders/FinalPass.frag.glsl +++ b/src/Shaders/FinalPass.frag.glsl @@ -1,6 +1,7 @@ #version 430 uniform vec3 La; +uniform float Gamma; layout (binding=0) uniform sampler2D DiffuseTexture; layout (binding=1) uniform sampler2D LightingTexture; @@ -18,5 +19,6 @@ void main() vec4 DiffuseTexel = texture(DiffuseTexture, Input.TextureCoord); vec4 LightingTexel = texture(LightingTexture, Input.TextureCoord); - FragmentColor = DiffuseTexel * vec4(La, 1.0) + LightingTexel; + vec4 _FragmentColor = DiffuseTexel * vec4(La, 1.0) + LightingTexel; + FragmentColor = vec4(pow(_FragmentColor.rgb, vec3(1.0 / Gamma)), _FragmentColor.a); } \ No newline at end of file diff --git a/src/Shaders/Fragment2.glsl b/src/Shaders/Fragment2.glsl index 4dde49f..2467d35 100644 --- a/src/Shaders/Fragment2.glsl +++ b/src/Shaders/Fragment2.glsl @@ -13,11 +13,11 @@ uniform vec3 ls; uniform vec3 ld; uniform vec3 lp; uniform float LightRadius; -const float specularExponent = 50.0; +uniform float specularExponent; uniform vec3 CameraPosition; -const vec3 ks = vec3(1.0, 0.0, 0.0); -const vec3 kd = vec3(0.8, 0.8, 0.8); +const vec3 ks = vec3(1.0, 1.0, 1.0); +const vec3 kd = vec3(1.0, 1.0, 1.0); const vec3 ka = vec3(1.0, 1.0, 1.0); const float kshine = 1.0; diff --git a/src/Systems/RenderSystem.cpp b/src/Systems/RenderSystem.cpp index 2dc4116..47bc389 100755 --- a/src/Systems/RenderSystem.cpp +++ b/src/Systems/RenderSystem.cpp @@ -38,7 +38,8 @@ void Systems::RenderSystem::UpdateEntity(double dt, EntityID entity, EntityID pa position, pointLightComponent->Specular, pointLightComponent->Diffuse, - pointLightComponent->specularExponent + pointLightComponent->specularExponent, + pointLightComponent->Scale ); } From 22d855a521fd170174fc4b7b28504503d63e622c Mon Sep 17 00:00:00 2001 From: Tleety Date: Sun, 11 May 2014 00:02:34 +0200 Subject: [PATCH 50/65] Fixed attenuation for lights. --- src/Components/PointLight.h | 6 ++++-- src/GameWorld.cpp | 4 ++-- src/Renderer.cpp | 30 +++++++++++++++++++++--------- src/Renderer.h | 12 ++++-------- src/Shaders/Fragment.glsl | 4 ++-- src/Shaders/Fragment2.glsl | 19 +++++++++++++------ src/Shaders/Vertex2.glsl | 2 +- src/Systems/RenderSystem.cpp | 4 +++- 8 files changed, 50 insertions(+), 31 deletions(-) diff --git a/src/Components/PointLight.h b/src/Components/PointLight.h index ef6eec5..646ea01 100755 --- a/src/Components/PointLight.h +++ b/src/Components/PointLight.h @@ -13,10 +13,12 @@ struct PointLight : Component : Specular(1.0f, 1.0f, 1.0f) , Diffuse(0.4f, 0.4f, 0.4f) , specularExponent(50.0f) - , Scale(10.0f) + , ConstantAttenuation(1.05f) + , LinearAttenuation(0.f) + , QuadraticAttenuation(2.55f) { } - float constantAttenuation, linearAttenuation, quadraticAttenuation; + float ConstantAttenuation, LinearAttenuation, QuadraticAttenuation; Color color; glm::vec3 Specular; diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index f703c76..679a71b 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -224,11 +224,11 @@ void GameWorld::Initialize() CommitEntity(car); } */ - for(int i = 0; i < 20; i++) + for(int i = 0; i < 50; i++) { auto Light = CreateEntity(); auto transform = AddComponent(Light, "Transform"); - transform->Position = glm::vec3(i*cos(i), 3, 0 + i*sin(i)); + transform->Position = glm::vec3(i*cos(i), (float)(0.1*i), 0 + i*sin(i)); auto light = AddComponent(Light, "PointLight"); //light->Specular = glm::vec3(1.0f, 1.0f, 1.0f); auto model = AddComponent(Light, "Model"); diff --git a/src/Renderer.cpp b/src/Renderer.cpp index 82ac29a..b8204c7 100755 --- a/src/Renderer.cpp +++ b/src/Renderer.cpp @@ -132,7 +132,7 @@ void Renderer::LoadContent() m_FinalPassProgram.AddShader(std::shared_ptr(new FragmentShader("Shaders/FinalPass.frag.glsl"))); m_FinalPassProgram.Compile(); m_FinalPassProgram.Link(); - Gamma = 1; + Gamma = 2.2f; m_ScreenQuad = CreateQuad(); FrameBufferTextures(); @@ -215,10 +215,10 @@ void Renderer::DrawScene() // glUniform3fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "position"), Lights, Light_position.data()); // glUniform3fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "specular"), Lights, Light_specular.data()); // glUniform3fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "diffuse"), Lights, Light_diffuse.data()); - glUniform1fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "constantAttenuation"), Lights.size(), Light_constantAttenuation.data()); - glUniform1fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "linearAttenuation"), Lights.size(), Light_linearAttenuation.data()); - glUniform1fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "quadraticAttenuation"), Lights.size(), Light_quadraticAttenuation.data()); - glUniform1fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "spotExponent"), Lights.size(), Light_spotExponent.data()); +// glUniform1fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "constantAttenuation"), Lights.size(), Light_constantAttenuation.data()); +// glUniform1fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "linearAttenuation"), Lights.size(), Light_linearAttenuation.data()); +// glUniform1fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "quadraticAttenuation"), Lights.size(), Light_quadraticAttenuation.data()); +// glUniform1fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "spotExponent"), Lights.size(), Light_spotExponent.data()); if (m_DrawWireframe) { glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); @@ -373,15 +373,19 @@ void Renderer::AddPointLightToDraw( glm::vec3 _specular, glm::vec3 _diffuse, float _specularExponent, - float _scale + float _ConstantAttenuation, + float _LinearAttenuation, + float _QuadraticAttenuation ) { Light light; light.Position = _position; light.Diffuse = _diffuse; light.Specular = _specular; - light.Scale = _scale; light.SpecularExponent = _specularExponent; + light.ConstantAttenuation = _ConstantAttenuation; + light.LinearAttenuation = _LinearAttenuation; + light.QuadraticAttenuation = _QuadraticAttenuation; light.SphereModelMatrix = CreateLightMatrix(light); Lights.push_back(light); } @@ -723,9 +727,12 @@ void Renderer::DrawLightScene() glUniform3fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "ls"), 1, glm::value_ptr(light.Specular)); glUniform3fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "ld"), 1, glm::value_ptr(light.Diffuse)); glUniform3fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "lp"), 1, glm::value_ptr(light.Position)); - glUniform1f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "LightRadius"), light.Scale/2.f); glUniform3f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "CameraPosition"), m_Camera->Position().x, m_Camera->Position().y, m_Camera->Position().z); glUniform1f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "specularExponent"), light.SpecularExponent); + glUniform1f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "ConstantAttenuation"), light.ConstantAttenuation); + glUniform1f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "LinearAttenuation"), light.LinearAttenuation); + glUniform1f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "QuadraticAttenuation"), light.QuadraticAttenuation); + glDrawArrays(GL_TRIANGLES, 0, m_sphereModel->Vertices.size()); }; glEnable (GL_DEPTH_TEST); @@ -740,9 +747,14 @@ void Renderer::SetSphereModel( Model* _model ) glm::mat4 Renderer::CreateLightMatrix(Light &_light) { + float c = _light.ConstantAttenuation; + float l = _light.LinearAttenuation; + float q = _light.QuadraticAttenuation; + float cutOffRadius = abs(sqrt((-4*c*q) + pow(l, 2) + (1024*q) - l) / (2*q)); + glm::mat4 model; model *= glm::translate(_light.Position); - model *= glm::scale(glm::vec3(_light.Scale)); + model *= glm::scale(glm::vec3(cutOffRadius)); return model; } diff --git a/src/Renderer.h b/src/Renderer.h index 0a8bc12..f1f728e 100755 --- a/src/Renderer.h +++ b/src/Renderer.h @@ -24,12 +24,6 @@ public: int HEIGHT, WIDTH; std::list> ModelsToRender; - - std::vector Light_constantAttenuation; - std::vector Light_linearAttenuation; - std::vector Light_quadraticAttenuation; - std::vector Light_spotExponent; - std::list> AABBsToRender; Renderer(); @@ -45,7 +39,9 @@ public: glm::vec3 _specular, glm::vec3 _diffuse, float _specularExponent, - float _scale + float _ConstantAttenuation, + float _LinearAttenuation, + float _QuadraticAttenuation ); void AddAABBToDraw(glm::vec3 origin, glm::vec3 volumeVector, bool colliding); @@ -74,8 +70,8 @@ private: glm::vec3 Specular; glm::vec3 Diffuse; float SpecularExponent; - float Scale; glm::mat4 SphereModelMatrix; + float ConstantAttenuation, LinearAttenuation, QuadraticAttenuation; }; float Gamma; diff --git a/src/Shaders/Fragment.glsl b/src/Shaders/Fragment.glsl index 64d4a59..6741851 100755 --- a/src/Shaders/Fragment.glsl +++ b/src/Shaders/Fragment.glsl @@ -16,10 +16,10 @@ out vec4 frag_Normal; void main() { // Diffuse Texture - frag_Diffuse = texture2D(DiffuseTexture, Input.TextureCoord); + frag_Diffuse = texture(DiffuseTexture, Input.TextureCoord); // G-buffer Position - frag_Position = vec4(Input.Position.xyz, 0.0); + frag_Position = vec4(Input.Position.xyz, 1.0); // G-buffer Normal frag_Normal = vec4(Input.Normal, 0.0); diff --git a/src/Shaders/Fragment2.glsl b/src/Shaders/Fragment2.glsl index 2467d35..2a01693 100644 --- a/src/Shaders/Fragment2.glsl +++ b/src/Shaders/Fragment2.glsl @@ -12,15 +12,19 @@ uniform vec3 la; uniform vec3 ls; uniform vec3 ld; uniform vec3 lp; -uniform float LightRadius; uniform float specularExponent; uniform vec3 CameraPosition; +uniform float ConstantAttenuation; +uniform float LinearAttenuation; +uniform float QuadraticAttenuation; const vec3 ks = vec3(1.0, 1.0, 1.0); const vec3 kd = vec3(1.0, 1.0, 1.0); const vec3 ka = vec3(1.0, 1.0, 1.0); const float kshine = 1.0; + + in VertexData { vec3 Position; @@ -44,12 +48,15 @@ vec4 phong(vec3 position, vec3 normal) vec3 surfaceToViewer = normalize(-position); vec3 halfWay = normalize(surfaceToViewer + directionToLight); float dotSpecular = max(dot(halfWay, normal), 0.0); - float specularFactor = pow(dotSpecular, specularExponent * 2); + float specularFactor = pow(dotSpecular, specularExponent * 2.0); vec3 Is = ks * ls * specularFactor; //Attenuation float dist = distance(lightPos, position); - float attenuation = -log(min(1.0, dist / LightRadius)); + //float attenuation = -log(min(1.0, dist / LightRadius)); + + float attenuation = 1.0 / (ConstantAttenuation + (LinearAttenuation * dist) + (QuadraticAttenuation * dist * dist)); + //float attenuation = 1.0 / (1.0 - 0.0001 * pow(dist, 2)); //float attenuation = clamp(0.0, 1.0, 1.0 / (0.001 + (0.001 * dist) + (0.001 * dist * dist))); @@ -62,9 +69,9 @@ vec4 phong(vec3 position, vec3 normal) //att_s = 1.0 / (1.0 + att_s); //attenuation = attenuation / (1.0 - att_s); - float radius = 5.0; - float alpha = dist / radius; - float dampingFactor = 1.0 - pow(alpha, 3); + //float radius = 5.0; + //float alpha = dist / radius; + //float dampingFactor = 1.0 - pow(alpha, 3); return vec4((Id + Is) * attenuation, 1.0); diff --git a/src/Shaders/Vertex2.glsl b/src/Shaders/Vertex2.glsl index 3156821..b7a0ee3 100644 --- a/src/Shaders/Vertex2.glsl +++ b/src/Shaders/Vertex2.glsl @@ -15,5 +15,5 @@ void main() { gl_Position = MVP * vec4(Position, 1.0); Output.Position = Position; - Output.TextureCoord = (vec2(Position) + 1) / 2; + Output.TextureCoord = (vec2(Position) + 1.0) / 2.0; } \ No newline at end of file diff --git a/src/Systems/RenderSystem.cpp b/src/Systems/RenderSystem.cpp index 47bc389..5f7ba73 100755 --- a/src/Systems/RenderSystem.cpp +++ b/src/Systems/RenderSystem.cpp @@ -39,7 +39,9 @@ void Systems::RenderSystem::UpdateEntity(double dt, EntityID entity, EntityID pa pointLightComponent->Specular, pointLightComponent->Diffuse, pointLightComponent->specularExponent, - pointLightComponent->Scale + pointLightComponent->ConstantAttenuation, + pointLightComponent->LinearAttenuation, + pointLightComponent->QuadraticAttenuation ); } From 37a8af6b65aa9e10ac771cf00c9c60ee11ec1e12 Mon Sep 17 00:00:00 2001 From: Tleety Date: Sun, 11 May 2014 01:05:22 +0200 Subject: [PATCH 51/65] Added being able to change attenuation in real time --- src/Components/PointLight.h | 6 ++-- src/Renderer.cpp | 55 ++++++++++++++++++++++++++++++++++++- src/Renderer.h | 1 + 3 files changed, 58 insertions(+), 4 deletions(-) diff --git a/src/Components/PointLight.h b/src/Components/PointLight.h index 646ea01..b08be67 100755 --- a/src/Components/PointLight.h +++ b/src/Components/PointLight.h @@ -11,11 +11,11 @@ struct PointLight : Component { PointLight() : Specular(1.0f, 1.0f, 1.0f) - , Diffuse(0.4f, 0.4f, 0.4f) + , Diffuse(1.0f, 1.0f, 1.0f) , specularExponent(50.0f) - , ConstantAttenuation(1.05f) + , ConstantAttenuation(1.0f) , LinearAttenuation(0.f) - , QuadraticAttenuation(2.55f) + , QuadraticAttenuation(3.f) { } float ConstantAttenuation, LinearAttenuation, QuadraticAttenuation; diff --git a/src/Renderer.cpp b/src/Renderer.cpp index b8204c7..f652a28 100755 --- a/src/Renderer.cpp +++ b/src/Renderer.cpp @@ -133,6 +133,9 @@ void Renderer::LoadContent() m_FinalPassProgram.Compile(); m_FinalPassProgram.Link(); Gamma = 2.2f; + CAtt = 1.0f; + LAtt = 0.0f; + QAtt = 3.0f; m_ScreenQuad = CreateQuad(); FrameBufferTextures(); @@ -161,6 +164,49 @@ void Renderer::Draw(double dt) LOG_INFO("Gamma_DOWN: %f", Gamma); } + if(glfwGetKey(m_Window, GLFW_KEY_1)) + { + if(glfwGetKey(m_Window, GLFW_KEY_KP_ADD)) + { + CAtt += 0.5f * dt; + LOG_INFO("Const: %f", CAtt); + } + if(glfwGetKey(m_Window, GLFW_KEY_KP_SUBTRACT)) + { + CAtt -= 0.5f * dt; + LOG_INFO("Const: %f", CAtt); + } + } + if(glfwGetKey(m_Window, GLFW_KEY_2)) + { + if(glfwGetKey(m_Window, GLFW_KEY_KP_ADD)) + { + LAtt += 0.5f * dt; + LOG_INFO("Linear: %f", LAtt); + } + if(glfwGetKey(m_Window, GLFW_KEY_KP_SUBTRACT)) + { + LAtt -= 0.5f * dt; + LOG_INFO("Linear: %f", LAtt); + } + } + if(glfwGetKey(m_Window, GLFW_KEY_3)) + { + if(glfwGetKey(m_Window, GLFW_KEY_KP_ADD)) + { + QAtt += 0.5f * dt; + LOG_INFO("Quadratic: %f", QAtt); + } + if(glfwGetKey(m_Window, GLFW_KEY_KP_SUBTRACT)) + { + QAtt -= 0.5f * dt; + LOG_INFO("Quadratic: %f", QAtt); + } + } + + + + glDisable(GL_BLEND); DrawFBO(); @@ -657,7 +703,7 @@ void Renderer::DrawFBO() m_FinalPassProgram.Bind(); // Ambient light - glUniform3fv(glGetUniformLocation(m_FinalPassProgram.GetHandle(), "La"), 1, glm::value_ptr(glm::vec3(0.3f, 0.3f, 0.3f))); + glUniform3fv(glGetUniformLocation(m_FinalPassProgram.GetHandle(), "La"), 1, glm::value_ptr(glm::vec3(0.1f, 0.1f, 0.1f))); glUniform1f(glGetUniformLocation(m_FinalPassProgram.GetHandle(), "Gamma"), Gamma); glActiveTexture(GL_TEXTURE0); @@ -733,6 +779,10 @@ void Renderer::DrawLightScene() glUniform1f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "LinearAttenuation"), light.LinearAttenuation); glUniform1f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "QuadraticAttenuation"), light.QuadraticAttenuation); +// glUniform1f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "ConstantAttenuation"), CAtt); +// glUniform1f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "LinearAttenuation"), LAtt); +// glUniform1f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "QuadraticAttenuation"), QAtt); + glDrawArrays(GL_TRIANGLES, 0, m_sphereModel->Vertices.size()); }; glEnable (GL_DEPTH_TEST); @@ -750,6 +800,9 @@ glm::mat4 Renderer::CreateLightMatrix(Light &_light) float c = _light.ConstantAttenuation; float l = _light.LinearAttenuation; float q = _light.QuadraticAttenuation; +// float c = CAtt; +// float l = LAtt; +// float q = QAtt; float cutOffRadius = abs(sqrt((-4*c*q) + pow(l, 2) + (1024*q) - l) / (2*q)); glm::mat4 model; diff --git a/src/Renderer.h b/src/Renderer.h index f1f728e..672c6f6 100755 --- a/src/Renderer.h +++ b/src/Renderer.h @@ -85,6 +85,7 @@ private: bool m_DrawNormals; bool m_DrawWireframe; bool m_DrawBounds; + float CAtt, LAtt, QAtt; std::shared_ptr m_Skybox; From d9ca9ac1f70da9429f0bc79e62609ace9a84b92a Mon Sep 17 00:00:00 2001 From: Tleety Date: Sun, 11 May 2014 01:09:06 +0200 Subject: [PATCH 52/65] Removed unused code. --- src/Renderer.cpp | 85 ------------------------------------------------ 1 file changed, 85 deletions(-) diff --git a/src/Renderer.cpp b/src/Renderer.cpp index f652a28..a965873 100755 --- a/src/Renderer.cpp +++ b/src/Renderer.cpp @@ -143,7 +143,6 @@ void Renderer::LoadContent() void Renderer::Draw(double dt) { - if(glfwGetKey(m_Window, GLFW_KEY_F1)) { m_QuadView = false; @@ -204,9 +203,6 @@ void Renderer::Draw(double dt) } } - - - glDisable(GL_BLEND); DrawFBO(); @@ -230,87 +226,6 @@ void Renderer::DrawSkybox() m_Skybox->Draw(); } -void Renderer::DrawScene() -{ -// glBindFramebuffer(GL_FRAMEBUFFER, 0); -// glViewport(0, 0, WIDTH, HEIGHT); - - glClear(GL_DEPTH_BUFFER_BIT); - //glClearColor(1.0f, 1.0f, 0.0f, 1.0f); - - glEnable(GL_DEPTH_TEST); - glEnable(GL_CULL_FACE); - glCullFace(GL_BACK); -#ifdef DEBUG - glDisable(GL_CULL_FACE); - glPolygonMode(GL_BACK, GL_LINE); -#endif - - // Draw models - glm::mat4 depthViewMatrix = glm::lookAt(m_SunPosition, m_SunTarget, glm::vec3(0, 1, 0)) * glm::translate(-m_Camera->Position() * glm::vec3(1, 0, 0)); - glm::mat4 depthCamera = m_SunProjection * depthViewMatrix; - glm::mat4 biasMatrix( - 0.5, 0.0, 0.0, 0.0, - 0.0, 0.5, 0.0, 0.0, - 0.0, 0.0, 0.5, 0.0, - 0.5, 0.5, 0.5, 1.0 - ); - - m_ShaderProgram.Bind(); - glUniform1i(glGetUniformLocation(m_ShaderProgram.GetHandle(), "numberOfLights"), Lights.size()); -// glUniform3fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "position"), Lights, Light_position.data()); -// glUniform3fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "specular"), Lights, Light_specular.data()); -// glUniform3fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "diffuse"), Lights, Light_diffuse.data()); -// glUniform1fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "constantAttenuation"), Lights.size(), Light_constantAttenuation.data()); -// glUniform1fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "linearAttenuation"), Lights.size(), Light_linearAttenuation.data()); -// glUniform1fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "quadraticAttenuation"), Lights.size(), Light_quadraticAttenuation.data()); -// glUniform1fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "spotExponent"), Lights.size(), Light_spotExponent.data()); - if (m_DrawWireframe) - { - glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); - } - glActiveTexture(GL_TEXTURE1); - glBindTexture(GL_TEXTURE_2D, m_ShadowDepthTexture); - //DrawModels(m_ShaderProgram); - glm::mat4 cameraMatrix = m_Camera->ProjectionMatrix() * m_Camera->ViewMatrix(); - glm::mat4 depthCameraMatrix = biasMatrix * depthCamera; - glm::mat4 MVP; - glm::mat4 depthMVP; - for (auto tuple : ModelsToRender) - { - Model* model; - glm::mat4 modelMatrix; - bool visible; - std::tie(model, modelMatrix, visible, std::ignore) = tuple; - if (!visible) - continue; - - MVP = cameraMatrix * modelMatrix; - depthMVP = depthCameraMatrix * modelMatrix; - glUniformMatrix4fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "MVP"), 1, GL_FALSE, glm::value_ptr(MVP)); - glUniformMatrix4fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "DepthMVP"), 1, GL_FALSE, glm::value_ptr(depthMVP)); - glUniformMatrix4fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "model"), 1, GL_FALSE, glm::value_ptr(modelMatrix)); - glUniformMatrix4fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "view"), 1, GL_FALSE, glm::value_ptr(m_Camera->ViewMatrix())); - glBindVertexArray(model->VAO); - for (auto texGroup : model->TextureGroups) - { - glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_2D, *texGroup.Texture); - glDrawArrays(GL_TRIANGLES, texGroup.StartIndex, texGroup.EndIndex - texGroup.StartIndex + 1); - } - } - -#ifdef DEBUG - // Debug draw model normals - if (m_DrawNormals) - { - m_ShaderProgramNormals.Bind(); - glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); - DrawModels(m_ShaderProgramNormals); - } -#endif -} - void Renderer::DrawShadowMap() { glEnable(GL_DEPTH_TEST);//Tests where objects are and display them correctly From d7e5630f1b3d09386b0221905e4ab5c703696bea Mon Sep 17 00:00:00 2001 From: ViktorLjung Date: Sun, 11 May 2014 01:52:00 +0200 Subject: [PATCH 53/65] Tank with 8 wheels --- assets | 2 +- src/Components/Wheel.h | 4 +- src/Components/WheelPair.h | 16 ++ src/GameWorld.cpp | 269 ++++++++++++++++-- src/Physics/VehicleSetup.cpp | 30 +- src/Physics/VehicleSetup.h | 4 +- src/Systems/PhysicsSystem.cpp | 91 ++++-- src/Systems/PhysicsSystem.h | 1 + vs11/Returngeance/Returngeance.vcxproj | 1 + .../Returngeance/Returngeance.vcxproj.filters | 3 + 10 files changed, 357 insertions(+), 64 deletions(-) create mode 100644 src/Components/WheelPair.h diff --git a/assets b/assets index 672e8a2..8b6c48b 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit 672e8a2b11ecaafc95a5b0286b5ec310c62438ad +Subproject commit 8b6c48b26b3bbc10f5e66c1f59fec6ca935f641b diff --git a/src/Components/Wheel.h b/src/Components/Wheel.h index d4917db..533d193 100644 --- a/src/Components/Wheel.h +++ b/src/Components/Wheel.h @@ -14,7 +14,7 @@ struct Wheel : Component Wheel() : AxleID(0), Radius(0), Width(0), Mass(0), Steering(false), DownDirection(glm::vec3(0, -1, 0)), Friction(1.5f), SlipAngle(0.0f), - MaxBreakingTorque(1500.0f), ConnectedToHandbrake(false), SuspensionStrength(50.0f) { } + MaxBreakingTorque(1500.0f), ConnectedToHandbrake(false), SuspensionStrength(50.0f), TorqueRatio(0.25f) { } // The Hardpoint MUST be positioned INSIDE the chassis. glm::vec3 Hardpoint; @@ -30,6 +30,8 @@ struct Wheel : Component float SlipAngle; float MaxBreakingTorque; bool ConnectedToHandbrake; + // The wheels total TorqueRatio must be equal to 1 + float TorqueRatio; private: int ID; diff --git a/src/Components/WheelPair.h b/src/Components/WheelPair.h new file mode 100644 index 0000000..0173e30 --- /dev/null +++ b/src/Components/WheelPair.h @@ -0,0 +1,16 @@ +#ifndef Components_WheelPair_h__ +#define Components_WheelPair_h__ + +#include "Component.h" + +namespace Components +{ + + struct WheelPair : Component + { + // Flag for pair wheels + }; + +} + +#endif // Components_WheelPair_h__ diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index 8c36206..ad840a9 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -21,7 +21,7 @@ void GameWorld::Initialize() transform->Orientation = glm::quat(glm::vec3(0.0f, 0.0f, 0.0f)); auto model = AddComponent(ground, "Model"); //model->ModelFile = "Models/TestScene/testScene.obj"; - model->ModelFile = "Models/Placeholders/Terrain/Terrain.obj"; + model->ModelFile = "Models/Placeholders/Terrain/Terrain2.obj"; auto physics = AddComponent(ground, "Physics"); physics->Mass = 10; @@ -31,7 +31,7 @@ void GameWorld::Initialize() auto groundshape = CreateEntity(ground); auto transformshape = AddComponent(groundshape, "Transform"); auto meshShape = AddComponent(groundshape, "MeshShape"); - meshShape->ResourceName = "Models/Placeholders/Terrain/Terrain.obj"; + meshShape->ResourceName = "Models/Placeholders/Terrain/Terrain2.obj"; //meshShape->ResourceName = "Models/TestScene/testScene.obj"; @@ -52,26 +52,31 @@ void GameWorld::Initialize() CommitEntity(camera); } - { + /*{ auto jeep = CreateEntity(); auto transform = AddComponent(jeep, "Transform"); transform->Position = glm::vec3(0, 5, 0); transform->Orientation = glm::angleAxis(glm::pi()/2, glm::vec3(0, 1, 0)); auto physics = AddComponent(jeep, "Physics"); physics->Mass = 1800; - -// auto box = AddComponent(jeep, "Box"); -// box->Width = 1.487f; -// box->Height = 0.727f; -// box->Depth = 2.594f; - - auto meshShape = AddComponent(jeep, "MeshShape"); - meshShape->ResourceName = "Models/Jeep/Chassi/ChassiCollision.obj"; - + physics->Static = false; auto vehicle = AddComponent(jeep, "Vehicle"); - AddComponent(jeep, "Input"); + { + auto shape = CreateEntity(jeep); + auto transform = AddComponent(shape, "Transform"); + auto meshShape = AddComponent(shape, "MeshShape"); + meshShape->ResourceName = "Models/Jeep/Chassi/ChassiCollision.obj"; + CommitEntity(shape); + + // auto box = AddComponent(jeep, "Box"); + // box->Width = 1.487f; + // box->Height = 0.727f; + // box->Depth = 2.594f; + + } + { auto chassis = CreateEntity(jeep); auto transform = AddComponent(chassis, "Transform"); @@ -174,6 +179,236 @@ void GameWorld::Initialize() } CommitEntity(jeep); + }*/ + + + { + auto tank = CreateEntity(); + auto transform = AddComponent(tank, "Transform"); + transform->Position = glm::vec3(0, 5, 0); + transform->Orientation = glm::angleAxis(glm::pi()/2, glm::vec3(0, 1, 0)); + auto physics = AddComponent(tank, "Physics"); + physics->Mass = 45000; + physics->Static = false; + auto vehicle = AddComponent(tank, "Vehicle"); + vehicle->MaxTorque = 5200.f; + + AddComponent(tank, "Input"); + + { + auto shape = CreateEntity(tank); + auto transform = AddComponent(shape, "Transform"); + auto meshShape = AddComponent(shape, "MeshShape"); + meshShape->ResourceName = "Models/Tank/Fix/ChassiCollision.obj"; + CommitEntity(shape); + + // auto box = AddComponent(jeep, "Box"); + // box->Width = 1.487f; + // box->Height = 0.727f; + // box->Depth = 2.594f; + + } + + { + auto chassis = CreateEntity(tank); + auto transform = AddComponent(chassis, "Transform"); + transform->Position = glm::vec3(0, 0, 0); // 0.6577f + auto model = AddComponent(chassis, "Model"); + model->ModelFile = "Models/Tank/Fix/Chassi.obj"; + } + { + auto top = CreateEntity(tank); + auto transform = AddComponent(top, "Transform"); + transform->Position = glm::vec3(0, 1.2, 1.95); // 0.6577f + auto model = AddComponent(top, "Model"); + model->ModelFile = "Models/Tank/Fix/Top.obj"; + + { + auto top = CreateEntity(tank); + auto transform = AddComponent(top, "Transform"); + transform->Position = glm::vec3(0, 1, 0.5); // 0.6577f + auto model = AddComponent(top, "Model"); + model->ModelFile = "Models/Tank/Fix/Barrel.obj"; + } + } + + { + auto lightentity = CreateEntity(tank); + auto transform = AddComponent(lightentity, "Transform"); + transform->Position = glm::vec3(0, 15, 0); + auto light = AddComponent(lightentity, "PointLight"); + light->Diffuse = glm::vec3(128.f/255.f, 172.f/255.f, 242.f/255.f); + light->Specular = glm::vec3(1.f); + light->constantAttenuation = 0.3f; + light->linearAttenuation = 0.003f; + light->quadraticAttenuation = 0.002f; + } + +// auto wheelpair = CreateEntity(tank); +// SetProperty(wheelpair, "Name", "WheelPair"); +// AddComponent(wheelpair, "WheelPairThingy"); + + //Create wheels + float wheelOffset = 0.4f; + float springLength = 0.3f; + float suspensionStrength = 25.f; + + { + auto wheel = CreateEntity(tank); + auto transform = AddComponent(wheel, "Transform"); + transform->Position = glm::vec3(1.88f, -0.83f - wheelOffset, -2.6f); + transform->Orientation = glm::angleAxis(glm::pi(), glm::vec3(0, 1, 0)); + auto model = AddComponent(wheel, "Model"); + model->ModelFile = "Models/Tank/Fix/WheelPhysics.obj"; + auto Wheel = AddComponent(wheel, "Wheel"); + Wheel->Hardpoint = transform->Position + glm::vec3(0.f, springLength, 0.f); + Wheel->AxleID = 0; + Wheel->Mass = 2000; + Wheel->Radius = 0.6f; + Wheel->Steering = true; + Wheel->SuspensionStrength = suspensionStrength; + Wheel->Friction = 3.f; + Wheel->ConnectedToHandbrake = true; + Wheel->TorqueRatio = 0.125f; + CommitEntity(wheel); + } + { + auto wheel = CreateEntity(tank); + auto transform = AddComponent(wheel, "Transform"); + transform->Position = glm::vec3(1.88f, -0.83f - wheelOffset, -0.83f); + transform->Orientation = glm::angleAxis(glm::pi(), glm::vec3(0, 1, 0)); + auto model = AddComponent(wheel, "Model"); + model->ModelFile = "Models/Tank/Fix/WheelPhysics.obj"; + auto Wheel = AddComponent(wheel, "Wheel"); + Wheel->Hardpoint = transform->Position + glm::vec3(0.f, springLength, 0.f); + Wheel->AxleID = 0; + Wheel->Mass = 2000; + Wheel->Radius = 0.6f; + Wheel->Steering = false; + Wheel->SuspensionStrength = suspensionStrength; + Wheel->Friction = 3.f; + Wheel->ConnectedToHandbrake = true; + Wheel->TorqueRatio = 0.125f; + CommitEntity(wheel); + } + + { + auto wheel = CreateEntity(tank); + auto transform = AddComponent(wheel, "Transform"); + transform->Position = glm::vec3(-1.88f, -0.83f - wheelOffset, -2.6f); + transform->Orientation = glm::angleAxis(glm::pi(), glm::vec3(0, 1, 0)); + auto model = AddComponent(wheel, "Model"); + model->ModelFile = "Models/Tank/Fix/WheelPhysics.obj"; + auto Wheel = AddComponent(wheel, "Wheel"); + Wheel->Hardpoint = transform->Position + glm::vec3(0.f, springLength, 0.f); + Wheel->AxleID = 0; + Wheel->Mass = 2000; + Wheel->Radius = 0.6f; + Wheel->Steering = true; + Wheel->SuspensionStrength = suspensionStrength; + Wheel->Friction = 3.f; + Wheel->ConnectedToHandbrake = true; + Wheel->TorqueRatio = 0.125f; + CommitEntity(wheel); + } + { + auto wheel = CreateEntity(tank); + auto transform = AddComponent(wheel, "Transform"); + transform->Position = glm::vec3(-1.88f, -0.83f - wheelOffset, -0.83f); + transform->Orientation = glm::angleAxis(glm::pi(), glm::vec3(0, 1, 0)); + auto model = AddComponent(wheel, "Model"); + model->ModelFile = "Models/Tank/Fix/WheelPhysics.obj"; + auto Wheel = AddComponent(wheel, "Wheel"); + Wheel->Hardpoint = transform->Position + glm::vec3(0.f, springLength, 0.f); + Wheel->AxleID = 0; + Wheel->Mass = 2000; + Wheel->Radius = 0.6f; + Wheel->Steering = false; + Wheel->SuspensionStrength = suspensionStrength; + Wheel->Friction = 3.f; + Wheel->ConnectedToHandbrake = true; + Wheel->TorqueRatio = 0.125f; + CommitEntity(wheel); + } + + + //Back + { + auto wheel = CreateEntity(tank); + auto transform = AddComponent(wheel, "Transform"); + transform->Position = glm::vec3(1.88f, -0.83f - wheelOffset, 1.f); + auto model = AddComponent(wheel, "Model"); + model->ModelFile = "Models/Tank/Fix/WheelPhysics.obj"; + auto Wheel = AddComponent(wheel, "Wheel"); + Wheel->Hardpoint = transform->Position + glm::vec3(0.f, springLength, 0.f); + Wheel->AxleID = 1; + Wheel->Mass = 2000; + Wheel->Radius = 0.6f; + Wheel->Steering = false; + Wheel->SuspensionStrength = suspensionStrength; + Wheel->Friction = 3.f; + Wheel->ConnectedToHandbrake = true; + Wheel->TorqueRatio = 0.125f; + CommitEntity(wheel); + } + { + auto wheel = CreateEntity(tank); + auto transform = AddComponent(wheel, "Transform"); + transform->Position = glm::vec3(1.88f, -0.83f - wheelOffset, 2.95f); + auto model = AddComponent(wheel, "Model"); + model->ModelFile = "Models/Tank/Fix/WheelPhysics.obj"; + auto Wheel = AddComponent(wheel, "Wheel"); + Wheel->Hardpoint = transform->Position + glm::vec3(0.f, springLength, 0.f); + Wheel->AxleID = 1; + Wheel->Mass = 2000; + Wheel->Radius = 0.6f; + Wheel->Steering = false; + Wheel->SuspensionStrength = suspensionStrength; + Wheel->Friction = 3.f; + Wheel->ConnectedToHandbrake = true; + Wheel->TorqueRatio = 0.125f; + CommitEntity(wheel); + } + + { + auto wheel = CreateEntity(tank); + auto transform = AddComponent(wheel, "Transform"); + transform->Position = glm::vec3(-1.88f, -0.83f - wheelOffset, 1.f); + transform->Orientation = glm::angleAxis(glm::pi(), glm::vec3(0, 1, 0)); + auto model = AddComponent(wheel, "Model"); + model->ModelFile = "Models/Tank/Fix/WheelPhysics.obj"; + auto Wheel = AddComponent(wheel, "Wheel"); + Wheel->Hardpoint = transform->Position + glm::vec3(0.f, springLength, 0.f); + Wheel->AxleID = 1; + Wheel->Mass = 2000; + Wheel->Radius = 0.6f; + Wheel->Steering = false; + Wheel->SuspensionStrength = suspensionStrength; + Wheel->Friction = 3.f; + Wheel->ConnectedToHandbrake = true; + Wheel->TorqueRatio = 0.125f; + CommitEntity(wheel); + } + { + auto wheel = CreateEntity(tank); + auto transform = AddComponent(wheel, "Transform"); + transform->Position = glm::vec3(-1.88f, -0.83f - wheelOffset, 2.95f); + auto model = AddComponent(wheel, "Model"); + model->ModelFile = "Models/Tank/Fix/WheelPhysics.obj"; + auto Wheel = AddComponent(wheel, "Wheel"); + Wheel->Hardpoint = transform->Position + glm::vec3(0.f, springLength, 0.f); + Wheel->AxleID = 1; + Wheel->Mass = 2000; + Wheel->Radius = 0.6f; + Wheel->Steering = false; + Wheel->SuspensionStrength = suspensionStrength; + Wheel->Friction = 3.f; + Wheel->ConnectedToHandbrake = true; + Wheel->TorqueRatio = 0.125f; + CommitEntity(wheel); + } + + CommitEntity(tank); } /* @@ -202,18 +437,13 @@ void GameWorld::Initialize() for(int i = 0; i < 1; i++) { - auto wall = CreateEntity(); - auto transform = AddComponent(wall, "Transform"); - transform->Position = glm::vec3(10, 0, -20 + (-10 * i)); - //transform->Orientation = glm::angleAxis(glm::pi()/2.f, glm::vec3(0, 1, 0)); - for (int y = 0; y < 15; y++) { for (int x = -5; x < 5; x++) { auto brick = CreateEntity(); auto transform = AddComponent(brick, "Transform"); - transform->Position = glm::vec3(x + 0.01f, y * 0.3f + 0.01f, 0); + transform->Position = glm::vec3(x + 0.01f, y * 0.3f + 0.01f, -20); transform->Position.x += (y % 2)*0.5f; transform->Scale = glm::vec3(1, 0.3f, 0.4f); transform->Orientation = glm::quat(glm::vec3(0.0f, 0.0f, 0.0f)); @@ -235,7 +465,6 @@ void GameWorld::Initialize() CommitEntity(brick); } } - CommitEntity(wall); } /*for (int x = 0; x < 5; x++) diff --git a/src/Physics/VehicleSetup.cpp b/src/Physics/VehicleSetup.cpp index a309824..1babfcb 100644 --- a/src/Physics/VehicleSetup.cpp +++ b/src/Physics/VehicleSetup.cpp @@ -197,23 +197,21 @@ void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultT transmission.m_gearsRatio.setSize(numberOfGears); transmission.m_wheelsTorqueRatio.setSize(data.m_numWheels); - transmission.m_downshiftRPM = 1500.0f; - transmission.m_upshiftRPM = 3500.0f; + transmission.m_downshiftRPM = 3500.0f; //HACK: Should be in VehicleComponent + transmission.m_upshiftRPM = 7000.0f; transmission.m_clutchDelayTime = 0.0f; - transmission.m_reverseGearRatio = 1.0f; - transmission.m_gearsRatio[0] = 2.0f; - transmission.m_gearsRatio[1] = 1.5f; - transmission.m_gearsRatio[2] = 1.0f; - transmission.m_gearsRatio[3] = 0.75f; - transmission.m_wheelsTorqueRatio[0] = 0.2f; - transmission.m_wheelsTorqueRatio[1] = 0.2f; - transmission.m_wheelsTorqueRatio[2] = 0.3f; - transmission.m_wheelsTorqueRatio[3] = 0.3f; - - //transmission.m_wheelsTorqueRatio[4] = 0.1f; - //transmission.m_wheelsTorqueRatio[5] = 0.1f; - // HACK: fix support for more than 4 wheels, m_wheelsTorqueRatio must equal 1 for all wheels + transmission.m_reverseGearRatio = 1.2f; + transmission.m_gearsRatio[0] = 3.0f; + transmission.m_gearsRatio[1] = 2.25f; + transmission.m_gearsRatio[2] = 1.5f; + transmission.m_gearsRatio[3] = 1.0f; + + for(int i = 0; i < m_Wheels.size(); i++) + { + // The wheels total TorqueRatio must be equal to 1 + transmission.m_wheelsTorqueRatio[i] = m_Wheels[i].WheelComponent->TorqueRatio; + } transmission.m_primaryTransmissionRatio = hkpVehicleDefaultTransmission::calculatePrimaryTransmissionRatio( vehicleComponent.TopSpeed, @@ -287,7 +285,7 @@ void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultV // The threshold in m/s at which the algorithm switches from // using the normalSpinDamping to the collisionSpinDamping. - velocityDamper.m_collisionThreshold = 1.0f; + velocityDamper.m_collisionThreshold = 100.0f; } void VehicleSetup::setupWheelCollide(const hkpWorld* world, const hkpVehicleInstance& vehicle, hkpVehicleRayCastWheelCollide& wheelCollide) diff --git a/src/Physics/VehicleSetup.h b/src/Physics/VehicleSetup.h index b54adbd..83647bb 100644 --- a/src/Physics/VehicleSetup.h +++ b/src/Physics/VehicleSetup.h @@ -21,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -43,7 +44,7 @@ public: Components::Wheel* WheelComponent; Components::Transform* TransformComponent; }; - + std::vector m_Wheels; virtual void setupVehicleData(const hkpWorld* world, hkpVehicleData& data); @@ -58,6 +59,7 @@ public: virtual void setupComponent(const hkpVehicleData& data, hkpVehicleDefaultVelocityDamper& velocityDamper, Components::Vehicle vehicleComponent); virtual void setupWheelCollide(const hkpWorld* world, const hkpVehicleInstance& vehicle, hkpVehicleRayCastWheelCollide& wheelCollide); + }; #endif // Physics_Vehicle_h__ diff --git a/src/Systems/PhysicsSystem.cpp b/src/Systems/PhysicsSystem.cpp index fb54b87..9e14054 100644 --- a/src/Systems/PhysicsSystem.cpp +++ b/src/Systems/PhysicsSystem.cpp @@ -111,6 +111,8 @@ void Systems::PhysicsSystem::RegisterComponents(ComponentFactory* cf) cf->Register("Wheel", []() { return new Components::Wheel(); }); cf->Register("MeshShape", []() { return new Components::MeshShape(); }); cf->Register("HingeConstraint", []() { return new Components::HingeConstraint(); }); + cf->Register("WheelPair", []() { return new Components::WheelPair(); }); + } void Systems::PhysicsSystem::Update(double dt) @@ -225,9 +227,14 @@ void Systems::PhysicsSystem::UpdateEntity(double dt, EntityID entity, EntityID p m_PhysicsWorld->markForWrite(); hkpVehicleDriverInputAnalogStatus* deviceStatus = (hkpVehicleDriverInputAnalogStatus*)m_Vehicles[entity]->m_deviceStatus; - if(inputComponent->KeyState[GLFW_KEY_UP] != 0 || inputComponent->KeyState[GLFW_KEY_DOWN] != 0) + if(inputComponent->KeyState[GLFW_KEY_UP] != 0) { - deviceStatus->m_positionY += inputComponent->KeyState[GLFW_KEY_UP] * -1 * 1.f * dt + inputComponent->KeyState[GLFW_KEY_DOWN] * 1 * 1.f * dt; + deviceStatus->m_positionY += inputComponent->KeyState[GLFW_KEY_UP] * -1 * 1.f * dt; + } + else if (inputComponent->KeyState[GLFW_KEY_DOWN] != 0) + { + deviceStatus->m_positionY += inputComponent->KeyState[GLFW_KEY_DOWN] * 1 * 1.f * dt; + deviceStatus->m_reverseButtonPressed = true; } else { @@ -310,7 +317,7 @@ void Systems::PhysicsSystem::OnEntityCommit( EntityID entity ) auto physicsComponent = m_World->GetComponent(entity, "Physics"); if (physicsComponent) { - + hkpShape* shape; if(entityParent != entity) { LOG_ERROR("Entity: %i , Only the baseparent can have a PhysicsComponent", entity); @@ -330,7 +337,7 @@ void Systems::PhysicsSystem::OnEntityCommit( EntityID entity ) hkpListShape* listShape = new hkpListShape(shapeArray.begin(), shapeArray.getSize(), hkpShapeContainer::REFERENCE_POLICY_INCREMENT); // Save the listShape for further use m_ListShapes[entity] = listShape; - + shape = listShape; ////////////////////////////////// //******************************// @@ -342,11 +349,11 @@ void Systems::PhysicsSystem::OnEntityCommit( EntityID entity ) m_Shapes.erase(entity); hkMassProperties massProperties; - hkpInertiaTensorComputer::computeShapeVolumeMassProperties(listShape, physicsComponent->Mass, massProperties); + hkpInertiaTensorComputer::computeShapeVolumeMassProperties(shape, physicsComponent->Mass, massProperties); hkpRigidBodyCinfo rigidBodyInfo; { - rigidBodyInfo.m_shape = listShape; + rigidBodyInfo.m_shape = shape; rigidBodyInfo.m_motionType = hkpMotion::MOTION_DYNAMIC; auto absoluteTransform = m_World->GetSystem("TransformSystem")->AbsoluteTransform(entity); hkVector4 position = ConvertPosition(absoluteTransform.Position); @@ -361,13 +368,48 @@ void Systems::PhysicsSystem::OnEntityCommit( EntityID entity ) // Create RigidBody hkpRigidBody* rigidBody = new hkpRigidBody(rigidBodyInfo); - m_PhysicsWorld->markForWrite(); - m_PhysicsWorld->addEntity(rigidBody); - m_RigidBodies[entity] = rigidBody; - m_PhysicsWorld->unmarkForWrite(); + auto vehicleComponent = m_World->GetComponent(entity, "Vehicle"); + if (vehicleComponent && m_Vehicles.find(entity) == m_Vehicles.end()) + { + for (int i = 0; i < m_Wheels.size(); i++) + { + if(m_World->GetEntityParent(m_Wheels[i]) != entity) + { + m_Wheels.erase(m_Wheels.begin() + i); + i--; + } + } - listShape->removeReference(); - rigidBody->removeReference(); + + VehicleSetup vehicleSetup; + // Create the basic vehicle. + m_Vehicles[entity] = new hkpVehicleInstance(rigidBody); + m_PhysicsWorld->markForWrite(); + vehicleSetup.buildVehicle(m_World, m_PhysicsWorld, *m_Vehicles[entity], entity, m_Wheels); + // Add the vehicle's entities and phantoms to the world + m_Vehicles[entity]->addToWorld(m_PhysicsWorld); + + m_RigidBodies[entity] = rigidBody; + + // The vehicle is an action + m_PhysicsWorld->addAction(m_Vehicles[entity]); + m_PhysicsWorld->unmarkForWrite(); + + //m_Vehicles[entity]->m_rpm = 0.0f; // Not sure why this one should be here + m_Wheels.clear(); + shape->removeReference(); + rigidBody->removeReference(); + } + else + { + m_PhysicsWorld->markForWrite(); + m_PhysicsWorld->addEntity(rigidBody); + m_RigidBodies[entity] = rigidBody; + m_PhysicsWorld->unmarkForWrite(); + + shape->removeReference(); + rigidBody->removeReference(); + } } else // Static { @@ -390,14 +432,14 @@ void Systems::PhysicsSystem::OnEntityCommit( EntityID entity ) // This must be called after adding the instances and before using the shape. staticCompoundShape->bake(); - + shape = staticCompoundShape; m_Shapes.erase(entity); hkMassProperties massProperties; - hkpInertiaTensorComputer::computeShapeVolumeMassProperties(staticCompoundShape, physicsComponent->Mass, massProperties); + hkpInertiaTensorComputer::computeShapeVolumeMassProperties(shape, physicsComponent->Mass, massProperties); hkpRigidBodyCinfo rigidBodyInfo; { - rigidBodyInfo.m_shape = staticCompoundShape; + rigidBodyInfo.m_shape = shape; rigidBodyInfo.m_motionType = hkpMotion::MOTION_FIXED; auto absoluteTransform = m_World->GetSystem("TransformSystem")->AbsoluteTransform(entity); hkVector4 position = ConvertPosition(absoluteTransform.Position); @@ -417,8 +459,10 @@ void Systems::PhysicsSystem::OnEntityCommit( EntityID entity ) m_RigidBodies[entity] = rigidBody; m_PhysicsWorld->unmarkForWrite(); - staticCompoundShape->removeReference(); + shape->removeReference(); rigidBody->removeReference(); + + } } @@ -441,11 +485,7 @@ void Systems::PhysicsSystem::OnEntityCommit( EntityID entity ) else if(boxComponent) { hkReal thickness = 0.05; - hkpBoxShape* boxShape = new hkpBoxShape(hkVector4(boxComponent->Width, boxComponent->Height, boxComponent->Depth), thickness); - - hkpShapeShrinker* shapeShrinker = new hkpShapeShrinker(); - boxShape = shapeShrinker->shrinkBoxShape(boxShape, thickness, 0); // HACK: Unsure about the 3rd argument - delete shapeShrinker; + hkpBoxShape* boxShape = new hkpBoxShape(hkVector4(boxComponent->Width- thickness, boxComponent->Height -thickness, boxComponent->Depth - thickness), thickness); hkQsTransform transform( ConvertPosition(transformComponent->Position), ConvertRotation(transformComponent->Orientation), ConvertScale(transformComponent->Scale)); hkpConvexTransformShape* transformedBoxShape = new hkpConvexTransformShape( boxShape, transform ); @@ -477,7 +517,7 @@ void Systems::PhysicsSystem::OnEntityCommit( EntityID entity ) } hkpExtendedMeshShape* mesh = new hkpExtendedMeshShape(); - hkReal thickness = 0.00f; // HACK: Convex radius should be 0 for static shapes and 0.05 for dynamic shapes. + hkReal thickness = 0.05f; // HACK: Convex radius should be 0 for static shapes and 0.05 for dynamic shapes. mesh->setRadius(thickness); { hkpExtendedMeshShape::TrianglesSubpart part; @@ -527,8 +567,9 @@ void Systems::PhysicsSystem::SetupVisualDebugger(hkpPhysicsContext* worlds) { // Setup the visual debugger hkArray contexts; + contexts.pushBack(worlds); - + m_VisualDebugger = new hkVisualDebugger(contexts); m_VisualDebugger->serve(); @@ -562,7 +603,7 @@ glm::vec3 Systems::PhysicsSystem::ConvertPosition(const hkVector4 &hkPosition) const hkVector4& Systems::PhysicsSystem::ConvertPosition(glm::vec3 glmPosition) { - return hkVector4( glmPosition.x, glmPosition.y, glmPosition.z ); + return hkVector4( glmPosition.x, glmPosition.y, glmPosition.z); } glm::quat Systems::PhysicsSystem::ConvertRotation(const hkQuaternion &hkRotation) @@ -572,7 +613,7 @@ glm::quat Systems::PhysicsSystem::ConvertRotation(const hkQuaternion &hkRotation const hkQuaternion& Systems::PhysicsSystem::ConvertRotation(glm::quat glmRotation) { - return hkQuaternion(glmRotation.x, glmRotation.y, glmRotation.z, glmRotation.w ); + return hkQuaternion(glmRotation.x, glmRotation.y, glmRotation.z, glmRotation.w); } glm::vec3 Systems::PhysicsSystem::ConvertScale(const hkVector4 &hkScale) diff --git a/src/Systems/PhysicsSystem.h b/src/Systems/PhysicsSystem.h index c74a5ec..9ef1260 100644 --- a/src/Systems/PhysicsSystem.h +++ b/src/Systems/PhysicsSystem.h @@ -11,6 +11,7 @@ #include "Components/Input.h" #include "Components/MeshShape.h" #include "Components/HingeConstraint.h" +#include "Components/WheelPair.h" #include "OBJ.h" // Math and base include diff --git a/vs11/Returngeance/Returngeance.vcxproj b/vs11/Returngeance/Returngeance.vcxproj index 6e66309..bae6084 100755 --- a/vs11/Returngeance/Returngeance.vcxproj +++ b/vs11/Returngeance/Returngeance.vcxproj @@ -140,6 +140,7 @@ + diff --git a/vs11/Returngeance/Returngeance.vcxproj.filters b/vs11/Returngeance/Returngeance.vcxproj.filters index cf6f009..6f29356 100755 --- a/vs11/Returngeance/Returngeance.vcxproj.filters +++ b/vs11/Returngeance/Returngeance.vcxproj.filters @@ -242,6 +242,9 @@ Physics\Components + + Physics\Components + From 2aa51c3e90a7dcdeeb7071df5d50307050a7dd47 Mon Sep 17 00:00:00 2001 From: ViktorLjung Date: Mon, 12 May 2014 14:04:55 +0200 Subject: [PATCH 54/65] Tank sterring event-based --- src/Components/TankSteering.h | 14 +++ src/Events/TankSteer.h | 19 ++++ src/GameWorld.cpp | 21 +++-- src/GameWorld.h | 1 + src/Systems/FreeSteeringSystem.cpp | 16 ++-- src/Systems/InputSystem.cpp | 11 +-- src/Systems/InputSystem.h | 2 +- src/Systems/PhysicsSystem.cpp | 88 +++++-------------- src/Systems/PhysicsSystem.h | 5 ++ src/Systems/TankSteeringSystem.cpp | 87 ++++++++++++++++++ src/Systems/TankSteeringSystem.h | 45 ++++++++++ vs11/Returngeance/Returngeance.vcxproj | 4 + .../Returngeance/Returngeance.vcxproj.filters | 19 +++- 13 files changed, 244 insertions(+), 88 deletions(-) create mode 100644 src/Components/TankSteering.h create mode 100644 src/Events/TankSteer.h create mode 100644 src/Systems/TankSteeringSystem.cpp create mode 100644 src/Systems/TankSteeringSystem.h diff --git a/src/Components/TankSteering.h b/src/Components/TankSteering.h new file mode 100644 index 0000000..963d81c --- /dev/null +++ b/src/Components/TankSteering.h @@ -0,0 +1,14 @@ +#ifndef TankSteering_h__ +#define TankSteering_h__ + +#include "Component.h" + +namespace Components +{ + struct TankSteering : Component + { + + }; +} + +#endif // TankSteering_h__ \ No newline at end of file diff --git a/src/Events/TankSteer.h b/src/Events/TankSteer.h new file mode 100644 index 0000000..3ee6dc9 --- /dev/null +++ b/src/Events/TankSteer.h @@ -0,0 +1,19 @@ +#ifndef Events_TankSteer_h__ +#define Events_TankSteer_h__ +#include "Entity.h" +#include "EventBroker.h" + +namespace Events +{ + +struct TankSteer : Event +{ + EntityID Entity; + float PositionX; + float PositionY; + bool Handbrake; +}; + +} + +#endif // Events_TankSteer_h__ \ No newline at end of file diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index 4744912..979376b 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -12,7 +12,9 @@ void GameWorld::Initialize() BindKey(GLFW_KEY_S, "+backward"); BindKey(GLFW_KEY_A, "+left"); BindKey(GLFW_KEY_D, "+right"); - BindKey(GLFW_KEY_SPACE, "+up"); + BindKey(GLFW_KEY_SPACE, "+handbrake"); + + BindKey(GLFW_KEY_Q, "+up"); BindKey(GLFW_KEY_LEFT_CONTROL, "+down"); BindKey(GLFW_KEY_LEFT_ALT, "+slow"); BindKey(GLFW_KEY_LEFT_SHIFT, "+fast"); @@ -20,6 +22,12 @@ void GameWorld::Initialize() BindMouseButton(GLFW_MOUSE_BUTTON_2, "+attack2"); BindMouseButton(GLFW_MOUSE_BUTTON_3, "+attack3"); + + BindKey(GLFW_KEY_UP, "+cam_forward"); + BindKey(GLFW_KEY_DOWN, "+cam_backward"); + BindKey(GLFW_KEY_LEFT, "+cam_right"); + BindKey(GLFW_KEY_RIGHT, "+cam_left"); + RegisterComponents(); { @@ -214,7 +222,7 @@ void GameWorld::Initialize() physics->Static = false; auto vehicle = AddComponent(tank, "Vehicle"); vehicle->MaxTorque = 5200.f; - + AddComponent(tank, "TankSteering"); AddComponent(tank, "Input"); { @@ -542,11 +550,11 @@ void GameWorld::RegisterSystems() //m_SystemFactory.Register("CollisionSystem", [this]() { return new Systems::CollisionSystem(this); }); ////m_SystemFactory.Register("ParticleSystem", [this]() { return new Systems::ParticleSystem(this); }); //m_SystemFactory.Register("PlayerSystem", [this]() { return new Systems::PlayerSystem(this); }); - m_SystemFactory.Register("FreeSteeringSystem", [this]() { return new Systems::FreeSteeringSystem(this); }); - m_SystemFactory.Register("SoundSystem", [this]() { return new Systems::SoundSystem(this); }); - m_SystemFactory.Register("PhysicsSystem", [this]() { return new Systems::PhysicsSystem(this); }); - m_SystemFactory.Register("RenderSystem", [this]() { return new Systems::RenderSystem(this, m_Renderer); }); m_SystemFactory.Register("FreeSteeringSystem", [this]() { return new Systems::FreeSteeringSystem(this, m_EventBroker); }); + m_SystemFactory.Register("TankSteeringSystem", [this]() { return new Systems::TankSteeringSystem(this, m_EventBroker); }); + m_SystemFactory.Register("SoundSystem", [this]() { return new Systems::SoundSystem(this, m_EventBroker); }); + m_SystemFactory.Register("PhysicsSystem", [this]() { return new Systems::PhysicsSystem(this, m_EventBroker); }); + m_SystemFactory.Register("RenderSystem", [this]() { return new Systems::RenderSystem(this, m_EventBroker, m_Renderer); }); } void GameWorld::AddSystems() @@ -559,6 +567,7 @@ void GameWorld::AddSystems() ////AddSystem("ParticleSystem"); //AddSystem("PlayerSystem"); AddSystem("FreeSteeringSystem"); + AddSystem("TankSteeringSystem"); AddSystem("SoundSystem"); AddSystem("PhysicsSystem"); AddSystem("RenderSystem"); diff --git a/src/GameWorld.h b/src/GameWorld.h index 6c03eb7..6e9c9e4 100755 --- a/src/GameWorld.h +++ b/src/GameWorld.h @@ -12,6 +12,7 @@ //#include "Systems/ParticleSystem.h" //#include "Systems/PlayerSystem.h" #include "Systems/FreeSteeringSystem.h" +#include "Systems/TankSteeringSystem.h" #include "Systems/RenderSystem.h" #include "Systems/SoundSystem.h" #include "Systems/PhysicsSystem.h" diff --git a/src/Systems/FreeSteeringSystem.cpp b/src/Systems/FreeSteeringSystem.cpp index b382b23..8373c80 100755 --- a/src/Systems/FreeSteeringSystem.cpp +++ b/src/Systems/FreeSteeringSystem.cpp @@ -38,35 +38,35 @@ void Systems::FreeSteeringSystem::UpdateEntity(double dt, EntityID entity, Entit bool Systems::FreeSteeringSystem::FreeSteeringInputController::OnCommand(const Events::InputCommand &event) { // Movement - if (event.Command == "+forward") + if (event.Command == "+cam_forward") { Movement.z += -1.f; } - else if (event.Command == "-forward") + else if (event.Command == "-cam_forward") { Movement.z -= -1.f; } - else if (event.Command == "+backward") + else if (event.Command == "+cam_backward") { Movement.z += 1.f; } - else if (event.Command == "-backward") + else if (event.Command == "-cam_backward") { Movement.z -= 1.f; } - else if (event.Command == "+right") + else if (event.Command == "+cam_right") { Movement.x += 1.f; } - else if (event.Command == "-right") + else if (event.Command == "-cam_right") { Movement.x -= 1.f; } - else if (event.Command == "+left") + else if (event.Command == "+cam_left") { Movement.x += -1.f; } - else if (event.Command == "-left") + else if (event.Command == "-cam_left") { Movement.x -= -1.f; } diff --git a/src/Systems/InputSystem.cpp b/src/Systems/InputSystem.cpp index 3c9fdfd..18a21aa 100755 --- a/src/Systems/InputSystem.cpp +++ b/src/Systems/InputSystem.cpp @@ -44,7 +44,7 @@ bool Systems::InputSystem::OnKeyDown(const Events::KeyDown &event) auto bindingIt = m_KeyBindings.find(event.KeyCode); if (bindingIt != m_KeyBindings.end()) { - PublishCommand(0, bindingIt->second, false); + PublishCommand(0, bindingIt->second, 1.f, false); } return true; @@ -55,7 +55,7 @@ bool Systems::InputSystem::OnKeyUp(const Events::KeyUp &event) auto bindingIt = m_KeyBindings.find(event.KeyCode); if (bindingIt != m_KeyBindings.end()) { - PublishCommand(0, bindingIt->second, true); + PublishCommand(0, bindingIt->second, 1.f, true); } return true; @@ -66,7 +66,7 @@ bool Systems::InputSystem::OnMousePress(const Events::MousePress &event) auto bindingIt = m_MouseButtonBindings.find(event.Button); if (bindingIt != m_MouseButtonBindings.end()) { - PublishCommand(0, bindingIt->second, false); + PublishCommand(0, bindingIt->second, 1.f, false); } return true; @@ -77,7 +77,7 @@ bool Systems::InputSystem::OnMouseRelease(const Events::MouseRelease &event) auto bindingIt = m_MouseButtonBindings.find(event.Button); if (bindingIt != m_MouseButtonBindings.end()) { - PublishCommand(0, bindingIt->second, true); + PublishCommand(0, bindingIt->second, 1.f, true); } return true; @@ -113,7 +113,7 @@ bool Systems::InputSystem::OnBindMouseButton(const Events::BindMouseButton &even return true; } -void Systems::InputSystem::PublishCommand(int playerID, std::string command, bool release /*= false*/) +void Systems::InputSystem::PublishCommand(int playerID, std::string command, float value, bool release /*= false*/) { if (release && command.at(0) == '+') { @@ -123,6 +123,7 @@ void Systems::InputSystem::PublishCommand(int playerID, std::string command, boo Events::InputCommand e; e.PlayerID = playerID; e.Command = command; + e.Value = value; EventBroker->Publish(e); LOG_DEBUG("Input: Published command %s for player %i", e.Command.c_str(), playerID); diff --git a/src/Systems/InputSystem.h b/src/Systems/InputSystem.h index c56cccf..f912de0 100755 --- a/src/Systems/InputSystem.h +++ b/src/Systems/InputSystem.h @@ -48,7 +48,7 @@ private: EventRelay m_EBindMouseButton; bool OnBindMouseButton(const Events::BindMouseButton &event); - void PublishCommand(int playerID, std::string command, bool release = false); + void PublishCommand(int playerID, std::string command, float value, bool release = false); }; } diff --git a/src/Systems/PhysicsSystem.cpp b/src/Systems/PhysicsSystem.cpp index 2000a3c..5fad34c 100644 --- a/src/Systems/PhysicsSystem.cpp +++ b/src/Systems/PhysicsSystem.cpp @@ -28,6 +28,9 @@ void Systems::PhysicsSystem::Initialize() { m_Accumulator = 0; + + // Events + EVENT_SUBSCRIBE_MEMBER(m_ETankSteer, &Systems::PhysicsSystem::OnTankSteer); hkMemorySystem::FrameInfo finfo(6000 * 1024); // Allocate 6MB of Physics solver buffer hkMemoryRouter* memoryRouter = hkMemoryInitUtil::initDefault(hkMallocAllocator::m_defaultMallocAllocator, finfo); @@ -219,73 +222,7 @@ void Systems::PhysicsSystem::UpdateEntity(double dt, EntityID entity, EntityID p } } - // HACK: Vehicle test-controls - auto vehicleComponent = m_World->GetComponent(entity, "Vehicle"); - auto inputComponent = m_World->GetComponent(entity, "Input"); - if (vehicleComponent && inputComponent && m_Vehicles.find(entity) != m_Vehicles.end() && m_RigidBodies.find(entity) != m_RigidBodies.end()) - { - m_PhysicsWorld->markForWrite(); - hkpVehicleDriverInputAnalogStatus* deviceStatus = (hkpVehicleDriverInputAnalogStatus*)m_Vehicles[entity]->m_deviceStatus; - - if(inputComponent->KeyState[GLFW_KEY_UP] != 0) - { - deviceStatus->m_positionY += inputComponent->KeyState[GLFW_KEY_UP] * -1 * 1.f * dt; - } - else if (inputComponent->KeyState[GLFW_KEY_DOWN] != 0) - { - deviceStatus->m_positionY += inputComponent->KeyState[GLFW_KEY_DOWN] * 1 * 1.f * dt; - deviceStatus->m_reverseButtonPressed = true; - } - else - { - deviceStatus->m_positionY = 0; - } - - if(deviceStatus->m_positionY > 1) - deviceStatus->m_positionY = 1; - else if(deviceStatus->m_positionY < -1) - deviceStatus->m_positionY = -1; - - float turningSpeed = 3.f; - - if(inputComponent->KeyState[GLFW_KEY_LEFT] != 0 || inputComponent->KeyState[GLFW_KEY_RIGHT] != 0) - { - deviceStatus->m_positionX += inputComponent->KeyState[GLFW_KEY_LEFT] * -1 * turningSpeed * dt + inputComponent->KeyState[GLFW_KEY_RIGHT] * 1 * turningSpeed * dt; - } - else - { - if(deviceStatus->m_positionX > 0) - { - deviceStatus->m_positionX += -1 * (turningSpeed*2) *dt; - } - else if(deviceStatus->m_positionX < 0) - { - deviceStatus->m_positionX += 1 * (turningSpeed*2) * dt; - } - - if (deviceStatus->m_positionX > -0.1 && deviceStatus->m_positionX < 0.1) - { - deviceStatus->m_positionX = 0.f; - } - } - - if(deviceStatus->m_positionX > 1) - deviceStatus->m_positionX = 1; - else if(deviceStatus->m_positionX < -1) - deviceStatus->m_positionX = -1; - - deviceStatus->m_handbrakeButtonPressed = inputComponent->KeyState[GLFW_KEY_RIGHT_CONTROL]; - - if(inputComponent->KeyState[GLFW_KEY_R] && !inputComponent->LastKeyState[GLFW_KEY_R]) - { - transformComponent->Position = transformComponent->Position + glm::vec3(0, 5, 0); - transformComponent->Orientation = glm::quat(glm::vec3(0.0f, 0.0f, 0.0f)); - m_RigidBodies[entity]->setLinearVelocity(hkVector4(0, 0, 0)); - m_RigidBodies[entity]->setAngularVelocity(hkVector4(0, 0, 0)); - } - - m_PhysicsWorld->unmarkForWrite(); - } + } void Systems::PhysicsSystem::OnEntityCommit( EntityID entity ) @@ -626,3 +563,20 @@ const hkVector4& Systems::PhysicsSystem::ConvertScale(glm::vec3 glmScale) return hkVector4(glmScale.x, glmScale.y, glmScale.z); } +bool Systems::PhysicsSystem::OnTankSteer(const Events::TankSteer &event) +{ + auto vehicleComponent = m_World->GetComponent(event.Entity, "Vehicle"); + auto inputComponent = m_World->GetComponent(event.Entity, "Input"); + if (vehicleComponent && inputComponent && m_Vehicles.find(event.Entity) != m_Vehicles.end() && m_RigidBodies.find(event.Entity) != m_RigidBodies.end()) + { + m_PhysicsWorld->markForWrite(); + hkpVehicleDriverInputAnalogStatus* deviceStatus = (hkpVehicleDriverInputAnalogStatus*)m_Vehicles[event.Entity]->m_deviceStatus; + deviceStatus->m_positionX = event.PositionX; + deviceStatus->m_positionY = event.PositionY; + deviceStatus->m_handbrakeButtonPressed = event.Handbrake; + m_PhysicsWorld->unmarkForWrite(); + } + + return true; +} + diff --git a/src/Systems/PhysicsSystem.h b/src/Systems/PhysicsSystem.h index 7592a7b..b8fc262 100644 --- a/src/Systems/PhysicsSystem.h +++ b/src/Systems/PhysicsSystem.h @@ -12,6 +12,7 @@ #include "Components/MeshShape.h" #include "Components/HingeConstraint.h" #include "Components/WheelPair.h" +#include "Events/TankSteer.h" #include "OBJ.h" // Math and base include @@ -79,6 +80,10 @@ private: double m_Accumulator; hkpWorld* m_PhysicsWorld; + // Events + EventRelay m_ETankSteer; + bool OnTankSteer(const Events::TankSteer &event); + void SetUpPhysicsState(EntityID entity, EntityID parent); void TearDownPhysicsState(EntityID entity, EntityID parent); diff --git a/src/Systems/TankSteeringSystem.cpp b/src/Systems/TankSteeringSystem.cpp new file mode 100644 index 0000000..f0a4e30 --- /dev/null +++ b/src/Systems/TankSteeringSystem.cpp @@ -0,0 +1,87 @@ +#include "PrecompiledHeader.h" +#include "TankSteeringSystem.h" +#include "World.h" + +void Systems::TankSteeringSystem::RegisterComponents( ComponentFactory* cf ) +{ + cf->Register("TankSteering", []() { return new Components::TankSteering(); }); +} + +void Systems::TankSteeringSystem::Initialize() +{ + m_InputController = std::unique_ptr(new TankSteeringInputController(EventBroker)); + m_InputController->PositionX = 0; + m_InputController->PositionY = 0; + m_InputController->Handbrake = false; +} + +void Systems::TankSteeringSystem::Update(double dt) +{ + +} + +void Systems::TankSteeringSystem::UpdateEntity(double dt, EntityID entity, EntityID parent) +{ + auto tankSteeringComponent = m_World->GetComponent(entity, "TankSteering"); + if(tankSteeringComponent) + { + Events::TankSteer e; + e.Entity = entity; + e.PositionX = m_InputController->PositionX; + e.PositionY = m_InputController->PositionY; + e.Handbrake = m_InputController->Handbrake; + EventBroker->Publish(e); + } +} + +bool Systems::TankSteeringSystem::TankSteeringInputController::OnCommand(const Events::InputCommand &event) +{ + float val = boost::any_cast(event.Value); + if (event.Command == "+right") + { + PositionX += val; + } + else if (event.Command == "-right") + { + PositionX -= val; + } + else if (event.Command == "+left") + { + PositionX += -val; + } + else if (event.Command == "-left") + { + PositionX -= -val; + } + else if (event.Command == "+forward") + { + PositionY += -val; + } + else if (event.Command == "-forward") + { + PositionY -= -val; + } + else if (event.Command == "+backward") + { + PositionY += val; + } + else if (event.Command == "-backward") + { + PositionY -= val; + } + + else if (event.Command == "+handbrake") + { + Handbrake = true; + } + else if (event.Command == "-handbrake") + { + Handbrake = false; + } + return true; +} + +bool Systems::TankSteeringSystem::TankSteeringInputController::OnMouseMove( const Events::MouseMove &event ) +{ + return false; +} diff --git a/src/Systems/TankSteeringSystem.h b/src/Systems/TankSteeringSystem.h new file mode 100644 index 0000000..5c7a02e --- /dev/null +++ b/src/Systems/TankSteeringSystem.h @@ -0,0 +1,45 @@ +#include + +#include "System.h" +#include "Events/TankSteer.h" +#include "Components/Transform.h" +#include "Components/TankSteering.h" +#include "Components/Vehicle.h" +#include "InputController.h" + +namespace Systems +{ + + class TankSteeringSystem : public System + { + public: + TankSteeringSystem(World* world, std::shared_ptr<::EventBroker> eventBroker) + : System(world, eventBroker) { } + + void RegisterComponents(ComponentFactory* cf) override; + void Initialize() override; + + void Update(double dt) override; + void UpdateEntity(double dt, EntityID entity, EntityID parent) override; + + private: + class TankSteeringInputController; + std::unique_ptr m_InputController; + }; + + class TankSteeringSystem::TankSteeringInputController : InputController + { + public: + TankSteeringInputController(std::shared_ptr<::EventBroker> eventBroker) + : InputController(eventBroker) { } + + float PositionY; + float PositionX; + bool Handbrake; + + protected: + virtual bool OnCommand(const Events::InputCommand &event); + virtual bool OnMouseMove(const Events::MouseMove &event); + }; + +} \ No newline at end of file diff --git a/vs11/Returngeance/Returngeance.vcxproj b/vs11/Returngeance/Returngeance.vcxproj index ac4c36b..47fff50 100755 --- a/vs11/Returngeance/Returngeance.vcxproj +++ b/vs11/Returngeance/Returngeance.vcxproj @@ -115,6 +115,7 @@ + @@ -138,6 +139,7 @@ + @@ -155,6 +157,7 @@ + @@ -179,6 +182,7 @@ + diff --git a/vs11/Returngeance/Returngeance.vcxproj.filters b/vs11/Returngeance/Returngeance.vcxproj.filters index 169f797..8b1f1a3 100755 --- a/vs11/Returngeance/Returngeance.vcxproj.filters +++ b/vs11/Returngeance/Returngeance.vcxproj.filters @@ -57,6 +57,9 @@ Input + + Physics\Systems + @@ -128,6 +131,9 @@ {ee125b77-b275-4841-abc9-374957a89916} + + {42ae084f-ade8-402c-87ba-f03f6b846bc8} + @@ -228,7 +234,6 @@ Audio - Physics\Components @@ -305,6 +310,18 @@ GUI + + Physics + + + Physics\Components + + + Physics\Events + + + Physics\Systems + From 4639a6e4c33ec414da46dc2f57f58f267ac7c07d Mon Sep 17 00:00:00 2001 From: Tleety Date: Mon, 12 May 2014 18:03:39 +0200 Subject: [PATCH 55/65] Working shadows, however ugly they are. --- src/GameWorld.cpp | 32 ++++---- src/Renderer.cpp | 128 +++++++++++++++++++++++--------- src/Renderer.h | 1 + src/Shaders/FinalPass.frag.glsl | 5 ++ src/Shaders/Fragment.glsl | 16 +++- src/Shaders/Fragment2.glsl | 3 - src/Shaders/Vertex.glsl | 3 + src/Shaders/Vertex2.glsl | 3 + 8 files changed, 136 insertions(+), 55 deletions(-) diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index 679a71b..19026b2 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -49,6 +49,17 @@ void GameWorld::Initialize() AddComponent(jeep, "Input"); + for(int i = 0; i < 5; i++) + { + auto Light = CreateEntity(jeep); + auto transform = AddComponent(Light, "Transform"); + transform->Position = glm::vec3((5+(i/2.f))*cos(i/5.0f), 0.3f, 0 + (5+(i/5.f))*sin(i/2.0f)); + auto light = AddComponent(Light, "PointLight"); + light->Specular = glm::vec3(1.0f, 1.0f, 1.0f); + light->Diffuse = glm::vec3((float)(rand()%255)/255.f, (float)(rand()%255)/255.f, (float)(rand()%255)/255.f); + auto model = AddComponent(Light, "Model"); + model->ModelFile = "Models/Placeholders/PhysicsTest/PointLight.obj"; + } { auto camera = CreateEntity(); @@ -69,7 +80,7 @@ void GameWorld::Initialize() auto transform = AddComponent(chassis, "Transform"); transform->Position = glm::vec3(0, -0.6577f, 0); auto model = AddComponent(chassis, "Model"); - model->ModelFile = "Models/JeepV2/Chassi/chassi.OBJ"; + model->ModelFile = "Models/Jeep/Chassi/chassi.OBJ"; } @@ -79,7 +90,7 @@ void GameWorld::Initialize() transform->Position = glm::vec3(1.4f, 0.5546f - 0.6577f - 0.2, -0.9242f); transform->Scale = glm::vec3(1.0f); auto model = AddComponent(wheel, "Model"); - model->ModelFile = "Models/JeepV2/WheelFront/wheelFront.obj"; + model->ModelFile = "Models/Jeep/WheelFront/wheelFront.obj"; auto Wheel = AddComponent(wheel, "Wheel"); Wheel->Hardpoint = transform->Position + glm::vec3(0.f, 1.f, 0.f); Wheel->AxleID = 0; @@ -99,7 +110,7 @@ void GameWorld::Initialize() transform->Scale = glm::vec3(1.0f); transform->Orientation = glm::angleAxis(glm::pi(), glm::vec3(0, 0, 1)); auto model = AddComponent(wheel, "Model"); - model->ModelFile = "Models/JeepV2/WheelFront/wheelFront.obj"; + model->ModelFile = "Models/Jeep/WheelFront/wheelFront.obj"; auto Wheel = AddComponent(wheel, "Wheel"); Wheel->Hardpoint = transform->Position + glm::vec3(0.f, 1.f, 0.f); Wheel->AxleID = 0; @@ -117,7 +128,7 @@ void GameWorld::Initialize() auto transform = AddComponent(wheel, "Transform"); transform->Position = glm::vec3(0.2726f, 0.2805f - 0.6577f, 1.9307f); auto model = AddComponent(wheel, "Model"); - model->ModelFile = "Models/JeepV2/WheelBack/wheelBack.obj"; + model->ModelFile = "Models/Jeep/WheelBack/wheelBack.obj"; auto Wheel = AddComponent(wheel, "Wheel"); Wheel->Hardpoint = transform->Position + glm::vec3(0.f, 1.f, 0.f); Wheel->AxleID = 1; @@ -135,7 +146,7 @@ void GameWorld::Initialize() transform->Position = glm::vec3(-0.2726f, 0.2805f - 0.6577f, 1.9307f); transform->Orientation = glm::angleAxis(glm::pi(), glm::vec3(0, 0, 1)); auto model = AddComponent(wheel, "Model"); - model->ModelFile = "Models/JeepV2/WheelBack/wheelBack.obj"; + model->ModelFile = "Models/Jeep/WheelBack/wheelBack.obj"; auto Wheel = AddComponent(wheel, "Wheel"); Wheel->Hardpoint = transform->Position + glm::vec3(0.f, 1.f, 0.f); Wheel->AxleID = 1; @@ -224,16 +235,7 @@ void GameWorld::Initialize() CommitEntity(car); } */ - for(int i = 0; i < 50; i++) - { - auto Light = CreateEntity(); - auto transform = AddComponent(Light, "Transform"); - transform->Position = glm::vec3(i*cos(i), (float)(0.1*i), 0 + i*sin(i)); - auto light = AddComponent(Light, "PointLight"); - //light->Specular = glm::vec3(1.0f, 1.0f, 1.0f); - auto model = AddComponent(Light, "Model"); - model->ModelFile = "Models/Placeholders/PhysicsTest/PointLight.obj"; - } + for(int i = 0; i < 10; i++) diff --git a/src/Renderer.cpp b/src/Renderer.cpp index a965873..429e449 100755 --- a/src/Renderer.cpp +++ b/src/Renderer.cpp @@ -13,7 +13,10 @@ Renderer::Renderer() m_DrawWireframe = false; m_DrawBounds = false; #endif - + Gamma = 2.2f; + CAtt = 1.0f; + LAtt = 0.0f; + QAtt = 3.0f; m_ShadowMapRes = 2048; m_SunPosition = glm::vec3(0, 3.5f, 10); m_SunTarget = glm::vec3(0, 0, 0); @@ -89,12 +92,7 @@ void Renderer::LoadContent() m_ShaderProgramNormals.AddShader(std::shared_ptr(new FragmentShader("Shaders/Normals.frag.glsl"))); m_ShaderProgramNormals.Compile(); m_ShaderProgramNormals.Link(); - - m_ShaderProgramShadows.AddShader(std::shared_ptr(new VertexShader("Shaders/ShadowMap.vert.glsl"))); - m_ShaderProgramShadows.AddShader(std::shared_ptr(new FragmentShader("Shaders/ShadowMap.frag.glsl"))); - m_ShaderProgramShadows.Compile(); - m_ShaderProgramShadows.Link(); - + m_ShaderProgramShadowsDrawDepth.AddShader(std::shared_ptr(new VertexShader("Shaders/VisualizeDepth.vert.glsl"))); m_ShaderProgramShadowsDrawDepth.AddShader(std::shared_ptr(new FragmentShader("Shaders/VisualizeDepth.frag.glsl"))); m_ShaderProgramShadowsDrawDepth.Compile(); @@ -110,9 +108,15 @@ void Renderer::LoadContent() m_ShaderProgramSkybox.Compile(); m_ShaderProgramSkybox.Link();*/ + m_ShaderProgramShadows.AddShader(std::shared_ptr(new VertexShader("Shaders/ShadowMap.vert.glsl"))); + m_ShaderProgramShadows.AddShader(std::shared_ptr(new FragmentShader("Shaders/ShadowMap.frag.glsl"))); + m_ShaderProgramShadows.Compile(); + m_ShaderProgramShadows.Link(); + m_FirstPassProgram.AddShader(std::shared_ptr(new VertexShader("Shaders/Vertex.glsl"))); m_FirstPassProgram.AddShader(std::shared_ptr(new FragmentShader("Shaders/Fragment.glsl"))); m_FirstPassProgram.Compile(); + glBindFragDataLocation(m_FirstPassProgram.GetHandle(), 0, "frag_Diffuse"); glBindFragDataLocation(m_FirstPassProgram.GetHandle(), 1, "frag_Position"); glBindFragDataLocation(m_FirstPassProgram.GetHandle(), 2, "frag_Normal"); @@ -132,12 +136,8 @@ void Renderer::LoadContent() m_FinalPassProgram.AddShader(std::shared_ptr(new FragmentShader("Shaders/FinalPass.frag.glsl"))); m_FinalPassProgram.Compile(); m_FinalPassProgram.Link(); - Gamma = 2.2f; - CAtt = 1.0f; - LAtt = 0.0f; - QAtt = 3.0f; m_ScreenQuad = CreateQuad(); - + CreateShadowMap(m_ShadowMapRes); FrameBufferTextures(); } @@ -226,6 +226,32 @@ void Renderer::DrawSkybox() m_Skybox->Draw(); } +void Renderer::CreateShadowMap(int resolution) +{ + glGenFramebuffers(1, &m_ShadowFrameBuffer); + glBindFramebuffer(GL_FRAMEBUFFER, m_ShadowFrameBuffer); + + // Depth texture + glGenTextures(1, &m_ShadowDepthTexture); + glBindTexture(GL_TEXTURE_2D, m_ShadowDepthTexture); + glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, resolution, resolution, 0, GL_DEPTH_COMPONENT, GL_FLOAT, 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); + + //glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE ); + //glTexParameteri( GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE, GL_INTENSITY ); + + glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, m_ShadowDepthTexture, 0); + glDrawBuffer(GL_NONE); + + if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { + LOG_ERROR("Framebuffer incomplete!"); + return; + } +} + void Renderer::DrawShadowMap() { glEnable(GL_DEPTH_TEST);//Tests where objects are and display them correctly @@ -239,14 +265,9 @@ void Renderer::DrawShadowMap() glClear(GL_DEPTH_BUFFER_BIT); //glClearColor(0.0f, 0.0f, 0.0f, 0.0f); - //Creates the "camera" for the shadowmap from the direction of the sun. - glm::mat4 depthViewMatrix = glm::lookAt(m_SunPosition, m_SunTarget, glm::vec3(0, 1, 0)) * glm::translate(-m_Camera->Position() * glm::vec3(1, 0, 0)); -// glm::mat4 depthViewMatrix = glm::lookAt(m_SunPosition, m_SunTarget, glm::vec3(0, 1, 0)); + glm::mat4 depthViewMatrix = glm::lookAt(m_SunPosition, m_SunTarget, glm::vec3(0, 1, 0)); glm::mat4 depthCamera = m_SunProjection * depthViewMatrix; - - //glm::mat4 cameraMatrix = depthProjectionMatrix * m_Camera->ViewMatrix(); - glm::mat4 MVP; m_ShaderProgramShadows.Bind(); @@ -271,6 +292,7 @@ void Renderer::DrawShadowMap() glDrawArrays(GL_TRIANGLES, texGroup.StartIndex, texGroup.EndIndex - texGroup.StartIndex + 1); } } + } void Renderer::DrawDebugShadowMap() @@ -529,6 +551,14 @@ void Renderer::FrameBufferTextures() glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + /*glGenTextures(1, &m_fShadowTexture); + glBindTexture(GL_TEXTURE_2D, m_fShadowTexture); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB10_A2, WIDTH, HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);*/ + //Bind fb glBindFramebuffer(GL_FRAMEBUFFER, m_fbBasePass); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_fDepthBuffer); @@ -537,11 +567,12 @@ void Renderer::FrameBufferTextures() glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_fDiffuseTexture, 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, m_fPositionTexture, 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, m_fNormalsTexture, 0); + //glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3, GL_TEXTURE_2D, m_fShadowTexture, 0); GLenum fbStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER); if(fbStatus != GL_FRAMEBUFFER_COMPLETE) { - LOG_ERROR("DeferredLighting:Init: FrameBuffer incomplete: 0x%x\n", fbStatus); + LOG_ERROR("DeferredLighting:Init: m_fbBasePass incomplete: 0x%x\n", fbStatus); //exit(1); } @@ -562,15 +593,18 @@ void Renderer::FrameBufferTextures() fbStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER); if(fbStatus != GL_FRAMEBUFFER_COMPLETE) { - LOG_ERROR("DeferredLighting:Init: FrameBuffer incomplete: 0x%x\n", fbStatus); + LOG_ERROR("DeferredLighting:Init: m_fbLightingPass incomplete: 0x%x\n", fbStatus); //exit(1); } + } void Renderer::DrawFBO() { + DrawShadowMap(); + /* Base pass */ @@ -586,8 +620,10 @@ void Renderer::DrawFBO() m_FirstPassProgram.Bind(); GLenum windowBuffOpaque[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2 }; glDrawBuffers(3, windowBuffOpaque); - + glCullFace(GL_BACK); + + glViewport(0, 0, WIDTH, HEIGHT); DrawFBOScene(); /* @@ -617,7 +653,7 @@ void Renderer::DrawFBO() m_FinalPassProgram.Bind(); - // Ambient light + // Ambient light & Shadow Matrix glUniform3fv(glGetUniformLocation(m_FinalPassProgram.GetHandle(), "La"), 1, glm::value_ptr(glm::vec3(0.1f, 0.1f, 0.1f))); glUniform1f(glGetUniformLocation(m_FinalPassProgram.GetHandle(), "Gamma"), Gamma); @@ -634,8 +670,27 @@ void Renderer::DrawFBO() void Renderer::DrawFBOScene() { + glEnable(GL_DEPTH_TEST);//Tests where objects are and display them correctly + glEnable(GL_CULL_FACE); //removes triangles on the wrong side of the object + glCullFace(GL_BACK); //Make it so that only the back faces are rendered + glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); //Draws filled polygons + glm::mat4 cameraMatrix = m_Camera->ProjectionMatrix() * m_Camera->ViewMatrix(); glm::mat4 MVP; + glm::mat4 biasMatrix( + 0.5, 0.0, 0.0, 0.0, + 0.0, 0.5, 0.0, 0.0, + 0.0, 0.0, 0.5, 0.0, + 0.5, 0.5, 0.5, 1.0 + ); + + glm::mat4 depthViewMatrix = glm::lookAt(m_SunPosition, m_SunTarget, glm::vec3(0, 1, 0)); + glm::mat4 depthCamera = m_SunProjection * depthViewMatrix; + glm::mat4 depthCameraMatrix = biasMatrix * depthCamera; + glm::mat4 depthMVP; + + glActiveTexture(GL_TEXTURE1); + glBindTexture(GL_TEXTURE_2D, m_ShadowDepthTexture); for (auto tuple : ModelsToRender) { @@ -645,9 +700,11 @@ void Renderer::DrawFBOScene() std::tie(model, modelMatrix, visible, std::ignore) = tuple; if (!visible) continue; - + MVP = cameraMatrix * modelMatrix; + depthMVP = depthCameraMatrix * modelMatrix; glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "MVP"), 1, GL_FALSE, glm::value_ptr(MVP)); + glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "DepthMVP"), 1, GL_FALSE, glm::value_ptr(depthMVP)); glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "M"), 1, GL_FALSE, glm::value_ptr(modelMatrix)); glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "V"), 1, GL_FALSE, glm::value_ptr(m_Camera->ViewMatrix())); glUniformMatrix4fv(glGetUniformLocation(m_FirstPassProgram.GetHandle(), "P"), 1, GL_FALSE, glm::value_ptr(m_Camera->ProjectionMatrix())); @@ -690,13 +747,12 @@ void Renderer::DrawLightScene() glUniform3fv(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "lp"), 1, glm::value_ptr(light.Position)); glUniform3f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "CameraPosition"), m_Camera->Position().x, m_Camera->Position().y, m_Camera->Position().z); glUniform1f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "specularExponent"), light.SpecularExponent); - glUniform1f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "ConstantAttenuation"), light.ConstantAttenuation); - glUniform1f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "LinearAttenuation"), light.LinearAttenuation); - glUniform1f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "QuadraticAttenuation"), light.QuadraticAttenuation); - -// glUniform1f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "ConstantAttenuation"), CAtt); -// glUniform1f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "LinearAttenuation"), LAtt); -// glUniform1f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "QuadraticAttenuation"), QAtt); +// glUniform1f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "ConstantAttenuation"), light.ConstantAttenuation); +// glUniform1f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "LinearAttenuation"), light.LinearAttenuation); +// glUniform1f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "QuadraticAttenuation"), light.QuadraticAttenuation); + glUniform1f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "ConstantAttenuation"), CAtt); + glUniform1f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "LinearAttenuation"), LAtt); + glUniform1f(glGetUniformLocation(m_SecondPassProgram.GetHandle(), "QuadraticAttenuation"), QAtt); glDrawArrays(GL_TRIANGLES, 0, m_sphereModel->Vertices.size()); }; @@ -712,12 +768,12 @@ void Renderer::SetSphereModel( Model* _model ) glm::mat4 Renderer::CreateLightMatrix(Light &_light) { - float c = _light.ConstantAttenuation; - float l = _light.LinearAttenuation; - float q = _light.QuadraticAttenuation; -// float c = CAtt; -// float l = LAtt; -// float q = QAtt; +// float c = _light.ConstantAttenuation; +// float l = _light.LinearAttenuation; +// float q = _light.QuadraticAttenuation; + float c = CAtt; + float l = LAtt; + float q = QAtt; float cutOffRadius = abs(sqrt((-4*c*q) + pow(l, 2) + (1024*q) - l) / (2*q)); glm::mat4 model; diff --git a/src/Renderer.h b/src/Renderer.h index 672c6f6..e1a2aec 100755 --- a/src/Renderer.h +++ b/src/Renderer.h @@ -105,6 +105,7 @@ private: GLuint m_fBlendTexture; GLuint m_fbLightingPass; GLuint m_fLightingTexture; + GLuint m_fShadowTexture; GLuint m_fDepthBuffer; GLenum draw_bufs[2]; diff --git a/src/Shaders/FinalPass.frag.glsl b/src/Shaders/FinalPass.frag.glsl index c6b9257..2a6cf4c 100644 --- a/src/Shaders/FinalPass.frag.glsl +++ b/src/Shaders/FinalPass.frag.glsl @@ -5,6 +5,7 @@ uniform float Gamma; layout (binding=0) uniform sampler2D DiffuseTexture; layout (binding=1) uniform sampler2D LightingTexture; +layout (binding=2) uniform sampler2D ShadowTexture; in VertexData { @@ -18,7 +19,11 @@ void main() { vec4 DiffuseTexel = texture(DiffuseTexture, Input.TextureCoord); vec4 LightingTexel = texture(LightingTexture, Input.TextureCoord); + vec4 ShadowTexel = texture(ShadowTexture, Input.TextureCoord); + vec4 _FragmentColor = DiffuseTexel * vec4(La, 1.0) + LightingTexel; FragmentColor = vec4(pow(_FragmentColor.rgb, vec3(1.0 / Gamma)), _FragmentColor.a); + //FragmentColor = ShadowTexel; + } \ No newline at end of file diff --git a/src/Shaders/Fragment.glsl b/src/Shaders/Fragment.glsl index 6741851..e64e2ec 100755 --- a/src/Shaders/Fragment.glsl +++ b/src/Shaders/Fragment.glsl @@ -1,22 +1,36 @@ #version 430 layout (binding=0) uniform sampler2D DiffuseTexture; +layout (binding=1) uniform sampler2D ShadowTexture; in VertexData { vec3 Position; vec3 Normal; vec2 TextureCoord; + vec4 ShadowCoord; } Input; out vec4 frag_Diffuse; out vec4 frag_Position; out vec4 frag_Normal; +float Shadow(vec4 ShadowCoord) +{ + if( texture(ShadowTexture, Input.ShadowCoord.xy).z < ShadowCoord.z ) + { + return 0.3; + } + else + { + return 1.0; + } +} + void main() { // Diffuse Texture - frag_Diffuse = texture(DiffuseTexture, Input.TextureCoord); + frag_Diffuse = texture(DiffuseTexture, Input.TextureCoord) * Shadow(Input.ShadowCoord); // G-buffer Position frag_Position = vec4(Input.Position.xyz, 1.0); diff --git a/src/Shaders/Fragment2.glsl b/src/Shaders/Fragment2.glsl index 2a01693..f531f76 100644 --- a/src/Shaders/Fragment2.glsl +++ b/src/Shaders/Fragment2.glsl @@ -23,8 +23,6 @@ const vec3 kd = vec3(1.0, 1.0, 1.0); const vec3 ka = vec3(1.0, 1.0, 1.0); const float kshine = 1.0; - - in VertexData { vec3 Position; @@ -73,7 +71,6 @@ vec4 phong(vec3 position, vec3 normal) //float alpha = dist / radius; //float dampingFactor = 1.0 - pow(alpha, 3); - return vec4((Id + Is) * attenuation, 1.0); } diff --git a/src/Shaders/Vertex.glsl b/src/Shaders/Vertex.glsl index ea38b24..2f799ef 100755 --- a/src/Shaders/Vertex.glsl +++ b/src/Shaders/Vertex.glsl @@ -4,6 +4,7 @@ uniform mat4 MVP; uniform mat4 M; uniform mat4 V; uniform mat4 P; +uniform mat4 DepthMVP; layout (location = 0) in vec3 Position; layout (location = 1) in vec3 Normal; @@ -14,6 +15,7 @@ out VertexData vec3 Position; vec3 Normal; vec2 TextureCoord; + vec4 ShadowCoord; } Output; void main() @@ -23,4 +25,5 @@ void main() Output.Position = vec3(V * M * vec4(Position, 1.0)); Output.Normal = normalize(vec3(inverse(transpose(V * M)) * vec4(Normal, 0.0))); Output.TextureCoord = TextureCoord; + Output.ShadowCoord = DepthMVP * vec4(Position, 1.0); } \ No newline at end of file diff --git a/src/Shaders/Vertex2.glsl b/src/Shaders/Vertex2.glsl index b7a0ee3..e617846 100644 --- a/src/Shaders/Vertex2.glsl +++ b/src/Shaders/Vertex2.glsl @@ -5,6 +5,8 @@ uniform mat4 MVP; layout (location = 0) in vec3 Position; layout (location = 2) in vec2 TextureCoord; +uniform mat4 depthBiasMVP; + out VertexData { vec3 Position; @@ -16,4 +18,5 @@ void main() gl_Position = MVP * vec4(Position, 1.0); Output.Position = Position; Output.TextureCoord = (vec2(Position) + 1.0) / 2.0; + } \ No newline at end of file From 5d48ea7e2aa15bc2765f93a87dc6ca844d970b3f Mon Sep 17 00:00:00 2001 From: Stiffly Date: Mon, 12 May 2014 22:05:56 +0200 Subject: [PATCH 56/65] not reversed input for Camera... --- src/Systems/FreeSteeringSystem.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Systems/FreeSteeringSystem.cpp b/src/Systems/FreeSteeringSystem.cpp index 8373c80..d59b475 100755 --- a/src/Systems/FreeSteeringSystem.cpp +++ b/src/Systems/FreeSteeringSystem.cpp @@ -56,19 +56,19 @@ bool Systems::FreeSteeringSystem::FreeSteeringInputController::OnCommand(const E } else if (event.Command == "+cam_right") { - Movement.x += 1.f; + Movement.x -= 1.f; } else if (event.Command == "-cam_right") { - Movement.x -= 1.f; + Movement.x += 1.f; } else if (event.Command == "+cam_left") { - Movement.x += -1.f; + Movement.x -= -1.f; } else if (event.Command == "-cam_left") { - Movement.x -= -1.f; + Movement.x += -1.f; } else if (event.Command == "+up") { From ddc41b88a77c94d0f41a5ef4134c74bfda931f6b Mon Sep 17 00:00:00 2001 From: ViktorLjung Date: Mon, 12 May 2014 22:15:21 +0200 Subject: [PATCH 57/65] Fixed relative transform rotations (For real this time?) --- src/Systems/TransformSystem.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Systems/TransformSystem.cpp b/src/Systems/TransformSystem.cpp index 383c123..ba9bbb1 100755 --- a/src/Systems/TransformSystem.cpp +++ b/src/Systems/TransformSystem.cpp @@ -74,10 +74,10 @@ Components::Transform Systems::TransformSystem::AbsoluteTransform(EntityID entit auto transform2 = m_World->GetComponent(entity, "Transform"); // Position - if (entity != 0) - absPosition += transform2->Orientation * transform->Position; - else + if (entity == 0) absPosition += transform->Position; + else + absPosition = transform2->Orientation * (absPosition + transform->Position); // Orientation absOrientation = transform->Orientation * absOrientation; // Scale From 19a2879104b842dfdd7916cb72ef1f655e2cd3e2 Mon Sep 17 00:00:00 2001 From: Stiffly Date: Mon, 12 May 2014 22:21:27 +0200 Subject: [PATCH 58/65] Emitter childed to a wheel. BUG FIXED: Billboarding calculation. --- assets | 2 +- src/GameWorld.cpp | 33 +++++++++++++++++-- src/Renderer.cpp | 10 +++--- src/Systems/ParticleSystem.cpp | 15 +++++---- src/Systems/ParticleSystem.h | 7 +++- .../Returngeance/Returngeance.vcxproj.filters | 3 -- 6 files changed, 52 insertions(+), 18 deletions(-) diff --git a/assets b/assets index 8b6c48b..e2b54e6 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit 8b6c48b26b3bbc10f5e66c1f59fec6ca935f641b +Subproject commit e2b54e6212eb1233e6f9935b9e5d7c0295f9ffc6 diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index 979376b..1cae957 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -436,6 +436,31 @@ void GameWorld::Initialize() Wheel->ConnectedToHandbrake = true; Wheel->TorqueRatio = 0.125f; CommitEntity(wheel); + + auto entity = CreateEntity(wheel); + auto transformComponent = AddComponent(entity, "Transform"); + /*transformComponent->Position = glm::vec3(0,3,0);*/ + transformComponent->Scale = glm::vec3(3,3,3); + transformComponent->Orientation = glm::angleAxis(glm::pi()/2, glm::vec3(1,0,0)); + auto emitterComponent = AddComponent(entity, "ParticleEmitter"); + emitterComponent->SpawnCount = 2; + emitterComponent->SpawnFrequency = 0.01; + emitterComponent->SpreadAngle = glm::pi()/4; + emitterComponent->UseGoalVelocity = false; + emitterComponent->LifeTime = 2.0; + emitterComponent->ScaleSpectrum.push_back(glm::vec3(0.1)); + auto modelComponent = AddComponent(entity, "Model"); + modelComponent->ModelFile = "Models/Placeholders/PhysicsTest/PointLight.obj"; + CommitEntity(entity); + + auto particleEntity = CreateEntity(entity); + auto TEMP = AddComponent(particleEntity, "Transform"); + TEMP->Scale = glm::vec3(0); + auto spriteComponent = AddComponent(particleEntity, "Sprite"); + spriteComponent->SpriteFile = "Models/Textures/Sprites/Dust.png"; + emitterComponent->ParticleTemplate = particleEntity; + + CommitEntity(particleEntity); } CommitEntity(tank); @@ -528,6 +553,10 @@ void GameWorld::Initialize() GetSystem("SoundSystem")->PlaySound(emitter); CommitEntity(entity); }*/ + + { + + } } void GameWorld::Update(double dt) @@ -548,7 +577,7 @@ void GameWorld::RegisterSystems() m_SystemFactory.Register("InputSystem", [this]() { return new Systems::InputSystem(this, m_EventBroker); }); m_SystemFactory.Register("DebugSystem", [this]() { return new Systems::DebugSystem(this, m_EventBroker); }); //m_SystemFactory.Register("CollisionSystem", [this]() { return new Systems::CollisionSystem(this); }); - ////m_SystemFactory.Register("ParticleSystem", [this]() { return new Systems::ParticleSystem(this); }); + m_SystemFactory.Register("ParticleSystem", [this]() { return new Systems::ParticleSystem(this, m_EventBroker); }); //m_SystemFactory.Register("PlayerSystem", [this]() { return new Systems::PlayerSystem(this); }); m_SystemFactory.Register("FreeSteeringSystem", [this]() { return new Systems::FreeSteeringSystem(this, m_EventBroker); }); m_SystemFactory.Register("TankSteeringSystem", [this]() { return new Systems::TankSteeringSystem(this, m_EventBroker); }); @@ -564,7 +593,7 @@ void GameWorld::AddSystems() AddSystem("InputSystem"); AddSystem("DebugSystem"); //AddSystem("CollisionSystem"); - ////AddSystem("ParticleSystem"); + AddSystem("ParticleSystem"); //AddSystem("PlayerSystem"); AddSystem("FreeSteeringSystem"); AddSystem("TankSteeringSystem"); diff --git a/src/Renderer.cpp b/src/Renderer.cpp index 99f27a9..2905891 100755 --- a/src/Renderer.cpp +++ b/src/Renderer.cpp @@ -274,10 +274,9 @@ void Renderer::DrawScene() glm::mat4 billboardMatrix; std::tie(texture, modelMatrix, billboardMatrix) = tuple; - //MVP = cameraMatrix * glm::inverse(glm::toMat4(m_Camera->Orientation()) * modelMatrix ); - MVP = cameraMatrix * billboardMatrix * modelMatrix; - + MVP = cameraMatrix * modelMatrix * billboardMatrix; + depthMVP = depthCameraMatrix * modelMatrix; glUniformMatrix4fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "MVP"), 1, GL_FALSE, glm::value_ptr(MVP)); glUniformMatrix4fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "DepthMVP"), 1, GL_FALSE, glm::value_ptr(depthMVP)); @@ -410,11 +409,12 @@ void Renderer::AddTextureToDraw(Texture* texture, glm::vec3 position, glm::quat glm::vec3 camToParticle = glm::normalize(m_Camera->Position() - position); glm::vec3 up = glm::vec3(0,1,0); - glm::vec3 rightVec = glm::cross(up, camToParticle); + glm::vec3 rightVec = glm::normalize(glm::cross(up, camToParticle)); + glm::vec3 up2 = glm::normalize(glm::cross(camToParticle, rightVec)); glm::mat4 billboardMatrix; billboardMatrix[0] = glm::vec4(rightVec, 0); - billboardMatrix[1] = glm::vec4(up, 0); + billboardMatrix[1] = glm::vec4(up2, 0); billboardMatrix[2] = glm::vec4(camToParticle, 0); //billboardMatrix[3] = glm::vec4(position, 0); diff --git a/src/Systems/ParticleSystem.cpp b/src/Systems/ParticleSystem.cpp index e77e9c9..0882f9d 100644 --- a/src/Systems/ParticleSystem.cpp +++ b/src/Systems/ParticleSystem.cpp @@ -4,6 +4,11 @@ #include "World.h" +void Systems::ParticleSystem::Initialize() +{ + m_TransformSystem = m_World->GetSystem("TransformSystem"); +} + void Systems::ParticleSystem::Update(double dt) { @@ -19,16 +24,13 @@ void Systems::ParticleSystem::UpdateEntity(double dt, EntityID entity, EntityID if(emitterComponent) { emitterComponent->TimeSinceLastSpawn += dt; - auto transformComponent = m_World->GetComponent(entity, "Transform"); + auto emitterTransformComponent = m_World->GetComponent(entity, "Transform"); if(emitterComponent->TimeSinceLastSpawn > emitterComponent->SpawnFrequency) { SpawnParticles(entity); emitterComponent->TimeSinceLastSpawn = 0; } - - - std::list::iterator it; for(it = m_ParticleEmitter[entity].begin(); it != m_ParticleEmitter[entity].end();) { @@ -82,7 +84,7 @@ void Systems::ParticleSystem::UpdateEntity(double dt, EntityID entity, EntityID } - transformComponent->Position += transformComponent->Velocity * (float)dt; + transformComponent->Position += transformComponent->Velocity * (float)dt; it++; } @@ -101,6 +103,7 @@ void Systems::ParticleSystem::SpawnParticles(EntityID emitterID) { auto emitterComponent = m_World->GetComponent(emitterID, "ParticleEmitter"); auto emitterTransform = m_World->GetComponent(emitterID, "Transform"); + glm::vec3 emitterPos = m_TransformSystem->AbsolutePosition(emitterID); glm::quat emitterOrientation = emitterTransform->Orientation; float tempSpeed = 4; @@ -111,7 +114,7 @@ void Systems::ParticleSystem::SpawnParticles(EntityID emitterID) auto ent = m_World->CloneEntity(emitterComponent->ParticleTemplate); auto particleTransform = m_World->GetComponent(ent, "Transform"); - particleTransform->Position = emitterTransform->Position; + particleTransform->Position = emitterPos; particleTransform->Orientation = emitterOrientation; //The emitter's orientation as "start value" times the default direction for emitter. Times the speed, and then rotate on x and y axis with the randomized spread angle. diff --git a/src/Systems/ParticleSystem.h b/src/Systems/ParticleSystem.h index d976105..06cbe63 100644 --- a/src/Systems/ParticleSystem.h +++ b/src/Systems/ParticleSystem.h @@ -2,6 +2,7 @@ #define ParticleSystem_h__ #include "System.h" +#include "Systems/TransformSystem.h" #include "Components/Transform.h" #include "Components/ParticleEmitter.h" #include "Components/Particle.h" @@ -25,10 +26,13 @@ namespace Systems class ParticleSystem : public System { public: - ParticleSystem(World* world); + ParticleSystem(World* world, std::shared_ptr<::EventBroker> eventBroker) + : System(world, eventBroker) { } + void RegisterComponents(ComponentFactory* cf) override; void Update(double dt) override; void UpdateEntity(double dt, EntityID entity, EntityID parent) override; + void Initialize() override; private: void SpawnParticles(EntityID emitterID); float RandomizeAngle(float spreadAngle); @@ -39,6 +43,7 @@ private: void Billboard(); std::map> m_ParticleEmitter; std::map m_TimeSinceLastSpawn; + std::shared_ptr m_TransformSystem; }; diff --git a/vs11/Returngeance/Returngeance.vcxproj.filters b/vs11/Returngeance/Returngeance.vcxproj.filters index 4128eef..cd6fb6b 100755 --- a/vs11/Returngeance/Returngeance.vcxproj.filters +++ b/vs11/Returngeance/Returngeance.vcxproj.filters @@ -273,9 +273,6 @@ Particle System\Components - - Physics\Components - GUI From 92e9fd10495b121eaea2fd1e43f65d979c6b56a9 Mon Sep 17 00:00:00 2001 From: ViktorLjung Date: Mon, 12 May 2014 22:24:53 +0200 Subject: [PATCH 59/65] fixup! Fixed relative transform rotations (For real this time?) --- src/Systems/TransformSystem.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Systems/TransformSystem.cpp b/src/Systems/TransformSystem.cpp index ba9bbb1..3eccc26 100755 --- a/src/Systems/TransformSystem.cpp +++ b/src/Systems/TransformSystem.cpp @@ -24,10 +24,10 @@ glm::vec3 Systems::TransformSystem::AbsolutePosition(EntityID entity) //absPosition += transform->Position; entity = m_World->GetEntityParent(entity); auto transform2 = m_World->GetComponent(entity, "Transform"); - if (entity != 0) - absPosition += transform2->Orientation * transform->Position; - else + if (entity == 0) absPosition += transform->Position; + else + absPosition = transform2->Orientation * (absPosition + transform->Position); } while (entity != 0); return absPosition * accumulativeOrientation; From 38482431a1b07a79d2483862b3defdb4a5773cf6 Mon Sep 17 00:00:00 2001 From: ViktorLjung Date: Mon, 12 May 2014 22:33:53 +0200 Subject: [PATCH 60/65] Tank tower and barrel steering working --- src/Components/BarrelSteering.h | 20 ++++ src/Components/TowerSteering.h | 20 ++++ src/Components/Vehicle.h | 3 +- src/Events/BindKey.h | 3 + src/Events/InputCommand.h | 2 +- src/GameWorld.cpp | 73 ++++++++----- src/GameWorld.h | 6 +- src/Physics/VehicleSetup.cpp | 9 +- src/Systems/InputSystem.cpp | 27 +++-- src/Systems/InputSystem.h | 6 +- src/Systems/PhysicsSystem.cpp | 11 +- src/Systems/PhysicsSystem.h | 1 + src/Systems/TankSteeringSystem.cpp | 103 +++++++++++------- src/Systems/TankSteeringSystem.h | 45 +++++++- src/World.h | 5 + vs11/Returngeance/Returngeance.vcxproj | 2 + .../Returngeance/Returngeance.vcxproj.filters | 6 + 17 files changed, 246 insertions(+), 96 deletions(-) create mode 100644 src/Components/BarrelSteering.h create mode 100644 src/Components/TowerSteering.h diff --git a/src/Components/BarrelSteering.h b/src/Components/BarrelSteering.h new file mode 100644 index 0000000..58ab2fa --- /dev/null +++ b/src/Components/BarrelSteering.h @@ -0,0 +1,20 @@ +#ifndef BarrelSteering_h__ +#define BarrelSteering_h__ + +#include "Component.h" + +namespace Components +{ + + struct BarrelSteering : Component + { + BarrelSteering() + : Velocity(1.f), Axis(glm::vec3(0,1,0)){ } + + float Velocity; + glm::vec3 Axis; + }; + +} + +#endif // BarrelSteering_h__ \ No newline at end of file diff --git a/src/Components/TowerSteering.h b/src/Components/TowerSteering.h new file mode 100644 index 0000000..38a2320 --- /dev/null +++ b/src/Components/TowerSteering.h @@ -0,0 +1,20 @@ +#ifndef TowerSteering_h__ +#define TowerSteering_h__ + +#include "Component.h" + + namespace Components +{ + +struct TowerSteering : Component +{ + TowerSteering() + : Velocity(1.f), Axis(glm::vec3(0,1,0)){ } + + float Velocity; + glm::vec3 Axis; +}; + +} + +#endif // TowerSteering_h__ \ No newline at end of file diff --git a/src/Components/Vehicle.h b/src/Components/Vehicle.h index 388d9f2..6522a1f 100644 --- a/src/Components/Vehicle.h +++ b/src/Components/Vehicle.h @@ -11,7 +11,7 @@ struct Vehicle : Component { Vehicle() : MaxTorque(1000.0f), MinRPM(1000.0f), OptimalRPM(3000.0f), MaxRPM(4000.0f), MaxSteeringAngle(35), TopSpeed(130.0f), - MaxSpeedFullSteeringAngle(40.0f){ } + MaxSpeedFullSteeringAngle(40.0f), SpringDamping(1.f){ } float MaxTorque; float MinRPM; @@ -22,6 +22,7 @@ struct Vehicle : Component //TopSpeed not working fully yet float TopSpeed; float MaxSpeedFullSteeringAngle; + float SpringDamping; }; } diff --git a/src/Events/BindKey.h b/src/Events/BindKey.h index a774942..17c786f 100644 --- a/src/Events/BindKey.h +++ b/src/Events/BindKey.h @@ -1,6 +1,8 @@ #ifndef Events_BindKey_h__ #define Events_BindKey_h__ +#include + #include "EventBroker.h" namespace Events @@ -10,6 +12,7 @@ struct BindKey : Event { int KeyCode; std::string Command; + float Value; }; } diff --git a/src/Events/InputCommand.h b/src/Events/InputCommand.h index bd18f6a..cde1dab 100644 --- a/src/Events/InputCommand.h +++ b/src/Events/InputCommand.h @@ -12,7 +12,7 @@ struct InputCommand : Event { unsigned int PlayerID; std::string Command; - boost::any Value; + float Value; }; } diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index 979376b..2d743f9 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -8,11 +8,25 @@ void GameWorld::Initialize() m_ResourceManager.Preload("Model", "Models/Placeholders/PhysicsTest/Plane.obj"); m_ResourceManager.Preload("Model", "Models/Placeholders/PhysicsTest/ArrowCube.obj"); - BindKey(GLFW_KEY_W, "+forward"); - BindKey(GLFW_KEY_S, "+backward"); - BindKey(GLFW_KEY_A, "+left"); - BindKey(GLFW_KEY_D, "+right"); - BindKey(GLFW_KEY_SPACE, "+handbrake"); + BindKey(GLFW_KEY_W, "vertical", -1.f); + BindKey(GLFW_KEY_S, "vertical", 1.f); + BindKey(GLFW_KEY_A, "horizontal", -1.f); + BindKey(GLFW_KEY_D, "horizontal", 1.f); + + BindKey(GLFW_KEY_UP, "barrel_rotation", 1.f); + BindKey(GLFW_KEY_DOWN, "barrel_rotation", -1.f); + BindKey(GLFW_KEY_LEFT, "tower_rotation", 1.f); + BindKey(GLFW_KEY_RIGHT, "tower_rotation", -1.f); + + BindKey(GLFW_KEY_SPACE, "handbrake", 1.f); +// +// BindKey(GLFW_KEY_UP, "vertical", -1.f); +// BindKey(GLFW_KEY_DOWN, "vertical", 1.f); +// BindKey(GLFW_KEY_LEFT, "horizontal", -1.f); +// BindKey(GLFW_KEY_RIGHT, "horizontal", 1.f); + /* + BindKey(GLFW_KEY_Q, "+tower_right"); + BindKey(GLFW_KEY_E, "+tower_left"); BindKey(GLFW_KEY_Q, "+up"); BindKey(GLFW_KEY_LEFT_CONTROL, "+down"); @@ -25,8 +39,8 @@ void GameWorld::Initialize() BindKey(GLFW_KEY_UP, "+cam_forward"); BindKey(GLFW_KEY_DOWN, "+cam_backward"); - BindKey(GLFW_KEY_LEFT, "+cam_right"); - BindKey(GLFW_KEY_RIGHT, "+cam_left"); + BindKey(GLFW_KEY_LEFT, "+cam_left"); + BindKey(GLFW_KEY_RIGHT, "+cam_right");*/ RegisterComponents(); @@ -242,23 +256,29 @@ void GameWorld::Initialize() { auto chassis = CreateEntity(tank); auto transform = AddComponent(chassis, "Transform"); - transform->Position = glm::vec3(0, 0, 0); // 0.6577f + transform->Position = glm::vec3(0, 0, 0); auto model = AddComponent(chassis, "Model"); model->ModelFile = "Models/Tank/Fix/Chassi.obj"; } { - auto top = CreateEntity(tank); - auto transform = AddComponent(top, "Transform"); - transform->Position = glm::vec3(0, 1.2, 1.95); // 0.6577f - auto model = AddComponent(top, "Model"); + auto tower = CreateEntity(tank); + SetProperty(tower, "Name", "tower"); + auto transform = AddComponent(tower, "Transform"); + transform->Position = glm::vec3(0, 1.2, 1.95); + auto model = AddComponent(tower, "Model"); model->ModelFile = "Models/Tank/Fix/Top.obj"; - + auto towerSteering = AddComponent(tower, "TowerSteering"); + towerSteering->Axis = glm::vec3(0.f, 1.f, 0.f); + towerSteering->Velocity = glm::pi()/4.f; { - auto top = CreateEntity(tank); - auto transform = AddComponent(top, "Transform"); - transform->Position = glm::vec3(0, 1, 0.5); // 0.6577f - auto model = AddComponent(top, "Model"); + auto barrel = CreateEntity(tower); + auto transform = AddComponent(barrel, "Transform"); + transform->Position = glm::vec3(0, 0, -2.f); + auto model = AddComponent(barrel, "Model"); model->ModelFile = "Models/Tank/Fix/Barrel.obj"; + auto barrelSteering = AddComponent(barrel, "BarrelSteering"); + barrelSteering->Axis = glm::vec3(1.f, 0.f, 0.f); + barrelSteering->Velocity = glm::pi()/4.f; } } @@ -297,7 +317,7 @@ void GameWorld::Initialize() Wheel->Radius = 0.6f; Wheel->Steering = true; Wheel->SuspensionStrength = suspensionStrength; - Wheel->Friction = 3.f; + Wheel->Friction = 4.f; Wheel->ConnectedToHandbrake = true; Wheel->TorqueRatio = 0.125f; CommitEntity(wheel); @@ -316,7 +336,7 @@ void GameWorld::Initialize() Wheel->Radius = 0.6f; Wheel->Steering = false; Wheel->SuspensionStrength = suspensionStrength; - Wheel->Friction = 3.f; + Wheel->Friction = 4.f; Wheel->ConnectedToHandbrake = true; Wheel->TorqueRatio = 0.125f; CommitEntity(wheel); @@ -336,7 +356,7 @@ void GameWorld::Initialize() Wheel->Radius = 0.6f; Wheel->Steering = true; Wheel->SuspensionStrength = suspensionStrength; - Wheel->Friction = 3.f; + Wheel->Friction = 4.f; Wheel->ConnectedToHandbrake = true; Wheel->TorqueRatio = 0.125f; CommitEntity(wheel); @@ -355,7 +375,7 @@ void GameWorld::Initialize() Wheel->Radius = 0.6f; Wheel->Steering = false; Wheel->SuspensionStrength = suspensionStrength; - Wheel->Friction = 3.f; + Wheel->Friction = 4.f; Wheel->ConnectedToHandbrake = true; Wheel->TorqueRatio = 0.125f; CommitEntity(wheel); @@ -376,7 +396,7 @@ void GameWorld::Initialize() Wheel->Radius = 0.6f; Wheel->Steering = false; Wheel->SuspensionStrength = suspensionStrength; - Wheel->Friction = 3.f; + Wheel->Friction = 4.f; Wheel->ConnectedToHandbrake = true; Wheel->TorqueRatio = 0.125f; CommitEntity(wheel); @@ -394,7 +414,7 @@ void GameWorld::Initialize() Wheel->Radius = 0.6f; Wheel->Steering = false; Wheel->SuspensionStrength = suspensionStrength; - Wheel->Friction = 3.f; + Wheel->Friction = 4.f; Wheel->ConnectedToHandbrake = true; Wheel->TorqueRatio = 0.125f; CommitEntity(wheel); @@ -414,7 +434,7 @@ void GameWorld::Initialize() Wheel->Radius = 0.6f; Wheel->Steering = false; Wheel->SuspensionStrength = suspensionStrength; - Wheel->Friction = 3.f; + Wheel->Friction = 4.f; Wheel->ConnectedToHandbrake = true; Wheel->TorqueRatio = 0.125f; CommitEntity(wheel); @@ -432,7 +452,7 @@ void GameWorld::Initialize() Wheel->Radius = 0.6f; Wheel->Steering = false; Wheel->SuspensionStrength = suspensionStrength; - Wheel->Friction = 3.f; + Wheel->Friction = 4.f; Wheel->ConnectedToHandbrake = true; Wheel->TorqueRatio = 0.125f; CommitEntity(wheel); @@ -573,11 +593,12 @@ void GameWorld::AddSystems() AddSystem("RenderSystem"); } -void GameWorld::BindKey(int keyCode, std::string command) +void GameWorld::BindKey(int keyCode, std::string command, float value) { Events::BindKey e; e.KeyCode = keyCode; e.Command = command; + e.Value = value; m_EventBroker->Publish(e); } diff --git a/src/GameWorld.h b/src/GameWorld.h index 6e9c9e4..2dfcb96 100755 --- a/src/GameWorld.h +++ b/src/GameWorld.h @@ -34,6 +34,10 @@ #include "Components/Vehicle.h" #include "Components/Wheel.h" #include "Components/HingeConstraint.h" +#include "Components/TankSteering.h" +#include "Components/TowerSteering.h" +#include "Components/BarrelSteering.h" + class GameWorld : public World { @@ -52,7 +56,7 @@ public: private: std::shared_ptr m_Renderer; - void BindKey(int keyCode, std::string command); + void BindKey(int keyCode, std::string command, float value); void BindMouseButton(int button, std::string command); }; diff --git a/src/Physics/VehicleSetup.cpp b/src/Physics/VehicleSetup.cpp index 1babfcb..90e65dc 100644 --- a/src/Physics/VehicleSetup.cpp +++ b/src/Physics/VehicleSetup.cpp @@ -104,7 +104,7 @@ void VehicleSetup::setupVehicleData(const hkpWorld* world, hkpVehicleData& data data.m_torquePitchFactor = 0.5f; data.m_torqueYawFactor = 0.35f; - data.m_chassisUnitInertiaYaw = 1.0f; + data.m_chassisUnitInertiaYaw = 0.8f; data.m_chassisUnitInertiaRoll = 1.0f; data.m_chassisUnitInertiaPitch = 1.0f; @@ -246,9 +246,8 @@ void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultS suspension.m_wheelParams[i].m_length = suspensionLength; suspension.m_wheelSpringParams[i].m_strength = m_Wheels[i].WheelComponent->SuspensionStrength; - const float wd = 3.0f; - suspension.m_wheelSpringParams[i].m_dampingCompression = wd; - suspension.m_wheelSpringParams[i].m_dampingRelaxation = wd; + suspension.m_wheelSpringParams[i].m_dampingCompression = vehicleComponent.SpringDamping; + suspension.m_wheelSpringParams[i].m_dampingRelaxation = vehicleComponent.SpringDamping; suspension.m_wheelParams[i].m_hardpointChassisSpace.set(m_Wheels[i].WheelComponent->Hardpoint.x, m_Wheels[i].WheelComponent->Hardpoint.y, m_Wheels[i].WheelComponent->Hardpoint.z); @@ -285,7 +284,7 @@ void VehicleSetup::setupComponent(const hkpVehicleData& data, hkpVehicleDefaultV // The threshold in m/s at which the algorithm switches from // using the normalSpinDamping to the collisionSpinDamping. - velocityDamper.m_collisionThreshold = 100.0f; + velocityDamper.m_collisionThreshold = 1.0f; } void VehicleSetup::setupWheelCollide(const hkpWorld* world, const hkpVehicleInstance& vehicle, hkpVehicleRayCastWheelCollide& wheelCollide) diff --git a/src/Systems/InputSystem.cpp b/src/Systems/InputSystem.cpp index 18a21aa..4868213 100755 --- a/src/Systems/InputSystem.cpp +++ b/src/Systems/InputSystem.cpp @@ -44,7 +44,11 @@ bool Systems::InputSystem::OnKeyDown(const Events::KeyDown &event) auto bindingIt = m_KeyBindings.find(event.KeyCode); if (bindingIt != m_KeyBindings.end()) { - PublishCommand(0, bindingIt->second, 1.f, false); + std::string command; + float value; + std::tie(command, value) = bindingIt->second; + m_KeyBindingValues[command] += value; + PublishCommand(0, command, std::max(-1.f, std::min(m_KeyBindingValues[command], 1.f))); } return true; @@ -55,7 +59,11 @@ bool Systems::InputSystem::OnKeyUp(const Events::KeyUp &event) auto bindingIt = m_KeyBindings.find(event.KeyCode); if (bindingIt != m_KeyBindings.end()) { - PublishCommand(0, bindingIt->second, 1.f, true); + std::string command; + float value; + std::tie(command, value) = bindingIt->second; + m_KeyBindingValues[command] -= value; + PublishCommand(0, command, std::max(-1.f, std::min(m_KeyBindingValues[command], 1.f))); } return true; @@ -66,7 +74,7 @@ bool Systems::InputSystem::OnMousePress(const Events::MousePress &event) auto bindingIt = m_MouseButtonBindings.find(event.Button); if (bindingIt != m_MouseButtonBindings.end()) { - PublishCommand(0, bindingIt->second, 1.f, false); + PublishCommand(0, bindingIt->second, 1.f); } return true; @@ -77,7 +85,7 @@ bool Systems::InputSystem::OnMouseRelease(const Events::MouseRelease &event) auto bindingIt = m_MouseButtonBindings.find(event.Button); if (bindingIt != m_MouseButtonBindings.end()) { - PublishCommand(0, bindingIt->second, 1.f, true); + PublishCommand(0, bindingIt->second, 1.f); } return true; @@ -91,7 +99,7 @@ bool Systems::InputSystem::OnBindKey(const Events::BindKey &event) } else { - m_KeyBindings[event.KeyCode] = event.Command; + m_KeyBindings[event.KeyCode] = std::make_tuple(event.Command, event.Value); LOG_DEBUG("Input: Bound key %c to %s", (char)event.KeyCode, event.Command.c_str()); } @@ -113,18 +121,13 @@ bool Systems::InputSystem::OnBindMouseButton(const Events::BindMouseButton &even return true; } -void Systems::InputSystem::PublishCommand(int playerID, std::string command, float value, bool release /*= false*/) +void Systems::InputSystem::PublishCommand(int playerID, std::string command, float value) { - if (release && command.at(0) == '+') - { - command[0] = '-'; - } - Events::InputCommand e; e.PlayerID = playerID; e.Command = command; e.Value = value; EventBroker->Publish(e); - LOG_DEBUG("Input: Published command %s for player %i", e.Command.c_str(), playerID); + LOG_DEBUG("Input: Published command %s=%f for player %i", e.Command.c_str(), e.Value, playerID); } diff --git a/src/Systems/InputSystem.h b/src/Systems/InputSystem.h index f912de0..b9461a2 100755 --- a/src/Systems/InputSystem.h +++ b/src/Systems/InputSystem.h @@ -3,6 +3,7 @@ #include #include +#include #include "System.h" #include "Components/Input.h" @@ -30,7 +31,8 @@ public: private: // Input binding tables - std::unordered_map m_KeyBindings; // GLFW_KEY... -> command string + std::unordered_map> m_KeyBindings; // GLFW_KEY... -> command string & value + std::unordered_map m_KeyBindingValues; // command string -> command value std::unordered_map m_MouseButtonBindings; // GLFW_MOUSE_BUTTON... -> command string // Input events @@ -48,7 +50,7 @@ private: EventRelay m_EBindMouseButton; bool OnBindMouseButton(const Events::BindMouseButton &event); - void PublishCommand(int playerID, std::string command, float value, bool release = false); + void PublishCommand(int playerID, std::string command, float value); }; } diff --git a/src/Systems/PhysicsSystem.cpp b/src/Systems/PhysicsSystem.cpp index 5fad34c..02259ad 100644 --- a/src/Systems/PhysicsSystem.cpp +++ b/src/Systems/PhysicsSystem.cpp @@ -31,7 +31,7 @@ void Systems::PhysicsSystem::Initialize() // Events EVENT_SUBSCRIBE_MEMBER(m_ETankSteer, &Systems::PhysicsSystem::OnTankSteer); - + hkMemorySystem::FrameInfo finfo(6000 * 1024); // Allocate 6MB of Physics solver buffer hkMemoryRouter* memoryRouter = hkMemoryInitUtil::initDefault(hkMallocAllocator::m_defaultMallocAllocator, finfo); hkBaseSystem::init(memoryRouter, HavokErrorReport); @@ -115,7 +115,6 @@ void Systems::PhysicsSystem::RegisterComponents(ComponentFactory* cf) cf->Register("MeshShape", []() { return new Components::MeshShape(); }); cf->Register("HingeConstraint", []() { return new Components::HingeConstraint(); }); cf->Register("WheelPair", []() { return new Components::WheelPair(); }); - } void Systems::PhysicsSystem::Update(double dt) @@ -550,7 +549,9 @@ glm::quat Systems::PhysicsSystem::ConvertRotation(const hkQuaternion &hkRotation const hkQuaternion& Systems::PhysicsSystem::ConvertRotation(glm::quat glmRotation) { - return hkQuaternion(glmRotation.x, glmRotation.y, glmRotation.z, glmRotation.w); + hkQuaternion quat = hkQuaternion(glmRotation.x, glmRotation.y, glmRotation.z, glmRotation.w); + quat.normalize(); + return quat; } glm::vec3 Systems::PhysicsSystem::ConvertScale(const hkVector4 &hkScale) @@ -566,8 +567,7 @@ const hkVector4& Systems::PhysicsSystem::ConvertScale(glm::vec3 glmScale) bool Systems::PhysicsSystem::OnTankSteer(const Events::TankSteer &event) { auto vehicleComponent = m_World->GetComponent(event.Entity, "Vehicle"); - auto inputComponent = m_World->GetComponent(event.Entity, "Input"); - if (vehicleComponent && inputComponent && m_Vehicles.find(event.Entity) != m_Vehicles.end() && m_RigidBodies.find(event.Entity) != m_RigidBodies.end()) + if (vehicleComponent && m_Vehicles.find(event.Entity) != m_Vehicles.end() && m_RigidBodies.find(event.Entity) != m_RigidBodies.end()) { m_PhysicsWorld->markForWrite(); hkpVehicleDriverInputAnalogStatus* deviceStatus = (hkpVehicleDriverInputAnalogStatus*)m_Vehicles[event.Entity]->m_deviceStatus; @@ -579,4 +579,3 @@ bool Systems::PhysicsSystem::OnTankSteer(const Events::TankSteer &event) return true; } - diff --git a/src/Systems/PhysicsSystem.h b/src/Systems/PhysicsSystem.h index b8fc262..968db95 100644 --- a/src/Systems/PhysicsSystem.h +++ b/src/Systems/PhysicsSystem.h @@ -12,6 +12,7 @@ #include "Components/MeshShape.h" #include "Components/HingeConstraint.h" #include "Components/WheelPair.h" +#include "Components/TowerSteering.h" #include "Events/TankSteer.h" #include "OBJ.h" diff --git a/src/Systems/TankSteeringSystem.cpp b/src/Systems/TankSteeringSystem.cpp index f0a4e30..eee50cc 100644 --- a/src/Systems/TankSteeringSystem.cpp +++ b/src/Systems/TankSteeringSystem.cpp @@ -5,19 +5,20 @@ void Systems::TankSteeringSystem::RegisterComponents( ComponentFactory* cf ) { cf->Register("TankSteering", []() { return new Components::TankSteering(); }); + cf->Register("TowerSteering", []() { return new Components::TowerSteering(); }); + cf->Register("BarrelSteering", []() { return new Components::BarrelSteering(); }); } void Systems::TankSteeringSystem::Initialize() { - m_InputController = std::unique_ptr(new TankSteeringInputController(EventBroker)); - m_InputController->PositionX = 0; - m_InputController->PositionY = 0; - m_InputController->Handbrake = false; + m_TankInputController = std::unique_ptr(new TankSteeringInputController(EventBroker)); + m_TowerInputController = std::unique_ptr(new TowerSteeringInputController(EventBroker)); } void Systems::TankSteeringSystem::Update(double dt) { - + m_TankInputController->Update(dt); + m_TowerInputController->Update(dt); } void Systems::TankSteeringSystem::UpdateEntity(double dt, EntityID entity, EntityID parent) @@ -27,61 +28,85 @@ void Systems::TankSteeringSystem::UpdateEntity(double dt, EntityID entity, Entit { Events::TankSteer e; e.Entity = entity; - e.PositionX = m_InputController->PositionX; - e.PositionY = m_InputController->PositionY; - e.Handbrake = m_InputController->Handbrake; + e.PositionX = m_TankInputController->PositionX; + e.PositionY = m_TankInputController->PositionY; + e.Handbrake = m_TankInputController->Handbrake; EventBroker->Publish(e); } + + auto towerSteeringComponent = m_World->GetComponent(entity, "TowerSteering"); + if(towerSteeringComponent) + { + auto transformComponent = m_World->GetComponent(entity, "Transform"); + glm::quat orientation = glm::angleAxis(towerSteeringComponent->Velocity * m_TowerInputController->TowerDirection * (float)dt, towerSteeringComponent->Axis); + transformComponent->Orientation *= orientation; + } + + auto barrelSteeringComponent = m_World->GetComponent(entity, "BarrelSteering"); + if(barrelSteeringComponent) + { + auto transformComponent = m_World->GetComponent(entity, "Transform"); + glm::quat orientation = glm::angleAxis(barrelSteeringComponent->Velocity * m_TowerInputController->BarrelDirection * (float)dt, barrelSteeringComponent->Axis); + transformComponent->Orientation *= orientation; + } +} + +void Systems::TankSteeringSystem::TankSteeringInputController::Update( double dt ) +{ + PositionX = m_Horizontal; + PositionY = m_Vertical; +} + +void Systems::TankSteeringSystem::TowerSteeringInputController::Update( double dt ) +{ + TowerDirection = m_TowerDirection; + BarrelDirection = m_BarrelDirection; } bool Systems::TankSteeringSystem::TankSteeringInputController::OnCommand(const Events::InputCommand &event) { - float val = boost::any_cast(event.Value); - if (event.Command == "+right") + float val = event.Value; + if (event.Command == "horizontal") { - PositionX += val; + m_Horizontal = val; } - else if (event.Command == "-right") + else if (event.Command == "vertical") { - PositionX -= val; + m_Vertical = val; } - else if (event.Command == "+left") + + else if (event.Command == "handbrake") { - PositionX += -val; - } - else if (event.Command == "-left") - { - PositionX -= -val; - } - else if (event.Command == "+forward") - { - PositionY += -val; - } - else if (event.Command == "-forward") - { - PositionY -= -val; - } - else if (event.Command == "+backward") - { - PositionY += val; - } - else if (event.Command == "-backward") - { - PositionY -= val; + Handbrake = val; } - else if (event.Command == "+handbrake") + return true; +} + +bool Systems::TankSteeringSystem::TowerSteeringInputController::OnCommand( const Events::InputCommand &event ) +{ + float val = event.Value; + if(event.Command == "tower_rotation") { - Handbrake = true; + m_TowerDirection = val; } - else if (event.Command == "-handbrake") + else if(event.Command == "barrel_rotation") { - Handbrake = false; + m_BarrelDirection = val; } return true; } +bool Systems::TankSteeringSystem::TowerSteeringInputController::OnMouseMove( const Events::MouseMove &event ) +{ + return false; +} + bool Systems::TankSteeringSystem::TankSteeringInputController::OnMouseMove( const Events::MouseMove &event ) { return false; } + + + + diff --git a/src/Systems/TankSteeringSystem.h b/src/Systems/TankSteeringSystem.h index 5c7a02e..dee4707 100644 --- a/src/Systems/TankSteeringSystem.h +++ b/src/Systems/TankSteeringSystem.h @@ -4,6 +4,8 @@ #include "Events/TankSteer.h" #include "Components/Transform.h" #include "Components/TankSteering.h" +#include "Components/TowerSteering.h" +#include "Components/BarrelSteering.h" #include "Components/Vehicle.h" #include "InputController.h" @@ -24,22 +26,59 @@ namespace Systems private: class TankSteeringInputController; - std::unique_ptr m_InputController; + std::unique_ptr m_TankInputController; + class TowerSteeringInputController; + std::unique_ptr m_TowerInputController; }; class TankSteeringSystem::TankSteeringInputController : InputController { public: TankSteeringInputController(std::shared_ptr<::EventBroker> eventBroker) - : InputController(eventBroker) { } + : InputController(eventBroker) + { + m_Horizontal = 0.f; + m_Vertical = 0.f; + PositionX = 0; + PositionY = 0; + Handbrake = false; + } float PositionY; float PositionX; bool Handbrake; - + void Update(double dt); protected: virtual bool OnCommand(const Events::InputCommand &event); virtual bool OnMouseMove(const Events::MouseMove &event); + + private: + float m_Horizontal; + float m_Vertical; + }; + + class TankSteeringSystem::TowerSteeringInputController : InputController + { + public: + TowerSteeringInputController(std::shared_ptr<::EventBroker> eventBroker) + : InputController(eventBroker) + { + m_TowerDirection = 0.f; + m_BarrelDirection = 0.f; + TowerDirection = 0.f; + BarrelDirection = 0.f; + } + + float TowerDirection; + float BarrelDirection; + void Update(double dt); + protected: + virtual bool OnCommand(const Events::InputCommand &event); + virtual bool OnMouseMove(const Events::MouseMove &event); + + private: + float m_TowerDirection; + float m_BarrelDirection; }; } \ No newline at end of file diff --git a/src/World.h b/src/World.h index 3581be1..7ce77db 100755 --- a/src/World.h +++ b/src/World.h @@ -61,6 +61,11 @@ public: m_EntityProperties[entity][property] = value; } + void SetProperty(EntityID entity, std::string property, char* value) + { + m_EntityProperties[entity][property] = std::string(value); + } + template std::shared_ptr AddComponent(EntityID entity, std::string componentType); std::shared_ptr AddComponent(EntityID entity, std::string componentType); diff --git a/vs11/Returngeance/Returngeance.vcxproj b/vs11/Returngeance/Returngeance.vcxproj index 47fff50..9affcba 100755 --- a/vs11/Returngeance/Returngeance.vcxproj +++ b/vs11/Returngeance/Returngeance.vcxproj @@ -124,6 +124,7 @@ + @@ -141,6 +142,7 @@ + diff --git a/vs11/Returngeance/Returngeance.vcxproj.filters b/vs11/Returngeance/Returngeance.vcxproj.filters index 8b1f1a3..0323b51 100755 --- a/vs11/Returngeance/Returngeance.vcxproj.filters +++ b/vs11/Returngeance/Returngeance.vcxproj.filters @@ -322,6 +322,12 @@ Physics\Systems + + Physics\Components + + + Physics\Components + From ccd1393dac181e95f4500a0a24962f57e73db433 Mon Sep 17 00:00:00 2001 From: Tleety Date: Mon, 12 May 2014 23:02:19 +0200 Subject: [PATCH 61/65] Fixed some shadow buggs. --- src/Renderer.cpp | 14 +++++++------- src/Shaders/Fragment.glsl | 5 ++++- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/src/Renderer.cpp b/src/Renderer.cpp index 429e449..2e781a0 100755 --- a/src/Renderer.cpp +++ b/src/Renderer.cpp @@ -17,10 +17,10 @@ Renderer::Renderer() CAtt = 1.0f; LAtt = 0.0f; QAtt = 3.0f; - m_ShadowMapRes = 2048; + m_ShadowMapRes = 2048*8; m_SunPosition = glm::vec3(0, 3.5f, 10); m_SunTarget = glm::vec3(0, 0, 0); - m_SunProjection = glm::ortho(-100, 100, -100, 100, -100, 100); + m_SunProjection = glm::ortho(-200.f, 200.f, -200.f, 200.f, -100, 200); /* Lights = 0;*/ } @@ -256,7 +256,7 @@ void Renderer::DrawShadowMap() { glEnable(GL_DEPTH_TEST);//Tests where objects are and display them correctly glEnable(GL_CULL_FACE); //removes triangles on the wrong side of the object - glCullFace(GL_FRONT); //Make it so that only the back faces are rendered + glCullFace(GL_BACK); //Make it so that only the back faces are rendered //Binds the FBO and sets the veiwport, witch in effect is how large the shadowmap is and what resolution it has. glBindFramebuffer(GL_FRAMEBUFFER, m_ShadowFrameBuffer); @@ -653,7 +653,7 @@ void Renderer::DrawFBO() m_FinalPassProgram.Bind(); - // Ambient light & Shadow Matrix + // Ambient light glUniform3fv(glGetUniformLocation(m_FinalPassProgram.GetHandle(), "La"), 1, glm::value_ptr(glm::vec3(0.1f, 0.1f, 0.1f))); glUniform1f(glGetUniformLocation(m_FinalPassProgram.GetHandle(), "Gamma"), Gamma); @@ -670,9 +670,9 @@ void Renderer::DrawFBO() void Renderer::DrawFBOScene() { - glEnable(GL_DEPTH_TEST);//Tests where objects are and display them correctly - glEnable(GL_CULL_FACE); //removes triangles on the wrong side of the object - glCullFace(GL_BACK); //Make it so that only the back faces are rendered +// glEnable(GL_DEPTH_TEST);//Tests where objects are and display them correctly +// glEnable(GL_CULL_FACE); //removes triangles on the wrong side of the object +// glCullFace(GL_BACK); //Make it so that only the back faces are rendered glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); //Draws filled polygons glm::mat4 cameraMatrix = m_Camera->ProjectionMatrix() * m_Camera->ViewMatrix(); diff --git a/src/Shaders/Fragment.glsl b/src/Shaders/Fragment.glsl index e64e2ec..cc5370f 100755 --- a/src/Shaders/Fragment.glsl +++ b/src/Shaders/Fragment.glsl @@ -17,7 +17,10 @@ out vec4 frag_Normal; float Shadow(vec4 ShadowCoord) { - if( texture(ShadowTexture, Input.ShadowCoord.xy).z < ShadowCoord.z ) + //float cosTheta = clamp(dot(Input.Normal, 1.0), 0.0, 1.0); + float bias = 0.0005; // cosTheta is dot( n,l ), clamped between 0 and 1 + bias = clamp(bias, 0.0, 0.01); + if( texture(ShadowTexture, Input.ShadowCoord.xy).z < ShadowCoord.z - bias) { return 0.3; } From b9231e4d462af0b4592066854f48f179d66a0742 Mon Sep 17 00:00:00 2001 From: ViktorLjung Date: Tue, 13 May 2014 01:50:58 +0200 Subject: [PATCH 62/65] Shots need more work --- assets | 2 +- src/Components/BarrelSteering.h | 2 +- src/Components/Shot.h | 17 +++ src/Events/SetVelocity.h | 17 +++ src/GameWorld.cpp | 135 ++++++++++++++++-- src/GameWorld.h | 2 +- src/Systems/PhysicsSystem.cpp | 6 + src/Systems/PhysicsSystem.h | 4 + src/Systems/TankSteeringSystem.cpp | 19 +++ src/Systems/TankSteeringSystem.h | 9 +- vs11/Returngeance/Returngeance.vcxproj | 2 + .../Returngeance/Returngeance.vcxproj.filters | 6 + 12 files changed, 207 insertions(+), 14 deletions(-) create mode 100644 src/Components/Shot.h create mode 100644 src/Events/SetVelocity.h diff --git a/assets b/assets index 8b6c48b..05b3d22 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit 8b6c48b26b3bbc10f5e66c1f59fec6ca935f641b +Subproject commit 05b3d22b01131512cc370dacd507a22e88c46e57 diff --git a/src/Components/BarrelSteering.h b/src/Components/BarrelSteering.h index 58ab2fa..f3ee943 100644 --- a/src/Components/BarrelSteering.h +++ b/src/Components/BarrelSteering.h @@ -10,9 +10,9 @@ namespace Components { BarrelSteering() : Velocity(1.f), Axis(glm::vec3(0,1,0)){ } - float Velocity; glm::vec3 Axis; + EntityID ShotTemplate; }; } diff --git a/src/Components/Shot.h b/src/Components/Shot.h new file mode 100644 index 0000000..324a9c5 --- /dev/null +++ b/src/Components/Shot.h @@ -0,0 +1,17 @@ +#ifndef Shot_h__ +#define Shot_h__ + +#include "Component.h" + +namespace Components +{ + + struct Shot : Component + { + Shot(); + float Speed; + }; + +} + +#endif // Shot_h__ \ No newline at end of file diff --git a/src/Events/SetVelocity.h b/src/Events/SetVelocity.h new file mode 100644 index 0000000..3bdb8a1 --- /dev/null +++ b/src/Events/SetVelocity.h @@ -0,0 +1,17 @@ +#ifndef Events_SetVelocity_h__ +#define Events_SetVelocity_h__ +#include "Entity.h" +#include "EventBroker.h" + +namespace Events +{ + + struct SetVelocity : Event + { + EntityID Entity; + glm::vec3 Velocity; + }; + +} + +#endif // Events_SetVelocity_h__ \ No newline at end of file diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index 2d743f9..411d27f 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -19,6 +19,8 @@ void GameWorld::Initialize() BindKey(GLFW_KEY_RIGHT, "tower_rotation", -1.f); BindKey(GLFW_KEY_SPACE, "handbrake", 1.f); + + BindKey(GLFW_KEY_Z, "shoot", 1.f); // // BindKey(GLFW_KEY_UP, "vertical", -1.f); // BindKey(GLFW_KEY_DOWN, "vertical", 1.f); @@ -264,7 +266,7 @@ void GameWorld::Initialize() auto tower = CreateEntity(tank); SetProperty(tower, "Name", "tower"); auto transform = AddComponent(tower, "Transform"); - transform->Position = glm::vec3(0, 1.2, 1.95); + transform->Position = glm::vec3(0.f, 1.2f, 1.8f); auto model = AddComponent(tower, "Model"); model->ModelFile = "Models/Tank/Fix/Top.obj"; auto towerSteering = AddComponent(tower, "TowerSteering"); @@ -273,12 +275,37 @@ void GameWorld::Initialize() { auto barrel = CreateEntity(tower); auto transform = AddComponent(barrel, "Transform"); - transform->Position = glm::vec3(0, 0, -2.f); + transform->Position = glm::vec3(-0.018f, -0.2, -1.3f); auto model = AddComponent(barrel, "Model"); model->ModelFile = "Models/Tank/Fix/Barrel.obj"; auto barrelSteering = AddComponent(barrel, "BarrelSteering"); barrelSteering->Axis = glm::vec3(1.f, 0.f, 0.f); barrelSteering->Velocity = glm::pi()/4.f; + { + auto shot = CreateEntity(barrel); + auto transform = AddComponent(shot, "Transform"); + transform->Position = glm::vec3(0.35f, 1.f, -2.f); + auto shotComponent = AddComponent(shot, "Shot"); + shotComponent->Speed = 5; + auto physics = AddComponent(shot, "Physics"); + physics->Mass = 10.f; + physics->Static = false; + auto modelComponent = AddComponent(shot, "Model"); + modelComponent->ModelFile = "Models/Placeholders/PhysicsTest/Cube.obj"; + + { + auto shape = CreateEntity(tank); + auto transform = AddComponent(shape, "Transform"); + auto boxShape = AddComponent(shape, "BoxShape"); + boxShape->Width = 0.5f; + boxShape->Height = 0.5f; + boxShape->Depth = 0.5f; + CommitEntity(shape); + } + CommitEntity(shot); + barrelSteering->ShotTemplate = shot; + } + CommitEntity(barrel); } } @@ -306,7 +333,7 @@ void GameWorld::Initialize() { auto wheel = CreateEntity(tank); auto transform = AddComponent(wheel, "Transform"); - transform->Position = glm::vec3(1.88f, -0.83f - wheelOffset, -2.6f); + transform->Position = glm::vec3(1.68f, -0.83f - wheelOffset, -2.6f); transform->Orientation = glm::angleAxis(glm::pi(), glm::vec3(0, 1, 0)); auto model = AddComponent(wheel, "Model"); model->ModelFile = "Models/Tank/Fix/WheelPhysics.obj"; @@ -320,12 +347,23 @@ void GameWorld::Initialize() Wheel->Friction = 4.f; Wheel->ConnectedToHandbrake = true; Wheel->TorqueRatio = 0.125f; + Wheel->Width = 0.6f; + { + auto shape = CreateEntity(wheel); + auto shapetransform = AddComponent(shape, "Transform"); + shapetransform->Position = glm::vec3(0.f, 0.32f, 0.f) + transform->Position; + auto boxShape = AddComponent(shape, "BoxShape"); + boxShape->Width = 0.7f; + boxShape->Height = 0.34f; + boxShape->Depth = 0.7f; + CommitEntity(shape); + } CommitEntity(wheel); } { auto wheel = CreateEntity(tank); auto transform = AddComponent(wheel, "Transform"); - transform->Position = glm::vec3(1.88f, -0.83f - wheelOffset, -0.83f); + transform->Position = glm::vec3(1.68f, -0.83f - wheelOffset, -0.83f); transform->Orientation = glm::angleAxis(glm::pi(), glm::vec3(0, 1, 0)); auto model = AddComponent(wheel, "Model"); model->ModelFile = "Models/Tank/Fix/WheelPhysics.obj"; @@ -339,13 +377,24 @@ void GameWorld::Initialize() Wheel->Friction = 4.f; Wheel->ConnectedToHandbrake = true; Wheel->TorqueRatio = 0.125f; + Wheel->Width = 0.6f; + { + auto shape = CreateEntity(wheel); + auto shapetransform = AddComponent(shape, "Transform"); + shapetransform->Position = glm::vec3(0.f, 0.32f, 0.f) + transform->Position; + auto boxShape = AddComponent(shape, "BoxShape"); + boxShape->Width = 0.7f; + boxShape->Height = 0.34f; + boxShape->Depth = 0.7f; + CommitEntity(shape); + } CommitEntity(wheel); } { auto wheel = CreateEntity(tank); auto transform = AddComponent(wheel, "Transform"); - transform->Position = glm::vec3(-1.88f, -0.83f - wheelOffset, -2.6f); + transform->Position = glm::vec3(-1.68f, -0.83f - wheelOffset, -2.6f); transform->Orientation = glm::angleAxis(glm::pi(), glm::vec3(0, 1, 0)); auto model = AddComponent(wheel, "Model"); model->ModelFile = "Models/Tank/Fix/WheelPhysics.obj"; @@ -359,12 +408,23 @@ void GameWorld::Initialize() Wheel->Friction = 4.f; Wheel->ConnectedToHandbrake = true; Wheel->TorqueRatio = 0.125f; + Wheel->Width = 0.6f; + { + auto shape = CreateEntity(wheel); + auto shapetransform = AddComponent(shape, "Transform"); + shapetransform->Position = glm::vec3(0.f, 0.32f, 0.f) + transform->Position; + auto boxShape = AddComponent(shape, "BoxShape"); + boxShape->Width = 0.7f; + boxShape->Height = 0.34f; + boxShape->Depth = 0.7f; + CommitEntity(shape); + } CommitEntity(wheel); } { auto wheel = CreateEntity(tank); auto transform = AddComponent(wheel, "Transform"); - transform->Position = glm::vec3(-1.88f, -0.83f - wheelOffset, -0.83f); + transform->Position = glm::vec3(-1.68f, -0.83f - wheelOffset, -0.83f); transform->Orientation = glm::angleAxis(glm::pi(), glm::vec3(0, 1, 0)); auto model = AddComponent(wheel, "Model"); model->ModelFile = "Models/Tank/Fix/WheelPhysics.obj"; @@ -378,6 +438,17 @@ void GameWorld::Initialize() Wheel->Friction = 4.f; Wheel->ConnectedToHandbrake = true; Wheel->TorqueRatio = 0.125f; + Wheel->Width = 0.6f; + { + auto shape = CreateEntity(wheel); + auto shapetransform = AddComponent(shape, "Transform"); + shapetransform->Position = glm::vec3(0.f, 0.32f, 0.f) + transform->Position; + auto boxShape = AddComponent(shape, "BoxShape"); + boxShape->Width = 0.7f; + boxShape->Height = 0.34f; + boxShape->Depth = 0.7f; + CommitEntity(shape); + } CommitEntity(wheel); } @@ -386,7 +457,7 @@ void GameWorld::Initialize() { auto wheel = CreateEntity(tank); auto transform = AddComponent(wheel, "Transform"); - transform->Position = glm::vec3(1.88f, -0.83f - wheelOffset, 1.f); + transform->Position = glm::vec3(1.68f, -0.83f - wheelOffset, 1.f); auto model = AddComponent(wheel, "Model"); model->ModelFile = "Models/Tank/Fix/WheelPhysics.obj"; auto Wheel = AddComponent(wheel, "Wheel"); @@ -399,12 +470,23 @@ void GameWorld::Initialize() Wheel->Friction = 4.f; Wheel->ConnectedToHandbrake = true; Wheel->TorqueRatio = 0.125f; + Wheel->Width = 0.6f; + { + auto shape = CreateEntity(wheel); + auto shapetransform = AddComponent(shape, "Transform"); + shapetransform->Position = glm::vec3(0.f, 0.32f, 0.f) + transform->Position; + auto boxShape = AddComponent(shape, "BoxShape"); + boxShape->Width = 0.7f; + boxShape->Height = 0.34f; + boxShape->Depth = 0.7f; + CommitEntity(shape); + } CommitEntity(wheel); } { auto wheel = CreateEntity(tank); auto transform = AddComponent(wheel, "Transform"); - transform->Position = glm::vec3(1.88f, -0.83f - wheelOffset, 2.95f); + transform->Position = glm::vec3(1.68f, -0.83f - wheelOffset, 2.95f); auto model = AddComponent(wheel, "Model"); model->ModelFile = "Models/Tank/Fix/WheelPhysics.obj"; auto Wheel = AddComponent(wheel, "Wheel"); @@ -417,13 +499,24 @@ void GameWorld::Initialize() Wheel->Friction = 4.f; Wheel->ConnectedToHandbrake = true; Wheel->TorqueRatio = 0.125f; + Wheel->Width = 0.6f; + { + auto shape = CreateEntity(wheel); + auto shapetransform = AddComponent(shape, "Transform"); + shapetransform->Position = glm::vec3(0.f, 0.32f, 0.f) + transform->Position; + auto boxShape = AddComponent(shape, "BoxShape"); + boxShape->Width = 0.7f; + boxShape->Height = 0.34f; + boxShape->Depth = 0.7f; + CommitEntity(shape); + } CommitEntity(wheel); } { auto wheel = CreateEntity(tank); auto transform = AddComponent(wheel, "Transform"); - transform->Position = glm::vec3(-1.88f, -0.83f - wheelOffset, 1.f); + transform->Position = glm::vec3(-1.68f, -0.83f - wheelOffset, 1.f); transform->Orientation = glm::angleAxis(glm::pi(), glm::vec3(0, 1, 0)); auto model = AddComponent(wheel, "Model"); model->ModelFile = "Models/Tank/Fix/WheelPhysics.obj"; @@ -437,12 +530,23 @@ void GameWorld::Initialize() Wheel->Friction = 4.f; Wheel->ConnectedToHandbrake = true; Wheel->TorqueRatio = 0.125f; + Wheel->Width = 0.6f; + { + auto shape = CreateEntity(wheel); + auto shapetransform = AddComponent(shape, "Transform"); + shapetransform->Position = glm::vec3(0.f, 0.32f, 0.f) + transform->Position; + auto boxShape = AddComponent(shape, "BoxShape"); + boxShape->Width = 0.7f; + boxShape->Height = 0.34f; + boxShape->Depth = 0.7f; + CommitEntity(shape); + } CommitEntity(wheel); } { auto wheel = CreateEntity(tank); auto transform = AddComponent(wheel, "Transform"); - transform->Position = glm::vec3(-1.88f, -0.83f - wheelOffset, 2.95f); + transform->Position = glm::vec3(-1.68f, -0.83f - wheelOffset, 2.95f); auto model = AddComponent(wheel, "Model"); model->ModelFile = "Models/Tank/Fix/WheelPhysics.obj"; auto Wheel = AddComponent(wheel, "Wheel"); @@ -455,6 +559,17 @@ void GameWorld::Initialize() Wheel->Friction = 4.f; Wheel->ConnectedToHandbrake = true; Wheel->TorqueRatio = 0.125f; + Wheel->Width = 0.6f; + { + auto shape = CreateEntity(wheel); + auto shapetransform = AddComponent(shape, "Transform"); + shapetransform->Position = glm::vec3(0.f, 0.32f, 0.f) + transform->Position; + auto boxShape = AddComponent(shape, "BoxShape"); + boxShape->Width = 0.7f; + boxShape->Height = 0.34f; + boxShape->Depth = 0.7f; + CommitEntity(shape); + } CommitEntity(wheel); } diff --git a/src/GameWorld.h b/src/GameWorld.h index 2dfcb96..e924cc0 100755 --- a/src/GameWorld.h +++ b/src/GameWorld.h @@ -37,7 +37,7 @@ #include "Components/TankSteering.h" #include "Components/TowerSteering.h" #include "Components/BarrelSteering.h" - +#include "Components/Shot.h" class GameWorld : public World { diff --git a/src/Systems/PhysicsSystem.cpp b/src/Systems/PhysicsSystem.cpp index 02259ad..5e4a71f 100644 --- a/src/Systems/PhysicsSystem.cpp +++ b/src/Systems/PhysicsSystem.cpp @@ -31,6 +31,7 @@ void Systems::PhysicsSystem::Initialize() // Events EVENT_SUBSCRIBE_MEMBER(m_ETankSteer, &Systems::PhysicsSystem::OnTankSteer); + EVENT_SUBSCRIBE_MEMBER(m_ETankSteer, &Systems::PhysicsSystem::OnSetVelocity); hkMemorySystem::FrameInfo finfo(6000 * 1024); // Allocate 6MB of Physics solver buffer hkMemoryRouter* memoryRouter = hkMemoryInitUtil::initDefault(hkMallocAllocator::m_defaultMallocAllocator, finfo); @@ -579,3 +580,8 @@ bool Systems::PhysicsSystem::OnTankSteer(const Events::TankSteer &event) return true; } + +bool Systems::PhysicsSystem::OnSetVelocity( const Events::SetVelocity &event ) +{ + +} diff --git a/src/Systems/PhysicsSystem.h b/src/Systems/PhysicsSystem.h index 968db95..7b2d259 100644 --- a/src/Systems/PhysicsSystem.h +++ b/src/Systems/PhysicsSystem.h @@ -14,6 +14,7 @@ #include "Components/WheelPair.h" #include "Components/TowerSteering.h" #include "Events/TankSteer.h" +#include "Events/SetVelocity.h" #include "OBJ.h" // Math and base include @@ -85,6 +86,9 @@ private: EventRelay m_ETankSteer; bool OnTankSteer(const Events::TankSteer &event); + EventRelay m_ESetVelocity; + bool OnSetVelocity(const Events::SetVelocity &event); + void SetUpPhysicsState(EntityID entity, EntityID parent); void TearDownPhysicsState(EntityID entity, EntityID parent); diff --git a/src/Systems/TankSteeringSystem.cpp b/src/Systems/TankSteeringSystem.cpp index eee50cc..5e6c025 100644 --- a/src/Systems/TankSteeringSystem.cpp +++ b/src/Systems/TankSteeringSystem.cpp @@ -49,6 +49,19 @@ void Systems::TankSteeringSystem::UpdateEntity(double dt, EntityID entity, Entit glm::quat orientation = glm::angleAxis(barrelSteeringComponent->Velocity * m_TowerInputController->BarrelDirection * (float)dt, barrelSteeringComponent->Axis); transformComponent->Orientation *= orientation; } + + auto shotComponent = m_World->GetComponent(entity, "Shot"); + if(shotComponent) + { + if(m_TowerInputController->shoot) + { + auto absoluteOrientation = m_World->GetSystem("TransformSystem")->AbsoluteOrientation(entity); + Events::SetVelocity e; + e.Entity = entity; + e.Velocity = absoluteOrientation * (glm::vec3(0.f, 0.f, 1.f) * shotComponent->Speed * (float)dt); + EventBroker->Publish(e); + } + } } void Systems::TankSteeringSystem::TankSteeringInputController::Update( double dt ) @@ -61,6 +74,7 @@ void Systems::TankSteeringSystem::TowerSteeringInputController::Update( double d { TowerDirection = m_TowerDirection; BarrelDirection = m_BarrelDirection; + shoot = m_Shoot; } bool Systems::TankSteeringSystem::TankSteeringInputController::OnCommand(const Events::InputCommand &event) @@ -94,6 +108,11 @@ bool Systems::TankSteeringSystem::TowerSteeringInputController::OnCommand( const { m_BarrelDirection = val; } + + else if (event.Command == "shoot") + { + shoot = (bool)val; + } return true; } diff --git a/src/Systems/TankSteeringSystem.h b/src/Systems/TankSteeringSystem.h index dee4707..1622063 100644 --- a/src/Systems/TankSteeringSystem.h +++ b/src/Systems/TankSteeringSystem.h @@ -2,11 +2,14 @@ #include "System.h" #include "Events/TankSteer.h" +#include "Events/SetVelocity.h" #include "Components/Transform.h" #include "Components/TankSteering.h" #include "Components/TowerSteering.h" #include "Components/BarrelSteering.h" #include "Components/Vehicle.h" +#include "Components/Shot.h" +#include "Systems/TransformSystem.h" #include "InputController.h" namespace Systems @@ -67,10 +70,13 @@ namespace Systems m_BarrelDirection = 0.f; TowerDirection = 0.f; BarrelDirection = 0.f; + + m_Shoot = false; } float TowerDirection; float BarrelDirection; + bool shoot; void Update(double dt); protected: virtual bool OnCommand(const Events::InputCommand &event); @@ -78,7 +84,8 @@ namespace Systems private: float m_TowerDirection; - float m_BarrelDirection; + float m_BarrelDirection; + bool m_Shoot; }; } \ No newline at end of file diff --git a/vs11/Returngeance/Returngeance.vcxproj b/vs11/Returngeance/Returngeance.vcxproj index 9affcba..4b16aef 100755 --- a/vs11/Returngeance/Returngeance.vcxproj +++ b/vs11/Returngeance/Returngeance.vcxproj @@ -137,6 +137,7 @@ + @@ -159,6 +160,7 @@ + diff --git a/vs11/Returngeance/Returngeance.vcxproj.filters b/vs11/Returngeance/Returngeance.vcxproj.filters index 0323b51..21aa2cd 100755 --- a/vs11/Returngeance/Returngeance.vcxproj.filters +++ b/vs11/Returngeance/Returngeance.vcxproj.filters @@ -328,6 +328,12 @@ Physics\Components + + Physics\Components + + + Physics\Events + From df13663ca8c885f4724fa622a61a8410db8294f6 Mon Sep 17 00:00:00 2001 From: Stiffly Date: Tue, 13 May 2014 00:55:42 +0200 Subject: [PATCH 63/65] Two emitters and following camera --- assets | 2 +- src/Components/ParticleEmitter.h | 1 + src/GameWorld.cpp | 70 +++++++++++++++++++++----------- 3 files changed, 49 insertions(+), 24 deletions(-) diff --git a/assets b/assets index e2b54e6..908d0eb 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit e2b54e6212eb1233e6f9935b9e5d7c0295f9ffc6 +Subproject commit 908d0eb8034d334437e79a2e524de9c7d9310ea6 diff --git a/src/Components/ParticleEmitter.h b/src/Components/ParticleEmitter.h index 1b30c8d..bb57c99 100755 --- a/src/Components/ParticleEmitter.h +++ b/src/Components/ParticleEmitter.h @@ -23,6 +23,7 @@ struct ParticleEmitter : Component EntityID ParticleTemplate; float SpawnFrequency; + float Speed; int SpawnCount; std::vector ColorSpectrum; std::vector ScaleSpectrum; diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index 1cae957..056598c 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -69,18 +69,7 @@ void GameWorld::Initialize() CommitEntity(ground); } - { - auto camera = CreateEntity(); - auto transform = AddComponent(camera, "Transform"); - transform->Position.z = 20.f; - transform->Position.y = 10.f; - transform->Orientation = glm::quat(glm::vec3(-glm::pi() / 8.f, 0.f, 0.f)); - auto cameraComp = AddComponent(camera, "Camera"); - cameraComp->FarClip = 2000.f; - AddComponent(camera, "Input"); - auto freeSteering = AddComponent(camera, "FreeSteering"); - CommitEntity(camera); - } + /*{ auto jeep = CreateEntity(); @@ -398,6 +387,30 @@ void GameWorld::Initialize() Wheel->ConnectedToHandbrake = true; Wheel->TorqueRatio = 0.125f; CommitEntity(wheel); + + auto entity = CreateEntity(tank); + auto transformComponent = AddComponent(entity, "Transform"); + transformComponent->Position = glm::vec3(2,-1.7,2.0); + transformComponent->Scale = glm::vec3(3,3,3); + transformComponent->Orientation = glm::angleAxis(glm::pi()/2, glm::vec3(1,0,0)); + auto emitterComponent = AddComponent(entity, "ParticleEmitter"); + emitterComponent->SpawnCount = 2; + emitterComponent->SpawnFrequency = 0.005; + emitterComponent->SpreadAngle = glm::pi(); + emitterComponent->UseGoalVelocity = false; + emitterComponent->LifeTime = 0.5; + //emitterComponent->AngularVelocitySpectrum.push_back(glm::pi() / 100); + emitterComponent->ScaleSpectrum.push_back(glm::vec3(0.05)); + CommitEntity(entity); + + auto particleEntity = CreateEntity(entity); + auto TEMP = AddComponent(particleEntity, "Transform"); + TEMP->Scale = glm::vec3(0); + auto spriteComponent = AddComponent(particleEntity, "Sprite"); + spriteComponent->SpriteFile = "Models/Textures/Sprites/Dust.png"; + emitterComponent->ParticleTemplate = particleEntity; + + CommitEntity(particleEntity); } { @@ -437,20 +450,19 @@ void GameWorld::Initialize() Wheel->TorqueRatio = 0.125f; CommitEntity(wheel); - auto entity = CreateEntity(wheel); + auto entity = CreateEntity(tank); auto transformComponent = AddComponent(entity, "Transform"); - /*transformComponent->Position = glm::vec3(0,3,0);*/ + transformComponent->Position = glm::vec3(-2,-1.7,2.0); transformComponent->Scale = glm::vec3(3,3,3); transformComponent->Orientation = glm::angleAxis(glm::pi()/2, glm::vec3(1,0,0)); auto emitterComponent = AddComponent(entity, "ParticleEmitter"); emitterComponent->SpawnCount = 2; - emitterComponent->SpawnFrequency = 0.01; - emitterComponent->SpreadAngle = glm::pi()/4; + emitterComponent->SpawnFrequency = 0.005; + emitterComponent->SpreadAngle = glm::pi(); emitterComponent->UseGoalVelocity = false; - emitterComponent->LifeTime = 2.0; - emitterComponent->ScaleSpectrum.push_back(glm::vec3(0.1)); - auto modelComponent = AddComponent(entity, "Model"); - modelComponent->ModelFile = "Models/Placeholders/PhysicsTest/PointLight.obj"; + emitterComponent->LifeTime = 0.5; + //emitterComponent->AngularVelocitySpectrum.push_back(glm::pi() / 100); + emitterComponent->ScaleSpectrum.push_back(glm::vec3(0.05)); CommitEntity(entity); auto particleEntity = CreateEntity(entity); @@ -464,8 +476,23 @@ void GameWorld::Initialize() } CommitEntity(tank); + { + auto camera = CreateEntity(tank); + auto transform = AddComponent(camera, "Transform"); + transform->Position.z = 20.f; + transform->Position.y = 7.f; + //transform->Orientation = glm::quat(glm::vec3(-glm::pi() / 8.f, 0.f, 0.f)); + transform->Orientation = glm::angleAxis(glm::pi() / 100, glm::vec3(1,0,0)); + auto cameraComp = AddComponent(camera, "Camera"); + cameraComp->FarClip = 2000.f; + AddComponent(camera, "Input"); + auto freeSteering = AddComponent(camera, "FreeSteering"); + CommitEntity(camera); + } } + + /* for(int i = 0; i < 10; i++) { @@ -554,9 +581,6 @@ void GameWorld::Initialize() CommitEntity(entity); }*/ - { - - } } void GameWorld::Update(double dt) From d259811795ce694dfa30e6eca297c1a4c970a773 Mon Sep 17 00:00:00 2001 From: sippeangelo Date: Tue, 13 May 2014 00:55:32 +0200 Subject: [PATCH 64/65] Xbox360 controller support --- src/Engine.h | 4 +- src/Events/BindGamepadAxis.h | 21 +++ src/Events/BindGamepadButton.h | 21 +++ src/Events/GamepadAxis.h | 32 ++++ src/Events/GamepadButton.h | 45 +++++ src/GUI/Frame.h | 70 +++---- src/GameWorld.cpp | 47 ++++- src/GameWorld.h | 2 + src/InputManager.cpp | 120 ++++++++++-- src/InputManager.h | 19 +- src/Systems/InputSystem.cpp | 102 +++++++++- src/Systems/InputSystem.h | 18 +- src/Systems/TankSteeringSystem.cpp | 6 +- src/Util/Rectangle.h | 176 +++++++++--------- vs11/Returngeance/Returngeance.vcxproj | 20 +- .../Returngeance/Returngeance.vcxproj.filters | 12 ++ 16 files changed, 552 insertions(+), 163 deletions(-) create mode 100644 src/Events/BindGamepadAxis.h create mode 100644 src/Events/BindGamepadButton.h create mode 100644 src/Events/GamepadAxis.h create mode 100644 src/Events/GamepadButton.h diff --git a/src/Engine.h b/src/Engine.h index 25337c4..c063960 100755 --- a/src/Engine.h +++ b/src/Engine.h @@ -19,7 +19,7 @@ public: m_InputManager = std::make_shared(m_Renderer->GetWindow(), m_EventBroker); - m_UIParent = std::make_shared(m_EventBroker); + //m_UIParent = std::make_shared(m_EventBroker); m_World = std::make_shared(m_EventBroker, m_Renderer); m_World->Initialize(); @@ -46,7 +46,7 @@ private: std::shared_ptr m_EventBroker; std::shared_ptr m_Renderer; std::shared_ptr m_InputManager; - std::shared_ptr m_UIParent; + //std::shared_ptr m_UIParent; // TODO: This should ultimately live in GameFrame std::shared_ptr m_World; diff --git a/src/Events/BindGamepadAxis.h b/src/Events/BindGamepadAxis.h new file mode 100644 index 0000000..b1e16f8 --- /dev/null +++ b/src/Events/BindGamepadAxis.h @@ -0,0 +1,21 @@ +#ifndef Events_BindGamepadAxis_h__ +#define Events_BindGamepadAxis_h__ + +#include + +#include "EventBroker.h" +#include "Events/GamepadAxis.h" + +namespace Events +{ + +struct BindGamepadAxis : Event +{ + Gamepad::Axis Axis; + std::string Command; + float Value; +}; + +} + +#endif // Events_BindGamepadAxis_h__ \ No newline at end of file diff --git a/src/Events/BindGamepadButton.h b/src/Events/BindGamepadButton.h new file mode 100644 index 0000000..72641d8 --- /dev/null +++ b/src/Events/BindGamepadButton.h @@ -0,0 +1,21 @@ +#ifndef Events_BindGamepadButton_h__ +#define Events_BindGamepadButton_h__ + +#include + +#include "EventBroker.h" +#include "Events/GamepadButton.h" + +namespace Events +{ + +struct BindGamepadButton : Event +{ + Gamepad::Button Button; + std::string Command; + float Value; +}; + +} + +#endif // Events_BindGamepadButton_h__ \ No newline at end of file diff --git a/src/Events/GamepadAxis.h b/src/Events/GamepadAxis.h new file mode 100644 index 0000000..3d47767 --- /dev/null +++ b/src/Events/GamepadAxis.h @@ -0,0 +1,32 @@ +#ifndef Events_GamepadAxis_h__ +#define Events_GamepadAxis_h__ + +#include "EventBroker.h" + +namespace Gamepad +{ + enum class Axis + { + LeftX, + LeftY, + RightX, + RightY, + LeftTrigger, + RightTrigger, + LAST = RightTrigger + }; +} + +namespace Events +{ + +struct GamepadAxis : Event +{ + int GamepadID; + Gamepad::Axis Axis; + float Value; +}; + +} + +#endif // Events_GamepadAxis_h__ \ No newline at end of file diff --git a/src/Events/GamepadButton.h b/src/Events/GamepadButton.h new file mode 100644 index 0000000..a99583c --- /dev/null +++ b/src/Events/GamepadButton.h @@ -0,0 +1,45 @@ +#ifndef Events_GamepadButton_h__ +#define Events_GamepadButton_h__ + +#include "EventBroker.h" + +namespace Gamepad +{ + enum class Button + { + Up, + Down, + Left, + Right, + Start, + Back, + LeftThumb, + RightThumb, + LeftShoulder, + RightShoulder, + A, + B, + X, + Y, + LAST = Y + }; +} + +namespace Events +{ + +struct GamepadButtonDown : Event +{ + int GamepadID; + Gamepad::Button Button; +}; + +struct GamepadButtonUp : Event +{ + int GamepadID; + Gamepad::Button Button; +}; + +} + +#endif // Events_GamepadButton_h__ \ No newline at end of file diff --git a/src/GUI/Frame.h b/src/GUI/Frame.h index 19f534a..bb8d51f 100644 --- a/src/GUI/Frame.h +++ b/src/GUI/Frame.h @@ -8,41 +8,41 @@ namespace GUI { - -class Frame : public Rectangle -{ -public: - enum class Anchor - { - Left, - Right, - Top, - Bottom - }; - - // Set up a base frame with an event broker - Frame(std::shared_ptr<::EventBroker> eventBroker) - : EventBroker(eventBroker) - , Rectangle() - { Initialize(); } - // Create a frame as a child - Frame(std::shared_ptr parent) - : Rectangle(static_cast(*parent)) // Clone parent rectangle using copy constructor - { SetParent(parent); Initialize(); } - - virtual void Initialize() { } - std::shared_ptr Parent() const { return m_Parent; } - void SetParent(std::shared_ptr parent) - { - m_Parent = parent; - EventBroker = parent->EventBroker; - } - virtual void Update(double dt) { } - -protected: - std::shared_ptr<::EventBroker> EventBroker; - std::shared_ptr m_Parent; -}; +// +//class Frame : public Rectangle +//{ +//public: +// enum class Anchor +// { +// Left, +// Right, +// Top, +// Bottom +// }; +// +// // Set up a base frame with an event broker +// Frame(std::shared_ptr<::EventBroker> eventBroker) +// : EventBroker(eventBroker) +// , Rectangle() +// { Initialize(); } +// // Create a frame as a child +// Frame(std::shared_ptr parent) +// : Rectangle(static_cast(*parent)) // Clone parent rectangle using copy constructor +// { SetParent(parent); Initialize(); } +// +// virtual void Initialize() { } +// std::shared_ptr Parent() const { return m_Parent; } +// void SetParent(std::shared_ptr parent) +// { +// m_Parent = parent; +// EventBroker = parent->EventBroker; +// } +// virtual void Update(double dt) { } +// +//protected: +// std::shared_ptr<::EventBroker> EventBroker; +// std::shared_ptr m_Parent; +//}; } diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index 2d743f9..8b29bff 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -8,17 +8,38 @@ void GameWorld::Initialize() m_ResourceManager.Preload("Model", "Models/Placeholders/PhysicsTest/Plane.obj"); m_ResourceManager.Preload("Model", "Models/Placeholders/PhysicsTest/ArrowCube.obj"); - BindKey(GLFW_KEY_W, "vertical", -1.f); - BindKey(GLFW_KEY_S, "vertical", 1.f); + BindKey(GLFW_KEY_W, "vertical", 1.f); + BindKey(GLFW_KEY_S, "vertical", -1.f); BindKey(GLFW_KEY_A, "horizontal", -1.f); BindKey(GLFW_KEY_D, "horizontal", 1.f); + BindGamepadAxis(Gamepad::Axis::LeftX, "horizontal", 1.f); + BindGamepadAxis(Gamepad::Axis::RightTrigger, "vertical", 1.f); + BindGamepadAxis(Gamepad::Axis::LeftTrigger, "vertical", -1.f); BindKey(GLFW_KEY_UP, "barrel_rotation", 1.f); BindKey(GLFW_KEY_DOWN, "barrel_rotation", -1.f); - BindKey(GLFW_KEY_LEFT, "tower_rotation", 1.f); - BindKey(GLFW_KEY_RIGHT, "tower_rotation", -1.f); + BindKey(GLFW_KEY_LEFT, "tower_rotation", -1.f); + BindKey(GLFW_KEY_RIGHT, "tower_rotation", 1.f); + BindGamepadAxis(Gamepad::Axis::RightX, "tower_rotation", 1.f); + BindGamepadAxis(Gamepad::Axis::RightY, "barrel_rotation", 1.f); BindKey(GLFW_KEY_SPACE, "handbrake", 1.f); + BindGamepadButton(Gamepad::Button::A, "handbrake", 1.f); + + //BindGamepadButton(Gamepad::Button::Up, "Gamepad::Button::Up", 1.f); + //BindGamepadButton(Gamepad::Button::Down, "Gamepad::Button::Down", 1.f); + //BindGamepadButton(Gamepad::Button::Left, "Gamepad::Button::Left", 1.f); + //BindGamepadButton(Gamepad::Button::Right, "Gamepad::Button::Right", 1.f); + //BindGamepadButton(Gamepad::Button::Start, "Gamepad::Button::Start", 1.f); + //BindGamepadButton(Gamepad::Button::Back, "Gamepad::Button::Back", 1.f); + //BindGamepadButton(Gamepad::Button::LeftThumb, "Gamepad::Button::LeftThumb", 1.f); + //BindGamepadButton(Gamepad::Button::RightThumb, "Gamepad::Button::RightThumb", 1.f); + //BindGamepadButton(Gamepad::Button::LeftShoulder, "Gamepad::Button::LeftShoulder", 1.f); + //BindGamepadButton(Gamepad::Button::RightShoulder, "Gamepad::Button::RightShoulder", 1.f); + //BindGamepadButton(Gamepad::Button::A, "Gamepad::Button::A", 1.f); + //BindGamepadButton(Gamepad::Button::B, "Gamepad::Button::B", 1.f); + //BindGamepadButton(Gamepad::Button::X, "Gamepad::Button::X", 1.f); + //BindGamepadButton(Gamepad::Button::Y, "Gamepad::Button::Y", 1.f); // // BindKey(GLFW_KEY_UP, "vertical", -1.f); // BindKey(GLFW_KEY_DOWN, "vertical", 1.f); @@ -609,3 +630,21 @@ void GameWorld::BindMouseButton(int button, std::string command) e.Command = command; m_EventBroker->Publish(e); } + +void GameWorld::BindGamepadAxis(Gamepad::Axis axis, std::string command, float value) +{ + Events::BindGamepadAxis e; + e.Axis = axis; + e.Command = command; + e.Value = value; + m_EventBroker->Publish(e); +} + +void GameWorld::BindGamepadButton(Gamepad::Button button, std::string command, float value) +{ + Events::BindGamepadButton e; + e.Button = button; + e.Command = command; + e.Value = value; + m_EventBroker->Publish(e); +} diff --git a/src/GameWorld.h b/src/GameWorld.h index 2dfcb96..d258196 100755 --- a/src/GameWorld.h +++ b/src/GameWorld.h @@ -58,6 +58,8 @@ private: void BindKey(int keyCode, std::string command, float value); void BindMouseButton(int button, std::string command); + void BindGamepadAxis(Gamepad::Axis axis, std::string command, float value); + void BindGamepadButton(Gamepad::Button button, std::string command, float value); }; #endif // GameWorld_h__ diff --git a/src/InputManager.cpp b/src/InputManager.cpp index 9f09b1c..fc225ec 100644 --- a/src/InputManager.cpp +++ b/src/InputManager.cpp @@ -1,13 +1,14 @@ #include "PrecompiledHeader.h" #include "InputManager.h" +void InputManager::Initialize() +{ + m_LastGamepadAxisState = std::array(); + m_LastGamepadButtonState = std::array(); +} + void InputManager::Update(double dt) { - m_LastKeyState = m_CurrentKeyState; - m_LastMouseState = m_CurrentMouseState; - m_LastMouseX = m_CurrentMouseX; - m_LastMouseY = m_CurrentMouseY; - // Keyboard input for (int i = 0; i <= GLFW_KEY_LAST; ++i) { @@ -19,13 +20,13 @@ void InputManager::Update(double dt) { Events::KeyDown e; e.KeyCode = i; - m_EventBroker->Publish(e); + m_EventBroker->Publish(e); } else { Events::KeyUp e; e.KeyCode = i; - m_EventBroker->Publish(e); + m_EventBroker->Publish(e); } } } @@ -41,18 +42,18 @@ void InputManager::Update(double dt) { Events::MousePress e; e.Button = i; - m_EventBroker->Publish(e); + m_EventBroker->Publish(e); } else { Events::MouseRelease e; e.Button = i; - m_EventBroker->Publish(e); + m_EventBroker->Publish(e); } } } - // Cursor position + // Mouse movement glfwGetCursorPos(m_GLFWWindow, &m_CurrentMouseX, &m_CurrentMouseY); m_CurrentMouseDeltaX = m_CurrentMouseX - m_LastMouseX; m_CurrentMouseDeltaY = m_CurrentMouseY - m_LastMouseY; @@ -64,7 +65,7 @@ void InputManager::Update(double dt) e.Y = m_CurrentMouseY; e.DeltaX = m_CurrentMouseDeltaX; e.DeltaY = m_CurrentMouseDeltaY; - m_EventBroker->Publish(e); + m_EventBroker->Publish(e); } // // Lock mouse while holding LMB @@ -83,4 +84,101 @@ void InputManager::Update(double dt) // { // glfwSetInputMode(m_GLFWWindow, GLFW_CURSOR, GLFW_CURSOR_NORMAL); // } + + // Xbox360 controller + DWORD dwResult; + for (int i = 0; i < XUSER_MAX_COUNT; i++) + { + XINPUT_STATE state = { 0 }; + // Simply get the state of the controller from XInput. + dwResult = XInputGetState(i, &state); + if (dwResult == 0) + { + m_CurrentGamepadAxisState[i][static_cast(Gamepad::Axis::LeftX)] = state.Gamepad.sThumbLX / 32767.f; + m_CurrentGamepadAxisState[i][static_cast(Gamepad::Axis::LeftY)] = state.Gamepad.sThumbLY / 32767.f; + m_CurrentGamepadAxisState[i][static_cast(Gamepad::Axis::RightX)] = state.Gamepad.sThumbRX / 32767.f; + m_CurrentGamepadAxisState[i][static_cast(Gamepad::Axis::RightY)] = state.Gamepad.sThumbRY / 32767.f; + m_CurrentGamepadAxisState[i][static_cast(Gamepad::Axis::LeftTrigger)] = state.Gamepad.bLeftTrigger / 255.f; + m_CurrentGamepadAxisState[i][static_cast(Gamepad::Axis::RightTrigger)] = state.Gamepad.bRightTrigger / 255.f; + PublishGamepadAxisIfChanged(i, Gamepad::Axis::LeftX); + PublishGamepadAxisIfChanged(i, Gamepad::Axis::LeftY); + PublishGamepadAxisIfChanged(i, Gamepad::Axis::RightX); + PublishGamepadAxisIfChanged(i, Gamepad::Axis::RightY); + PublishGamepadAxisIfChanged(i, Gamepad::Axis::LeftTrigger); + PublishGamepadAxisIfChanged(i, Gamepad::Axis::RightTrigger); + + m_CurrentGamepadButtonState[i][static_cast(Gamepad::Button::Up)] = static_cast(state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_UP); + m_CurrentGamepadButtonState[i][static_cast(Gamepad::Button::Down)] = static_cast(state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_DOWN); + m_CurrentGamepadButtonState[i][static_cast(Gamepad::Button::Left)] = static_cast(state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_LEFT); + m_CurrentGamepadButtonState[i][static_cast(Gamepad::Button::Right)] = static_cast(state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_RIGHT); + m_CurrentGamepadButtonState[i][static_cast(Gamepad::Button::Start)] = static_cast(state.Gamepad.wButtons & XINPUT_GAMEPAD_START); + m_CurrentGamepadButtonState[i][static_cast(Gamepad::Button::Back)] = static_cast(state.Gamepad.wButtons & XINPUT_GAMEPAD_BACK); + m_CurrentGamepadButtonState[i][static_cast(Gamepad::Button::LeftThumb)] = static_cast(state.Gamepad.wButtons & XINPUT_GAMEPAD_LEFT_THUMB); + m_CurrentGamepadButtonState[i][static_cast(Gamepad::Button::RightThumb)] = static_cast(state.Gamepad.wButtons & XINPUT_GAMEPAD_RIGHT_THUMB); + m_CurrentGamepadButtonState[i][static_cast(Gamepad::Button::LeftShoulder)] = static_cast(state.Gamepad.wButtons & XINPUT_GAMEPAD_LEFT_SHOULDER); + m_CurrentGamepadButtonState[i][static_cast(Gamepad::Button::RightShoulder)] = static_cast(state.Gamepad.wButtons & XINPUT_GAMEPAD_RIGHT_SHOULDER); + m_CurrentGamepadButtonState[i][static_cast(Gamepad::Button::A)] = static_cast(state.Gamepad.wButtons & XINPUT_GAMEPAD_A); + m_CurrentGamepadButtonState[i][static_cast(Gamepad::Button::B)] = static_cast(state.Gamepad.wButtons & XINPUT_GAMEPAD_B); + m_CurrentGamepadButtonState[i][static_cast(Gamepad::Button::X)] = static_cast(state.Gamepad.wButtons & XINPUT_GAMEPAD_X); + m_CurrentGamepadButtonState[i][static_cast(Gamepad::Button::Y)] = static_cast(state.Gamepad.wButtons & XINPUT_GAMEPAD_Y); + PublishGamepadButtonIfChanged(i, Gamepad::Button::Up); + PublishGamepadButtonIfChanged(i, Gamepad::Button::Down); + PublishGamepadButtonIfChanged(i, Gamepad::Button::Left); + PublishGamepadButtonIfChanged(i, Gamepad::Button::Right); + PublishGamepadButtonIfChanged(i, Gamepad::Button::Start); + PublishGamepadButtonIfChanged(i, Gamepad::Button::Back); + PublishGamepadButtonIfChanged(i, Gamepad::Button::LeftThumb); + PublishGamepadButtonIfChanged(i, Gamepad::Button::RightThumb); + PublishGamepadButtonIfChanged(i, Gamepad::Button::LeftShoulder); + PublishGamepadButtonIfChanged(i, Gamepad::Button::RightShoulder); + PublishGamepadButtonIfChanged(i, Gamepad::Button::A); + PublishGamepadButtonIfChanged(i, Gamepad::Button::B); + PublishGamepadButtonIfChanged(i, Gamepad::Button::X); + PublishGamepadButtonIfChanged(i, Gamepad::Button::Y); + } + } + + m_LastKeyState = m_CurrentKeyState; + m_LastMouseState = m_CurrentMouseState; + m_LastMouseX = m_CurrentMouseX; + m_LastMouseY = m_CurrentMouseY; + m_LastGamepadAxisState = m_CurrentGamepadAxisState; + m_LastGamepadButtonState = m_CurrentGamepadButtonState; +} + +void InputManager::PublishGamepadAxisIfChanged(int gamepadID, Gamepad::Axis axis) +{ + float currentValue = m_CurrentGamepadAxisState[gamepadID][static_cast(axis)]; + float lastValue = m_LastGamepadAxisState[gamepadID][static_cast(axis)]; + if (currentValue != lastValue) + { + Events::GamepadAxis e; + e.GamepadID = gamepadID; + e.Axis = axis; + e.Value = currentValue; + m_EventBroker->Publish(e); + } +} + +void InputManager::PublishGamepadButtonIfChanged(int gamepadID, Gamepad::Button button) +{ + bool currentState = m_CurrentGamepadButtonState[gamepadID][static_cast(button)]; + float lastState = m_LastGamepadButtonState[gamepadID][static_cast(button)]; + if (currentState != lastState) + { + if (currentState == true) + { + Events::GamepadButtonDown e; + e.GamepadID = gamepadID; + e.Button = button; + m_EventBroker->Publish(e); + } + else + { + Events::GamepadButtonUp e; + e.GamepadID = gamepadID; + e.Button = button; + m_EventBroker->Publish(e); + } + } } diff --git a/src/InputManager.h b/src/InputManager.h index 5acaaa2..41d77e7 100644 --- a/src/InputManager.h +++ b/src/InputManager.h @@ -3,12 +3,16 @@ #include +#include + #include "EventBroker.h" #include "Events/KeyDown.h" #include "Events/KeyUp.h" #include "Events/MousePress.h" #include "Events/MouseRelease.h" #include "Events/MouseMove.h" +#include "Events/GamepadAxis.h" +#include "Events/GamepadButton.h" class InputManager { @@ -22,7 +26,10 @@ public: , m_LastMouseState() , m_CurrentMouseX(0), m_CurrentMouseY(0) , m_LastMouseX(0), m_LastMouseY(0) - , m_CurrentMouseDeltaX(0), m_CurrentMouseDeltaY(0) { } + , m_CurrentMouseDeltaX(0), m_CurrentMouseDeltaY(0) + { Initialize(); } + + void Initialize(); void Update(double dt); @@ -34,9 +41,19 @@ private: std::array m_LastKeyState; std::array m_CurrentMouseState; std::array m_LastMouseState; + typedef std::array(Gamepad::Axis::LAST) + 1> GamepadAxisState; + std::array m_CurrentGamepadAxisState; + std::array m_LastGamepadAxisState; + typedef std::array(Gamepad::Button::LAST) + 1> GamepadButtonState; + std::array m_CurrentGamepadButtonState; + std::array m_LastGamepadButtonState; + double m_CurrentMouseX, m_CurrentMouseY; double m_LastMouseX, m_LastMouseY; double m_CurrentMouseDeltaX, m_CurrentMouseDeltaY; + + void PublishGamepadAxisIfChanged(int gamepadID, Gamepad::Axis axis); + void PublishGamepadButtonIfChanged(int gamepadID, Gamepad::Button button); }; #endif // InputManager_h__ diff --git a/src/Systems/InputSystem.cpp b/src/Systems/InputSystem.cpp index 4868213..7c4cde7 100755 --- a/src/Systems/InputSystem.cpp +++ b/src/Systems/InputSystem.cpp @@ -10,12 +10,17 @@ void Systems::InputSystem::RegisterComponents(ComponentFactory* cf) void Systems::InputSystem::Initialize() { // Subscribe to events - EVENT_SUBSCRIBE_MEMBER(m_EKeyDown, &Systems::InputSystem::OnKeyDown) - EVENT_SUBSCRIBE_MEMBER(m_EKeyUp, &Systems::InputSystem::OnKeyUp) - EVENT_SUBSCRIBE_MEMBER(m_EMousePress, &Systems::InputSystem::OnMousePress) - EVENT_SUBSCRIBE_MEMBER(m_EMouseRelease, &Systems::InputSystem::OnMouseRelease) - EVENT_SUBSCRIBE_MEMBER(m_EBindKey, &Systems::InputSystem::OnBindKey) - EVENT_SUBSCRIBE_MEMBER(m_EBindMouseButton, &Systems::InputSystem::OnBindMouseButton) + EVENT_SUBSCRIBE_MEMBER(m_EKeyDown, &Systems::InputSystem::OnKeyDown); + EVENT_SUBSCRIBE_MEMBER(m_EKeyUp, &Systems::InputSystem::OnKeyUp); + EVENT_SUBSCRIBE_MEMBER(m_EMousePress, &Systems::InputSystem::OnMousePress); + EVENT_SUBSCRIBE_MEMBER(m_EMouseRelease, &Systems::InputSystem::OnMouseRelease); + EVENT_SUBSCRIBE_MEMBER(m_EGamepadAxis, &Systems::InputSystem::OnGamepadAxis); + EVENT_SUBSCRIBE_MEMBER(m_EGamepadButtonDown, &Systems::InputSystem::OnGamepadButtonDown); + EVENT_SUBSCRIBE_MEMBER(m_EGamepadButtonUp, &Systems::InputSystem::OnGamepadButtonUp); + EVENT_SUBSCRIBE_MEMBER(m_EBindKey, &Systems::InputSystem::OnBindKey); + EVENT_SUBSCRIBE_MEMBER(m_EBindMouseButton, &Systems::InputSystem::OnBindMouseButton); + EVENT_SUBSCRIBE_MEMBER(m_EBindGamepadAxis, &Systems::InputSystem::OnBindGamepadAxis); + EVENT_SUBSCRIBE_MEMBER(m_EBindGamepadButton, &Systems::InputSystem::OnBindGamepadButton); } void Systems::InputSystem::Update(double dt) @@ -47,8 +52,8 @@ bool Systems::InputSystem::OnKeyDown(const Events::KeyDown &event) std::string command; float value; std::tie(command, value) = bindingIt->second; - m_KeyBindingValues[command] += value; - PublishCommand(0, command, std::max(-1.f, std::min(m_KeyBindingValues[command], 1.f))); + m_CommandValues[command] += value; + PublishCommand(0, command, std::max(-1.f, std::min(m_CommandValues[command], 1.f))); } return true; @@ -62,8 +67,8 @@ bool Systems::InputSystem::OnKeyUp(const Events::KeyUp &event) std::string command; float value; std::tie(command, value) = bindingIt->second; - m_KeyBindingValues[command] -= value; - PublishCommand(0, command, std::max(-1.f, std::min(m_KeyBindingValues[command], 1.f))); + m_CommandValues[command] -= value; + PublishCommand(0, command, std::max(-1.f, std::min(m_CommandValues[command], 1.f))); } return true; @@ -91,6 +96,51 @@ bool Systems::InputSystem::OnMouseRelease(const Events::MouseRelease &event) return true; } +bool Systems::InputSystem::OnGamepadAxis(const Events::GamepadAxis &event) +{ + auto bindingIt = m_GamepadAxisBindings.find(event.Axis); + if (bindingIt != m_GamepadAxisBindings.end()) + { + std::string command; + float value; + std::tie(command, value) = bindingIt->second; + PublishCommand(event.GamepadID + 1, command, event.Value * value); + } + + return true; +} + +bool Systems::InputSystem::OnGamepadButtonDown(const Events::GamepadButtonDown &event) +{ + auto bindingIt = m_GamepadButtonBindings.find(event.Button); + if (bindingIt != m_GamepadButtonBindings.end()) + { + std::string command; + float value; + std::tie(command, value) = bindingIt->second; + m_CommandValues[command] += value; + PublishCommand(event.GamepadID + 1, command, std::max(-1.f, std::min(m_CommandValues[command], 1.f))); + } + + return true; +} + +bool Systems::InputSystem::OnGamepadButtonUp(const Events::GamepadButtonUp &event) +{ + auto bindingIt = m_GamepadButtonBindings.find(event.Button); + if (bindingIt != m_GamepadButtonBindings.end()) + { + std::string command; + float value; + std::tie(command, value) = bindingIt->second; + m_CommandValues[command] -= value; + PublishCommand(event.GamepadID + 1, command, std::max(-1.f, std::min(m_CommandValues[command], 1.f))); + } + + return true; +} + + bool Systems::InputSystem::OnBindKey(const Events::BindKey &event) { if (event.Command.empty()) @@ -121,6 +171,36 @@ bool Systems::InputSystem::OnBindMouseButton(const Events::BindMouseButton &even return true; } +bool Systems::InputSystem::OnBindGamepadAxis(const Events::BindGamepadAxis &event) +{ + if (event.Command.empty()) + { + m_GamepadAxisBindings.erase(event.Axis); + } + else + { + m_GamepadAxisBindings[event.Axis] = std::make_tuple(event.Command, event.Value); + LOG_DEBUG("Input: Bound gamepad axis %i to %s", event.Axis, event.Command.c_str()); + } + + return true; +} + +bool Systems::InputSystem::OnBindGamepadButton(const Events::BindGamepadButton &event) +{ + if (event.Command.empty()) + { + m_GamepadButtonBindings.erase(event.Button); + } + else + { + m_GamepadButtonBindings[event.Button] = std::make_tuple(event.Command, event.Value); + LOG_DEBUG("Input: Bound gamepad axis %i to %s", event.Button, event.Command.c_str()); + } + + return true; +} + void Systems::InputSystem::PublishCommand(int playerID, std::string command, float value) { Events::InputCommand e; @@ -131,3 +211,5 @@ void Systems::InputSystem::PublishCommand(int playerID, std::string command, flo LOG_DEBUG("Input: Published command %s=%f for player %i", e.Command.c_str(), e.Value, playerID); } + + diff --git a/src/Systems/InputSystem.h b/src/Systems/InputSystem.h index b9461a2..ce9a7f3 100755 --- a/src/Systems/InputSystem.h +++ b/src/Systems/InputSystem.h @@ -11,8 +11,12 @@ #include "Events/KeyDown.h" #include "Events/MousePress.h" #include "Events/MouseRelease.h" +#include "Events/GamepadAxis.h" +#include "Events/GamepadButton.h" #include "Events/BindKey.h" #include "Events/BindMouseButton.h" +#include "Events/BindGamepadAxis.h" +#include "Events/BindGamepadButton.h" #include "Events/InputCommand.h" namespace Systems @@ -30,10 +34,12 @@ public: void Update(double dt) override; private: + std::unordered_map m_CommandValues; // command string -> command current value // Input binding tables std::unordered_map> m_KeyBindings; // GLFW_KEY... -> command string & value - std::unordered_map m_KeyBindingValues; // command string -> command value std::unordered_map m_MouseButtonBindings; // GLFW_MOUSE_BUTTON... -> command string + std::unordered_map> m_GamepadAxisBindings; // Gamepad::Axis -> command string & value + std::unordered_map> m_GamepadButtonBindings; // Gamepad::Button -> command string // Input events EventRelay m_EKeyDown; @@ -44,11 +50,21 @@ private: bool OnMousePress(const Events::MousePress &event); EventRelay m_EMouseRelease; bool OnMouseRelease(const Events::MouseRelease &event); + EventRelay m_EGamepadAxis; + bool OnGamepadAxis(const Events::GamepadAxis &event); + EventRelay m_EGamepadButtonDown; + bool OnGamepadButtonDown(const Events::GamepadButtonDown &event); + EventRelay m_EGamepadButtonUp; + bool OnGamepadButtonUp(const Events::GamepadButtonUp &event); // Input binding events EventRelay m_EBindKey; bool OnBindKey(const Events::BindKey &event); EventRelay m_EBindMouseButton; bool OnBindMouseButton(const Events::BindMouseButton &event); + EventRelay m_EBindGamepadAxis; + bool OnBindGamepadAxis(const Events::BindGamepadAxis &event); + EventRelay m_EBindGamepadButton; + bool OnBindGamepadButton(const Events::BindGamepadButton &event); void PublishCommand(int playerID, std::string command, float value); }; diff --git a/src/Systems/TankSteeringSystem.cpp b/src/Systems/TankSteeringSystem.cpp index eee50cc..9d631c8 100644 --- a/src/Systems/TankSteeringSystem.cpp +++ b/src/Systems/TankSteeringSystem.cpp @@ -72,12 +72,12 @@ bool Systems::TankSteeringSystem::TankSteeringInputController::OnCommand(const E } else if (event.Command == "vertical") { - m_Vertical = val; + m_Vertical = -val; } else if (event.Command == "handbrake") { - Handbrake = val; + Handbrake = val > 0; } return true; @@ -88,7 +88,7 @@ bool Systems::TankSteeringSystem::TowerSteeringInputController::OnCommand( const float val = event.Value; if(event.Command == "tower_rotation") { - m_TowerDirection = val; + m_TowerDirection = -val; } else if(event.Command == "barrel_rotation") { diff --git a/src/Util/Rectangle.h b/src/Util/Rectangle.h index 0d0db32..a257855 100644 --- a/src/Util/Rectangle.h +++ b/src/Util/Rectangle.h @@ -3,93 +3,93 @@ #include -struct Rectangle -{ - Rectangle() - : X(0), Y(0), Width(0), Height(0) { } - - Rectangle(int x, int y, int width = 0, int height = 0) - : X(x), Y(y), Width(width), Height(height) { } - - /*Rectangle(const Rectangle &rect) - : X(rect.X), Y(rect.Y), Width(rect.Width), Height(rect.Height) { }*/ - - int X; - int Y; - int Width; - int Height; - - const int& GetLeft() const { return X; } - void SetLeft(int left) - { - Width += X - left; - X = left; - } - int GetRight() const { return X + Width; } - void SetRight(int right) - { - Width = right - X; - } - const int& GetTop() const { return Y; } - void SetTop(int top) - { - Height += Y - top; - Y = top; - } - int GetBottom() const { return Y + Height; } - int SetBottom(int bottom) - { - Height = bottom - Y; - } - - Rectangle& operator+=(const Rectangle &rhs) - { - SetLeft(std::min(GetLeft(), rhs.GetLeft())); - SetRight(std::max(GetRight(), rhs.GetRight())); - SetTop(std::min(GetTop(), rhs.GetTop())); - SetBottom(std::max(GetBottom(), rhs.GetBottom())); - } - - static bool Intersects(const Rectangle &r1, const Rectangle &r2) - { - return !(r2.GetLeft() > r1.GetRight() || r2.GetRight() < r1.GetLeft() || r2.GetTop() > r1.GetBottom() || r2.GetBottom() < r1.GetTop()); - } -}; - -inline bool operator==(const Rectangle &r1, const Rectangle &r2) -{ - return (r1.X == r2.X) && (r1.Y == r2.Y) && (r1.Width == r2.Width) && (r1.Height == r2.Height); -} - -inline bool operator!=(const Rectangle &lhs, const Rectangle &rhs) -{ - return !(lhs == rhs); -} - -inline bool operator<(const Rectangle &lhs, const Rectangle &rhs) -{ - return (lhs.Width < rhs.Width) && (lhs.Height < rhs.Height); -} - -inline bool operator>(const Rectangle &lhs, const Rectangle &rhs) -{ - return rhs < lhs; -} - -inline bool operator<=(const Rectangle &lhs, const Rectangle &rhs) -{ - return !(lhs > rhs); -} - -inline bool operator>=(const Rectangle &lhs, const Rectangle &rhs) -{ - return !(lhs < rhs); -} - -inline Rectangle operator+(Rectangle lhs, const Rectangle &rhs) -{ - lhs += rhs; - return lhs; -} +//struct Rectangle +//{ +// Rectangle() +// : X(0), Y(0), Width(0), Height(0) { } +// +// Rectangle(int x, int y, int width = 0, int height = 0) +// : X(x), Y(y), Width(width), Height(height) { } +// +// /*Rectangle(const Rectangle &rect) +// : X(rect.X), Y(rect.Y), Width(rect.Width), Height(rect.Height) { }*/ +// +// int X; +// int Y; +// int Width; +// int Height; +// +// const int& GetLeft() const { return X; } +// void SetLeft(int left) +// { +// Width += X - left; +// X = left; +// } +// int GetRight() const { return X + Width; } +// void SetRight(int right) +// { +// Width = right - X; +// } +// const int& GetTop() const { return Y; } +// void SetTop(int top) +// { +// Height += Y - top; +// Y = top; +// } +// int GetBottom() const { return Y + Height; } +// int SetBottom(int bottom) +// { +// Height = bottom - Y; +// } +// +// Rectangle& operator+=(const Rectangle &rhs) +// { +// SetLeft(std::min(GetLeft(), rhs.GetLeft())); +// SetRight(std::max(GetRight(), rhs.GetRight())); +// SetTop(std::min(GetTop(), rhs.GetTop())); +// SetBottom(std::max(GetBottom(), rhs.GetBottom())); +// } +// +// static bool Intersects(const Rectangle &r1, const Rectangle &r2) +// { +// return !(r2.GetLeft() > r1.GetRight() || r2.GetRight() < r1.GetLeft() || r2.GetTop() > r1.GetBottom() || r2.GetBottom() < r1.GetTop()); +// } +//}; +// +//inline bool operator==(const Rectangle &r1, const Rectangle &r2) +//{ +// return (r1.X == r2.X) && (r1.Y == r2.Y) && (r1.Width == r2.Width) && (r1.Height == r2.Height); +//} +// +//inline bool operator!=(const Rectangle &lhs, const Rectangle &rhs) +//{ +// return !(lhs == rhs); +//} +// +//inline bool operator<(const Rectangle &lhs, const Rectangle &rhs) +//{ +// return (lhs.Width < rhs.Width) && (lhs.Height < rhs.Height); +//} +// +//inline bool operator>(const Rectangle &lhs, const Rectangle &rhs) +//{ +// return rhs < lhs; +//} +// +//inline bool operator<=(const Rectangle &lhs, const Rectangle &rhs) +//{ +// return !(lhs > rhs); +//} +// +//inline bool operator>=(const Rectangle &lhs, const Rectangle &rhs) +//{ +// return !(lhs < rhs); +//} +// +//inline Rectangle operator+(Rectangle lhs, const Rectangle &rhs) +//{ +// lhs += rhs; +// return lhs; +//} #endif // Util_Rectangle_h__ diff --git a/vs11/Returngeance/Returngeance.vcxproj b/vs11/Returngeance/Returngeance.vcxproj index 9affcba..3ca02eb 100755 --- a/vs11/Returngeance/Returngeance.vcxproj +++ b/vs11/Returngeance/Returngeance.vcxproj @@ -39,21 +39,21 @@ - $(HAVOK_2013_1_0_r1_ROOT)\Source;$(BOOST_1_55_0_ROOT);$(SolutionDir)\..\src;$(SolutionDir)\..\libs;$(SolutionDir)\..\libs\glew-1.10.0\include;$(SolutionDir)\..\libs\glfw-3.0.4\include;$(SolutionDir)\..\libs\glm-0.9.5.3;$(SolutionDir)\..\libs\openal-soft-1.15.1\include;$(SolutionDir)\..\libs\bullet-2.82-r2704\src;$(SolutionDir)\..\libs\SOIL\src;$(IncludePath) - $(HAVOK_2013_1_0_r1_ROOT)\Lib\win32_vs2012_win7\debug_dll;$(BOOST_1_55_0_ROOT)\lib32-msvc-11.0;$(SolutionDir)\..\libs\glew-1.10.0\lib\Debug\Win32;$(SolutionDir)\..\libs\glfw-3.0.4\lib\Debug;$(SolutionDir)\..\libs\openal-soft-1.15.1\lib\Win32\Debug;$(SolutionDir)\..\libs\bullet-2.82-r2704\lib\Debug;$(SolutionDir)\..\libs\SOIL\lib\Debug;$(LibraryPath) + $(HAVOK_2013_1_0_r1_ROOT)\Source;$(BOOST_1_55_0_ROOT);$(SolutionDir)\..\src;$(SolutionDir)\..\libs;$(SolutionDir)\..\libs\glew-1.10.0\include;$(SolutionDir)\..\libs\glfw-3.0.4\include;$(SolutionDir)\..\libs\glm-0.9.5.3;$(SolutionDir)\..\libs\openal-soft-1.15.1\include;$(SolutionDir)\..\libs\bullet-2.82-r2704\src;$(SolutionDir)\..\libs\SOIL\src;$(DXSDK_DIR)\Include;$(IncludePath) + $(HAVOK_2013_1_0_r1_ROOT)\Lib\win32_vs2012_win7\debug_dll;$(BOOST_1_55_0_ROOT)\lib32-msvc-11.0;$(SolutionDir)\..\libs\glew-1.10.0\lib\Debug\Win32;$(SolutionDir)\..\libs\glfw-3.0.4\lib\Debug;$(SolutionDir)\..\libs\openal-soft-1.15.1\lib\Win32\Debug;$(SolutionDir)\..\libs\bullet-2.82-r2704\lib\Debug;$(SolutionDir)\..\libs\SOIL\lib\Debug;$(LibraryPath);$(DXSDK_DIR)\Lib\x86 $(SolutionDir)\..\bin\$(Configuration)\ $(SolutionDir)\..\obj\$(Configuration)\ - $(HAVOK_2013_1_0_r1_ROOT)\Source;$(BOOST_1_55_0_ROOT);$(SolutionDir)\..\src;$(SolutionDir)\..\libs;$(SolutionDir)\..\libs\glew-1.10.0\include;$(SolutionDir)\..\libs\glfw-3.0.4\include;$(SolutionDir)\..\libs\glm-0.9.5.3;$(SolutionDir)\..\libs\openal-soft-1.15.1\include;$(SolutionDir)\..\libs\bullet-2.82-r2704\src;$(SolutionDir)\..\libs\SOIL\src;$(IncludePath) - $(HAVOK_2013_1_0_r1_ROOT)\Lib\win32_vs2012_win7\release_dll;$(BOOST_1_55_0_ROOT)\lib32-msvc-11.0;$(SolutionDir)\..\libs\glfw-3.0.4\lib\Release;$(SolutionDir)\..\libs\glew-1.10.0\lib\Release\Win32;$(SolutionDir)\..\libs\openal-soft-1.15.1\lib\Win32\Release;$(SolutionDir)\..\libs\bullet-2.82-r2704\lib\Release;$(SolutionDir)\..\libs\SOIL\lib\Release;$(LibraryPath) + $(HAVOK_2013_1_0_r1_ROOT)\Source;$(BOOST_1_55_0_ROOT);$(SolutionDir)\..\src;$(SolutionDir)\..\libs;$(SolutionDir)\..\libs\glew-1.10.0\include;$(SolutionDir)\..\libs\glfw-3.0.4\include;$(SolutionDir)\..\libs\glm-0.9.5.3;$(SolutionDir)\..\libs\openal-soft-1.15.1\include;$(SolutionDir)\..\libs\bullet-2.82-r2704\src;$(SolutionDir)\..\libs\SOIL\src;$(DXSDK_DIR)\Include;$(IncludePath) + $(HAVOK_2013_1_0_r1_ROOT)\Lib\win32_vs2012_win7\release_dll;$(BOOST_1_55_0_ROOT)\lib32-msvc-11.0;$(SolutionDir)\..\libs\glfw-3.0.4\lib\Release;$(SolutionDir)\..\libs\glew-1.10.0\lib\Release\Win32;$(SolutionDir)\..\libs\openal-soft-1.15.1\lib\Win32\Release;$(SolutionDir)\..\libs\bullet-2.82-r2704\lib\Release;$(SolutionDir)\..\libs\SOIL\lib\Release;$(LibraryPath);$(DXSDK_DIR)\Lib\x86 $(SolutionDir)\..\bin\$(Configuration)\ $(SolutionDir)\..\obj\$(Configuration)\ Level3 - _WINDOWS;WIN32;_WIN32;_DEBUG;HK_DEBUG;HK_DEBUG_SLOW;_XT_STATICLINK;_CONSOLE;_ALLOW_ITERATOR_DEBUG_LEVEL_MISMATCH;HK_CONFIG_SIMD=1;DEBUG;_CRT_SECURE_NO_WARNINGS;_MBCS;%(PreprocessorDefinitions) + _X86_;_WINDOWS;WIN32;_WIN32;_DEBUG;HK_DEBUG;HK_DEBUG_SLOW;_XT_STATICLINK;_CONSOLE;_ALLOW_ITERATOR_DEBUG_LEVEL_MISMATCH;HK_CONFIG_SIMD=1;DEBUG;_CRT_SECURE_NO_WARNINGS;_MBCS;%(PreprocessorDefinitions) Create PrecompiledHeader.h MultiThreadedDebugDLL @@ -65,7 +65,7 @@ true - OpenAL32.lib;opengl32.lib;glu32.lib;SOIL.lib;glew32d.lib;glfw3.lib;hkBase.lib;hkVisualize.lib;hkInternal.lib;hkSerialize.lib;hkGeometryUtilities.lib;hkcdInternal.lib;hkcdCollide.lib;hkpCollide.lib;hkpConstraint.lib;hkpConstraintSolver.lib;hkpDynamics.lib;hkpInternal.lib;hkpUtilities.lib;hkSceneData.lib;hkpVehicle.lib;%(AdditionalDependencies) + OpenAL32.lib;opengl32.lib;glu32.lib;SOIL.lib;XInput9_1_0.lib;glew32d.lib;glfw3.lib;hkBase.lib;hkVisualize.lib;hkInternal.lib;hkSerialize.lib;hkGeometryUtilities.lib;hkcdInternal.lib;hkcdCollide.lib;hkpCollide.lib;hkpConstraint.lib;hkpConstraintSolver.lib;hkpDynamics.lib;hkpInternal.lib;hkpUtilities.lib;hkSceneData.lib;hkpVehicle.lib;%(AdditionalDependencies) /ignore:4221 @@ -80,7 +80,7 @@ true true true - _CRT_SECURE_NO_WARNINGS;_MBCS;HK_CONFIG_SIMD=1;%(PreprocessorDefinitions) + _X86_;_CRT_SECURE_NO_WARNINGS;_MBCS;HK_CONFIG_SIMD=1;%(PreprocessorDefinitions) Create PrecompiledHeader.h StreamingSIMDExtensions2 @@ -89,7 +89,7 @@ true true true - OpenAL32.lib;opengl32.lib;glu32.lib;SOIL.lib;glew32.lib;glfw3.lib;hkBase.lib;hkVisualize.lib;hkInternal.lib;hkSerialize.lib;hkGeometryUtilities.lib;hkcdInternal.lib;hkcdCollide.lib;hkpCollide.lib;hkpConstraint.lib;hkpConstraintSolver.lib;hkpDynamics.lib;hkpInternal.lib;hkpUtilities.lib;hkSceneData.lib;hkpVehicle.lib;%(AdditionalDependencies) + OpenAL32.lib;opengl32.lib;glu32.lib;SOIL.lib;XInput9_1_0.lib;glew32.lib;glfw3.lib;hkBase.lib;hkVisualize.lib;hkInternal.lib;hkSerialize.lib;hkGeometryUtilities.lib;hkcdInternal.lib;hkcdCollide.lib;hkpCollide.lib;hkpConstraint.lib;hkpConstraintSolver.lib;hkpDynamics.lib;hkpInternal.lib;hkpUtilities.lib;hkSceneData.lib;hkpVehicle.lib;%(AdditionalDependencies) @@ -150,8 +150,12 @@ + + + + diff --git a/vs11/Returngeance/Returngeance.vcxproj.filters b/vs11/Returngeance/Returngeance.vcxproj.filters index 0323b51..081f144 100755 --- a/vs11/Returngeance/Returngeance.vcxproj.filters +++ b/vs11/Returngeance/Returngeance.vcxproj.filters @@ -328,6 +328,18 @@ Physics\Components + + Input\Events + + + Input\Events + + + Input\Events + + + Input\Events + From ce5b62cf6d2b9de188d1e93817d7842681d1cb44 Mon Sep 17 00:00:00 2001 From: ViktorLjung Date: Tue, 13 May 2014 03:32:58 +0200 Subject: [PATCH 65/65] =?UTF-8?q?Shots=20fired!=20=EF=BC=88=20=EF=BE=9F?= =?UTF-8?q?=D0=94=EF=BE=9F=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- assets | 2 +- src/Components/BarrelSteering.h | 7 +- src/Components/Shot.h | 17 ----- src/Components/TowerSteering.h | 5 +- src/GameWorld.cpp | 64 ++++++++++--------- src/GameWorld.h | 1 - src/Systems/PhysicsSystem.cpp | 7 +- src/Systems/TankSteeringSystem.cpp | 28 ++++---- src/Systems/TankSteeringSystem.h | 5 +- src/World.cpp | 4 ++ vs11/Returngeance/Returngeance.vcxproj | 1 - .../Returngeance/Returngeance.vcxproj.filters | 3 - 12 files changed, 70 insertions(+), 74 deletions(-) delete mode 100644 src/Components/Shot.h diff --git a/assets b/assets index 05b3d22..15ac025 160000 --- a/assets +++ b/assets @@ -1 +1 @@ -Subproject commit 05b3d22b01131512cc370dacd507a22e88c46e57 +Subproject commit 15ac02523ad374b4aaf60a16db89b1934de7f303 diff --git a/src/Components/BarrelSteering.h b/src/Components/BarrelSteering.h index f3ee943..1cd71be 100644 --- a/src/Components/BarrelSteering.h +++ b/src/Components/BarrelSteering.h @@ -9,10 +9,13 @@ namespace Components struct BarrelSteering : Component { BarrelSteering() - : Velocity(1.f), Axis(glm::vec3(0,1,0)){ } - float Velocity; + : TurnSpeed(1.f), Axis(glm::vec3(0,1,0)){ } + float TurnSpeed; glm::vec3 Axis; EntityID ShotTemplate; + float ShotSpeed; + + virtual BarrelSteering* Clone() const override { return new BarrelSteering(*this); } }; } diff --git a/src/Components/Shot.h b/src/Components/Shot.h deleted file mode 100644 index 324a9c5..0000000 --- a/src/Components/Shot.h +++ /dev/null @@ -1,17 +0,0 @@ -#ifndef Shot_h__ -#define Shot_h__ - -#include "Component.h" - -namespace Components -{ - - struct Shot : Component - { - Shot(); - float Speed; - }; - -} - -#endif // Shot_h__ \ No newline at end of file diff --git a/src/Components/TowerSteering.h b/src/Components/TowerSteering.h index 38a2320..f4f72b9 100644 --- a/src/Components/TowerSteering.h +++ b/src/Components/TowerSteering.h @@ -9,10 +9,11 @@ struct TowerSteering : Component { TowerSteering() - : Velocity(1.f), Axis(glm::vec3(0,1,0)){ } + : TurnSpeed(1.f), Axis(glm::vec3(0,1,0)){ } - float Velocity; + float TurnSpeed; glm::vec3 Axis; + virtual TowerSteering* Clone() const override { return new TowerSteering(*this); } }; } diff --git a/src/GameWorld.cpp b/src/GameWorld.cpp index c3f653e..6368764 100755 --- a/src/GameWorld.cpp +++ b/src/GameWorld.cpp @@ -221,7 +221,7 @@ void GameWorld::Initialize() auto tank = CreateEntity(); auto transform = AddComponent(tank, "Transform"); transform->Position = glm::vec3(0, 5, 0); - transform->Orientation = glm::angleAxis(glm::pi()/2, glm::vec3(0, 1, 0)); + //transform->Orientation = glm::angleAxis(0.f, glm::vec3(0, 1, 0)); auto physics = AddComponent(tank, "Physics"); physics->Mass = 45000; physics->Static = false; @@ -260,7 +260,7 @@ void GameWorld::Initialize() model->ModelFile = "Models/Tank/Fix/Top.obj"; auto towerSteering = AddComponent(tower, "TowerSteering"); towerSteering->Axis = glm::vec3(0.f, 1.f, 0.f); - towerSteering->Velocity = glm::pi()/4.f; + towerSteering->TurnSpeed = glm::pi()/4.f; { auto barrel = CreateEntity(tower); auto transform = AddComponent(barrel, "Transform"); @@ -269,21 +269,23 @@ void GameWorld::Initialize() model->ModelFile = "Models/Tank/Fix/Barrel.obj"; auto barrelSteering = AddComponent(barrel, "BarrelSteering"); barrelSteering->Axis = glm::vec3(1.f, 0.f, 0.f); - barrelSteering->Velocity = glm::pi()/4.f; + barrelSteering->TurnSpeed = glm::pi()/4.f; + barrelSteering->ShotSpeed = 70.f; { auto shot = CreateEntity(barrel); auto transform = AddComponent(shot, "Transform"); - transform->Position = glm::vec3(0.35f, 1.f, -2.f); - auto shotComponent = AddComponent(shot, "Shot"); - shotComponent->Speed = 5; + transform->Position = glm::vec3(0.35f, 0.f, -2.f); + transform->Orientation = glm::angleAxis(-glm::pi()/2.f, glm::vec3(1, 0, 0)); + transform->Scale = glm::vec3(3.f); + AddComponent(shot, "Template"); auto physics = AddComponent(shot, "Physics"); physics->Mass = 10.f; physics->Static = false; auto modelComponent = AddComponent(shot, "Model"); - modelComponent->ModelFile = "Models/Placeholders/PhysicsTest/Cube.obj"; + modelComponent->ModelFile = "Models/Placeholders/rocket/Rocket.obj"; { - auto shape = CreateEntity(tank); + auto shape = CreateEntity(shot); auto transform = AddComponent(shape, "Transform"); auto boxShape = AddComponent(shape, "BoxShape"); boxShape->Width = 0.5f; @@ -501,7 +503,7 @@ void GameWorld::Initialize() } CommitEntity(wheel); - auto entity = CreateEntity(tank); + /*auto entity = CreateEntity(tank); auto transformComponent = AddComponent(entity, "Transform"); transformComponent->Position = glm::vec3(2,-1.7,2.0); transformComponent->Scale = glm::vec3(3,3,3); @@ -523,7 +525,7 @@ void GameWorld::Initialize() spriteComponent->SpriteFile = "Models/Textures/Sprites/Dust.png"; emitterComponent->ParticleTemplate = particleEntity; - CommitEntity(particleEntity); + CommitEntity(particleEntity);*/ } { @@ -585,29 +587,29 @@ void GameWorld::Initialize() } CommitEntity(wheel); - auto entity = CreateEntity(tank); - auto transformComponent = AddComponent(entity, "Transform"); - transformComponent->Position = glm::vec3(-2,-1.7,2.0); - transformComponent->Scale = glm::vec3(3,3,3); - transformComponent->Orientation = glm::angleAxis(glm::pi()/2, glm::vec3(1,0,0)); - auto emitterComponent = AddComponent(entity, "ParticleEmitter"); - emitterComponent->SpawnCount = 2; - emitterComponent->SpawnFrequency = 0.005; - emitterComponent->SpreadAngle = glm::pi(); - emitterComponent->UseGoalVelocity = false; - emitterComponent->LifeTime = 0.5; - //emitterComponent->AngularVelocitySpectrum.push_back(glm::pi() / 100); - emitterComponent->ScaleSpectrum.push_back(glm::vec3(0.05)); - CommitEntity(entity); + //auto entity = CreateEntity(tank); + //auto transformComponent = AddComponent(entity, "Transform"); + //transformComponent->Position = glm::vec3(-2,-1.7,2.0); + //transformComponent->Scale = glm::vec3(3,3,3); + //transformComponent->Orientation = glm::angleAxis(glm::pi()/2, glm::vec3(1,0,0)); + //auto emitterComponent = AddComponent(entity, "ParticleEmitter"); + //emitterComponent->SpawnCount = 2; + //emitterComponent->SpawnFrequency = 0.005; + //emitterComponent->SpreadAngle = glm::pi(); + //emitterComponent->UseGoalVelocity = false; + //emitterComponent->LifeTime = 0.5; + ////emitterComponent->AngularVelocitySpectrum.push_back(glm::pi() / 100); + //emitterComponent->ScaleSpectrum.push_back(glm::vec3(0.05)); + //CommitEntity(entity); - auto particleEntity = CreateEntity(entity); - auto TEMP = AddComponent(particleEntity, "Transform"); - TEMP->Scale = glm::vec3(0); - auto spriteComponent = AddComponent(particleEntity, "Sprite"); - spriteComponent->SpriteFile = "Models/Textures/Sprites/Dust.png"; - emitterComponent->ParticleTemplate = particleEntity; + //auto particleEntity = CreateEntity(entity); + //auto TEMP = AddComponent(particleEntity, "Transform"); + //TEMP->Scale = glm::vec3(0); + //auto spriteComponent = AddComponent(particleEntity, "Sprite"); + //spriteComponent->SpriteFile = "Models/Textures/Sprites/Dust.png"; + //emitterComponent->ParticleTemplate = particleEntity; - CommitEntity(particleEntity); + //CommitEntity(particleEntity); } CommitEntity(tank); diff --git a/src/GameWorld.h b/src/GameWorld.h index 27a36dd..f884e2f 100755 --- a/src/GameWorld.h +++ b/src/GameWorld.h @@ -38,7 +38,6 @@ #include "Components/TankSteering.h" #include "Components/TowerSteering.h" #include "Components/BarrelSteering.h" -#include "Components/Shot.h" class GameWorld : public World { diff --git a/src/Systems/PhysicsSystem.cpp b/src/Systems/PhysicsSystem.cpp index 5e4a71f..8efa4bb 100644 --- a/src/Systems/PhysicsSystem.cpp +++ b/src/Systems/PhysicsSystem.cpp @@ -31,7 +31,7 @@ void Systems::PhysicsSystem::Initialize() // Events EVENT_SUBSCRIBE_MEMBER(m_ETankSteer, &Systems::PhysicsSystem::OnTankSteer); - EVENT_SUBSCRIBE_MEMBER(m_ETankSteer, &Systems::PhysicsSystem::OnSetVelocity); + EVENT_SUBSCRIBE_MEMBER(m_ESetVelocity, &Systems::PhysicsSystem::OnSetVelocity); hkMemorySystem::FrameInfo finfo(6000 * 1024); // Allocate 6MB of Physics solver buffer hkMemoryRouter* memoryRouter = hkMemoryInitUtil::initDefault(hkMallocAllocator::m_defaultMallocAllocator, finfo); @@ -583,5 +583,8 @@ bool Systems::PhysicsSystem::OnTankSteer(const Events::TankSteer &event) bool Systems::PhysicsSystem::OnSetVelocity( const Events::SetVelocity &event ) { - + m_PhysicsWorld->markForWrite(); + m_RigidBodies[event.Entity]->setLinearVelocity(ConvertPosition(event.Velocity)); + m_PhysicsWorld->unmarkForWrite(); + return true; } diff --git a/src/Systems/TankSteeringSystem.cpp b/src/Systems/TankSteeringSystem.cpp index 5e6c025..11f83b6 100644 --- a/src/Systems/TankSteeringSystem.cpp +++ b/src/Systems/TankSteeringSystem.cpp @@ -38,7 +38,7 @@ void Systems::TankSteeringSystem::UpdateEntity(double dt, EntityID entity, Entit if(towerSteeringComponent) { auto transformComponent = m_World->GetComponent(entity, "Transform"); - glm::quat orientation = glm::angleAxis(towerSteeringComponent->Velocity * m_TowerInputController->TowerDirection * (float)dt, towerSteeringComponent->Axis); + glm::quat orientation = glm::angleAxis(towerSteeringComponent->TurnSpeed * m_TowerInputController->TowerDirection * (float)dt, towerSteeringComponent->Axis); transformComponent->Orientation *= orientation; } @@ -46,21 +46,25 @@ void Systems::TankSteeringSystem::UpdateEntity(double dt, EntityID entity, Entit if(barrelSteeringComponent) { auto transformComponent = m_World->GetComponent(entity, "Transform"); - glm::quat orientation = glm::angleAxis(barrelSteeringComponent->Velocity * m_TowerInputController->BarrelDirection * (float)dt, barrelSteeringComponent->Axis); + auto absoluteTransform = m_World->GetSystem("TransformSystem")->AbsoluteTransform(entity); + glm::quat orientation = glm::angleAxis(barrelSteeringComponent->TurnSpeed * m_TowerInputController->BarrelDirection * (float)dt, barrelSteeringComponent->Axis); transformComponent->Orientation *= orientation; - } - auto shotComponent = m_World->GetComponent(entity, "Shot"); - if(shotComponent) - { - if(m_TowerInputController->shoot) + if(m_TowerInputController->Shoot && m_TimeSinceLastShot[entity] > 1.0) { - auto absoluteOrientation = m_World->GetSystem("TransformSystem")->AbsoluteOrientation(entity); + EntityID clone = m_World->CloneEntity(barrelSteeringComponent->ShotTemplate); + auto templateAbsoluteTransform = m_World->GetSystem("TransformSystem")->AbsoluteTransform(barrelSteeringComponent->ShotTemplate); + auto cloneTransform = m_World->GetComponent(clone, "Transform"); + cloneTransform->Position = templateAbsoluteTransform.Position; + cloneTransform->Orientation = absoluteTransform.Orientation * cloneTransform->Orientation; Events::SetVelocity e; - e.Entity = entity; - e.Velocity = absoluteOrientation * (glm::vec3(0.f, 0.f, 1.f) * shotComponent->Speed * (float)dt); + e.Entity = clone; + e.Velocity = absoluteTransform.Orientation * (glm::vec3(0.f, 0.f, -1.f) * barrelSteeringComponent->ShotSpeed); EventBroker->Publish(e); + m_TimeSinceLastShot[entity] = 0; } + + m_TimeSinceLastShot[entity] += dt; } } @@ -74,7 +78,7 @@ void Systems::TankSteeringSystem::TowerSteeringInputController::Update( double d { TowerDirection = m_TowerDirection; BarrelDirection = m_BarrelDirection; - shoot = m_Shoot; + Shoot = m_Shoot; } bool Systems::TankSteeringSystem::TankSteeringInputController::OnCommand(const Events::InputCommand &event) @@ -111,7 +115,7 @@ bool Systems::TankSteeringSystem::TowerSteeringInputController::OnCommand( const else if (event.Command == "shoot") { - shoot = (bool)val; + m_Shoot = val > 0; } return true; } diff --git a/src/Systems/TankSteeringSystem.h b/src/Systems/TankSteeringSystem.h index 1622063..d264325 100644 --- a/src/Systems/TankSteeringSystem.h +++ b/src/Systems/TankSteeringSystem.h @@ -8,7 +8,6 @@ #include "Components/TowerSteering.h" #include "Components/BarrelSteering.h" #include "Components/Vehicle.h" -#include "Components/Shot.h" #include "Systems/TransformSystem.h" #include "InputController.h" @@ -32,6 +31,8 @@ namespace Systems std::unique_ptr m_TankInputController; class TowerSteeringInputController; std::unique_ptr m_TowerInputController; + + std::map m_TimeSinceLastShot; }; class TankSteeringSystem::TankSteeringInputController : InputController @@ -76,7 +77,7 @@ namespace Systems float TowerDirection; float BarrelDirection; - bool shoot; + bool Shoot; void Update(double dt); protected: virtual bool OnCommand(const Events::InputCommand &event); diff --git a/src/World.cpp b/src/World.cpp index 01713ab..c84a2bd 100755 --- a/src/World.cpp +++ b/src/World.cpp @@ -170,6 +170,8 @@ EntityID World::CloneEntity(EntityID entity, EntityID parent /* = 0 */) for (auto pair : m_EntityComponents[entity]) { auto type = pair.first; + if (type == "Template") + continue; auto component = std::shared_ptr(pair.second->Clone()); if (component != nullptr) { @@ -186,6 +188,8 @@ EntityID World::CloneEntity(EntityID entity, EntityID parent /* = 0 */) } } + CommitEntity(clone); + return clone; } diff --git a/vs11/Returngeance/Returngeance.vcxproj b/vs11/Returngeance/Returngeance.vcxproj index 8d2c9e7..297bb80 100755 --- a/vs11/Returngeance/Returngeance.vcxproj +++ b/vs11/Returngeance/Returngeance.vcxproj @@ -139,7 +139,6 @@ - diff --git a/vs11/Returngeance/Returngeance.vcxproj.filters b/vs11/Returngeance/Returngeance.vcxproj.filters index f3d89c8..b58c65d 100755 --- a/vs11/Returngeance/Returngeance.vcxproj.filters +++ b/vs11/Returngeance/Returngeance.vcxproj.filters @@ -337,9 +337,6 @@ Physics\Components - - Physics\Components - Physics\Events