Indentation style changed to Allman

Using Artistic Style (http://astyle.sourceforge.net/)
Options:
--style=allman
--indent=tab
--keep-one-line-blocks
--align-pointer=type
--align-reference=name
This commit is contained in:
2014-04-11 20:56:19 +02:00
parent 34bcfbce08
commit 4c081d0e1c
56 changed files with 599 additions and 438 deletions
+5 -5
View File
@@ -68,11 +68,11 @@ void Camera::Orientation(glm::quat val)
void Camera::UpdateProjectionMatrix() void Camera::UpdateProjectionMatrix()
{ {
m_ProjectionMatrix = glm::perspective( m_ProjectionMatrix = glm::perspective(
m_FOV, m_FOV,
m_AspectRatio, m_AspectRatio,
m_NearClip, m_NearClip,
m_FarClip m_FarClip
); );
} }
void Camera::UpdateViewMatrix() void Camera::UpdateViewMatrix()
+10 -10
View File
@@ -5,15 +5,15 @@
namespace Components namespace Components
{ {
// http://bulletphysics.org/mediawiki-1.5.8/index.php/Constraints // http://bulletphysics.org/mediawiki-1.5.8/index.php/Constraints
struct BallSocketConstraint : Component struct BallSocketConstraint : Component
{ {
// Create constraint between these entities // Create constraint between these entities
EntityID EntityA; EntityID EntityA;
EntityID EntityB; EntityID EntityB;
// The pivot point in local coordinates // The pivot point in local coordinates
glm::vec3 PivotA; glm::vec3 PivotA;
glm::vec3 PivotB; glm::vec3 PivotB;
}; };
} }
#endif // Components_BallSocketConstraint_h__ #endif // Components_BallSocketConstraint_h__
+6 -6
View File
@@ -6,12 +6,12 @@
namespace Components namespace Components
{ {
struct BoxShape : Component struct BoxShape : Component
{ {
float Height; float Height;
float Width; float Width;
float Depth; float Depth;
}; };
} }
+3 -3
View File
@@ -5,10 +5,10 @@
namespace Components namespace Components
{ {
struct CompoundShape : Component struct CompoundShape : Component
{ {
}; };
} }
#endif // Components_CompoundShape_h__ #endif // Components_CompoundShape_h__
+4 -4
View File
@@ -7,10 +7,10 @@
namespace Components namespace Components
{ {
struct CustomShape : Component struct CustomShape : Component
{ {
std::string fileName; std::string fileName;
}; };
} }
+4 -4
View File
@@ -5,10 +5,10 @@
namespace Components namespace Components
{ {
struct FreeSteering : Component struct FreeSteering : Component
{ {
float Speed = 35; float Speed = 35;
}; };
} }
#endif // FreeSteering_h__ #endif // FreeSteering_h__
+25 -25
View File
@@ -5,31 +5,31 @@
namespace Components namespace Components
{ {
// http://bulletphysics.org/mediawiki-1.5.8/index.php/Constraints // http://bulletphysics.org/mediawiki-1.5.8/index.php/Constraints
struct HingeConstraint : Component struct HingeConstraint : Component
{ {
// Create constraint between these entities // Create constraint between these entities
EntityID EntityA; EntityID EntityA;
EntityID EntityB; EntityID EntityB;
// The pivot point in local coordinates // The pivot point in local coordinates
glm::vec3 PivotA; glm::vec3 PivotA;
glm::vec3 PivotB; glm::vec3 PivotB;
// The axis to rotate around // The axis to rotate around
glm::vec3 AxisA; glm::vec3 AxisA;
glm::vec3 AxisB; glm::vec3 AxisB;
/* /*
void setLimit(btScalar low, void setLimit(btScalar low,
btScalar high, btScalar high,
btScalar softness = 0.9f, btScalar softness = 0.9f,
btScalar_biasFactor = 0.3f, btScalar_biasFactor = 0.3f,
btScalar relaxationFactor = 1.0f) btScalar relaxationFactor = 1.0f)
*/ */
float LowLimit; float LowLimit;
float HighLimit; float HighLimit;
float Softness = 0.9f; float Softness = 0.9f;
float BiasFactor = 0.3f; float BiasFactor = 0.3f;
float RelaxationFactor = 1.0f; float RelaxationFactor = 1.0f;
}; };
} }
#endif // Components_HingeConstraint_h__ #endif // Components_HingeConstraint_h__
+4 -4
View File
@@ -5,10 +5,10 @@
namespace Components namespace Components
{ {
struct MeshShape : Component struct MeshShape : Component
{ {
std::string Filename; std::string Filename;
}; };
} }
#endif // Components_MeshShape_h__ #endif // Components_MeshShape_h__
+6 -6
View File
@@ -6,12 +6,12 @@
namespace Components namespace Components
{ {
struct Physics : Component struct Physics : Component
{ {
float Mass = 0; float Mass = 0;
float Friction = 0; float Friction = 0;
glm::vec3 Gravity = glm::vec3(0, -9.82f, 0); glm::vec3 Gravity = glm::vec3(0, -9.82f, 0);
}; };
} }
+7 -7
View File
@@ -5,12 +5,12 @@
namespace Components namespace Components
{ {
// http://bulletphysics.org/mediawiki-1.5.8/index.php/Constraints // http://bulletphysics.org/mediawiki-1.5.8/index.php/Constraints
struct SliderConstraint : Component struct SliderConstraint : Component
{ {
// Create constraint between these entities // Create constraint between these entities
EntityID EntityA; EntityID EntityA;
EntityID EntityB; EntityID EntityB;
}; };
} }
#endif // Components_SliderConstraint_h__ #endif // Components_SliderConstraint_h__
+5 -5
View File
@@ -6,11 +6,11 @@
namespace Components namespace Components
{ {
struct SphereShape : Component struct SphereShape : Component
{ {
float Radius; float Radius;
float RollingFriction; float RollingFriction;
}; };
} }
+4 -4
View File
@@ -5,10 +5,10 @@
namespace Components namespace Components
{ {
struct StaticMeshShape : Component struct StaticMeshShape : Component
{ {
std::string Filename; std::string Filename;
}; };
} }
#endif // Components_StaticMeshShape_h__ #endif // Components_StaticMeshShape_h__
+15 -12
View File
@@ -15,7 +15,8 @@ CubemapTexture::CubemapTexture(std::string posXFile, std::string negXFile, std::
CubemapTexture::~CubemapTexture() CubemapTexture::~CubemapTexture()
{ {
if (m_Texture != 0) { if (m_Texture != 0)
{
//glDeleteTextures(1, &m_Texture); //glDeleteTextures(1, &m_Texture);
} }
} }
@@ -25,17 +26,18 @@ void CubemapTexture::Load()
m_Loaded = true; m_Loaded = true;
m_Texture = SOIL_load_OGL_cubemap( m_Texture = SOIL_load_OGL_cubemap(
m_TextureFiles[0].c_str(), m_TextureFiles[0].c_str(),
m_TextureFiles[1].c_str(), m_TextureFiles[1].c_str(),
m_TextureFiles[2].c_str(), m_TextureFiles[2].c_str(),
m_TextureFiles[3].c_str(), m_TextureFiles[3].c_str(),
m_TextureFiles[4].c_str(), m_TextureFiles[4].c_str(),
m_TextureFiles[5].c_str(), m_TextureFiles[5].c_str(),
SOIL_LOAD_AUTO, SOIL_LOAD_AUTO,
SOIL_CREATE_NEW_ID, SOIL_CREATE_NEW_ID,
0); 0);
if (m_Texture == 0) { if (m_Texture == 0)
{
LOG_ERROR("SOIL cubemap loading error: %s", SOIL_last_result()); LOG_ERROR("SOIL cubemap loading error: %s", SOIL_last_result());
return; return;
} }
@@ -49,7 +51,8 @@ void CubemapTexture::Load()
void CubemapTexture::Bind(GLenum textureUnit) void CubemapTexture::Bind(GLenum textureUnit)
{ {
if (!m_Loaded) { if (!m_Loaded)
{
LOG_WARNING("Cubemap \"%s\" was not loaded before being bound! Attempting to load now...", m_TextureFiles[0].c_str()); LOG_WARNING("Cubemap \"%s\" was not loaded before being bound! Attempting to load now...", m_TextureFiles[0].c_str());
Load(); Load();
} }
+6 -6
View File
@@ -7,12 +7,12 @@ class CubemapTexture
{ {
public: public:
CubemapTexture( CubemapTexture(
std::string posXFile, std::string posXFile,
std::string negXFile, std::string negXFile,
std::string posYFile, std::string posYFile,
std::string negYFile, std::string negYFile,
std::string posZFile, std::string posZFile,
std::string negZFile); std::string negZFile);
~CubemapTexture(); ~CubemapTexture();
void Load(); void Load();
+5 -2
View File
@@ -18,9 +18,12 @@ public:
T Create(std::string name) T Create(std::string name)
{ {
auto it = m_FactoryFunctions.find(name); auto it = m_FactoryFunctions.find(name);
if (it != m_FactoryFunctions.end()) { if (it != m_FactoryFunctions.end())
{
return it->second(); return it->second();
} else { }
else
{
return nullptr; return nullptr;
} }
} }
+32 -16
View File
@@ -12,13 +12,16 @@ Model::Model(OBJ &obj)
OBJ::MaterialInfo* currentMaterial = nullptr; OBJ::MaterialInfo* currentMaterial = nullptr;
TextureGroup* currentTexGroup = nullptr; TextureGroup* currentTexGroup = nullptr;
int index = 0; int index = 0;
for (auto face : obj.Faces) { for (auto face : obj.Faces)
if (face.Material == nullptr) { {
if (face.Material == nullptr)
{
LOG_ERROR("Missing material for .obj file \"%s\"", obj.Path().string().c_str()); LOG_ERROR("Missing material for .obj file \"%s\"", obj.Path().string().c_str());
return; return;
} }
// New material // New material
if (face.Material != currentMaterial) { if (face.Material != currentMaterial)
{
currentMaterial = face.Material; currentMaterial = face.Material;
// Load texture // Load texture
std::shared_ptr<Texture> texture = std::make_shared<Texture>(currentMaterial->TextureFile); std::shared_ptr<Texture> texture = std::make_shared<Texture>(currentMaterial->TextureFile);
@@ -30,18 +33,21 @@ Model::Model(OBJ &obj)
} }
// Face definitions // Face definitions
for (auto faceDef : face.Definitions) { for (auto faceDef : face.Definitions)
{
glm::vec3 vertex; glm::vec3 vertex;
std::tie(vertex.x, vertex.y, vertex.z) = obj.Vertices.at(faceDef.VertexIndex - 1); std::tie(vertex.x, vertex.y, vertex.z) = obj.Vertices.at(faceDef.VertexIndex - 1);
Vertices.push_back(vertex); Vertices.push_back(vertex);
if (faceDef.NormalIndex != 0) { if (faceDef.NormalIndex != 0)
{
glm::vec3 normal; glm::vec3 normal;
std::tie(normal.x, normal.y, normal.z) = obj.Normals.at(faceDef.NormalIndex - 1); std::tie(normal.x, normal.y, normal.z) = obj.Normals.at(faceDef.NormalIndex - 1);
Normals.push_back(normal); Normals.push_back(normal);
} }
if (faceDef.TextureCoordIndex != 0) { if (faceDef.TextureCoordIndex != 0)
{
glm::vec2 texCoord; glm::vec2 texCoord;
// TODO: W-coord? // TODO: W-coord?
std::tie(texCoord.x, texCoord.y, std::ignore) = obj.TextureCoords.at(faceDef.TextureCoordIndex - 1); std::tie(texCoord.x, texCoord.y, std::ignore) = obj.TextureCoords.at(faceDef.TextureCoordIndex - 1);
@@ -53,19 +59,20 @@ Model::Model(OBJ &obj)
} }
} }
if (Vertices.size() > 0) { if (Vertices.size() > 0)
{
CreateBuffers(Vertices, Normals, TextureCoords); CreateBuffers(Vertices, Normals, TextureCoords);
} }
} }
bool Model::Loadobj(const char* path, std::vector <glm::vec3> & out_vertices, std::vector <glm::vec3> &out_normals, std::vector <glm::vec2> & out_TextureCoords) bool Model::Loadobj(const char* path, std::vector <glm::vec3> &out_vertices, std::vector <glm::vec3> &out_normals, std::vector <glm::vec2> &out_TextureCoords)
{ {
std::vector< unsigned int > vertexIndices, TextureCoordIndices, normalIndices; std::vector< unsigned int > vertexIndices, TextureCoordIndices, normalIndices;
std::vector< glm::vec3 > temp_vertices; std::vector< glm::vec3 > temp_vertices;
std::vector< glm::vec2 > temp_TextureCoords; std::vector< glm::vec2 > temp_TextureCoords;
std::vector< glm::vec3 > temp_normals; std::vector< glm::vec3 > temp_normals;
FILE * file = fopen(path, "r"); FILE* file = fopen(path, "r");
LOG_INFO("Loading .obj file"); LOG_INFO("Loading .obj file");
if( file == NULL ) if( file == NULL )
{ {
@@ -154,7 +161,7 @@ bool Model::Loadobj(const char* path, std::vector <glm::vec3> & out_vertices, st
fscanf(file, "%s\n", &fileName); fscanf(file, "%s\n", &fileName);
FILE * mtlfile = fopen(fileName, "r"); FILE* mtlfile = fopen(fileName, "r");
LOG_INFO("Loading .mtl file"); LOG_INFO("Loading .mtl file");
if( mtlfile == NULL ) if( mtlfile == NULL )
{ {
@@ -197,32 +204,41 @@ void Model::CreateBuffers( std::vector<glm::vec3> vertices, std::vector<glm::vec
LOG_INFO("Generating VertexBuffer"); LOG_INFO("Generating VertexBuffer");
glGenBuffers(1, &VertexBuffer); glGenBuffers(1, &VertexBuffer);
if (vertices.size() > 0) { if (vertices.size() > 0)
{
glBindBuffer(GL_ARRAY_BUFFER, VertexBuffer); glBindBuffer(GL_ARRAY_BUFFER, VertexBuffer);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec3), &vertices[0], GL_STATIC_DRAW); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec3), &vertices[0], GL_STATIC_DRAW);
GLERROR("GLEW: BufferFail, VertexBuffer"); GLERROR("GLEW: BufferFail, VertexBuffer");
} else { }
else
{
LOG_WARNING("Created empty vertex buffer!"); LOG_WARNING("Created empty vertex buffer!");
} }
LOG_INFO("Generating NormalBuffer"); LOG_INFO("Generating NormalBuffer");
glGenBuffers(1, &NormalBuffer); glGenBuffers(1, &NormalBuffer);
if (normals.size() > 0) { if (normals.size() > 0)
{
glBindBuffer(GL_ARRAY_BUFFER, NormalBuffer); glBindBuffer(GL_ARRAY_BUFFER, NormalBuffer);
glBufferData(GL_ARRAY_BUFFER, normals.size() * sizeof(glm::vec3), &normals[0], GL_STATIC_DRAW); glBufferData(GL_ARRAY_BUFFER, normals.size() * sizeof(glm::vec3), &normals[0], GL_STATIC_DRAW);
GLERROR("GLEW: BufferFail, NormalBuffer"); GLERROR("GLEW: BufferFail, NormalBuffer");
} else { }
else
{
LOG_WARNING("Created empty normal buffer!"); LOG_WARNING("Created empty normal buffer!");
} }
LOG_INFO("Generating textureCoordBuffer"); LOG_INFO("Generating textureCoordBuffer");
glGenBuffers(1, &TextureCoordBuffer); glGenBuffers(1, &TextureCoordBuffer);
if (textureCoords.size() > 0) { if (textureCoords.size() > 0)
{
glBindBuffer(GL_ARRAY_BUFFER, TextureCoordBuffer); glBindBuffer(GL_ARRAY_BUFFER, TextureCoordBuffer);
glBufferData(GL_ARRAY_BUFFER, textureCoords.size() * sizeof(glm::vec2), &textureCoords[0], GL_STATIC_DRAW); glBufferData(GL_ARRAY_BUFFER, textureCoords.size() * sizeof(glm::vec2), &textureCoords[0], GL_STATIC_DRAW);
GLERROR("GLEW: BufferFail, TextureCoordBuffer"); GLERROR("GLEW: BufferFail, TextureCoordBuffer");
} else { }
else
{
LOG_WARNING("Created empty texture coordinate buffer!"); LOG_WARNING("Created empty texture coordinate buffer!");
} }
+9 -9
View File
@@ -43,17 +43,17 @@ private:
GLuint TextureCoordBuffer; GLuint TextureCoordBuffer;
bool Loadobj( bool Loadobj(
const char* path, const char* path,
std::vector <glm::vec3> & out_vertices, std::vector <glm::vec3> &out_vertices,
std::vector <glm::vec3> &out_normals, std::vector <glm::vec3> &out_normals,
std::vector <glm::vec2> & out_TextureCoords std::vector <glm::vec2> &out_TextureCoords
); );
void CreateBuffers( void CreateBuffers(
std::vector<glm::vec3> _Vertices, std::vector<glm::vec3> _Vertices,
std::vector<glm::vec3> _Normals, std::vector<glm::vec3> _Normals,
std::vector<glm::vec2>_TextureCoords std::vector<glm::vec2>_TextureCoords
); );
}; };
#endif // Model_h__ #endif // Model_h__
+54 -26
View File
@@ -7,7 +7,8 @@ bool OBJ::LoadFromFile(std::string filename)
// http://paulbourke.net/dataformats/obj/ // http://paulbourke.net/dataformats/obj/
std::ifstream file(m_Path.string()); std::ifstream file(m_Path.string());
if (!file.is_open()) { if (!file.is_open())
{
LOG_ERROR("Failed to open .obj \"%s\"", m_Path.string().c_str()); LOG_ERROR("Failed to open .obj \"%s\"", m_Path.string().c_str());
return false; return false;
} }
@@ -15,7 +16,8 @@ bool OBJ::LoadFromFile(std::string filename)
LOG_INFO("Parsing .obj \"%s\"", m_Path.string().c_str()); LOG_INFO("Parsing .obj \"%s\"", m_Path.string().c_str());
std::string line; std::string line;
while (std::getline(file, line)) { while (std::getline(file, line))
{
if (line.length() == 0) if (line.length() == 0)
continue; continue;
@@ -29,7 +31,8 @@ bool OBJ::LoadFromFile(std::string filename)
continue; continue;
// Material files // Material files
if (prefix == "mtllib") { if (prefix == "mtllib")
{
std::string materialFilename; std::string materialFilename;
ss >> materialFilename; ss >> materialFilename;
m_MaterialPath = m_Path.branch_path() / materialFilename; m_MaterialPath = m_Path.branch_path() / materialFilename;
@@ -38,7 +41,8 @@ bool OBJ::LoadFromFile(std::string filename)
} }
// Material statement // Material statement
if (prefix == "usemtl") { if (prefix == "usemtl")
{
std::string material; std::string material;
ss >> material; ss >> material;
m_CurrentMaterial = &Materials[material]; m_CurrentMaterial = &Materials[material];
@@ -46,7 +50,8 @@ bool OBJ::LoadFromFile(std::string filename)
} }
// Vertices // Vertices
if (prefix == "v") { if (prefix == "v")
{
float x, y, z; float x, y, z;
ss >> x >> y >> z; ss >> x >> y >> z;
Vertices.push_back(std::make_tuple(x, y, z)); Vertices.push_back(std::make_tuple(x, y, z));
@@ -54,26 +59,30 @@ bool OBJ::LoadFromFile(std::string filename)
} }
// Normals // Normals
if (prefix == "vn") { if (prefix == "vn")
{
float x, y, z; float x, y, z;
ss >> x >> y >> z; ss >> x >> y >> z;
Normals.push_back(std::make_tuple(x, y, z)); Normals.push_back(std::make_tuple(x, y, z));
} }
// Texture coordinates // Texture coordinates
if (prefix == "vt") { if (prefix == "vt")
{
float u, v, w; float u, v, w;
ss >> u >> v >> w; ss >> u >> v >> w;
TextureCoords.push_back(std::make_tuple(u, v, w)); TextureCoords.push_back(std::make_tuple(u, v, w));
} }
// Face definitions // Face definitions
if (prefix == "f") { if (prefix == "f")
{
Face face; Face face;
face.Material = m_CurrentMaterial; face.Material = m_CurrentMaterial;
std::string faceDefString; std::string faceDefString;
while (ss >> faceDefString) { while (ss >> faceDefString)
{
std::stringstream ss2(faceDefString); std::stringstream ss2(faceDefString);
FaceDefinition faceDef = { 0, 0, 0 }; FaceDefinition faceDef = { 0, 0, 0 };
@@ -82,10 +91,13 @@ bool OBJ::LoadFromFile(std::string filename)
if (!ss2) if (!ss2)
continue; continue;
if (ss2.peek() == '/') { if (ss2.peek() == '/')
{
ss2.ignore(); ss2.ignore();
ss2 >> faceDef.NormalIndex; ss2 >> faceDef.NormalIndex;
} else { }
else
{
ss2 >> faceDef.TextureCoordIndex; ss2 >> faceDef.TextureCoordIndex;
ss2.ignore(); ss2.ignore();
ss2 >> faceDef.NormalIndex; ss2 >> faceDef.NormalIndex;
@@ -103,7 +115,8 @@ void OBJ::ParseMaterial()
{ {
// http://paulbourke.net/dataformats/mtl/ // http://paulbourke.net/dataformats/mtl/
std::ifstream file(m_MaterialPath.string()); std::ifstream file(m_MaterialPath.string());
if (!file.is_open()) { if (!file.is_open())
{
LOG_ERROR("Failed to open .mtl \"%s\"", m_MaterialPath.string().c_str()); LOG_ERROR("Failed to open .mtl \"%s\"", m_MaterialPath.string().c_str());
return; return;
} }
@@ -114,7 +127,8 @@ void OBJ::ParseMaterial()
MaterialInfo* currentMaterial = nullptr; MaterialInfo* currentMaterial = nullptr;
std::string line; std::string line;
while (std::getline(file, line)) { while (std::getline(file, line))
{
if (line.length() == 0) if (line.length() == 0)
continue; continue;
@@ -124,7 +138,8 @@ void OBJ::ParseMaterial()
ss >> prefix; ss >> prefix;
// Create a new material definition // Create a new material definition
if (prefix == "newmtl") { if (prefix == "newmtl")
{
MaterialInfo mat = MaterialInfo mat =
{ {
"", "",
@@ -149,39 +164,47 @@ void OBJ::ParseMaterial()
continue; continue;
// Ambient color // Ambient color
if (prefix == "Ka") { if (prefix == "Ka")
{
float r, g, b; float r, g, b;
ss >> r >> g >> b; ss >> r >> g >> b;
currentMaterial->AmbientColor = std::make_tuple(r, g, b); currentMaterial->AmbientColor = std::make_tuple(r, g, b);
continue; continue;
} }
// Diffuse color // Diffuse color
if (prefix == "Kd") { if (prefix == "Kd")
{
float r, g, b; float r, g, b;
ss >> r >> g >> b; ss >> r >> g >> b;
currentMaterial->DiffuseColor = std::make_tuple(r, g, b); currentMaterial->DiffuseColor = std::make_tuple(r, g, b);
continue; continue;
} }
// Specular color // Specular color
if (prefix == "Ks") { if (prefix == "Ks")
{
float r, g, b; float r, g, b;
ss >> r >> g >> b; ss >> r >> g >> b;
currentMaterial->SpecularColor = std::make_tuple(r, g, b); currentMaterial->SpecularColor = std::make_tuple(r, g, b);
continue; continue;
} }
// Transmission filter // Transmission filter
if (prefix == "Tf") { if (prefix == "Tf")
{
std::stringstream ss2; std::stringstream ss2;
ss2 << ss.str(); ss2 << ss.str();
std::string command; std::string command;
ss2 >> command; ss2 >> command;
if (command == "xyz") { if (command == "xyz")
{
// TODO: "The "Ks xyz" statement specifies the specular reflectivity using CIEXYZ values." // TODO: "The "Ks xyz" statement specifies the specular reflectivity using CIEXYZ values."
} }
else if (command == "spectral") { else if (command == "spectral")
{
// TODO: "The "Tf spectral" statement specifies the transmission filter using a spectral curve." // TODO: "The "Tf spectral" statement specifies the transmission filter using a spectral curve."
} else { }
else
{
float r, g, b; float r, g, b;
ss >> r; ss >> r;
// G and B are optional // G and B are optional
@@ -195,22 +218,26 @@ void OBJ::ParseMaterial()
continue; continue;
} }
// Optical density // Optical density
if (prefix == "Ni") { if (prefix == "Ni")
{
ss >> currentMaterial->OpticalDensity; ss >> currentMaterial->OpticalDensity;
continue; continue;
} }
// Alpha // Alpha
if (prefix == "d" || prefix == "Tr") { if (prefix == "d" || prefix == "Tr")
{
ss >> currentMaterial->Alpha; ss >> currentMaterial->Alpha;
continue; continue;
} }
// Shininess // Shininess
if (prefix == "Ns") { if (prefix == "Ns")
{
ss >> currentMaterial->Shininess; ss >> currentMaterial->Shininess;
continue; continue;
} }
// Illumination model // Illumination model
if (prefix == "illum") { if (prefix == "illum")
{
int illum = 0; int illum = 0;
ss >> illum; ss >> illum;
currentMaterial->IlluminationModel = illum; currentMaterial->IlluminationModel = illum;
@@ -218,7 +245,8 @@ void OBJ::ParseMaterial()
} }
// Texture file // Texture file
// TODO: // TODO:
if (prefix == "map_Ka" || prefix == "map_Kd") { if (prefix == "map_Ka" || prefix == "map_Kd")
{
std::string textureFile; std::string textureFile;
ss >> textureFile; ss >> textureFile;
currentMaterial->TextureFile = (m_MaterialPath.branch_path() / textureFile).string(); currentMaterial->TextureFile = (m_MaterialPath.branch_path() / textureFile).string();
+39 -26
View File
@@ -24,7 +24,8 @@ Renderer::Renderer()
void Renderer::Initialize() void Renderer::Initialize()
{ {
// Initialize GLFW // Initialize GLFW
if (!glfwInit()) { if (!glfwInit())
{
LOG_ERROR("GLFW: Initialization failed"); LOG_ERROR("GLFW: Initialization failed");
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
@@ -35,7 +36,8 @@ void Renderer::Initialize()
// Antialiasing // Antialiasing
//glfwWindowHint(GLFW_SAMPLES, 16); //glfwWindowHint(GLFW_SAMPLES, 16);
m_Window = glfwCreateWindow(WIDTH, HEIGHT, "OpenGL", nullptr, nullptr); m_Window = glfwCreateWindow(WIDTH, HEIGHT, "OpenGL", nullptr, nullptr);
if (!m_Window) { if (!m_Window)
{
LOG_ERROR("GLFW: Failed to create window"); LOG_ERROR("GLFW: Failed to create window");
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
@@ -54,7 +56,8 @@ void Renderer::Initialize()
glfwSetWindowTitle(m_Window, ss.str().c_str()); glfwSetWindowTitle(m_Window, ss.str().c_str());
// Initialize GLEW // Initialize GLEW
if (glewInit() != GLEW_OK) { if (glewInit() != GLEW_OK)
{
LOG_ERROR("GLEW: Initialization failed"); LOG_ERROR("GLEW: Initialization failed");
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
@@ -134,7 +137,8 @@ void Renderer::CreateShadowMap(int resolution)
glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, m_ShadowDepthTexture, 0); glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, m_ShadowDepthTexture, 0);
glDrawBuffer(GL_NONE); glDrawBuffer(GL_NONE);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
{
LOG_ERROR("Framebuffer incomplete!"); LOG_ERROR("Framebuffer incomplete!");
return; return;
} }
@@ -149,11 +153,13 @@ void Renderer::Draw(double dt)
#ifdef DEBUG #ifdef DEBUG
// Draw bounding boxes // Draw bounding boxes
if (m_DrawBounds) { if (m_DrawBounds)
{
glEnable(GL_BLEND); glEnable(GL_BLEND);
glBlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ZERO); glBlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ZERO);
m_ShaderProgramDebugAABB.Bind(); m_ShaderProgramDebugAABB.Bind();
for (auto tuple : AABBsToRender) { for (auto tuple : AABBsToRender)
{
glm::mat4 modelMatrix; glm::mat4 modelMatrix;
bool colliding; bool colliding;
std::tie(modelMatrix, colliding) = tuple; std::tie(modelMatrix, colliding) = tuple;
@@ -211,11 +217,11 @@ void Renderer::DrawScene()
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::translate(-m_Camera->Position() * glm::vec3(1, 0, 0));
glm::mat4 depthCamera = m_SunProjection * depthViewMatrix; glm::mat4 depthCamera = m_SunProjection * depthViewMatrix;
glm::mat4 biasMatrix( glm::mat4 biasMatrix(
0.5, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0,
0.0, 0.5, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0,
0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.5, 0.0,
0.5, 0.5, 0.5, 1.0 0.5, 0.5, 0.5, 1.0
); );
m_ShaderProgram.Bind(); m_ShaderProgram.Bind();
glUniform1i(glGetUniformLocation(m_ShaderProgram.GetHandle(), "numberOfLights"), Lights); glUniform1i(glGetUniformLocation(m_ShaderProgram.GetHandle(), "numberOfLights"), Lights);
@@ -226,7 +232,8 @@ void Renderer::DrawScene()
glUniform1fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "linearAttenuation"), Lights, Light_linearAttenuation.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(), "quadraticAttenuation"), Lights, Light_quadraticAttenuation.data());
glUniform1fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "spotExponent"), Lights, Light_spotExponent.data()); glUniform1fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "spotExponent"), Lights, Light_spotExponent.data());
if (m_DrawWireframe) { if (m_DrawWireframe)
{
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
} }
glActiveTexture(GL_TEXTURE1); glActiveTexture(GL_TEXTURE1);
@@ -252,7 +259,8 @@ void Renderer::DrawScene()
glUniformMatrix4fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "model"), 1, GL_FALSE, glm::value_ptr(modelMatrix)); 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())); glUniformMatrix4fv(glGetUniformLocation(m_ShaderProgram.GetHandle(), "view"), 1, GL_FALSE, glm::value_ptr(m_Camera->ViewMatrix()));
glBindVertexArray(model->VAO); glBindVertexArray(model->VAO);
for (auto texGroup : model->TextureGroups) { for (auto texGroup : model->TextureGroups)
{
glActiveTexture(GL_TEXTURE0); glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, *texGroup.Texture); glBindTexture(GL_TEXTURE_2D, *texGroup.Texture);
glDrawArrays(GL_TRIANGLES, texGroup.StartIndex, texGroup.EndIndex - texGroup.StartIndex + 1); glDrawArrays(GL_TRIANGLES, texGroup.StartIndex, texGroup.EndIndex - texGroup.StartIndex + 1);
@@ -261,7 +269,8 @@ void Renderer::DrawScene()
#ifdef DEBUG #ifdef DEBUG
// Debug draw model normals // Debug draw model normals
if (m_DrawNormals) { if (m_DrawNormals)
{
m_ShaderProgramNormals.Bind(); m_ShaderProgramNormals.Bind();
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
DrawModels(m_ShaderProgramNormals); DrawModels(m_ShaderProgramNormals);
@@ -304,7 +313,8 @@ void Renderer::DrawShadowMap()
glUniformMatrix4fv(glGetUniformLocation(m_ShaderProgramShadows.GetHandle(), "MVP"), 1, GL_FALSE, glm::value_ptr(MVP)); glUniformMatrix4fv(glGetUniformLocation(m_ShaderProgramShadows.GetHandle(), "MVP"), 1, GL_FALSE, glm::value_ptr(MVP));
glBindVertexArray(model->VAO); glBindVertexArray(model->VAO);
for (auto texGroup : model->TextureGroups) { for (auto texGroup : model->TextureGroups)
{
glDrawArrays(GL_TRIANGLES, texGroup.StartIndex, texGroup.EndIndex - texGroup.StartIndex + 1); glDrawArrays(GL_TRIANGLES, texGroup.StartIndex, texGroup.EndIndex - texGroup.StartIndex + 1);
} }
} }
@@ -367,14 +377,14 @@ void Renderer::AddModelToDraw(std::shared_ptr<Model> model, glm::vec3 position,
} }
void Renderer::AddPointLightToDraw( void Renderer::AddPointLightToDraw(
glm::vec3 _position, glm::vec3 _position,
glm::vec3 _specular, glm::vec3 _specular,
glm::vec3 _diffuse, glm::vec3 _diffuse,
float _constantAttenuation, float _constantAttenuation,
float _linearAttenuation, float _linearAttenuation,
float _quadraticAttenuation, float _quadraticAttenuation,
float _spotExponent float _spotExponent
) )
{ {
Light_position.push_back(_position.x); Light_position.push_back(_position.x);
Light_position.push_back(_position.y); Light_position.push_back(_position.y);
@@ -402,7 +412,8 @@ void Renderer::AddAABBToDraw(glm::vec3 origin, glm::vec3 volumeVector, bool coll
GLuint Renderer::CreateQuad() GLuint Renderer::CreateQuad()
{ {
float quadVertices[] = { float quadVertices[] =
{
-1.0f, -1.0f, 0.0f, -1.0f, -1.0f, 0.0f,
1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f,
-1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f,
@@ -411,7 +422,8 @@ GLuint Renderer::CreateQuad()
1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f,
1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f,
}; };
float quadTexCoords[] = { float quadTexCoords[] =
{
0.0f, 0.0f, 0.0f, 0.0f,
1.0f, 1.0f, 1.0f, 1.0f,
0.0f, 1.0f, 0.0f, 1.0f,
@@ -443,7 +455,8 @@ GLuint Renderer::CreateQuad()
GLuint Renderer::CreateAABB() GLuint Renderer::CreateAABB()
{ {
float vertices[] = { float vertices[] =
{
// Bottom // Bottom
-1.0f, -1.0f, 1.0f, // 0 -1.0f, -1.0f, 1.0f, // 0
1.0f, -1.0f, 1.0f, // 1 1.0f, -1.0f, 1.0f, // 1
+8 -8
View File
@@ -42,14 +42,14 @@ public:
void AddModelToDraw(std::shared_ptr<Model> model, glm::vec3 position, glm::quat orientation, glm::vec3 scale, bool visible, bool shadowCaster); void AddModelToDraw(std::shared_ptr<Model> model, glm::vec3 position, glm::quat orientation, glm::vec3 scale, bool visible, bool shadowCaster);
void AddTextToDraw(); void AddTextToDraw();
void AddPointLightToDraw( void AddPointLightToDraw(
glm::vec3 _position, glm::vec3 _position,
glm::vec3 _specular, glm::vec3 _specular,
glm::vec3 _diffuse, glm::vec3 _diffuse,
float _constantAttenuation, float _constantAttenuation,
float _linearAttenuation, float _linearAttenuation,
float _quadraticAttenuation, float _quadraticAttenuation,
float _spotExponent float _spotExponent
); );
void AddAABBToDraw(glm::vec3 origin, glm::vec3 volumeVector, bool colliding); void AddAABBToDraw(glm::vec3 origin, glm::vec3 volumeVector, bool colliding);
void LoadContent(); void LoadContent();
+16 -8
View File
@@ -7,7 +7,8 @@ GLuint Shader::CompileShader(GLenum shaderType, std::string fileName)
std::string shaderFile; std::string shaderFile;
std::ifstream in(fileName, std::ios::in); std::ifstream in(fileName, std::ios::in);
if (!in) { if (!in)
{
LOG_ERROR("Error: Failed to open shader file \"%s\"", fileName.c_str()); LOG_ERROR("Error: Failed to open shader file \"%s\"", fileName.c_str());
return 0; return 0;
} }
@@ -31,7 +32,8 @@ GLuint Shader::CompileShader(GLenum shaderType, std::string fileName)
GLint compileStatus; GLint compileStatus;
glGetShaderiv(shader, GL_COMPILE_STATUS, &compileStatus); glGetShaderiv(shader, GL_COMPILE_STATUS, &compileStatus);
if(compileStatus != GL_TRUE) { if(compileStatus != GL_TRUE)
{
LOG_ERROR("Shader compilation failed"); LOG_ERROR("Shader compilation failed");
GLsizei infoLogLength; GLsizei infoLogLength;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLength); glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLength);
@@ -54,7 +56,8 @@ Shader::Shader(GLenum shaderType, std::string fileName) : m_ShaderType(shaderTyp
Shader::~Shader() Shader::~Shader()
{ {
if (m_ShaderHandle != 0) { if (m_ShaderHandle != 0)
{
glDeleteShader(m_ShaderHandle); glDeleteShader(m_ShaderHandle);
} }
} }
@@ -87,7 +90,8 @@ bool Shader::IsCompiled() const
ShaderProgram::~ShaderProgram() ShaderProgram::~ShaderProgram()
{ {
if (m_ShaderProgramHandle != 0) { if (m_ShaderProgramHandle != 0)
{
glDeleteProgram(m_ShaderProgramHandle); glDeleteProgram(m_ShaderProgramHandle);
} }
} }
@@ -99,8 +103,10 @@ void ShaderProgram::AddShader(std::shared_ptr<Shader> shader)
void ShaderProgram::Compile() void ShaderProgram::Compile()
{ {
for (auto &shader : m_Shaders) { for (auto &shader : m_Shaders)
if (!shader->IsCompiled()) { {
if (!shader->IsCompiled())
{
shader->Compile(); shader->Compile();
} }
} }
@@ -108,14 +114,16 @@ void ShaderProgram::Compile()
GLuint ShaderProgram::Link() GLuint ShaderProgram::Link()
{ {
if (m_Shaders.size() == 0) { if (m_Shaders.size() == 0)
{
LOG_ERROR("Failed to link shader program: No shaders bound"); LOG_ERROR("Failed to link shader program: No shaders bound");
return 0; return 0;
} }
LOG_INFO("Linking shader program"); LOG_INFO("Linking shader program");
m_ShaderProgramHandle = glCreateProgram(); m_ShaderProgramHandle = glCreateProgram();
for (auto &shader : m_Shaders) { for (auto &shader : m_Shaders)
{
glAttachShader(m_ShaderProgramHandle, shader->GetHandle()); glAttachShader(m_ShaderProgramHandle, shader->GetHandle());
} }
glLinkProgram(m_ShaderProgramHandle); glLinkProgram(m_ShaderProgramHandle);
+4 -2
View File
@@ -2,7 +2,8 @@
uniform vec4 Color; uniform vec4 Color;
in VertexData { in VertexData
{
vec3 Position; vec3 Position;
vec3 Normal; vec3 Normal;
vec2 TextureCoord; vec2 TextureCoord;
@@ -11,7 +12,8 @@ in VertexData {
out vec4 FragmentColor; out vec4 FragmentColor;
void main() { void main()
{
//FragmentColor = vec4(1.0 - gl_Color.r, 1.0 - gl_Color.g, 1.0 - gl_Color.b, 0.0); //FragmentColor = vec4(1.0 - gl_Color.r, 1.0 - gl_Color.g, 1.0 - gl_Color.b, 0.0);
FragmentColor = Color; FragmentColor = Color;
} }
+10 -6
View File
@@ -16,7 +16,8 @@ uniform float linearAttenuation[maxNumberOfLights];
uniform float quadraticAttenuation[maxNumberOfLights]; uniform float quadraticAttenuation[maxNumberOfLights];
uniform float spotExponent[maxNumberOfLights]; uniform float spotExponent[maxNumberOfLights];
in VertexData { in VertexData
{
vec3 Position; vec3 Position;
vec3 Normal; vec3 Normal;
vec2 TextureCoord; vec2 TextureCoord;
@@ -27,7 +28,8 @@ vec3 scene_ambient = vec3(0.5, 0.5, 0.5);
out vec4 fragmentColor; out vec4 fragmentColor;
void main() { void main()
{
// Texture // Texture
vec4 texel = texture2D(texture0, Input.TextureCoord); vec4 texel = texture2D(texture0, Input.TextureCoord);
@@ -50,10 +52,12 @@ void main() {
//float bias = 0.001 * tan(acos(cosTheta)); // cosTheta is dot( n,l ), clamped between 0 and 1 //float bias = 0.001 * tan(acos(cosTheta)); // cosTheta is dot( n,l ), clamped between 0 and 1
//bias = clamp(bias, 0.0, 0.01); //bias = clamp(bias, 0.0, 0.01);
float visibility = 1.0; 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) { 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; float bias = 0.00005;
vec4 shadowMapValue = texture(shadowMap, Input.ShadowCoord.xy); vec4 shadowMapValue = texture(shadowMap, Input.ShadowCoord.xy);
if (shadowMapValue.z < clamp(Input.ShadowCoord.z - bias, 0, 1)) { if (shadowMapValue.z < clamp(Input.ShadowCoord.z - bias, 0, 1))
{
visibility = 0.3; visibility = 0.3;
} }
} }
@@ -79,8 +83,8 @@ void main() {
float dist = length(position[i] - surfacePosition); float dist = length(position[i] - surfacePosition);
attenuation = 1.0 / (constantAttenuation[i] attenuation = 1.0 / (constantAttenuation[i]
+ linearAttenuation[i] * dist + linearAttenuation[i] * dist
+ quadraticAttenuation[i] * pow(dist, 2.0)); + quadraticAttenuation[i] * pow(dist, 2.0));
//attenuation = attenuation * pow(clampedCosine, spotExponent[i]); //attenuation = attenuation * pow(clampedCosine, spotExponent[i]);
// Diffuse light // Diffuse light
+2 -1
View File
@@ -4,6 +4,7 @@ uniform mat4 MVP;
out vec4 FragmentColor; out vec4 FragmentColor;
void main() { void main()
{
FragmentColor = vec4(1.0, 1.0, 1.0, 1.0); FragmentColor = vec4(1.0, 1.0, 1.0, 1.0);
} }
+4 -2
View File
@@ -5,13 +5,15 @@ uniform mat4 MVP;
layout(triangles) in; layout(triangles) in;
layout(line_strip, max_vertices = 6) out; layout(line_strip, max_vertices = 6) out;
in VertexData { in VertexData
{
vec3 Position; vec3 Position;
vec3 Normal; vec3 Normal;
vec2 TextureCoord; vec2 TextureCoord;
} Input[3]; } Input[3];
out VertexData { out VertexData
{
vec3 Position; vec3 Position;
vec3 Normal; vec3 Normal;
vec2 TextureCoord; vec2 TextureCoord;
+2 -1
View File
@@ -4,6 +4,7 @@ uniform mat4 MVP;
layout(location = 0) out float FragmentDepth; layout(location = 0) out float FragmentDepth;
void main() { void main()
{
FragmentDepth = gl_FragCoord.z; FragmentDepth = gl_FragCoord.z;
} }
+2 -1
View File
@@ -6,7 +6,8 @@ layout(location = 0) in vec3 Position;
layout(location = 1) in vec3 Normal; layout(location = 1) in vec3 Normal;
layout(location = 2) in vec2 TextureCoord; layout(location = 2) in vec2 TextureCoord;
out VertexData { out VertexData
{
vec3 Position; vec3 Position;
vec3 Normal; vec3 Normal;
vec2 TextureCoord; vec2 TextureCoord;
+2 -1
View File
@@ -2,7 +2,8 @@
uniform samplerCube CubemapTexture; uniform samplerCube CubemapTexture;
in VertexData { in VertexData
{
vec3 TextureCoord; vec3 TextureCoord;
} Input; } Input;
+2 -1
View File
@@ -4,7 +4,8 @@ uniform mat4 MVP;
layout(location = 0) in vec3 Position; layout(location = 0) in vec3 Position;
out VertexData { out VertexData
{
vec3 TextureCoord; vec3 TextureCoord;
} Output; } Output;
+2 -1
View File
@@ -7,7 +7,8 @@ layout(location = 0) in vec3 Position;
layout(location = 1) in vec3 Normal; layout(location = 1) in vec3 Normal;
layout(location = 2) in vec2 TextureCoord; layout(location = 2) in vec2 TextureCoord;
out VertexData { out VertexData
{
vec3 Position; vec3 Position;
vec3 Normal; vec3 Normal;
vec2 TextureCoord; vec2 TextureCoord;
+7 -5
View File
@@ -2,7 +2,8 @@
layout(binding = 0) uniform sampler2D DepthTexture; layout(binding = 0) uniform sampler2D DepthTexture;
in VertexData { in VertexData
{
vec3 Position; vec3 Position;
vec2 TextureCoord; vec2 TextureCoord;
} Input; } Input;
@@ -11,12 +12,13 @@ out vec4 FragmentColor;
float LinearizeDepth(float z) float LinearizeDepth(float z)
{ {
float n = 0.1; // camera z near float n = 0.1; // camera z near
float f = 800.0; // camera z far float f = 800.0; // camera z far
return (2.0 * n) / (f + n - z * (f - n)); return (2.0 * n) / (f + n - z * (f - n));
} }
void main() { void main()
{
float z = texture(DepthTexture, Input.TextureCoord).x; float z = texture(DepthTexture, Input.TextureCoord).x;
vec4 color = vec4(z, z, z, 0); vec4 color = vec4(z, z, z, 0);
+2 -1
View File
@@ -3,7 +3,8 @@
layout(location = 0) in vec3 Position; layout(location = 0) in vec3 Position;
layout(location = 2) in vec2 TextureCoord; layout(location = 2) in vec2 TextureCoord;
out VertexData { out VertexData
{
vec3 Position; vec3 Position;
vec2 TextureCoord; vec2 TextureCoord;
} Output; } Output;
+10 -8
View File
@@ -4,19 +4,20 @@
Skybox::Skybox(std::string skyboxPath, std::string extension /* = "png" */) Skybox::Skybox(std::string skyboxPath, std::string extension /* = "png" */)
{ {
m_Cubemap = std::make_shared<CubemapTexture>( m_Cubemap = std::make_shared<CubemapTexture>(
skyboxPath + "/right." + extension, skyboxPath + "/right." + extension,
skyboxPath + "/left." + extension, skyboxPath + "/left." + extension,
skyboxPath + "/top." + extension, skyboxPath + "/top." + extension,
skyboxPath + "/bottom." + extension, skyboxPath + "/bottom." + extension,
skyboxPath + "/front." + extension, skyboxPath + "/front." + extension,
skyboxPath + "/back." + extension); skyboxPath + "/back." + extension);
m_Cubemap->Load(); m_Cubemap->Load();
Initialize(); Initialize();
} }
void Skybox::Initialize() void Skybox::Initialize()
{ {
float cubeVertices[] = { float cubeVertices[] =
{
-1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f,
1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f,
@@ -29,7 +30,8 @@ void Skybox::Initialize()
}; };
//std::copy(cubeVertices, cubeVertices + (3*8 - 1), m_CubeVertices); //std::copy(cubeVertices, cubeVertices + (3*8 - 1), m_CubeVertices);
unsigned int cubeIndices[] = { unsigned int cubeIndices[] =
{
// Back // Back
0, 2, 3, 0, 2, 3,
0, 1, 2, 0, 1, 2,
+8 -8
View File
@@ -7,15 +7,15 @@
namespace Systems namespace Systems
{ {
class DebugSystem : public System class DebugSystem : public System
{ {
public: public:
DebugSystem(World* world) DebugSystem(World* world)
: System(world) { } : System(world) { }
void Update(double dt) override; void Update(double dt) override;
//void UpdateEntity(double dt, EntityID entity, EntityID parent) override; //void UpdateEntity(double dt, EntityID entity, EntityID parent) override;
}; };
} }
#endif // DebugSystem_h__ #endif // DebugSystem_h__
+20 -10
View File
@@ -16,39 +16,49 @@ void Systems::FreeSteeringSystem::UpdateEntity(double dt, EntityID entity, Entit
{ {
auto steering = m_World->GetComponent<Components::FreeSteering>(entity, "FreeSteering"); auto steering = m_World->GetComponent<Components::FreeSteering>(entity, "FreeSteering");
auto input = m_World->GetComponent<Components::Input>(entity, "Input"); auto input = m_World->GetComponent<Components::Input>(entity, "Input");
if (steering && input) { if (steering && input)
{
auto transform = m_World->GetComponent<Components::Transform>(entity, "Transform"); auto transform = m_World->GetComponent<Components::Transform>(entity, "Transform");
glm::vec3 Camera_Right = glm::vec3(glm::vec4(1, 0, 0, 0) * transform->Orientation); glm::vec3 Camera_Right = glm::vec3(glm::vec4(1, 0, 0, 0) * transform->Orientation);
glm::vec3 Camera_Forward = glm::vec3(glm::vec4(0, 0, 1, 0) * transform->Orientation); glm::vec3 Camera_Forward = glm::vec3(glm::vec4(0, 0, 1, 0) * transform->Orientation);
float speed = steering->Speed; float speed = steering->Speed;
if (input->KeyState[GLFW_KEY_LEFT_SHIFT]) { if (input->KeyState[GLFW_KEY_LEFT_SHIFT])
{
speed *= 4.0f; speed *= 4.0f;
} }
if (input->KeyState[GLFW_KEY_LEFT_ALT]) { if (input->KeyState[GLFW_KEY_LEFT_ALT])
{
speed /= 4.0f; speed /= 4.0f;
} }
if (input->KeyState[GLFW_KEY_A]) { if (input->KeyState[GLFW_KEY_A])
{
transform->Position -= Camera_Right * (float)dt * speed; transform->Position -= Camera_Right * (float)dt * speed;
} }
else if (input->KeyState[GLFW_KEY_D]) { else if (input->KeyState[GLFW_KEY_D])
{
transform->Position += Camera_Right * (float)dt * speed; transform->Position += Camera_Right * (float)dt * speed;
} }
if (input->KeyState[GLFW_KEY_W]) { if (input->KeyState[GLFW_KEY_W])
{
transform->Position -= Camera_Forward * (float)dt * speed; transform->Position -= Camera_Forward * (float)dt * speed;
} }
if (input->KeyState[GLFW_KEY_S]) { if (input->KeyState[GLFW_KEY_S])
{
transform->Position += Camera_Forward * (float)dt * speed; transform->Position += Camera_Forward * (float)dt * speed;
} }
if (input->KeyState[GLFW_KEY_SPACE]) { if (input->KeyState[GLFW_KEY_SPACE])
{
transform->Position += glm::vec3(0, 1, 0) * (float)dt * speed; transform->Position += glm::vec3(0, 1, 0) * (float)dt * speed;
} }
if (input->KeyState[GLFW_KEY_LEFT_CONTROL]) { if (input->KeyState[GLFW_KEY_LEFT_CONTROL])
{
transform->Position -= glm::vec3(0, 1, 0) * (float)dt * speed; transform->Position -= glm::vec3(0, 1, 0) * (float)dt * speed;
} }
if (input->MouseState[GLFW_MOUSE_BUTTON_LEFT]) { if (input->MouseState[GLFW_MOUSE_BUTTON_LEFT])
{
// TOUCHING THIS CODE MIGHT CAUSE THE UNIVERSE TO IMPLODE, ALSO DRAGONS // spelling tobias :3 // TOUCHING THIS CODE MIGHT CAUSE THE UNIVERSE TO IMPLODE, ALSO DRAGONS // spelling tobias :3
//--------------------------------------------------------------------- //---------------------------------------------------------------------
transform->Orientation = glm::angleAxis<float>(input->dY / 300.f, glm::vec3(1, 0, 0)) * transform->Orientation; transform->Orientation = glm::angleAxis<float>(input->dY / 300.f, glm::vec3(1, 0, 0)) * transform->Orientation;
+7 -7
View File
@@ -7,12 +7,12 @@
namespace Systems namespace Systems
{ {
class FreeSteeringSystem : public System class FreeSteeringSystem : public System
{ {
public: public:
FreeSteeringSystem(World* world); FreeSteeringSystem(World* world);
void Update(double dt) override; void Update(double dt) override;
void UpdateEntity(double dt, EntityID entity, EntityID parent) override; void UpdateEntity(double dt, EntityID entity, EntityID parent) override;
}; };
} }
+16 -8
View File
@@ -8,12 +8,14 @@ void Systems::InputSystem::Update(double dt)
m_LastMouseState = m_CurrentMouseState; m_LastMouseState = m_CurrentMouseState;
// Keyboard input // Keyboard input
for (int i = 0; i <= GLFW_KEY_LAST; ++i) { for (int i = 0; i <= GLFW_KEY_LAST; ++i)
{
m_CurrentKeyState[i] = glfwGetKey(m_Renderer->GetWindow(), i); m_CurrentKeyState[i] = glfwGetKey(m_Renderer->GetWindow(), i);
} }
// Mouse buttons // Mouse buttons
for (int i = 0; i <= GLFW_MOUSE_BUTTON_LAST; ++i) { for (int i = 0; i <= GLFW_MOUSE_BUTTON_LAST; ++i)
{
m_CurrentMouseState[i] = glfwGetMouseButton(m_Renderer->GetWindow(), i); m_CurrentMouseState[i] = glfwGetMouseButton(m_Renderer->GetWindow(), i);
} }
@@ -26,30 +28,36 @@ void Systems::InputSystem::Update(double dt)
m_LastMouseY = ypos; m_LastMouseY = ypos;
// Lock mouse while holding LMB // Lock mouse while holding LMB
if (m_CurrentMouseState[GLFW_MOUSE_BUTTON_LEFT]) { if (m_CurrentMouseState[GLFW_MOUSE_BUTTON_LEFT])
{
m_LastMouseX = m_Renderer->WIDTH / 2.f; // xpos; m_LastMouseX = m_Renderer->WIDTH / 2.f; // xpos;
m_LastMouseY = m_Renderer->HEIGHT / 2.f; // ypos; m_LastMouseY = m_Renderer->HEIGHT / 2.f; // ypos;
glfwSetCursorPos(m_Renderer->GetWindow(), m_LastMouseX, m_LastMouseY); glfwSetCursorPos(m_Renderer->GetWindow(), m_LastMouseX, m_LastMouseY);
} }
// Hide/show cursor with LMB // Hide/show cursor with LMB
if (m_CurrentMouseState[GLFW_MOUSE_BUTTON_LEFT] && !m_LastMouseState[GLFW_MOUSE_BUTTON_LEFT]) { if (m_CurrentMouseState[GLFW_MOUSE_BUTTON_LEFT] && !m_LastMouseState[GLFW_MOUSE_BUTTON_LEFT])
{
glfwSetInputMode(m_Renderer->GetWindow(), GLFW_CURSOR, GLFW_CURSOR_HIDDEN); glfwSetInputMode(m_Renderer->GetWindow(), GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
} }
if (!m_CurrentMouseState[GLFW_MOUSE_BUTTON_LEFT] && m_LastMouseState[GLFW_MOUSE_BUTTON_LEFT]) { if (!m_CurrentMouseState[GLFW_MOUSE_BUTTON_LEFT] && m_LastMouseState[GLFW_MOUSE_BUTTON_LEFT])
{
glfwSetInputMode(m_Renderer->GetWindow(), GLFW_CURSOR, GLFW_CURSOR_NORMAL); glfwSetInputMode(m_Renderer->GetWindow(), GLFW_CURSOR, GLFW_CURSOR_NORMAL);
} }
#ifdef DEBUG #ifdef DEBUG
// Wireframe // Wireframe
if (m_CurrentKeyState[GLFW_KEY_F1] && !m_LastKeyState[GLFW_KEY_F1]) { if (m_CurrentKeyState[GLFW_KEY_F1] && !m_LastKeyState[GLFW_KEY_F1])
{
m_Renderer->DrawWireframe(!m_Renderer->DrawWireframe()); m_Renderer->DrawWireframe(!m_Renderer->DrawWireframe());
} }
// Normals // Normals
if (m_CurrentKeyState[GLFW_KEY_F2] && !m_LastKeyState[GLFW_KEY_F2]) { if (m_CurrentKeyState[GLFW_KEY_F2] && !m_LastKeyState[GLFW_KEY_F2])
{
m_Renderer->DrawNormals(!m_Renderer->DrawNormals()); m_Renderer->DrawNormals(!m_Renderer->DrawNormals());
} }
// Bounds // Bounds
if (m_CurrentKeyState[GLFW_KEY_F3] && !m_LastKeyState[GLFW_KEY_F3]) { if (m_CurrentKeyState[GLFW_KEY_F3] && !m_LastKeyState[GLFW_KEY_F3])
{
m_Renderer->DrawBounds(!m_Renderer->DrawBounds()); m_Renderer->DrawBounds(!m_Renderer->DrawBounds());
} }
#endif #endif
+38 -18
View File
@@ -20,14 +20,16 @@ Systems::PhysicsSystem::PhysicsSystem(World* world) : System(world)
void Systems::PhysicsSystem::Update(double dt) void Systems::PhysicsSystem::Update(double dt)
{ {
// Update entity transform in physics world // Update entity transform in physics world
for (auto pair : *m_World->GetEntities()) { for (auto pair : *m_World->GetEntities())
{
EntityID entity = pair.first; EntityID entity = pair.first;
EntityID parent = pair.second; EntityID parent = pair.second;
if (parent != 0) if (parent != 0)
continue; continue;
if (m_PhysicsData.find(entity) != m_PhysicsData.end()) { if (m_PhysicsData.find(entity) != m_PhysicsData.end())
{
PhysicsData* physicsData = &m_PhysicsData[entity]; PhysicsData* physicsData = &m_PhysicsData[entity];
auto transformComponent = m_World->GetComponent<Components::Transform>(entity, "Transform"); auto transformComponent = m_World->GetComponent<Components::Transform>(entity, "Transform");
@@ -63,7 +65,8 @@ void Systems::PhysicsSystem::UpdateEntity(double dt, EntityID entity, EntityID p
if (physicsComponent || sphereShapeComponent || boxShapeComponent || meshShapeComponent || staticMeshShapeComponent) if (physicsComponent || sphereShapeComponent || boxShapeComponent || meshShapeComponent || staticMeshShapeComponent)
{ {
if (m_PhysicsData.find(entity) == m_PhysicsData.end()) { if (m_PhysicsData.find(entity) == m_PhysicsData.end())
{
SetUpPhysicsState(entity, parent); SetUpPhysicsState(entity, parent);
} }
@@ -84,7 +87,8 @@ void Systems::PhysicsSystem::UpdateEntity(double dt, EntityID entity, EntityID p
} }
else else
{ {
if (m_PhysicsData.find(entity) != m_PhysicsData.end()) { if (m_PhysicsData.find(entity) != m_PhysicsData.end())
{
TearDownPhysicsState(entity, parent); TearDownPhysicsState(entity, parent);
} }
} }
@@ -145,7 +149,7 @@ void Systems::PhysicsSystem::UpdateEntity(double dt, EntityID entity, EntityID p
btVector3 AxisB = btVector3(hingeComponent->AxisB.x, hingeComponent->AxisB.y, hingeComponent->AxisB.z); btVector3 AxisB = btVector3(hingeComponent->AxisB.x, hingeComponent->AxisB.y, hingeComponent->AxisB.z);
btHingeConstraint *hingeConstraint = new btHingeConstraint(*m_PhysicsData[entityA].RigidBody, *m_PhysicsData[entityB].RigidBody, PivotA, PivotB, AxisA, AxisB, true); btHingeConstraint* hingeConstraint = new btHingeConstraint(*m_PhysicsData[entityA].RigidBody, *m_PhysicsData[entityB].RigidBody, PivotA, PivotB, AxisA, AxisB, true);
hingeConstraint->setLimit(hingeComponent->LowLimit, hingeComponent->HighLimit, hingeComponent->Softness, hingeComponent->BiasFactor, hingeComponent->RelaxationFactor); hingeConstraint->setLimit(hingeComponent->LowLimit, hingeComponent->HighLimit, hingeComponent->Softness, hingeComponent->BiasFactor, hingeComponent->RelaxationFactor);
@@ -170,7 +174,8 @@ void Systems::PhysicsSystem::OnComponentRemoved(std::string type, Component* com
void Systems::PhysicsSystem::SetUpPhysicsState(EntityID entity, EntityID parent) void Systems::PhysicsSystem::SetUpPhysicsState(EntityID entity, EntityID parent)
{ {
auto transformComponent = m_World->GetComponent<Components::Transform>(entity, "Transform"); auto transformComponent = m_World->GetComponent<Components::Transform>(entity, "Transform");
if (!transformComponent) { if (!transformComponent)
{
LOG_WARNING("Physics component missing transform component on entity %i", entity); LOG_WARNING("Physics component missing transform component on entity %i", entity);
return; return;
} }
@@ -182,7 +187,8 @@ void Systems::PhysicsSystem::SetUpPhysicsState(EntityID entity, EntityID parent)
auto meshShapeComponent = m_World->GetComponent<Components::MeshShape>(entity, "MeshShape"); auto meshShapeComponent = m_World->GetComponent<Components::MeshShape>(entity, "MeshShape");
auto staticMeshShapeComponent = m_World->GetComponent<Components::StaticMeshShape>(entity, "StaticMeshShape"); auto staticMeshShapeComponent = m_World->GetComponent<Components::StaticMeshShape>(entity, "StaticMeshShape");
if (compoundShapeComponent && (sphereShapeComponent || boxShapeComponent || meshShapeComponent || staticMeshShapeComponent)) { if (compoundShapeComponent && (sphereShapeComponent || boxShapeComponent || meshShapeComponent || staticMeshShapeComponent))
{
LOG_WARNING("Entity %i has both compound shape and normal shape! Normal shapes must be children to entity with compound shape.", entity); LOG_WARNING("Entity %i has both compound shape and normal shape! Normal shapes must be children to entity with compound shape.", entity);
} }
@@ -192,7 +198,8 @@ void Systems::PhysicsSystem::SetUpPhysicsState(EntityID entity, EntityID parent)
auto baseCompoundShape = m_World->GetComponent<Components::CompoundShape>(baseParent, "CompoundShape");*/ auto baseCompoundShape = m_World->GetComponent<Components::CompoundShape>(baseParent, "CompoundShape");*/
// Set-up compound shape // Set-up compound shape
if (compoundShapeComponent) { if (compoundShapeComponent)
{
btCompoundShape* compoundShape = new btCompoundShape(); btCompoundShape* compoundShape = new btCompoundShape();
physicsData->CollisionShape = compoundShape; physicsData->CollisionShape = compoundShape;
@@ -201,7 +208,8 @@ void Systems::PhysicsSystem::SetUpPhysicsState(EntityID entity, EntityID parent)
physicsData->MotionState = new btDefaultMotionState(transform); physicsData->MotionState = new btDefaultMotionState(transform);
btVector3 inertia; btVector3 inertia;
if (physicsComponent->Mass != 0) { if (physicsComponent->Mass != 0)
{
physicsData->CollisionShape->calculateLocalInertia(physicsComponent->Mass, inertia); physicsData->CollisionShape->calculateLocalInertia(physicsComponent->Mass, inertia);
} }
@@ -212,24 +220,32 @@ void Systems::PhysicsSystem::SetUpPhysicsState(EntityID entity, EntityID parent)
} }
// Set-up normal shapes // Set-up normal shapes
else if (boxShapeComponent) { else if (boxShapeComponent)
{
physicsData->CollisionShape = new btBoxShape(btVector3(boxShapeComponent->Width, boxShapeComponent->Height, boxShapeComponent->Depth)); physicsData->CollisionShape = new btBoxShape(btVector3(boxShapeComponent->Width, boxShapeComponent->Height, boxShapeComponent->Depth));
} else if (sphereShapeComponent) { }
else if (sphereShapeComponent)
{
physicsData->CollisionShape = new btSphereShape(sphereShapeComponent->Radius); physicsData->CollisionShape = new btSphereShape(sphereShapeComponent->Radius);
} else if (meshShapeComponent) { }
else if (meshShapeComponent)
{
// TODO: Collision mesh things go here // TODO: Collision mesh things go here
//new btConvexTriangleMeshShape() //new btConvexTriangleMeshShape()
} }
if (boxShapeComponent || sphereShapeComponent || meshShapeComponent || staticMeshShapeComponent) { if (boxShapeComponent || sphereShapeComponent || meshShapeComponent || staticMeshShapeComponent)
{
btTransform transform; btTransform transform;
transform.setFromOpenGLMatrix(glm::value_ptr(glm::translate(glm::mat4(), transformComponent->Position) * glm::toMat4(transformComponent->Orientation))); transform.setFromOpenGLMatrix(glm::value_ptr(glm::translate(glm::mat4(), transformComponent->Position) * glm::toMat4(transformComponent->Orientation)));
// If there's a local physics component // If there's a local physics component
if (physicsComponent) { if (physicsComponent)
{
physicsData->MotionState = new btDefaultMotionState(transform); physicsData->MotionState = new btDefaultMotionState(transform);
btVector3 inertia; btVector3 inertia;
if (physicsComponent->Mass != 0) { if (physicsComponent->Mass != 0)
{
physicsData->CollisionShape->calculateLocalInertia(physicsComponent->Mass, inertia); physicsData->CollisionShape->calculateLocalInertia(physicsComponent->Mass, inertia);
} }
@@ -237,16 +253,20 @@ void Systems::PhysicsSystem::SetUpPhysicsState(EntityID entity, EntityID parent)
physicsData->RigidBody = new btRigidBody(rigidBodyCI); physicsData->RigidBody = new btRigidBody(rigidBodyCI);
m_DynamicsWorld->addRigidBody(physicsData->RigidBody); m_DynamicsWorld->addRigidBody(physicsData->RigidBody);
} else { }
else
{
// Otherwise, find our base parent and attach to compound shape // Otherwise, find our base parent and attach to compound shape
EntityID baseParent = m_World->GetEntityBaseParent(entity); EntityID baseParent = m_World->GetEntityBaseParent(entity);
auto basePhysicsComponent = m_World->GetComponent<Components::Physics>(baseParent, "Physics"); auto basePhysicsComponent = m_World->GetComponent<Components::Physics>(baseParent, "Physics");
if (!basePhysicsComponent) { if (!basePhysicsComponent)
{
LOG_WARNING("Failed to attach orphan collision shape on entity %i: missing physics component on base parent entity %i", entity, baseParent); LOG_WARNING("Failed to attach orphan collision shape on entity %i: missing physics component on base parent entity %i", entity, baseParent);
return; return;
} }
auto baseCompoundShapeComponent = m_World->GetComponent<Components::CompoundShape>(baseParent, "CompoundShape"); auto baseCompoundShapeComponent = m_World->GetComponent<Components::CompoundShape>(baseParent, "CompoundShape");
if (!baseCompoundShapeComponent) { if (!baseCompoundShapeComponent)
{
LOG_WARNING("Failed to attach orphan collision shape on entity %i: missing compound shape on base parent entity %i", entity, baseParent); LOG_WARNING("Failed to attach orphan collision shape on entity %i: missing compound shape on base parent entity %i", entity, baseParent);
return; return;
} }
+26 -26
View File
@@ -19,34 +19,34 @@
namespace Systems namespace Systems
{ {
class PhysicsSystem : public System class PhysicsSystem : public System
{
public:
PhysicsSystem(World* world);
void Update(double dt) override;
void UpdateEntity(double dt, EntityID entity, EntityID parent) override;
void OnComponentCreated(std::string type, std::shared_ptr<Component> component) override;
void OnComponentRemoved(std::string type, Component* component) override;
private:
btBroadphaseInterface* m_Broadphase;
btDefaultCollisionConfiguration* m_CollisionConfiguration;
btCollisionDispatcher* m_Dispatcher;
btSequentialImpulseConstraintSolver* m_Solver;
btDiscreteDynamicsWorld* m_DynamicsWorld;
struct PhysicsData
{ {
public: btRigidBody* RigidBody;
PhysicsSystem(World* world); btMotionState* MotionState;
void Update(double dt) override; btCollisionShape* CollisionShape;
void UpdateEntity(double dt, EntityID entity, EntityID parent) override;
void OnComponentCreated(std::string type, std::shared_ptr<Component> component) override;
void OnComponentRemoved(std::string type, Component* component) override;
private:
btBroadphaseInterface* m_Broadphase;
btDefaultCollisionConfiguration* m_CollisionConfiguration;
btCollisionDispatcher* m_Dispatcher;
btSequentialImpulseConstraintSolver* m_Solver;
btDiscreteDynamicsWorld* m_DynamicsWorld;
struct PhysicsData
{
btRigidBody* RigidBody;
btMotionState* MotionState;
btCollisionShape* CollisionShape;
};
std::map<EntityID, PhysicsData> m_PhysicsData;
std::map<std::pair<EntityID, EntityID>, btTypedConstraint*> m_Constraints;
void SetUpPhysicsState(EntityID entity, EntityID parent);
void TearDownPhysicsState(EntityID entity, EntityID parent);
}; };
std::map<EntityID, PhysicsData> m_PhysicsData;
std::map<std::pair<EntityID, EntityID>, btTypedConstraint*> m_Constraints;
void SetUpPhysicsState(EntityID entity, EntityID parent);
void TearDownPhysicsState(EntityID entity, EntityID parent);
};
} }
#endif // PhysicsSystem_h__ #endif // PhysicsSystem_h__
+19 -13
View File
@@ -4,7 +4,8 @@
void Systems::RenderSystem::OnComponentCreated(std::string type, std::shared_ptr<Component> component) void Systems::RenderSystem::OnComponentCreated(std::string type, std::shared_ptr<Component> component)
{ {
if(type == "Model") { if(type == "Model")
{
auto modelComponent = std::static_pointer_cast<Components::Model>(component); auto modelComponent = std::static_pointer_cast<Components::Model>(component);
} }
} }
@@ -17,8 +18,10 @@ void Systems::RenderSystem::UpdateEntity(double dt, EntityID entity, EntityID pa
// Draw models // Draw models
auto modelComponent = m_World->GetComponent<Components::Model>(entity, "Model"); auto modelComponent = m_World->GetComponent<Components::Model>(entity, "Model");
if (modelComponent != nullptr) { if (modelComponent != nullptr)
if (m_CachedModels.find(modelComponent->ModelFile) == m_CachedModels.end()){ {
if (m_CachedModels.find(modelComponent->ModelFile) == m_CachedModels.end())
{
m_CachedModels[modelComponent->ModelFile] = std::make_shared<Model>(OBJ(modelComponent->ModelFile)); m_CachedModels[modelComponent->ModelFile] = std::make_shared<Model>(OBJ(modelComponent->ModelFile));
} }
@@ -33,7 +36,8 @@ void Systems::RenderSystem::UpdateEntity(double dt, EntityID entity, EntityID pa
#ifdef DEBUG #ifdef DEBUG
auto collision = m_World->GetComponent<Components::Collision>(entity, "Collision"); auto collision = m_World->GetComponent<Components::Collision>(entity, "Collision");
auto bounds = m_World->GetComponent<Components::Bounds>(entity, "Bounds"); auto bounds = m_World->GetComponent<Components::Bounds>(entity, "Bounds");
if (bounds != nullptr) { if (bounds != nullptr)
{
glm::vec3 origin = m_TransformSystem->AbsolutePosition(entity) + (transformComponent->Scale * bounds->Origin); glm::vec3 origin = m_TransformSystem->AbsolutePosition(entity) + (transformComponent->Scale * bounds->Origin);
glm::vec3 volumeVector = transformComponent->Scale * bounds->VolumeVector; glm::vec3 volumeVector = transformComponent->Scale * bounds->VolumeVector;
m_Renderer->AddAABBToDraw(origin, volumeVector, (collision != nullptr && collision->CollidingEntities.size() > 0)); m_Renderer->AddAABBToDraw(origin, volumeVector, (collision != nullptr && collision->CollidingEntities.size() > 0));
@@ -41,20 +45,22 @@ void Systems::RenderSystem::UpdateEntity(double dt, EntityID entity, EntityID pa
#endif #endif
auto pointLightComponent = m_World->GetComponent<Components::PointLight>(entity, "PointLight"); auto pointLightComponent = m_World->GetComponent<Components::PointLight>(entity, "PointLight");
if (pointLightComponent != nullptr) { if (pointLightComponent != nullptr)
{
glm::vec3 position = m_TransformSystem->AbsolutePosition(entity); glm::vec3 position = m_TransformSystem->AbsolutePosition(entity);
m_Renderer->AddPointLightToDraw( m_Renderer->AddPointLightToDraw(
position, position,
pointLightComponent->Specular, pointLightComponent->Specular,
pointLightComponent->Diffuse, pointLightComponent->Diffuse,
pointLightComponent->constantAttenuation, pointLightComponent->constantAttenuation,
pointLightComponent->linearAttenuation, pointLightComponent->linearAttenuation,
pointLightComponent->quadraticAttenuation, pointLightComponent->quadraticAttenuation,
pointLightComponent->spotExponent); pointLightComponent->spotExponent);
} }
auto cameraComponent = m_World->GetComponent<Components::Camera>(entity, "Camera"); auto cameraComponent = m_World->GetComponent<Components::Camera>(entity, "Camera");
if (cameraComponent != nullptr) { if (cameraComponent != nullptr)
{
m_Renderer->GetCamera()->Position(transformComponent->Position); m_Renderer->GetCamera()->Position(transformComponent->Position);
m_Renderer->GetCamera()->Orientation(transformComponent->Orientation); m_Renderer->GetCamera()->Orientation(transformComponent->Orientation);
+13 -13
View File
@@ -17,23 +17,23 @@
namespace Systems namespace Systems
{ {
class RenderSystem : public System class RenderSystem : public System
{ {
public: public:
RenderSystem(World* world, std::shared_ptr<Renderer> renderer) RenderSystem(World* world, std::shared_ptr<Renderer> renderer)
: System(world), m_Renderer(renderer){ } : System(world), m_Renderer(renderer) { }
void Initialize() override; void Initialize() override;
std::unordered_map<std::string, std::shared_ptr<Model>> m_CachedModels; std::unordered_map<std::string, std::shared_ptr<Model>> m_CachedModels;
void OnComponentCreated(std::string type, std:: shared_ptr<Component> component) override; void OnComponentCreated(std::string type, std:: shared_ptr<Component> component) override;
void UpdateEntity(double dt, EntityID entity, EntityID parent) override; void UpdateEntity(double dt, EntityID entity, EntityID parent) override;
private: private:
std::shared_ptr<Renderer> m_Renderer; std::shared_ptr<Renderer> m_Renderer;
std::shared_ptr<Systems::TransformSystem> m_TransformSystem; std::shared_ptr<Systems::TransformSystem> m_TransformSystem;
}; };
} }
+16 -9
View File
@@ -3,7 +3,7 @@
#include "World.h" #include "World.h"
Systems::SoundSystem::SoundSystem(World* world) Systems::SoundSystem::SoundSystem(World* world)
: System(world) : System(world)
{ {
//initialize OpenAL //initialize OpenAL
ALCdevice* Device = alcOpenDevice(NULL); ALCdevice* Device = alcOpenDevice(NULL);
@@ -104,7 +104,8 @@ void Systems::SoundSystem::StopSound(std::shared_ptr<Components::SoundEmitter> e
void Systems::SoundSystem::OnComponentCreated(std::string type, std::shared_ptr<Component> component) void Systems::SoundSystem::OnComponentCreated(std::string type, std::shared_ptr<Component> component)
{ {
if(type == "SoundEmitter") { if(type == "SoundEmitter")
{
ALuint source = CreateSource(); ALuint source = CreateSource();
m_Sources[component.get()] = source; m_Sources[component.get()] = source;
} }
@@ -112,8 +113,10 @@ void Systems::SoundSystem::OnComponentCreated(std::string type, std::shared_ptr<
void Systems::SoundSystem::OnComponentRemoved(std::string type, Component* component) void Systems::SoundSystem::OnComponentRemoved(std::string type, Component* component)
{ {
if(type == "SoundEmitter") { if(type == "SoundEmitter")
if (m_Sources.find(component) != m_Sources.end()) { {
if (m_Sources.find(component) != m_Sources.end())
{
ALuint source = m_Sources[component]; ALuint source = m_Sources[component];
alDeleteSources(1, &source); alDeleteSources(1, &source);
} }
@@ -125,30 +128,34 @@ ALuint Systems::SoundSystem::LoadFile(std::string path)
if (m_BufferCache.find(path) != m_BufferCache.end()) if (m_BufferCache.find(path) != m_BufferCache.end())
return m_BufferCache[path]; return m_BufferCache[path];
FILE *fp = NULL; FILE* fp = NULL;
fp = fopen(path.c_str(), "rb"); fp = fopen(path.c_str(), "rb");
if (fp == NULL) { if (fp == NULL)
{
LOG_ERROR("Failed to load sound file \"%s\"", path.c_str()); LOG_ERROR("Failed to load sound file \"%s\"", path.c_str());
return 0; return 0;
} }
//CHECK FOR VALID WAVE-FILE //CHECK FOR VALID WAVE-FILE
fread(type, sizeof(char), 4, fp); fread(type, sizeof(char), 4, fp);
if(type[0]!='R' || type[1]!='I' || type[2]!='F' || type[3]!='F') { if(type[0]!='R' || type[1]!='I' || type[2]!='F' || type[3]!='F')
{
LOG_ERROR("ERROR: No RIFF in WAVE-file"); LOG_ERROR("ERROR: No RIFF in WAVE-file");
return 0; return 0;
} }
fread(&size, sizeof(unsigned long), 1, fp); fread(&size, sizeof(unsigned long), 1, fp);
fread(type, sizeof(char), 4, fp); fread(type, sizeof(char), 4, fp);
if(type[0]!='W' || type[1]!='A' || type[2]!='V' || type[3]!='E') { if(type[0]!='W' || type[1]!='A' || type[2]!='V' || type[3]!='E')
{
LOG_ERROR("ERROR: Not WAVE-file"); LOG_ERROR("ERROR: Not WAVE-file");
return 0; return 0;
} }
fread(type, sizeof(char), 4, fp); fread(type, sizeof(char), 4, fp);
if(type[0]!='f' || type[1]!='m' || type[2]!='t' || type[3]!=' ') { if(type[0]!='f' || type[1]!='m' || type[2]!='t' || type[3]!=' ')
{
LOG_ERROR("ERROR: No fmt in WAVE-file"); LOG_ERROR("ERROR: No fmt in WAVE-file");
return 0; return 0;
} }
+11 -11
View File
@@ -7,19 +7,19 @@
namespace Systems namespace Systems
{ {
class TransformSystem : public System class TransformSystem : public System
{ {
public: public:
TransformSystem(World* world) TransformSystem(World* world)
: System(world) { } : System(world) { }
//void Update(double dt) override; //void Update(double dt) override;
//void UpdateEntity(double dt, EntityID entity, EntityID parent) override; //void UpdateEntity(double dt, EntityID entity, EntityID parent) override;
glm::vec3 AbsolutePosition(EntityID entity); glm::vec3 AbsolutePosition(EntityID entity);
glm::quat AbsoluteOrientation(EntityID entity); glm::quat AbsoluteOrientation(EntityID entity);
glm::vec3 AbsoluteScale(EntityID entity); glm::vec3 AbsoluteScale(EntityID entity);
}; };
} }
+2 -1
View File
@@ -9,7 +9,8 @@ Texture::Texture(std::string path)
void Texture::Load(std::string path) void Texture::Load(std::string path)
{ {
auto cachedTexture = m_TextureCache.find(path); auto cachedTexture = m_TextureCache.find(path);
if (cachedTexture == m_TextureCache.end()) { if (cachedTexture == m_TextureCache.end())
{
m_TextureCache[path] = SOIL_load_OGL_texture(path.c_str(), 0, 0, SOIL_FLAG_INVERT_Y); m_TextureCache[path] = SOIL_load_OGL_texture(path.c_str(), 0, 0, SOIL_FLAG_INVERT_Y);
} }
+2 -1
View File
@@ -7,7 +7,8 @@
inline bool _GLERROR(char* info, char* file, char* func, unsigned int line) inline bool _GLERROR(char* info, char* file, char* func, unsigned int line)
{ {
GLenum error = glGetError(); GLenum error = glGetError();
if (error != GL_NO_ERROR) { if (error != GL_NO_ERROR)
{
_LOG(LOG_LEVEL_ERROR, file, func, line, "GL Error: %s %i %s", info, error, gluErrorString(error)); _LOG(LOG_LEVEL_ERROR, file, func, line, "GL Error: %s %i %s", info, error, gluErrorString(error));
return true; return true;
} }
+5 -2
View File
@@ -55,10 +55,13 @@ static void _LOG(_LOG_LEVEL logLevel, char* file, char* func, unsigned int line,
vsnprintf(message, size, format, args); vsnprintf(message, size, format, args);
va_end(args); va_end(args);
if (logLevel == LOG_LEVEL_ERROR) { if (logLevel == LOG_LEVEL_ERROR)
{
std::cerr << file << ":" << line << " " << func << std::endl; std::cerr << file << ":" << line << " " << func << std::endl;
std::cerr << _LOG_LEVEL_PREFIX[logLevel] << message << std::endl; std::cerr << _LOG_LEVEL_PREFIX[logLevel] << message << std::endl;
} else { }
else
{
std::cout << _LOG_LEVEL_PREFIX[logLevel] << message << std::endl; std::cout << _LOG_LEVEL_PREFIX[logLevel] << message << std::endl;
} }
+23 -11
View File
@@ -8,22 +8,27 @@ void World::RecycleEntityID(EntityID id)
EntityID World::GenerateEntityID() EntityID World::GenerateEntityID()
{ {
if (!m_RecycledEntityIDs.empty()) { if (!m_RecycledEntityIDs.empty())
{
EntityID id = m_RecycledEntityIDs.top(); EntityID id = m_RecycledEntityIDs.top();
m_RecycledEntityIDs.pop(); m_RecycledEntityIDs.pop();
return id; return id;
} else { }
else
{
return ++m_LastEntityID; return ++m_LastEntityID;
} }
} }
void World::RecursiveUpdate(std::shared_ptr<System> system, double dt, EntityID parentEntity) void World::RecursiveUpdate(std::shared_ptr<System> system, double dt, EntityID parentEntity)
{ {
for (auto pair : m_EntityParents) { for (auto pair : m_EntityParents)
{
EntityID child = pair.first; EntityID child = pair.first;
EntityID parent = pair.second; EntityID parent = pair.second;
if (parent == parentEntity) { if (parent == parentEntity)
{
system->UpdateEntity(dt, child, parent); system->UpdateEntity(dt, child, parent);
RecursiveUpdate(system, dt, child); RecursiveUpdate(system, dt, child);
} }
@@ -32,7 +37,8 @@ void World::RecursiveUpdate(std::shared_ptr<System> system, double dt, EntityID
void World::Update(double dt) void World::Update(double dt)
{ {
for (auto pair : m_Systems) { for (auto pair : m_Systems)
{
auto system = pair.second; auto system = pair.second;
system->Update(dt); system->Update(dt);
RecursiveUpdate(system, dt, 0); RecursiveUpdate(system, dt, 0);
@@ -73,8 +79,10 @@ bool World::ValidEntity(EntityID entity)
void World::RemoveEntity(EntityID entity) void World::RemoveEntity(EntityID entity)
{ {
m_EntitiesToRemove.push_back(entity); m_EntitiesToRemove.push_back(entity);
for (auto pair : m_EntityParents) { for (auto pair : m_EntityParents)
if (pair.second == entity) { {
if (pair.second == entity)
{
m_EntitiesToRemove.push_back(pair.first); m_EntitiesToRemove.push_back(pair.first);
} }
} }
@@ -82,14 +90,17 @@ void World::RemoveEntity(EntityID entity)
void World::ProcessEntityRemovals() void World::ProcessEntityRemovals()
{ {
for (auto entity : m_EntitiesToRemove) { for (auto entity : m_EntitiesToRemove)
{
m_EntityParents.erase(entity); m_EntityParents.erase(entity);
// Remove components // Remove components
for (auto pair : m_EntityComponents[entity]) { for (auto pair : m_EntityComponents[entity])
{
auto type = pair.first; auto type = pair.first;
auto component = pair.second; auto component = pair.second;
// Trigger events // Trigger events
for (auto pair : m_Systems) { for (auto pair : m_Systems)
{
auto system = pair.second; auto system = pair.second;
system->OnComponentRemoved(type, component.get()); system->OnComponentRemoved(type, component.get());
} }
@@ -123,7 +134,8 @@ void World::Initialize()
{ {
RegisterSystems(); RegisterSystems();
AddSystems(); AddSystems();
for (auto system : m_Systems) { for (auto system : m_Systems)
{
system.second->Initialize(); system.second->Initialize();
} }
+6 -3
View File
@@ -100,7 +100,8 @@ protected:
template <class T> template <class T>
std::shared_ptr<T> World::GetSystem(std::string systemType) std::shared_ptr<T> World::GetSystem(std::string systemType)
{ {
if (m_Systems.find(systemType) == m_Systems.end()) { if (m_Systems.find(systemType) == m_Systems.end())
{
LOG_WARNING("Tried to get pointer to unregistered system \"%s\"!", systemType.c_str()); LOG_WARNING("Tried to get pointer to unregistered system \"%s\"!", systemType.c_str());
return nullptr; return nullptr;
} }
@@ -112,7 +113,8 @@ template <class T>
std::shared_ptr<T> World::AddComponent(EntityID entity, std::string componentType) std::shared_ptr<T> World::AddComponent(EntityID entity, std::string componentType)
{ {
std::shared_ptr<T> component = std::shared_ptr<T>(static_cast<T*>(m_ComponentFactory.Create(componentType))); std::shared_ptr<T> component = std::shared_ptr<T>(static_cast<T*>(m_ComponentFactory.Create(componentType)));
if (component == nullptr) { if (component == nullptr)
{
LOG_ERROR("Failed to attach invalid component \"%s\" to entity #%i", componentType.c_str(), entity); LOG_ERROR("Failed to attach invalid component \"%s\" to entity #%i", componentType.c_str(), entity);
return nullptr; return nullptr;
} }
@@ -120,7 +122,8 @@ std::shared_ptr<T> World::AddComponent(EntityID entity, std::string componentTyp
component->Entity = entity; component->Entity = entity;
m_ComponentsOfType[componentType].push_back(component); m_ComponentsOfType[componentType].push_back(component);
m_EntityComponents[entity][componentType] = component; m_EntityComponents[entity][componentType] = component;
for (auto pair : m_Systems) { for (auto pair : m_Systems)
{
auto system = pair.second; auto system = pair.second;
system->OnComponentCreated(componentType, component); system->OnComponentCreated(componentType, component);
} }