Optimisations

Former-commit-id: 81d277a49b57f061a6339678bd953054e434c613
This commit is contained in:
Lynix 2013-07-03 01:17:22 +02:00
parent 3c1c04b2aa
commit b035852576
14 changed files with 179 additions and 173 deletions

View File

@ -12,9 +12,9 @@
template<typename Type, typename Parameters>
bool NzResourceLoader<Type, Parameters>::IsExtensionSupported(const NzString& extension)
{
for (auto loader = Type::s_loaders.begin(); loader != Type::s_loaders.end(); ++loader)
for (Loader& loader : Type::s_loaders)
{
ExtensionGetter isExtensionSupported = std::get<0>(*loader);
ExtensionGetter isExtensionSupported = std::get<0>(loader);
if (isExtensionSupported && isExtensionSupported(extension))
return true;
@ -45,15 +45,15 @@ bool NzResourceLoader<Type, Parameters>::LoadFromFile(Type* resource, const NzSt
NzFile file(path); // Ouvert seulement en cas de besoin
bool found = false;
for (auto loader = Type::s_loaders.begin(); loader != Type::s_loaders.end(); ++loader)
for (Loader& loader : Type::s_loaders)
{
ExtensionGetter isExtensionSupported = std::get<0>(*loader);
ExtensionGetter isExtensionSupported = std::get<0>(loader);
if (!isExtensionSupported || !isExtensionSupported(ext))
continue;
StreamChecker checkFunc = std::get<1>(*loader);
StreamLoader streamLoader = std::get<2>(*loader);
FileLoader fileLoader = std::get<3>(*loader);
StreamChecker checkFunc = std::get<1>(loader);
StreamLoader streamLoader = std::get<2>(loader);
FileLoader fileLoader = std::get<3>(loader);
if (checkFunc && !file.IsOpen())
{
@ -141,10 +141,10 @@ bool NzResourceLoader<Type, Parameters>::LoadFromStream(Type* resource, NzInputS
nzUInt64 streamPos = stream.GetCursorPos();
bool found = false;
for (auto loader = Type::s_loaders.begin(); loader != Type::s_loaders.end(); ++loader)
for (Loader& loader : Type::s_loaders)
{
StreamChecker checkFunc = std::get<1>(*loader);
StreamLoader streamLoader = std::get<2>(*loader);
StreamChecker checkFunc = std::get<1>(loader);
StreamLoader streamLoader = std::get<2>(loader);
stream.SetCursorPos(streamPos);

View File

@ -24,7 +24,7 @@ class NAZARA_API NzAbstractRenderQueue : NzNonCopyable
virtual void AddLight(const NzLight* light) = 0;
virtual void AddModel(const NzModel* model) = 0;
virtual void Clear() = 0;
virtual void Clear(bool fully) = 0;
};
#endif // NAZARA_ABSTRACTRENDERQUEUE_HPP

View File

@ -8,6 +8,8 @@
#define NAZARA_FORWARDRENDERQUEUE_HPP
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/Color.hpp>
#include <Nazara/Core/ResourceListener.hpp>
#include <Nazara/Graphics/AbstractRenderQueue.hpp>
#include <Nazara/Math/Box.hpp>
#include <Nazara/Math/Matrix4.hpp>
@ -18,7 +20,7 @@ class NzMaterial;
class NzSkeletalMesh;
class NzStaticMesh;
class NAZARA_API NzForwardRenderQueue : public NzAbstractRenderQueue
class NAZARA_API NzForwardRenderQueue : public NzAbstractRenderQueue, NzResourceListener
{
friend class NzForwardRenderTechnique;
@ -30,11 +32,21 @@ class NAZARA_API NzForwardRenderQueue : public NzAbstractRenderQueue
void AddLight(const NzLight* light);
void AddModel(const NzModel* model);
void Clear();
void Clear(bool fully);
void Sort(const NzCamera& camera);
private:
void OnResourceDestroy(const NzResource* resource, int index);
struct BillboardData
{
NzColor color;
NzVector3f position;
NzVector2f size;
float rotation;
};
struct MaterialComparator
{
bool operator()(const NzMaterial* mat1, const NzMaterial* mat2);
@ -76,6 +88,7 @@ class NAZARA_API NzForwardRenderQueue : public NzAbstractRenderQueue
typedef std::map<NzSkeletalMesh*, std::vector<SkeletalData>, SkeletalMeshComparator> SkeletalMeshContainer;
typedef std::map<NzStaticMesh*, std::vector<NzMatrix4f>, StaticMeshComparator> StaticMeshContainer;
std::map<NzMaterial*, std::vector<BillboardData>, MaterialComparator> billboards;
std::map<NzMaterial*, std::pair<SkeletalMeshContainer, StaticMeshContainer>, MaterialComparator> visibleModels;
std::vector<std::pair<unsigned int, bool>> visibleTransparentsModels;
std::vector<TransparentSkeletalModel> transparentSkeletalModels;

View File

@ -72,15 +72,15 @@ void NzLuaClass<T>::Register(NzLuaInstance& lua)
m_info->methods.resize(m_methods.size());
unsigned int index = 0;
for (auto it = m_methods.begin(); it != m_methods.end(); ++it)
for (auto& pair : m_methods)
{
m_info->methods[index] = it->second;
m_info->methods[index] = pair.second;
lua.PushValue(1);
lua.PushInteger(index);
lua.PushCFunction(MethodProxy, 2);
lua.SetField(it->first); // Méthode
lua.SetField(pair.first); // Méthode
index++;
}

View File

@ -150,7 +150,7 @@ void NzPluginManager::Uninitialize()
{
s_directories.clear();
for (auto pair : s_plugins)
for (auto& pair : s_plugins)
{
PluginUnload func = reinterpret_cast<PluginUnload>(pair.second->GetSymbol("NzPluginUnload"));
if (func)

View File

@ -124,15 +124,17 @@ void NzForwardRenderQueue::AddModel(const NzModel* model)
}
}
void NzForwardRenderQueue::Clear()
void NzForwardRenderQueue::Clear(bool fully)
{
directionnalLights.clear();
otherDrawables.clear();
visibleLights.clear();
visibleModels.clear();
visibleTransparentsModels.clear();
transparentSkeletalModels.clear();
transparentStaticModels.clear();
if (fully)
visibleModels.clear();
}
void NzForwardRenderQueue::Sort(const NzCamera& camera)
@ -164,6 +166,11 @@ void NzForwardRenderQueue::Sort(const NzCamera& camera)
std::sort(visibleTransparentsModels.begin(), visibleTransparentsModels.end(), comparator);
}
void NzForwardRenderQueue::OnResourceDestroy(const NzResource* resource, int index)
{
}
bool NzForwardRenderQueue::SkeletalMeshComparator::operator()(const NzSkeletalMesh* subMesh1, const NzSkeletalMesh* subMesh2)
{
const NzIndexBuffer* iBuffer1 = subMesh1->GetIndexBuffer();

View File

@ -56,104 +56,113 @@ void NzForwardRenderTechnique::Draw(const NzScene* scene)
int lightCountLocation = -1;
// Rendu des modèles opaques
for (auto matIt : m_renderQueue.visibleModels)
for (auto& matIt : m_renderQueue.visibleModels)
{
NzMaterial* material = matIt.first;
NzForwardRenderQueue::SkeletalMeshContainer& skeletalContainer = matIt.second.first;
NzForwardRenderQueue::StaticMeshContainer& staticContainer = matIt.second.second;
// On commence par récupérer le shader du matériau
const NzShader* shader;
if (material->HasCustomShader())
shader = material->GetCustomShader();
else
shader = NzShaderBuilder::Get(material->GetShaderFlags());
// Les uniformes sont conservées au sein du shader, inutile de les renvoyer tant que le shader reste le même
if (shader != lastShader)
if (!skeletalContainer.empty() || !staticContainer.empty())
{
// On récupère l'information sur l'éclairage en même temps que la position de l'uniforme "LightCount"
lightCountLocation = shader->GetUniformLocation(nzShaderUniform_LightCount);
NzMaterial* material = matIt.first;
NzRenderer::SetShader(shader);
// Couleur ambiante de la scène
shader->SendColor(shader->GetUniformLocation(nzShaderUniform_SceneAmbient), scene->GetAmbientColor());
// Position de la caméra
shader->SendVector(shader->GetUniformLocation(nzShaderUniform_CameraPosition), camera->GetPosition());
lightCount = 0;
// On envoie les lumières directionnelles s'il y a (Les mêmes pour tous)
if (lightCountLocation != -1)
{
for (const NzLight* light : m_renderQueue.directionnalLights)
{
light->Apply(shader, lightCount++);
if (lightCount > NAZARA_RENDERER_SHADER_MAX_LIGHTCOUNT)
break; // Prévenons les bêtises des utilisateurs
}
}
lastShader = shader;
}
material->Apply(shader);
// Meshs squelettiques
/*NzForwardRenderQueue::SkeletalMeshContainer& container = matIt.second.first;
if (!container.empty())
{
NzRenderer::SetVertexBuffer(m_skinningBuffer); // Vertex buffer commun
for (auto subMeshIt : container)
{
///TODO
}
}*/
// Meshs statiques
for (auto subMeshIt : matIt.second.second)
{
NzStaticMesh* mesh = subMeshIt.first;
const NzIndexBuffer* indexBuffer = mesh->GetIndexBuffer();
const NzVertexBuffer* vertexBuffer = mesh->GetVertexBuffer();
// Gestion du draw call avant la boucle de rendu
std::function<void(nzPrimitiveMode, unsigned int, unsigned int)> drawFunc;
unsigned int indexCount;
if (indexBuffer)
{
drawFunc = NzRenderer::DrawIndexedPrimitives;
indexCount = indexBuffer->GetIndexCount();
}
// On commence par récupérer le shader du matériau
const NzShader* shader;
if (material->HasCustomShader())
shader = material->GetCustomShader();
else
{
drawFunc = NzRenderer::DrawPrimitives;
indexCount = vertexBuffer->GetVertexCount();
}
shader = NzShaderBuilder::Get(material->GetShaderFlags());
NzRenderer::SetIndexBuffer(indexBuffer);
NzRenderer::SetVertexBuffer(vertexBuffer);
for (const NzMatrix4f& matrix : subMeshIt.second)
// Les uniformes sont conservées au sein du shader, inutile de les renvoyer tant que le shader reste le même
if (shader != lastShader)
{
// Calcul des lumières les plus proches
///TODO: LightManager ?
// On récupère l'information sur l'éclairage en même temps que la position de l'uniforme "LightCount"
lightCountLocation = shader->GetUniformLocation(nzShaderUniform_LightCount);
NzRenderer::SetShader(shader);
// Couleur ambiante de la scène
shader->SendColor(shader->GetUniformLocation(nzShaderUniform_SceneAmbient), scene->GetAmbientColor());
// Position de la caméra
shader->SendVector(shader->GetUniformLocation(nzShaderUniform_CameraPosition), camera->GetPosition());
lightCount = 0;
// On envoie les lumières directionnelles s'il y a (Les mêmes pour tous)
if (lightCountLocation != -1)
{
std::vector<const NzLight*>& visibleLights = m_renderQueue.visibleLights;
lightComparator.pos = matrix.GetTranslation();
std::sort(visibleLights.begin(), visibleLights.end(), lightComparator);
unsigned int max = std::min(std::min(NAZARA_RENDERER_SHADER_MAX_LIGHTCOUNT - lightCount, m_maxLightsPerObject), static_cast<unsigned int>(visibleLights.size()));
for (unsigned int i = 0; i < max; ++i)
visibleLights[i]->Apply(shader, lightCount++);
shader->SendInteger(lightCountLocation, lightCount);
for (const NzLight* light : m_renderQueue.directionnalLights)
{
light->Apply(shader, lightCount++);
if (lightCount > NAZARA_RENDERER_SHADER_MAX_LIGHTCOUNT)
break; // Prévenons les bêtises des utilisateurs
}
}
lastShader = shader;
}
NzRenderer::SetMatrix(nzMatrixType_World, matrix);
drawFunc(mesh->GetPrimitiveMode(), 0, indexCount);
material->Apply(shader);
// Meshs squelettiques
/*if (!skeletalContainer.empty())
{
NzRenderer::SetVertexBuffer(m_skinningBuffer); // Vertex buffer commun
for (auto& subMeshIt : container)
{
///TODO
}
}*/
// Meshs statiques
for (auto& subMeshIt : staticContainer)
{
NzStaticMesh* mesh = subMeshIt.first;
std::vector<NzMatrix4f>& matrices = subMeshIt.second;
if (!matrices.empty())
{
const NzIndexBuffer* indexBuffer = mesh->GetIndexBuffer();
const NzVertexBuffer* vertexBuffer = mesh->GetVertexBuffer();
// Gestion du draw call avant la boucle de rendu
std::function<void(nzPrimitiveMode, unsigned int, unsigned int)> drawFunc;
unsigned int indexCount;
if (indexBuffer)
{
drawFunc = NzRenderer::DrawIndexedPrimitives;
indexCount = indexBuffer->GetIndexCount();
}
else
{
drawFunc = NzRenderer::DrawPrimitives;
indexCount = vertexBuffer->GetVertexCount();
}
NzRenderer::SetIndexBuffer(indexBuffer);
NzRenderer::SetVertexBuffer(vertexBuffer);
for (const NzMatrix4f& matrix : matrices)
{
// Calcul des lumières les plus proches
///TODO: LightManager ?
if (lightCountLocation != -1)
{
std::vector<const NzLight*>& visibleLights = m_renderQueue.visibleLights;
lightComparator.pos = matrix.GetTranslation();
std::sort(visibleLights.begin(), visibleLights.end(), lightComparator);
unsigned int max = std::min(std::min(NAZARA_RENDERER_SHADER_MAX_LIGHTCOUNT - lightCount, m_maxLightsPerObject), static_cast<unsigned int>(visibleLights.size()));
for (unsigned int i = 0; i < max; ++i)
visibleLights[i]->Apply(shader, lightCount++);
shader->SendInteger(lightCountLocation, lightCount);
}
NzRenderer::SetMatrix(nzMatrixType_World, matrix);
drawFunc(mesh->GetPrimitiveMode(), 0, indexCount);
}
matrices.clear();
}
}
}
}

View File

@ -115,11 +115,11 @@ namespace
bool hasTexCoords = true;
NzBufferMapper<NzVertexBuffer> vertexMapper(vertexBuffer.get(), nzBufferAccess_WriteOnly);
NzMeshVertex* meshVertices = static_cast<NzMeshVertex*>(vertexMapper.GetPointer());
for (auto uvIt : vertices)
for (auto& uvIt : vertices)
{
for (auto normalIt : uvIt.second)
for (auto& normalIt : uvIt.second)
{
for (auto positionIt : normalIt.second)
for (auto& positionIt : normalIt.second)
{
NzMeshVertex& vertex = meshVertices[positionIt.second];
@ -261,7 +261,7 @@ namespace
specularMap.release();
}
else
NazaraWarning("Failed to load specular map (" + mtlMat->diffuseMap + ')');
NazaraWarning("Failed to load specular map (" + mtlMat->specularMap + ')');
}
// Si nous avons une alpha map ou des couleurs transparentes,

View File

@ -151,123 +151,99 @@ bool NzMTLParser::Parse()
}
else if (keyword == "map_ka")
{
NzString map = m_currentLine.SubString(m_currentLine.GetWordPosition(1));
if (!map.IsEmpty())
unsigned int mapPos = m_currentLine.GetWordPosition(1);
if (mapPos != NzString::npos)
{
NzString map = m_currentLine.SubString(mapPos);
if (!currentMaterial)
currentMaterial = &m_materials["default"];
currentMaterial->ambientMap = map;
}
#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
else
UnrecognizedLine();
#endif
}
else if (keyword == "map_kd")
{
NzString map = m_currentLine.SubString(m_currentLine.GetWordPosition(1));
if (!map.IsEmpty())
unsigned int mapPos = m_currentLine.GetWordPosition(1);
if (mapPos != NzString::npos)
{
NzString map = m_currentLine.SubString(mapPos);
if (!currentMaterial)
currentMaterial = &m_materials["default"];
currentMaterial->diffuseMap = map;
}
#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
else
UnrecognizedLine();
#endif
}
else if (keyword == "map_ks")
{
NzString map = m_currentLine.SubString(m_currentLine.GetWordPosition(1));
if (!map.IsEmpty())
unsigned int mapPos = m_currentLine.GetWordPosition(1);
if (mapPos != NzString::npos)
{
NzString map = m_currentLine.SubString(mapPos);
if (!currentMaterial)
currentMaterial = &m_materials["default"];
currentMaterial->specularMap = map;
}
#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
else
UnrecognizedLine();
#endif
}
else if (keyword == "map_bump" || keyword == "bump")
{
NzString map = m_currentLine.SubString(m_currentLine.GetWordPosition(1));
if (!map.IsEmpty())
unsigned int mapPos = m_currentLine.GetWordPosition(1);
if (mapPos != NzString::npos)
{
NzString map = m_currentLine.SubString(mapPos);
if (!currentMaterial)
currentMaterial = &m_materials["default"];
currentMaterial->bumpMap = map;
}
#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
else
UnrecognizedLine();
#endif
}
else if (keyword == "map_d")
{
NzString map = m_currentLine.SubString(m_currentLine.GetWordPosition(1));
if (!map.IsEmpty())
unsigned int mapPos = m_currentLine.GetWordPosition(1);
if (mapPos != NzString::npos)
{
NzString map = m_currentLine.SubString(mapPos);
if (!currentMaterial)
currentMaterial = &m_materials["default"];
currentMaterial->alphaMap = map;
}
#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
else
UnrecognizedLine();
#endif
}
else if (keyword == "map_decal" || keyword == "decal")
{
NzString map = m_currentLine.SubString(m_currentLine.GetWordPosition(1));
if (!map.IsEmpty())
unsigned int mapPos = m_currentLine.GetWordPosition(1);
if (mapPos != NzString::npos)
{
NzString map = m_currentLine.SubString(mapPos);
if (!currentMaterial)
currentMaterial = &m_materials["default"];
currentMaterial->decalMap = map;
}
#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
else
UnrecognizedLine();
#endif
}
else if (keyword == "map_disp" || keyword == "disp")
{
NzString map = m_currentLine.SubString(m_currentLine.GetWordPosition(1));
if (!map.IsEmpty())
unsigned int mapPos = m_currentLine.GetWordPosition(1);
if (mapPos != NzString::npos)
{
NzString map = m_currentLine.SubString(mapPos);
if (!currentMaterial)
currentMaterial = &m_materials["default"];
currentMaterial->displacementMap = map;
}
#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
else
UnrecognizedLine();
#endif
}
else if (keyword == "map_refl" || keyword == "refl")
{
NzString map = m_currentLine.SubString(m_currentLine.GetWordPosition(1));
if (!map.IsEmpty())
unsigned int mapPos = m_currentLine.GetWordPosition(1);
if (mapPos != NzString::npos)
{
NzString map = m_currentLine.SubString(mapPos);
if (!currentMaterial)
currentMaterial = &m_materials["default"];
currentMaterial->reflectionMap = map;
}
#if NAZARA_UTILITY_STRICT_RESOURCE_PARSING
else
UnrecognizedLine();
#endif
}
else if (keyword == "newmtl")
{

View File

@ -351,9 +351,9 @@ bool NzOBJParser::Parse()
std::unordered_map<NzString, unsigned int> materials;
unsigned int matCount = 0;
for (auto meshIt : meshes)
for (auto& meshIt : meshes)
{
for (auto matIt : meshIt.second)
for (auto& matIt : meshIt.second)
{
if (!matIt.second.empty())
{
@ -382,8 +382,8 @@ bool NzOBJParser::Parse()
}
m_materials.resize(matCount);
for (auto it : materials)
m_materials[it.second] = it.first;
for (const std::pair<NzString, unsigned int>& pair : materials)
m_materials[pair.second] = pair.first;
return true;
}

View File

@ -64,12 +64,12 @@ void NzScene::AddToVisibilityList(NzUpdatable* object)
void NzScene::Cull()
{
NzAbstractRenderQueue* renderQueue = m_impl->renderTechnique->GetRenderQueue();
renderQueue->Clear();
renderQueue->Clear(false);
m_impl->visibleUpdateList.clear();
// Frustum culling
RecursiveFrustumCull(renderQueue, m_impl->activeCamera->GetFrustum(), &m_impl->root);
RecursiveFrustumCull(m_impl->renderTechnique->GetRenderQueue(), m_impl->activeCamera->GetFrustum(), &m_impl->root);
///TODO: Occlusion culling

View File

@ -34,9 +34,9 @@ bool NzGLSLShader::Bind()
bool NzGLSLShader::BindTextures()
{
for (auto it = m_textures.begin(); it != m_textures.end(); ++it)
for (const std::pair<GLint, TextureSlot>& pair : m_textures)
{
TextureSlot& slot = it->second;
const TextureSlot& slot = pair.second;
if (slot.enabled)
NzRenderer::SetTexture(slot.unit, slot.texture);
}

View File

@ -1191,14 +1191,15 @@ void NzRenderer::Uninitialize()
s_instancingBuffer = nullptr;
// Libération des VAOs
for (auto pair : s_vaos)
for (auto& pair : s_vaos)
{
for (auto pair2 : pair.second)
for (auto& pair2 : pair.second)
{
GLuint vao = static_cast<GLuint>(pair2.second);
glDeleteVertexArrays(1, &vao);
}
}
s_vaos.clear();
NzOpenGL::Uninitialize();

View File

@ -126,7 +126,7 @@ void NzTextureSampler::SetDefaultAnisotropyLevel(nzUInt8 anisotropyLevel)
if (s_useAnisotropicFilter)
{
for (auto pair : s_samplers)
for (const std::pair<nzUInt32, GLuint>& pair : s_samplers)
{
if (((pair.first >> 5) & 0xFF) == 0)
glSamplerParameterf(pair.second, GL_TEXTURE_MAX_ANISOTROPY_EXT, static_cast<float>(anisotropyLevel));
@ -146,7 +146,7 @@ void NzTextureSampler::SetDefaultFilterMode(nzSamplerFilter filterMode)
s_defaultFilterMode = filterMode;
for (auto pair : s_samplers)
for (const std::pair<nzUInt32, GLuint>& pair : s_samplers)
{
if (((pair.first >> 1) & 0x3) == nzSamplerFilter_Default)
{
@ -201,7 +201,7 @@ void NzTextureSampler::SetDefaultWrapMode(nzSamplerWrap wrapMode)
s_defaultWrapMode = wrapMode;
GLenum wrapEnum = NzOpenGL::SamplerWrapMode[wrapMode];
for (auto pair : s_samplers)
for (const std::pair<nzUInt32, GLuint>& pair : s_samplers)
{
if (((pair.first >> 3) & 0x3) == nzSamplerWrap_Default)
{
@ -383,8 +383,8 @@ bool NzTextureSampler::Initialize()
void NzTextureSampler::Uninitialize()
{
for (auto it = s_samplers.begin(); it != s_samplers.end(); ++it)
glDeleteSamplers(1, &it->second);
for (const std::pair<nzUInt32, GLuint>& pair : s_samplers)
glDeleteSamplers(1, &pair.second);
s_samplers.clear();
}