From 71047b08ec5d4c9b986d49c5533aa491f19581ef Mon Sep 17 00:00:00 2001 From: William Moberg Date: Thu, 14 Jan 2016 16:27:45 +0100 Subject: [PATCH] Async load works, using exceptions for special resources. --- include/Engine/Core/ResourceManager.h | 177 +++++++++----------- include/Engine/Rendering/BaseTexture.h | 2 +- include/Engine/Rendering/Model.h | 7 +- include/Engine/Rendering/RawModel.h | 4 +- include/Engine/Rendering/Texture.h | 3 - src/Engine/Collision/Collision.cpp | 10 +- src/Engine/Core/ResourceManager.cpp | 3 + src/Engine/Rendering/Model.cpp | 27 ++- src/Engine/Rendering/RawModel.cpp | 28 +--- src/Engine/Rendering/RenderQueueFactory.cpp | 6 +- src/Engine/Rendering/Renderer.cpp | 4 +- src/Engine/Rendering/Texture.cpp | 69 ++++---- src/Game/Game.cpp | 1 + 13 files changed, 160 insertions(+), 181 deletions(-) diff --git a/include/Engine/Core/ResourceManager.h b/include/Engine/Core/ResourceManager.h index 32122092..9ebf545a 100644 --- a/include/Engine/Core/ResourceManager.h +++ b/include/Engine/Core/ResourceManager.h @@ -12,33 +12,13 @@ /** Base Resource class. Implement this class for every resource to be handled by the resource manager. - - If it should be possible to load the resource asyncronously (on a separate thread in the background), - using LoadAsync() then any necessary OpenGL calls (Eg. glGenBuffers(), glBindBuffer(), etc.) must be - made in GlCommands() method, and not inside the constructor (see Texture.cpp for an example). */ class Resource { friend class ResourceManager; -private: - bool m_FullyConstructed; - protected: - Resource() : m_FullyConstructed(false) { } - //This method only needs to be overridden if: - // 1: a) It should be possible to load the resource with LoadAsync(), or - // b) This resource will be loaded inside the constructor of another resource that can be loaded with LoadAsync(). - // c) Same as above but recursively. - // 2: a) The resource needs to make OpenGL calls, or - // b) The resource contains a resource that makes OGL calls, or - // c) The resource contains a resource that contains ... ... a resource that makes OGL calls, or - // - //If 2.a: any calls should be made in the GlCommands. - //If 2.b or 2.c: PostCtorGLCommands() should be called on the contained resource(s). - //If GlCommands needs to be overridden and GlCommands is also overridden by a baseclass then the baseclass - //implementation should be called in from the derived class implementation (see Model.cpp for an example). - virtual void GlCommands() { } + Resource() { } public: // Pretend that this is a pure virtual function that you have to implement @@ -47,21 +27,30 @@ public: virtual void Reload() { } virtual void OnChildReloaded(Resource* child) { } - //If this resource implements GlCommands and it is loaded in another resource, - //then the containing resource must also implement GlCommands and - //call this method in it (see RawModel.cpp for an example). - void PostCtorGLCommands() - { - if (!m_FullyConstructed) { - GlCommands(); - } - m_FullyConstructed = true; - } unsigned int TypeID; unsigned int ResourceID; }; +//Any class inheriting from this class will always be loaded on the master thread, not on a parallel worker thread. +//This is important in case some instructions must be executed on the main thread, e.g. OpenGL commands, like glBindBuffer. +//This resource can still be loaded asyncronously, but it will not be loaded in a thread, instead it's constructor will +//be called once on every ResourceManager::Load, just throw StillLoadingException in the constructor if it is not done yet. +class ThreadUnsafeResource : public Resource +{ + friend class ResourceManager; +protected: + //Should be thrown in a Resource's constructor if it cannot complete because another resource is still loading. + //Not actually an error, just a message to the ResourceManager. + struct StillLoadingException : public std::exception + { + virtual const char* what() const throw() + { + return "Resource is still loading."; + } + }; +}; + /** Singleton resource manager to keep track of and cache any external engine assets */ class ResourceManager { @@ -85,24 +74,20 @@ public: */ // TODO: Templateify static bool IsResourceLoaded(std::string resourceType, std::string resourceName); - - /** If the resource is not in cache, starts loading the resource and returns nullptr immediately. + + /** If Async is false: Hot-loads a resource and caches it for future use. + Fairly safe to assume that return value is always a valid pointer, will only return nullptr on error. + + If Async is true: If the resource is not loaded yet, starts loading the resource + in the background and returns nullptr immediately. If the resource has been loaded already, return a pointer to it. - @tparam T Resource type. - @param resourceName Fully qualified name of the resource to load. - */ - template - static T* LoadAsync(std::string resourceName, Resource* parent = nullptr); - - /** Hot-loads a resource and caches it for future use. - Fairly safe to assume that return value is a valid pointer, will only return nullptr on error. - @tparam T Resource type. + @tparam Async Set this to true if the resource should be loaded asyncronously. @param resourceName Fully qualified name of the resource to load. */ - template - static T* Load(std::string resourceName, Resource* parent = nullptr); + template + static T* Load(std::string resourceName, Resource* parent = nullptr); /** Reloads an already loaded resource, keeping its resource ID intact. @@ -116,6 +101,22 @@ public: static void Update(); private: + //Represents a pointer value to signify that a resource haven't failed, but is not fully loaded. + class SpecialResourcePointer + { + public: + SpecialResourcePointer() + : m_Val(new Resource()) + {} + ~SpecialResourcePointer() + { + delete m_Val; + } + //Make this class implicitly convertible to the Resource*. + operator Resource* const() const { return m_Val; } + private: + Resource* const m_Val; + }; //This is a haxy way to make sure that IsMainThread is run when the program starts, so the master thread id is set. struct MasterThreadChecker { @@ -124,7 +125,8 @@ private: ResourceManager::IsMainThread(); } }; - static MasterThreadChecker m_Checker; + const static SpecialResourcePointer m_StillLoading; + const static MasterThreadChecker m_Checker; static std::unordered_map m_CompilerTypenameToResourceType; static std::unordered_map> m_FactoryFunctions; // type -> factory function @@ -151,23 +153,8 @@ private: static Resource* createResource(std::string resourceType, std::string resourceName, Resource* parent); static bool IsMainThread(); - template - static Resource* Load(std::string resourceType, std::string resourceName, Resource* parent = nullptr); }; -template -T* ResourceManager::Load(std::string resourceName, Resource* parent /* = nullptr */) -{ - auto resourceTypename = typeid(T).name(); - auto it = m_CompilerTypenameToResourceType.find(resourceTypename); - if (it == m_CompilerTypenameToResourceType.end()) { - LOG_ERROR("Failed to load resource \"%s\" of type \"%s\": type not registered", resourceName.c_str(), resourceTypename); - return nullptr; - } - - return static_cast(Load(it->second, resourceName, parent)); -} - template void ResourceManager::RegisterType(std::string typeName) { @@ -175,28 +162,29 @@ void ResourceManager::RegisterType(std::string typeName) m_FactoryFunctions[typeName] = [](std::string resourceName) { return new T(resourceName); }; } -template -T* ResourceManager::LoadAsync(std::string resourceName, Resource* parent /* = nullptr */) +template +static T* ResourceManager::Load(std::string resourceName, Resource* parent /* = nullptr */) { - auto resourceTypename = typeid(T).name(); - auto it = m_CompilerTypenameToResourceType.find(resourceTypename); - if (it == m_CompilerTypenameToResourceType.end()) { - LOG_ERROR("Failed to load resource \"%s\" of type \"%s\": type not registered", resourceName.c_str(), resourceTypename); - return nullptr; - } + auto resourceTypename = typeid(T).name(); + auto iter = m_CompilerTypenameToResourceType.find(resourceTypename); + if (iter == m_CompilerTypenameToResourceType.end()) { + LOG_ERROR("Failed to load resource \"%s\" of type \"%s\": type not registered", resourceName.c_str(), resourceTypename); + return nullptr; + } - return static_cast(Load(it->second, resourceName, parent)); -} + std::string resourceType = iter->second; + constexpr bool mustNotLoadInThread = std::is_base_of::value; + if (mustNotLoadInThread && !IsMainThread()) { + LOG_ERROR("Failed to Load \"%s\": ThreadUnsafeResource type \"%s\" load in the constructor of another resource that is loaded asyncronously.", resourceName.c_str(), iter->second.c_str()); + return nullptr; + } -template -static Resource* ResourceManager::Load(std::string resourceType, std::string resourceName, Resource* parent /* = nullptr */) -{ auto cacheKey = std::make_pair(resourceType, resourceName); decltype(m_ResourceCache)::iterator it; //If a thread has already been launched to load this resource. auto tIt = m_LoadingThreads.find(cacheKey); if (tIt != m_LoadingThreads.end()) { - if (Async) { + if (async) { //Return null if the thread is still working. if (!tIt->second.try_join_for(boost::chrono::nanoseconds(1))) { return nullptr; @@ -211,38 +199,39 @@ static Resource* ResourceManager::Load(std::string resourceType, std::string res //Find the resource that the thread loaded. it = m_ResourceCache.find(cacheKey); if (it != m_ResourceCache.end()) { - //At this point the resource may not be completely - //done since the worker threads cannot do opengl commands. - if (IsMainThread()) { - //Do the gl commands to complete the resource if we are not a worker thread. - it->second->PostCtorGLCommands(); - } - return it->second; + //Threads should not be able to throw StillLoadingException, so no check should be needed. + return static_cast(it->second); } else { - //If resource is still null at cacheKey after thread finishes, it failed. + //If cacheKey does not exist after thread finishes, it failed. return nullptr; } } - //If resource has already been loaded and cached. + //If resource has already been cached and completely loaded. it = m_ResourceCache.find(cacheKey); - if (it != m_ResourceCache.end()) { - return it->second; + if (it != m_ResourceCache.end() && it->second != m_StillLoading) { + return static_cast(it->second); } + Resource* res = nullptr; //If resource is not cached.. - if (Async) { - //Create a thread that loads the resource into cache. - m_LoadingThreads[cacheKey] = boost::thread(createResource, resourceType, resourceName, parent); + if (async) { + if (mustNotLoadInThread) { + res = createResource(resourceType, resourceName, parent); + if (res != m_StillLoading) { + return static_cast(res); + } + } else { + //Create a thread that loads the resource into cache. + m_LoadingThreads[cacheKey] = boost::thread(createResource, resourceType, resourceName, parent); + } return nullptr; } else { //load and return the resource. - Resource* res = createResource(resourceType, resourceName, parent); - if (IsMainThread() && res != nullptr) { - //Do the gl commands to complete the resource if we are not a worker thread. - res->PostCtorGLCommands(); - } - return res; + do { + res = createResource(resourceType, resourceName, parent); + } while (res == m_StillLoading); + return static_cast(res); } } diff --git a/include/Engine/Rendering/BaseTexture.h b/include/Engine/Rendering/BaseTexture.h index 26ae399d..96df5561 100644 --- a/include/Engine/Rendering/BaseTexture.h +++ b/include/Engine/Rendering/BaseTexture.h @@ -3,7 +3,7 @@ #include "../Core/ResourceManager.h" -class BaseTexture : public Resource +class BaseTexture : public ThreadUnsafeResource { friend class ResourceManager; diff --git a/include/Engine/Rendering/Model.h b/include/Engine/Rendering/Model.h index ffef745c..77e3df76 100644 --- a/include/Engine/Rendering/Model.h +++ b/include/Engine/Rendering/Model.h @@ -4,21 +4,24 @@ #include "RawModel.h" #include "../OpenGL.h" -class Model : public RawModel +class Model : public ThreadUnsafeResource { friend class ResourceManager; private: Model(std::string fileName); - virtual void GlCommands() override; public: ~Model(); + const std::vector& TextureGroups() const { return m_RawModel->TextureGroups; } + const glm::mat4& Matrix() const { return m_RawModel->m_Matrix; } + const std::vector& Vertices() const { return m_RawModel->m_Vertices; } GLuint VAO; GLuint ElementBuffer; private: + RawModel* m_RawModel; GLuint VertexBuffer; GLuint DiffuseVertexColorBuffer; GLuint SpecularVertexColorBuffer; diff --git a/include/Engine/Rendering/RawModel.h b/include/Engine/Rendering/RawModel.h index 379b81ab..82619c86 100644 --- a/include/Engine/Rendering/RawModel.h +++ b/include/Engine/Rendering/RawModel.h @@ -24,7 +24,6 @@ class RawModel : public Resource protected: RawModel(std::string fileName); - virtual void GlCommands() override; public: ~RawModel(); @@ -47,8 +46,11 @@ public: struct MaterialGroup { float Shininess; + std::string TexturePath; std::shared_ptr<::Texture> Texture; + std::string NormalMapPath; std::shared_ptr<::Texture> NormalMap; + std::string SpecularMapPath; std::shared_ptr<::Texture> SpecularMap; unsigned int StartIndex; unsigned int EndIndex; diff --git a/include/Engine/Rendering/Texture.h b/include/Engine/Rendering/Texture.h index 8cdcaef0..16892afc 100644 --- a/include/Engine/Rendering/Texture.h +++ b/include/Engine/Rendering/Texture.h @@ -11,10 +11,7 @@ class Texture : public BaseTexture private: Texture(std::string path); - virtual void GlCommands() override; - GLint m_Format; - Image* m_Image; public: ~Texture(); diff --git a/src/Engine/Collision/Collision.cpp b/src/Engine/Collision/Collision.cpp index 7473c67f..7abc63ea 100644 --- a/src/Engine/Collision/Collision.cpp +++ b/src/Engine/Collision/Collision.cpp @@ -220,16 +220,16 @@ bool attachAABBComponentFromModel(World* world, EntityID id) } ComponentWrapper model = world->GetComponent(id, "Model"); ComponentWrapper collision = world->AttachComponent(id, "AABB"); - Model* modelRes = ResourceManager::LoadAsync(model["Resource"]); + Model* modelRes = ResourceManager::Load(model["Resource"]); if (modelRes == nullptr) { return false; } - glm::mat4 modelMatrix = modelRes->m_Matrix; + glm::mat4 modelMatrix = modelRes->Matrix(); glm::vec3 mini = glm::vec3(INFINITY, INFINITY, INFINITY); glm::vec3 maxi = glm::vec3(-INFINITY, -INFINITY, -INFINITY); - for (const auto& v : modelRes->m_Vertices) { + for (const auto& v : modelRes->Vertices()) { const auto& wPos = modelMatrix * glm::vec4(v.Position.x, v.Position.y, v.Position.z, 1); maxi.x = std::max(wPos.x, maxi.x); maxi.y = std::max(wPos.y, maxi.y); @@ -247,7 +247,7 @@ bool GetEntityBox(World* world, ComponentWrapper& AABBComponent, AABB& outBox) { ComponentWrapper& cTrans = world->GetComponent(AABBComponent.EntityID, "Transform"); ComponentWrapper model = world->GetComponent(AABBComponent.EntityID, "Model"); - Model* modelRes = ResourceManager::LoadAsync(model["Resource"]); + Model* modelRes = ResourceManager::Load(model["Resource"]); outBox.CreateFromCenter(AABBComponent["BoxCenter"], AABBComponent["BoxSize"]); glm::vec3 mini = outBox.MinCorner(); glm::vec3 maxi = outBox.MaxCorner(); @@ -255,7 +255,7 @@ bool GetEntityBox(World* world, ComponentWrapper& AABBComponent, AABB& outBox) if (modelRes == nullptr) { return false; } - glm::mat4 modelMatrix = modelRes->m_Matrix * + glm::mat4 modelMatrix = modelRes->Matrix() * glm::translate(glm::mat4(), (glm::vec3)cTrans["Position"]) * glm::scale((glm::vec3)cTrans["Scale"]); diff --git a/src/Engine/Core/ResourceManager.cpp b/src/Engine/Core/ResourceManager.cpp index 102e99ba..ffd6c76c 100644 --- a/src/Engine/Core/ResourceManager.cpp +++ b/src/Engine/Core/ResourceManager.cpp @@ -14,6 +14,7 @@ std::unordered_map ResourceManager::m_ResourceCount; FileWatcher ResourceManager::m_FileWatcher; std::unordered_map, boost::thread> ResourceManager::m_LoadingThreads; boost::recursive_mutex ResourceManager::m_Mutex; +const ResourceManager::SpecialResourcePointer ResourceManager::m_StillLoading; unsigned int ResourceManager::GetTypeID(std::string resourceType) { @@ -92,6 +93,8 @@ Resource* ResourceManager::createResource(std::string resourceType, std::string Resource* resource = nullptr; try { resource = facIt->second(resourceName); + } catch (const ThreadUnsafeResource::StillLoadingException&) { + resource = m_StillLoading; } catch (const std::exception& e) { LOG_ERROR("Failed to load resource \"%s\" of type \"%s\": %s", resourceName.c_str(), resourceType.c_str(), e.what()); } diff --git a/src/Engine/Rendering/Model.cpp b/src/Engine/Rendering/Model.cpp index c2aab44f..8e24b704 100644 --- a/src/Engine/Rendering/Model.cpp +++ b/src/Engine/Rendering/Model.cpp @@ -1,24 +1,35 @@ #include "Rendering/Model.h" Model::Model(std::string fileName) - : RawModel(fileName) { -} + //Load the RawModel asyncronously, this will be done on a separate thread in the background. + m_RawModel = ResourceManager::Load(fileName); + //If it is null, the model is not done yet, so tell resourceManager to try constructing me again later. + if (m_RawModel == nullptr) { + throw StillLoadingException(); + } -void Model::GlCommands() -{ - //Call the base class method. - RawModel::GlCommands(); + for (auto& group : m_RawModel->TextureGroups) { + if (!group.TexturePath.empty()) { + group.Texture = std::shared_ptr(ResourceManager::Load(group.TexturePath)); + } + if (!group.NormalMapPath.empty()) { + group.NormalMap = std::shared_ptr(ResourceManager::Load(group.NormalMapPath)); + } + if (!group.SpecularMapPath.empty()) { + group.SpecularMap = std::shared_ptr(ResourceManager::Load(group.SpecularMapPath)); + } + } // Generate GL buffers GLuint buffer; glGenBuffers(1, &buffer); glBindBuffer(GL_ARRAY_BUFFER, buffer); - glBufferData(GL_ARRAY_BUFFER, m_Vertices.size() * sizeof(Vertex), &m_Vertices[0], GL_STATIC_DRAW); + glBufferData(GL_ARRAY_BUFFER, m_RawModel->m_Vertices.size() * sizeof(RawModel::Vertex), &m_RawModel->m_Vertices[0], GL_STATIC_DRAW); glGenBuffers(1, &ElementBuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ElementBuffer); - glBufferData(GL_ELEMENT_ARRAY_BUFFER, m_Indices.size() * sizeof(unsigned int), &m_Indices[0], GL_STATIC_DRAW); + glBufferData(GL_ELEMENT_ARRAY_BUFFER, m_RawModel->m_Indices.size() * sizeof(unsigned int), &m_RawModel->m_Indices[0], GL_STATIC_DRAW); glGenVertexArrays(1, &VAO); glBindVertexArray(VAO); diff --git a/src/Engine/Rendering/RawModel.cpp b/src/Engine/Rendering/RawModel.cpp index 9428f21e..fbb406f6 100644 --- a/src/Engine/Rendering/RawModel.cpp +++ b/src/Engine/Rendering/RawModel.cpp @@ -141,9 +141,7 @@ RawModel::RawModel(std::string fileName) aiString path; aiTextureMapping mapping; material->GetTexture(aiTextureType_DIFFUSE, 0, &path, &mapping); - std::string absolutePath = (boost::filesystem::path(fileName).branch_path() / path.C_Str()).string(); - //LOG_DEBUG("Diffuse texture: %s", absolutePath.c_str()); - matGroup.Texture = std::shared_ptr(ResourceManager::Load(absolutePath)); + matGroup.TexturePath = (boost::filesystem::path(fileName).branch_path() / path.C_Str()).string(); } // Normal map //LOG_DEBUG("%i normal maps found", material->GetTextureCount(aiTextureType_HEIGHT)); @@ -151,9 +149,7 @@ RawModel::RawModel(std::string fileName) aiString path; aiTextureMapping mapping; material->GetTexture(aiTextureType_HEIGHT, 0, &path, &mapping); - std::string absolutePath = (boost::filesystem::path(fileName).branch_path() / path.C_Str()).string(); - //LOG_DEBUG("Normal map: %s", absolutePath.c_str()); - matGroup.NormalMap = std::shared_ptr(ResourceManager::Load(absolutePath)); + matGroup.NormalMapPath = (boost::filesystem::path(fileName).branch_path() / path.C_Str()).string(); } // Specular map //LOG_DEBUG("%i specular maps found", material->GetTextureCount(aiTextureType_SPECULAR)); @@ -161,9 +157,7 @@ RawModel::RawModel(std::string fileName) aiString path; aiTextureMapping mapping; material->GetTexture(aiTextureType_SPECULAR, 0, &path, &mapping); - std::string absolutePath = (boost::filesystem::path(fileName).branch_path() / path.C_Str()).string(); - //LOG_DEBUG("Specular map: %s", absolutePath.c_str()); - matGroup.SpecularMap = std::shared_ptr(ResourceManager::Load(absolutePath)); + matGroup.SpecularMapPath = (boost::filesystem::path(fileName).branch_path() / path.C_Str()).string(); } TextureGroups.push_back(matGroup); @@ -292,22 +286,6 @@ RawModel::RawModel(std::string fileName) } } -void RawModel::GlCommands() -{ - //Since RawModel contains Textures that was loaded in the constructor, their GlCommands must be run. - for (auto& texGroup : TextureGroups) { - if (texGroup.Texture) { - texGroup.Texture->PostCtorGLCommands(); - } - if (texGroup.NormalMap) { - texGroup.NormalMap->PostCtorGLCommands(); - } - if (texGroup.SpecularMap) { - texGroup.SpecularMap->PostCtorGLCommands(); - } - } -} - RawModel::~RawModel() { if (m_Skeleton) { diff --git a/src/Engine/Rendering/RenderQueueFactory.cpp b/src/Engine/Rendering/RenderQueueFactory.cpp index 71b2e086..66eacd67 100644 --- a/src/Engine/Rendering/RenderQueueFactory.cpp +++ b/src/Engine/Rendering/RenderQueueFactory.cpp @@ -84,12 +84,12 @@ void RenderQueueFactory::FillModels(World* world, RenderQueue* renderQueue) continue; } glm::vec4 color = modelC["Color"]; - Model* model = ResourceManager::LoadAsync(resource); + Model* model = ResourceManager::Load(resource); if (model == nullptr) { model = ResourceManager::Load("Models/Core/Error.obj"); } - for (auto texGroup : model->TextureGroups) { + for (auto texGroup : model->TextureGroups()) { ModelJob job; job.TextureID = (texGroup.Texture) ? texGroup.Texture->ResourceID : 0; job.DiffuseTexture = texGroup.Texture.get(); @@ -98,7 +98,7 @@ void RenderQueueFactory::FillModels(World* world, RenderQueue* renderQueue) job.Model = model; job.StartIndex = texGroup.StartIndex; job.EndIndex = texGroup.EndIndex; - job.ModelMatrix = model->m_Matrix * ModelMatrix(world, modelC.EntityID); + job.ModelMatrix = model->Matrix() * ModelMatrix(world, modelC.EntityID); job.Color = color; //TODO: RENDERER: Not sure if the best solution for pickingColor to entity link is this diff --git a/src/Engine/Rendering/Renderer.cpp b/src/Engine/Rendering/Renderer.cpp index 208f339b..d0788b94 100644 --- a/src/Engine/Rendering/Renderer.cpp +++ b/src/Engine/Rendering/Renderer.cpp @@ -161,8 +161,8 @@ void Renderer::DrawScreenQuad(GLuint textureToDraw) glBindVertexArray(m_ScreenQuad->VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ScreenQuad->ElementBuffer); - glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->TextureGroups[0].EndIndex - m_ScreenQuad->TextureGroups[0].StartIndex +1 - , GL_UNSIGNED_INT, 0, m_ScreenQuad->TextureGroups[0].StartIndex); + glDrawElementsBaseVertex(GL_TRIANGLES, m_ScreenQuad->TextureGroups()[0].EndIndex - m_ScreenQuad->TextureGroups()[0].StartIndex +1 + , GL_UNSIGNED_INT, 0, m_ScreenQuad->TextureGroups()[0].StartIndex); } void Renderer::InitializeTextures() diff --git a/src/Engine/Rendering/Texture.cpp b/src/Engine/Rendering/Texture.cpp index 7e1cd65b..57f3ca36 100644 --- a/src/Engine/Rendering/Texture.cpp +++ b/src/Engine/Rendering/Texture.cpp @@ -2,53 +2,48 @@ Texture::Texture(std::string path) { - m_Image = new PNG(path); + PNG image(path); - if (m_Image->Width == 0 && m_Image->Height == 0 || m_Image->Format == Image::ImageFormat::Unknown) { - delete m_Image; - m_Image = new PNG("Textures/Core/ErrorTexture.png"); - if (m_Image->Width == 0 && m_Image->Height == 0 || m_Image->Format == Image::ImageFormat::Unknown) { - LOG_ERROR("Couldn't even load the error texture. This is a dark day indeed."); - return; - } - } + if (image.Width == 0 && image.Height == 0 || image.Format == Image::ImageFormat::Unknown) { + image = PNG("Textures/Core/ErrorTexture.png"); + if (image.Width == 0 && image.Height == 0 || image.Format == Image::ImageFormat::Unknown) { + LOG_ERROR("Couldn't even load the error texture. This is a dark day indeed."); + return; + } + } - this->Width = m_Image->Width; - this->Height = m_Image->Height; + this->Width = image.Width; + this->Height = image.Height; - switch (m_Image->Format) { - case Image::ImageFormat::RGB: - m_Format = GL_RGB; - break; - case Image::ImageFormat::RGBA: - m_Format = GL_RGBA; - break; - } -} + GLint format; + switch (image.Format) { + case Image::ImageFormat::RGB: + format = GL_RGB; + break; + case Image::ImageFormat::RGBA: + format = GL_RGBA; + break; + } -void Texture::GlCommands() -{ - // Construct the OpenGL texture - glGenTextures(1, &m_Texture); - glBindTexture(GL_TEXTURE_2D, m_Texture); - glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - glTexImage2D(GL_TEXTURE_2D, 0, m_Format, Width, Height, 0, m_Format, GL_UNSIGNED_BYTE, m_Image->Data); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - GLERROR("Texture load"); - delete m_Image; - m_Image = nullptr; + // Construct the OpenGL texture + glGenTextures(1, &m_Texture); + glBindTexture(GL_TEXTURE_2D, m_Texture); + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + glTexImage2D(GL_TEXTURE_2D, 0, format, image.Width, image.Height, 0, format, GL_UNSIGNED_BYTE, image.Data); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + GLERROR("Texture load"); } Texture::~Texture() { - glDeleteTextures(1, &m_Texture); + glDeleteTextures(1, &m_Texture); } void Texture::Bind(GLenum textureUnit /* = GL_TEXTURE0 */) { - glActiveTexture(textureUnit); - glBindTexture(GL_TEXTURE_2D, m_Texture); + glActiveTexture(textureUnit); + glBindTexture(GL_TEXTURE_2D, m_Texture); } diff --git a/src/Game/Game.cpp b/src/Game/Game.cpp index 033db642..b6c8b21e 100644 --- a/src/Game/Game.cpp +++ b/src/Game/Game.cpp @@ -6,6 +6,7 @@ Game::Game(int argc, char* argv[]) { ResourceManager::RegisterType("ConfigFile"); ResourceManager::RegisterType("Model"); + ResourceManager::RegisterType("RawModel"); ResourceManager::RegisterType("Texture"); ResourceManager::RegisterType("EntityXMLFile"); ResourceManager::RegisterType("ShaderProgram");