Merge branch 'master' into vulkan

This commit is contained in:
Lynix
2018-04-26 22:48:49 +02:00
191 changed files with 5200 additions and 3554 deletions

View File

@@ -262,6 +262,8 @@ namespace Nz
*/
void Music::Pause()
{
NazaraAssert(m_source != InvalidSource, "Invalid sound emitter");
alSourcePause(m_source);
}

View File

@@ -37,6 +37,7 @@ namespace Nz
SoundEmitter(sound)
{
SetBuffer(sound.m_buffer);
EnableLooping(sound.IsLooping());
}
/*!
@@ -56,6 +57,8 @@ namespace Nz
*/
void Sound::EnableLooping(bool loop)
{
NazaraAssert(m_source != InvalidSource, "Invalid sound emitter");
alSourcei(m_source, AL_LOOPING, loop);
}
@@ -87,6 +90,8 @@ namespace Nz
*/
UInt32 Sound::GetPlayingOffset() const
{
NazaraAssert(m_source != InvalidSource, "Invalid sound emitter");
ALint samples = 0;
alGetSourcei(m_source, AL_SAMPLE_OFFSET, &samples);
@@ -108,6 +113,8 @@ namespace Nz
*/
bool Sound::IsLooping() const
{
NazaraAssert(m_source != InvalidSource, "Invalid sound emitter");
ALint loop;
alGetSourcei(m_source, AL_LOOPING, &loop);
@@ -205,6 +212,8 @@ namespace Nz
*/
void Sound::Pause()
{
NazaraAssert(m_source != InvalidSource, "Invalid sound emitter");
alSourcePause(m_source);
}
@@ -215,6 +224,7 @@ namespace Nz
*/
void Sound::Play()
{
NazaraAssert(m_source != InvalidSource, "Invalid sound emitter");
NazaraAssert(IsPlayable(), "Music is not playable");
alSourcePlay(m_source);
@@ -229,6 +239,7 @@ namespace Nz
*/
void Sound::SetBuffer(const SoundBuffer* buffer)
{
NazaraAssert(m_source != InvalidSource, "Invalid sound emitter");
NazaraAssert(!buffer || buffer->IsValid(), "Invalid sound buffer");
if (m_buffer == buffer)
@@ -251,14 +262,19 @@ namespace Nz
*/
void Sound::SetPlayingOffset(UInt32 offset)
{
NazaraAssert(m_source != InvalidSource, "Invalid sound emitter");
alSourcei(m_source, AL_SAMPLE_OFFSET, static_cast<ALint>(offset/1000.f * m_buffer->GetSampleRate()));
}
/*!
* \brief Stops the sound
*
* \remark This is one of the only function that can be called on a moved sound (and does nothing)
*/
void Sound::Stop()
{
alSourceStop(m_source);
if (m_source != InvalidSource)
alSourceStop(m_source);
}
}

View File

@@ -23,7 +23,6 @@ namespace Nz
/*!
* \brief Constructs a SoundEmitter object
*/
SoundEmitter::SoundEmitter()
{
alGenSources(1, &m_source);
@@ -39,22 +38,40 @@ namespace Nz
SoundEmitter::SoundEmitter(const SoundEmitter& emitter)
{
alGenSources(1, &m_source);
if (emitter.m_source != InvalidSource)
{
alGenSources(1, &m_source);
SetAttenuation(emitter.GetAttenuation());
SetMinDistance(emitter.GetMinDistance());
SetPitch(emitter.GetPitch());
// No copy for position or velocity
SetVolume(emitter.GetVolume());
SetAttenuation(emitter.GetAttenuation());
SetMinDistance(emitter.GetMinDistance());
SetPitch(emitter.GetPitch());
// No copy for position or velocity
SetVolume(emitter.GetVolume());
}
else
m_source = InvalidSource;
}
/*!
* \brief Constructs a SoundEmitter object by moving another
*
* \param emitter SoundEmitter to move
*
* \remark The moved sound emitter cannot be used after being moved
*/
SoundEmitter::SoundEmitter(SoundEmitter&& emitter) noexcept :
m_source(emitter.m_source)
{
emitter.m_source = InvalidSource;
}
/*!
* \brief Destructs the object
*/
SoundEmitter::~SoundEmitter()
{
alDeleteSources(1, &m_source);
if (m_source != InvalidSource)
alDeleteSources(1, &m_source);
}
/*!
@@ -65,6 +82,8 @@ namespace Nz
void SoundEmitter::EnableSpatialization(bool spatialization)
{
NazaraAssert(m_source != InvalidSource, "Invalid sound emitter");
alSourcei(m_source, AL_SOURCE_RELATIVE, !spatialization);
}
@@ -75,6 +94,8 @@ namespace Nz
float SoundEmitter::GetAttenuation() const
{
NazaraAssert(m_source != InvalidSource, "Invalid sound emitter");
ALfloat attenuation;
alGetSourcef(m_source, AL_ROLLOFF_FACTOR, &attenuation);
@@ -88,6 +109,8 @@ namespace Nz
float SoundEmitter::GetMinDistance() const
{
NazaraAssert(m_source != InvalidSource, "Invalid sound emitter");
ALfloat distance;
alGetSourcef(m_source, AL_REFERENCE_DISTANCE, &distance);
@@ -101,6 +124,8 @@ namespace Nz
float SoundEmitter::GetPitch() const
{
NazaraAssert(m_source != InvalidSource, "Invalid sound emitter");
ALfloat pitch;
alGetSourcef(m_source, AL_PITCH, &pitch);
@@ -114,6 +139,8 @@ namespace Nz
Vector3f SoundEmitter::GetPosition() const
{
NazaraAssert(m_source != InvalidSource, "Invalid sound emitter");
Vector3f position;
alGetSourcefv(m_source, AL_POSITION, position);
@@ -127,6 +154,8 @@ namespace Nz
Vector3f SoundEmitter::GetVelocity() const
{
NazaraAssert(m_source != InvalidSource, "Invalid sound emitter");
Vector3f velocity;
alGetSourcefv(m_source, AL_VELOCITY, velocity);
@@ -140,6 +169,8 @@ namespace Nz
float SoundEmitter::GetVolume() const
{
NazaraAssert(m_source != InvalidSource, "Invalid sound emitter");
ALfloat gain;
alGetSourcef(m_source, AL_GAIN, &gain);
@@ -153,6 +184,8 @@ namespace Nz
bool SoundEmitter::IsSpatialized() const
{
NazaraAssert(m_source != InvalidSource, "Invalid sound emitter");
ALint relative;
alGetSourcei(m_source, AL_SOURCE_RELATIVE, &relative);
@@ -167,6 +200,8 @@ namespace Nz
void SoundEmitter::SetAttenuation(float attenuation)
{
NazaraAssert(m_source != InvalidSource, "Invalid sound emitter");
alSourcef(m_source, AL_ROLLOFF_FACTOR, attenuation);
}
@@ -178,6 +213,8 @@ namespace Nz
void SoundEmitter::SetMinDistance(float minDistance)
{
NazaraAssert(m_source != InvalidSource, "Invalid sound emitter");
alSourcef(m_source, AL_REFERENCE_DISTANCE, minDistance);
}
@@ -189,6 +226,8 @@ namespace Nz
void SoundEmitter::SetPitch(float pitch)
{
NazaraAssert(m_source != InvalidSource, "Invalid sound emitter");
alSourcef(m_source, AL_PITCH, pitch);
}
@@ -200,6 +239,8 @@ namespace Nz
void SoundEmitter::SetPosition(const Vector3f& position)
{
NazaraAssert(m_source != InvalidSource, "Invalid sound emitter");
alSourcefv(m_source, AL_POSITION, position);
}
@@ -211,6 +252,8 @@ namespace Nz
void SoundEmitter::SetPosition(float x, float y, float z)
{
NazaraAssert(m_source != InvalidSource, "Invalid sound emitter");
alSource3f(m_source, AL_POSITION, x, y, z);
}
@@ -222,6 +265,8 @@ namespace Nz
void SoundEmitter::SetVelocity(const Vector3f& velocity)
{
NazaraAssert(m_source != InvalidSource, "Invalid sound emitter");
alSourcefv(m_source, AL_VELOCITY, velocity);
}
@@ -233,6 +278,8 @@ namespace Nz
void SoundEmitter::SetVelocity(float velX, float velY, float velZ)
{
NazaraAssert(m_source != InvalidSource, "Invalid sound emitter");
alSource3f(m_source, AL_VELOCITY, velX, velY, velZ);
}
@@ -244,9 +291,25 @@ namespace Nz
void SoundEmitter::SetVolume(float volume)
{
NazaraAssert(m_source != InvalidSource, "Invalid sound emitter");
alSourcef(m_source, AL_GAIN, volume * 0.01f);
}
/*!
* \brief Assign a sound emitter by moving it
*
* \param emitter SoundEmitter to move
*
* \return *this
*/
SoundEmitter& SoundEmitter::operator=(SoundEmitter&& emitter) noexcept
{
std::swap(m_source, emitter.m_source);
return *this;
}
/*!
* \brief Gets the status of the sound emitter
* \return Enumeration of type SoundStatus (Playing, Stopped, ...)
@@ -254,6 +317,8 @@ namespace Nz
SoundStatus SoundEmitter::GetInternalStatus() const
{
NazaraAssert(m_source != InvalidSource, "Invalid sound emitter");
ALint state;
alGetSourcei(m_source, AL_SOURCE_STATE, &state);

View File

@@ -3,8 +3,11 @@
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Core/Posix/DirectoryImpl.hpp>
#include <Nazara/Core/Directory.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Core/MemoryHelper.hpp>
#include <Nazara/Core/String.hpp>
#include <cstring>
#include <errno.h>
#include <sys/param.h>
#include <sys/stat.h>
@@ -13,9 +16,9 @@
namespace Nz
{
DirectoryImpl::DirectoryImpl(const Directory* parent)
DirectoryImpl::DirectoryImpl(const Directory* parent) :
m_parent(parent)
{
NazaraUnused(parent);
}
void DirectoryImpl::Close()
@@ -30,19 +33,29 @@ namespace Nz
UInt64 DirectoryImpl::GetResultSize() const
{
struct stat64 resulststat;
stat64(m_result->d_name, &resulststat);
String path = m_parent->GetPath();
std::size_t pathSize = path.GetSize();
return static_cast<UInt64>(resulststat.st_size);
std::size_t resultNameSize = std::strlen(m_result->d_name);
std::size_t fullNameSize = pathSize + 1 + resultNameSize;
StackArray<char> fullName = NazaraStackAllocationNoInit(char, fullNameSize + 1);
std::memcpy(&fullName[0], path.GetConstBuffer(), pathSize * sizeof(char));
fullName[pathSize] = '/';
std::memcpy(&fullName[pathSize + 1], m_result->d_name, resultNameSize * sizeof(char));
fullName[fullNameSize] = '\0';
struct stat64 results;
stat64(fullName.data(), &results);
return results.st_size;
}
bool DirectoryImpl::IsResultDirectory() const
{
struct stat64 filestats;
if (stat64(m_result->d_name, &filestats) == -1) // error
return false;
//TODO: Fix d_type handling (field can be missing or be a symbolic link, both cases which must be handled by calling stat)
return S_ISDIR(filestats.st_mode);
return m_result->d_type == DT_DIR;
}
bool DirectoryImpl::NextResult()

View File

@@ -43,6 +43,7 @@ namespace Nz
static bool Remove(const String& dirPath);
private:
const Directory* m_parent;
DIR* m_handle;
dirent64* m_result;
};

View File

@@ -28,7 +28,7 @@ namespace Nz
ResetBitPosition();
// Serialize will reset the bit position
if (!Serialize<UInt8>(*this, currentByte))
if (!Serialize(*this, currentByte))
NazaraWarning("Failed to flush bits");
}
}

View File

@@ -52,7 +52,7 @@ namespace Nz
*
* \param lineSize Maximum number of characters to read, or zero for no limit
*
* \return Line containing characters
* \return Line read from file
*
* \remark With the text stream option, "\r\n" is treated as "\n"
* \remark The line separator character is not returned as part of the string
@@ -87,8 +87,7 @@ namespace Nz
if (!SetCursorPos(GetCursorPos() - readSize + pos + 1))
NazaraWarning("Failed to reset cursor pos");
if (!line.IsEmpty())
break;
break;
}
else
{

View File

@@ -5932,7 +5932,7 @@ namespace Nz
* \param context Context of serialization
* \param string String to serialize
*/
bool Serialize(SerializationContext& context, const String& string)
bool Serialize(SerializationContext& context, const String& string, TypeTag<String>)
{
if (!Serialize(context, UInt32(string.GetSize())))
return false;
@@ -5947,7 +5947,7 @@ namespace Nz
* \param context Context of unserialization
* \param string String to unserialize
*/
bool Unserialize(SerializationContext& context, String* string)
bool Unserialize(SerializationContext& context, String* string, TypeTag<String>)
{
UInt32 size;
if (!Unserialize(context, &size))

View File

@@ -0,0 +1,947 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Engine - Graphics module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Graphics/BasicRenderQueue.hpp>
#include <Nazara/Graphics/AbstractViewer.hpp>
#include <Nazara/Utility/VertexStruct.hpp>
#include <limits>
#include <Nazara/Graphics/Debug.hpp>
///TODO: Replace sinus/cosinus by a lookup table (which will lead to a speed up about 10x)
namespace Nz
{
/*!
* \ingroup graphics
* \class Nz::BasicRenderQueue
* \brief Graphics class that represents a simple rendering queue
*/
/*!
* \brief Adds multiple billboards to the queue
*
* \param renderOrder Order of rendering
* \param material Material of the billboards
* \param count Number of billboards
* \param positionPtr Position of the billboards
* \param sizePtr Sizes of the billboards
* \param sinCosPtr Rotation of the billboards if null, Vector2f(0.f, 1.f) is used
* \param colorPtr Color of the billboards if null, Color::White is used
*
* \remark Produces a NazaraAssert if material is invalid
*/
void BasicRenderQueue::AddBillboards(int renderOrder, const Material* material, std::size_t billboardCount, const Recti& scissorRect, SparsePtr<const Vector3f> positionPtr, SparsePtr<const Vector2f> sizePtr, SparsePtr<const Vector2f> sinCosPtr, SparsePtr<const Color> colorPtr)
{
NazaraAssert(material, "Invalid material");
Vector2f defaultSinCos(0.f, 1.f); // sin(0) = 0, cos(0) = 1
if (!sinCosPtr)
sinCosPtr.Reset(&defaultSinCos, 0); // The trick here is to put the stride to zero, which leads the pointer to be immobile
if (!colorPtr)
colorPtr.Reset(&Color::White, 0); // Same
if (material->IsDepthSortingEnabled())
{
for (std::size_t i = 0; i < billboardCount; ++i)
{
depthSortedBillboards.Insert({
renderOrder,
material,
scissorRect,
{
*colorPtr++,
*positionPtr++,
*sizePtr++,
*sinCosPtr++
}
});
}
}
else
{
std::size_t billboardIndex = m_billboards.size();
m_billboards.resize(billboardIndex + billboardCount);
BillboardData* data = &m_billboards[billboardIndex];
for (std::size_t i = 0; i < billboardCount; ++i)
{
data->center = *positionPtr++;
data->color = *colorPtr++;
data->sinCos = *sinCosPtr++;
data->size = *sizePtr++;
data++;
}
billboards.Insert({
renderOrder,
material,
scissorRect,
billboardCount,
billboardIndex
});
}
}
/*!
* \brief Adds multiple billboards to the queue
*
* \param renderOrder Order of rendering
* \param material Material of the billboards
* \param count Number of billboards
* \param positionPtr Position of the billboards
* \param sizePtr Sizes of the billboards
* \param sinCosPtr Rotation of the billboards if null, Vector2f(0.f, 1.f) is used
* \param alphaPtr Alpha parameters of the billboards if null, 1.f is used
*
* \remark Produces a NazaraAssert if material is invalid
*/
void BasicRenderQueue::AddBillboards(int renderOrder, const Material* material, std::size_t billboardCount, const Recti& scissorRect, SparsePtr<const Vector3f> positionPtr, SparsePtr<const Vector2f> sizePtr, SparsePtr<const Vector2f> sinCosPtr, SparsePtr<const float> alphaPtr)
{
NazaraAssert(material, "Invalid material");
Vector2f defaultSinCos(0.f, 1.f); // sin(0) = 0, cos(0) = 1
if (!sinCosPtr)
sinCosPtr.Reset(&defaultSinCos, 0); // The trick here is to put the stride to zero, which leads the pointer to be immobile
float defaultAlpha = 1.f;
if (!alphaPtr)
alphaPtr.Reset(&defaultAlpha, 0); // Same
if (material->IsDepthSortingEnabled())
{
for (std::size_t i = 0; i < billboardCount; ++i)
{
depthSortedBillboards.Insert({
renderOrder,
material,
scissorRect,
{
ComputeColor(*alphaPtr++),
*positionPtr++,
*sizePtr++,
*sinCosPtr++
}
});
}
}
else
{
std::size_t billboardIndex = m_billboards.size();
m_billboards.resize(billboardIndex + billboardCount);
BillboardData* data = &m_billboards[billboardIndex];
for (std::size_t i = 0; i < billboardCount; ++i)
{
data->center = *positionPtr++;
data->color = ComputeColor(*alphaPtr++);
data->sinCos = *sinCosPtr++;
data->size = *sizePtr++;
data++;
}
billboards.Insert({
renderOrder,
material,
scissorRect,
billboardCount,
billboardIndex
});
}
}
/*!
* \brief Adds multiple billboards to the queue
*
* \param renderOrder Order of rendering
* \param material Material of the billboards
* \param count Number of billboards
* \param positionPtr Position of the billboards
* \param sizePtr Sizes of the billboards
* \param anglePtr Rotation of the billboards if null, 0.f is used
* \param colorPtr Color of the billboards if null, Color::White is used
*
* \remark Produces a NazaraAssert if material is invalid
*/
void BasicRenderQueue::AddBillboards(int renderOrder, const Material* material, std::size_t billboardCount, const Recti& scissorRect, SparsePtr<const Vector3f> positionPtr, SparsePtr<const Vector2f> sizePtr, SparsePtr<const float> anglePtr, SparsePtr<const Color> colorPtr)
{
NazaraAssert(material, "Invalid material");
float defaultRotation = 0.f;
if (!anglePtr)
anglePtr.Reset(&defaultRotation, 0); // The trick here is to put the stride to zero, which leads the pointer to be immobile
if (!colorPtr)
colorPtr.Reset(&Color::White, 0); // Same
if (material->IsDepthSortingEnabled())
{
for (std::size_t i = 0; i < billboardCount; ++i)
{
depthSortedBillboards.Insert({
renderOrder,
material,
scissorRect,
{
*colorPtr++,
*positionPtr++,
*sizePtr++,
ComputeSinCos(*anglePtr++)
}
});
}
}
else
{
std::size_t billboardIndex = m_billboards.size();
m_billboards.resize(billboardIndex + billboardCount);
BillboardData* data = &m_billboards[billboardIndex];
for (std::size_t i = 0; i < billboardCount; ++i)
{
data->center = *positionPtr++;
data->color = *colorPtr++;
data->sinCos = ComputeSinCos(*anglePtr++);
data->size = *sizePtr++;
data++;
}
billboards.Insert({
renderOrder,
material,
scissorRect,
billboardCount,
billboardIndex
});
}
}
/*!
* \brief Adds multiple billboards to the queue
*
* \param renderOrder Order of rendering
* \param material Material of the billboards
* \param count Number of billboards
* \param positionPtr Position of the billboards
* \param sizePtr Sizes of the billboards
* \param anglePtr Rotation of the billboards if null, 0.f is used
* \param alphaPtr Alpha parameters of the billboards if null, 1.f is used
*
* \remark Produces a NazaraAssert if material is invalid
*/
void BasicRenderQueue::AddBillboards(int renderOrder, const Material* material, std::size_t billboardCount, const Recti& scissorRect, SparsePtr<const Vector3f> positionPtr, SparsePtr<const Vector2f> sizePtr, SparsePtr<const float> anglePtr, SparsePtr<const float> alphaPtr)
{
NazaraAssert(material, "Invalid material");
float defaultRotation = 0.f;
if (!anglePtr)
anglePtr.Reset(&defaultRotation, 0); // The trick here is to put the stride to zero, which leads the pointer to be immobile
float defaultAlpha = 1.f;
if (!alphaPtr)
alphaPtr.Reset(&defaultAlpha, 0); // Same
if (material->IsDepthSortingEnabled())
{
for (std::size_t i = 0; i < billboardCount; ++i)
{
depthSortedBillboards.Insert({
renderOrder,
material,
scissorRect,
{
ComputeColor(*alphaPtr++),
*positionPtr++,
*sizePtr++,
ComputeSinCos(*anglePtr++)
}
});
}
}
else
{
std::size_t billboardIndex = m_billboards.size();
m_billboards.resize(billboardIndex + billboardCount);
BillboardData* data = &m_billboards[billboardIndex];
for (std::size_t i = 0; i < billboardCount; ++i)
{
data->center = *positionPtr++;
data->color = ComputeColor(*alphaPtr++);
data->sinCos = ComputeSinCos(*anglePtr++);
data->size = *sizePtr++;
data++;
}
billboards.Insert({
renderOrder,
material,
scissorRect,
billboardCount,
billboardIndex
});
}
}
/*!
* \brief Adds multiple billboards to the queue
*
* \param renderOrder Order of rendering
* \param material Material of the billboards
* \param count Number of billboards
* \param positionPtr Position of the billboards
* \param sizePtr Size of the billboards
* \param sinCosPtr Rotation of the billboards if null, Vector2f(0.f, 1.f) is used
* \param colorPtr Color of the billboards if null, Color::White is used
*
* \remark Produces a NazaraAssert if material is invalid
*/
void BasicRenderQueue::AddBillboards(int renderOrder, const Material* material, std::size_t billboardCount, const Recti& scissorRect, SparsePtr<const Vector3f> positionPtr, SparsePtr<const float> sizePtr, SparsePtr<const Vector2f> sinCosPtr, SparsePtr<const Color> colorPtr)
{
NazaraAssert(material, "Invalid material");
Vector2f defaultSinCos(0.f, 1.f); // sin(0) = 0, cos(0) = 1
if (!sinCosPtr)
sinCosPtr.Reset(&defaultSinCos, 0); // The trick here is to put the stride to zero, which leads the pointer to be immobile
if (!colorPtr)
colorPtr.Reset(&Color::White, 0); // Same
if (material->IsDepthSortingEnabled())
{
for (std::size_t i = 0; i < billboardCount; ++i)
{
depthSortedBillboards.Insert({
renderOrder,
material,
scissorRect,
{
*colorPtr++,
*positionPtr++,
ComputeSize(*sizePtr++),
*sinCosPtr++
}
});
}
}
else
{
std::size_t billboardIndex = m_billboards.size();
m_billboards.resize(billboardIndex + billboardCount);
BillboardData* data = &m_billboards[billboardIndex];
for (std::size_t i = 0; i < billboardCount; ++i)
{
data->center = *positionPtr++;
data->color = *colorPtr++;
data->sinCos = *sinCosPtr++;
data->size = ComputeSize(*sizePtr++);
data++;
}
billboards.Insert({
renderOrder,
material,
scissorRect,
billboardCount,
billboardIndex
});
}
}
/*!
* \brief Adds multiple billboards to the queue
*
* \param renderOrder Order of rendering
* \param material Material of the billboards
* \param count Number of billboards
* \param positionPtr Position of the billboards
* \param sizePtr Size of the billboards
* \param sinCosPtr Rotation of the billboards if null, Vector2f(0.f, 1.f) is used
* \param alphaPtr Alpha parameters of the billboards if null, 1.f is used
*
* \remark Produces a NazaraAssert if material is invalid
*/
void BasicRenderQueue::AddBillboards(int renderOrder, const Material* material, std::size_t billboardCount, const Recti& scissorRect, SparsePtr<const Vector3f> positionPtr, SparsePtr<const float> sizePtr, SparsePtr<const Vector2f> sinCosPtr, SparsePtr<const float> alphaPtr)
{
NazaraAssert(material, "Invalid material");
Vector2f defaultSinCos(0.f, 1.f); // sin(0) = 0, cos(0) = 1
if (!sinCosPtr)
sinCosPtr.Reset(&defaultSinCos, 0); // The trick here is to put the stride to zero, which leads the pointer to be immobile
float defaultAlpha = 1.f;
if (!alphaPtr)
alphaPtr.Reset(&defaultAlpha, 0); // Same
if (material->IsDepthSortingEnabled())
{
for (std::size_t i = 0; i < billboardCount; ++i)
{
depthSortedBillboards.Insert({
renderOrder,
material,
scissorRect,
{
ComputeColor(*alphaPtr++),
*positionPtr++,
ComputeSize(*sizePtr++),
*sinCosPtr++
}
});
}
}
else
{
std::size_t billboardIndex = m_billboards.size();
m_billboards.resize(billboardIndex + billboardCount);
BillboardData* data = &m_billboards[billboardIndex];
for (std::size_t i = 0; i < billboardCount; ++i)
{
data->center = *positionPtr++;
data->color = ComputeColor(*alphaPtr++);
data->sinCos = *sinCosPtr++;
data->size = ComputeSize(*sizePtr++);
data++;
}
billboards.Insert({
renderOrder,
material,
scissorRect,
billboardCount,
billboardIndex
});
}
}
/*!
* \brief Adds multiple billboards to the queue
*
* \param renderOrder Order of rendering
* \param material Material of the billboards
* \param count Number of billboards
* \param positionPtr Position of the billboards
* \param sizePtr Size of the billboards
* \param anglePtr Rotation of the billboards if null, 0.f is used
* \param colorPtr Color of the billboards if null, Color::White is used
*
* \remark Produces a NazaraAssert if material is invalid
*/
void BasicRenderQueue::AddBillboards(int renderOrder, const Material* material, std::size_t billboardCount, const Recti& scissorRect, SparsePtr<const Vector3f> positionPtr, SparsePtr<const float> sizePtr, SparsePtr<const float> anglePtr, SparsePtr<const Color> colorPtr)
{
NazaraAssert(material, "Invalid material");
float defaultRotation = 0.f;
if (!anglePtr)
anglePtr.Reset(&defaultRotation, 0); // The trick here is to put the stride to zero, which leads the pointer to be immobile
if (!colorPtr)
colorPtr.Reset(&Color::White, 0); // Same
if (material->IsDepthSortingEnabled())
{
for (std::size_t i = 0; i < billboardCount; ++i)
{
depthSortedBillboards.Insert({
renderOrder,
material,
scissorRect,
{
*colorPtr++,
*positionPtr++,
ComputeSize(*sizePtr++),
ComputeSinCos(*anglePtr++)
}
});
}
}
else
{
std::size_t billboardIndex = m_billboards.size();
m_billboards.resize(billboardIndex + billboardCount);
BillboardData* data = &m_billboards[billboardIndex];
for (std::size_t i = 0; i < billboardCount; ++i)
{
data->center = *positionPtr++;
data->color = *colorPtr++;
data->sinCos = ComputeSinCos(*anglePtr++);
data->size = ComputeSize(*sizePtr++);
data++;
}
billboards.Insert({
renderOrder,
material,
scissorRect,
billboardCount,
billboardIndex
});
}
}
/*!
* \brief Adds multiple billboards to the queue
*
* \param renderOrder Order of rendering
* \param material Material of the billboards
* \param count Number of billboards
* \param positionPtr Position of the billboards
* \param sizePtr Size of the billboards
* \param anglePtr Rotation of the billboards if null, 0.f is used
* \param alphaPtr Alpha parameters of the billboards if null, 1.f is used
*
* \remark Produces a NazaraAssert if material is invalid
*/
void BasicRenderQueue::AddBillboards(int renderOrder, const Material* material, std::size_t billboardCount, const Recti& scissorRect, SparsePtr<const Vector3f> positionPtr, SparsePtr<const float> sizePtr, SparsePtr<const float> anglePtr, SparsePtr<const float> alphaPtr)
{
NazaraAssert(material, "Invalid material");
float defaultRotation = 0.f;
if (!anglePtr)
anglePtr.Reset(&defaultRotation, 0); // The trick here is to put the stride to zero, which leads the pointer to be immobile
float defaultAlpha = 1.f;
if (!alphaPtr)
alphaPtr.Reset(&defaultAlpha, 0); // Same
if (material->IsDepthSortingEnabled())
{
for (std::size_t i = 0; i < billboardCount; ++i)
{
depthSortedBillboards.Insert({
renderOrder,
material,
scissorRect,
{
ComputeColor(*alphaPtr++),
*positionPtr++,
ComputeSize(*sizePtr++),
ComputeSinCos(*anglePtr++)
}
});
}
}
else
{
std::size_t billboardIndex = m_billboards.size();
m_billboards.resize(billboardIndex + billboardCount);
BillboardData* data = &m_billboards[billboardIndex];
for (std::size_t i = 0; i < billboardCount; ++i)
{
data->center = *positionPtr++;
data->color = ComputeColor(*alphaPtr++);
data->sinCos = ComputeSinCos(*anglePtr++);
data->size = ComputeSize(*sizePtr++);
data++;
}
billboards.Insert({
renderOrder,
material,
scissorRect,
billboardCount,
billboardIndex
});
}
}
/*!
* \brief Adds drawable to the queue
*
* \param renderOrder Order of rendering
* \param drawable Drawable user defined
*
* \remark Produces a NazaraError if drawable is invalid
*/
void BasicRenderQueue::AddDrawable(int renderOrder, const Drawable* drawable)
{
NazaraAssert(drawable, "Invalid material");
RegisterLayer(renderOrder);
customDrawables.Insert({
renderOrder,
drawable
});
}
/*!
* \brief Adds mesh to the queue
*
* \param renderOrder Order of rendering
* \param material Material of the mesh
* \param meshData Data of the mesh
* \param meshAABB Box of the mesh
* \param transformMatrix Matrix of the mesh
*
* \remark Produces a NazaraAssert if material is invalid
*/
void BasicRenderQueue::AddMesh(int renderOrder, const Material* material, const MeshData& meshData, const Boxf& meshAABB, const Matrix4f& transformMatrix, const Recti& scissorRect)
{
NazaraAssert(material, "Invalid material");
RegisterLayer(renderOrder);
Spheref obbSphere(transformMatrix.GetTranslation() + meshAABB.GetCenter(), meshAABB.GetSquaredRadius());
if (material->IsDepthSortingEnabled())
{
depthSortedModels.Insert({
renderOrder,
meshData,
material,
transformMatrix,
scissorRect,
obbSphere
});
}
else
{
models.Insert({
renderOrder,
meshData,
material,
transformMatrix,
scissorRect,
obbSphere
});
}
}
/*!
* \brief Adds sprites to the queue
*
* \param renderOrder Order of rendering
* \param material Material of the sprites
* \param vertices Buffer of data for the sprites
* \param spriteCount Number of sprites
* \param overlay Texture of the sprites
*
* \remark Produces a NazaraAssert if material is invalid
*/
void BasicRenderQueue::AddSprites(int renderOrder, const Material* material, const VertexStruct_XYZ_Color_UV* vertices, std::size_t spriteCount, const Recti& scissorRect, const Texture* overlay /*= nullptr*/)
{
NazaraAssert(material, "Invalid material");
RegisterLayer(renderOrder);
if (material->IsDepthSortingEnabled())
{
depthSortedSprites.Insert({
renderOrder,
spriteCount,
material,
overlay,
vertices,
scissorRect
});
}
else
{
basicSprites.Insert({
renderOrder,
spriteCount,
material,
overlay,
vertices,
scissorRect
});
}
}
/*!
* \brief Clears the queue
*
* \param fully Should everything be cleared or we can keep layers
*/
void BasicRenderQueue::Clear(bool fully)
{
AbstractRenderQueue::Clear(fully);
basicSprites.Clear();
billboards.Clear();
depthSortedBillboards.Clear();
depthSortedModels.Clear();
depthSortedSprites.Clear();
models.Clear();
m_pipelineCache.clear();
m_materialCache.clear();
m_overlayCache.clear();
m_shaderCache.clear();
m_textureCache.clear();
m_vertexBufferCache.clear();
m_billboards.clear();
m_renderLayers.clear();
}
/*!
* \brief Sorts the object according to the viewer position, furthest to nearest
*
* \param viewer Viewer of the scene
*/
void BasicRenderQueue::Sort(const AbstractViewer* viewer)
{
m_layerCache.clear();
for (int layer : m_renderLayers)
m_layerCache.emplace(layer, m_layerCache.size());
auto GetOrInsert = [](auto& container, auto&& value)
{
auto it = container.find(value);
if (it == container.end())
it = container.emplace(value, container.size()).first;
return it->second;
};
basicSprites.Sort([&](const SpriteChain& vertices)
{
// RQ index:
// - Layer (4bits)
// - Pipeline (8bits)
// - Material (8bits)
// - Shader? (8bits)
// - Textures (8bits)
// - Overlay (8bits)
// - Scissor (4bits)
// - Depth? (16bits)
UInt64 layerIndex = m_layerCache[vertices.layerIndex];
UInt64 pipelineIndex = GetOrInsert(m_pipelineCache, vertices.material->GetPipeline());
UInt64 materialIndex = GetOrInsert(m_materialCache, vertices.material);
UInt64 shaderIndex = GetOrInsert(m_shaderCache, vertices.material->GetShader());
UInt64 textureIndex = GetOrInsert(m_textureCache, vertices.material->GetDiffuseMap());
UInt64 overlayIndex = GetOrInsert(m_overlayCache, vertices.overlay);
UInt64 scissorIndex = 0; //< TODO
UInt64 depthIndex = 0; //< TODO
UInt64 index = (layerIndex & 0x0F) << 60 |
(pipelineIndex & 0xFF) << 52 |
(materialIndex & 0xFF) << 44 |
(shaderIndex & 0xFF) << 36 |
(textureIndex & 0xFF) << 28 |
(overlayIndex & 0xFF) << 20 |
(scissorIndex & 0x0F) << 16 |
(depthIndex & 0xFFFF) << 0;
return index;
});
billboards.Sort([&](const BillboardChain& billboard)
{
// RQ index:
// - Layer (4bits)
// - Pipeline (8bits)
// - Material (8bits)
// - Shader? (8bits)
// - Textures (8bits)
// - ??? (8bits)
// - Scissor (4bits)
// - Depth? (16bits)
UInt64 layerIndex = m_layerCache[billboard.layerIndex];
UInt64 pipelineIndex = GetOrInsert(m_pipelineCache, billboard.material->GetPipeline());
UInt64 materialIndex = GetOrInsert(m_materialCache, billboard.material);
UInt64 shaderIndex = GetOrInsert(m_shaderCache, billboard.material->GetShader());
UInt64 textureIndex = GetOrInsert(m_textureCache, billboard.material->GetDiffuseMap());
UInt64 unknownIndex = 0; //< ???
UInt64 scissorIndex = 0; //< TODO
UInt64 depthIndex = 0; //< TODO?
UInt64 index = (layerIndex & 0x0F) << 60 |
(pipelineIndex & 0xFF) << 52 |
(materialIndex & 0xFF) << 44 |
(shaderIndex & 0xFF) << 36 |
(textureIndex & 0xFF) << 28 |
(unknownIndex & 0xFF) << 20 |
(scissorIndex & 0x0F) << 16 |
(depthIndex & 0xFFFF) << 0;
return index;
});
customDrawables.Sort([&](const CustomDrawable& drawable)
{
// RQ index:
// - Layer (4bits)
UInt64 layerIndex = m_layerCache[drawable.layerIndex];
UInt64 index = (layerIndex & 0x0F) << 60;
return index;
});
models.Sort([&](const Model& renderData)
{
// RQ index:
// - Layer (4bits)
// - Pipeline (8bits)
// - Material (8bits)
// - Shader? (8bits)
// - Textures (8bits)
// - Buffers (8bits)
// - Scissor (4bits)
// - Depth? (16bits)
UInt64 layerIndex = m_layerCache[renderData.layerIndex];
UInt64 pipelineIndex = GetOrInsert(m_pipelineCache, renderData.material->GetPipeline());
UInt64 materialIndex = GetOrInsert(m_materialCache, renderData.material);
UInt64 shaderIndex = GetOrInsert(m_shaderCache, renderData.material->GetShader());
UInt64 textureIndex = GetOrInsert(m_textureCache, renderData.material->GetDiffuseMap());
UInt64 bufferIndex = GetOrInsert(m_vertexBufferCache, renderData.meshData.vertexBuffer);
UInt64 scissorIndex = 0; //< TODO
UInt64 depthIndex = 0; //< TODO
UInt64 index = (layerIndex & 0x0F) << 60 |
(pipelineIndex & 0xFF) << 52 |
(materialIndex & 0xFF) << 44 |
(shaderIndex & 0xFF) << 36 |
(textureIndex & 0xFF) << 28 |
(bufferIndex & 0xFF) << 20 |
(scissorIndex & 0x0F) << 16 |
(depthIndex & 0xFFFF) << 0;
return index;
});
static_assert(std::numeric_limits<float>::is_iec559, "The following sorting functions relies on IEEE 754 floatings-points");
#if defined(arm) && \
((defined(__MAVERICK__) && defined(NAZARA_BIG_ENDIAN)) || \
(!defined(__SOFTFP__) && !defined(__VFP_FP__) && !defined(__MAVERICK__)))
#error The following code relies on native-endian IEEE-754 representation, which your platform does not guarantee
#endif
Planef nearPlane = viewer->GetFrustum().GetPlane(FrustumPlane_Near);
depthSortedBillboards.Sort([&](const Billboard& billboard)
{
// RQ index:
// - Layer (4bits)
// - Depth (32bits)
// - ?? (28bits)
// Reinterpret depth as UInt32 (this will work as long as they're all either positive or negative,
// a negative distance may happen with billboard behind the camera which we don't care about since they'll be rendered)
float depth = nearPlane.Distance(billboard.data.center);
UInt64 layerIndex = m_layerCache[billboard.layerIndex];
UInt64 depthIndex = ~reinterpret_cast<UInt32&>(depth);
UInt64 index = (layerIndex & 0x0F) << 60 |
(depthIndex & 0xFFFFFFFF) << 28;
return index;
});
if (viewer->GetProjectionType() == ProjectionType_Orthogonal)
{
depthSortedModels.Sort([&](const Model& model)
{
// RQ index:
// - Layer (4bits)
// - Depth (32bits)
// - ?? (28bits)
float depth = nearPlane.Distance(model.obbSphere.GetPosition());
UInt64 layerIndex = m_layerCache[model.layerIndex];
UInt64 depthIndex = ~reinterpret_cast<UInt32&>(depth);
UInt64 index = (layerIndex & 0x0F) << 60 |
(depthIndex & 0xFFFFFFFF) << 28;
return index;
});
depthSortedSprites.Sort([&](const SpriteChain& spriteChain)
{
// RQ index:
// - Layer (4bits)
// - Depth (32bits)
// - ?? (28bits)
float depth = nearPlane.Distance(spriteChain.vertices[0].position);
UInt64 layerIndex = m_layerCache[spriteChain.layerIndex];
UInt64 depthIndex = ~reinterpret_cast<UInt32&>(depth);
UInt64 index = (layerIndex & 0x0F) << 60 |
(depthIndex & 0xFFFFFFFF) << 28;
return index;
});
}
else
{
Vector3f viewerPos = viewer->GetEyePosition();
depthSortedModels.Sort([&](const Model& model)
{
// RQ index:
// - Layer (4bits)
// - Depth (32bits)
// - ?? (28bits)
float depth = viewerPos.SquaredDistance(model.obbSphere.GetPosition());
UInt64 layerIndex = m_layerCache[model.layerIndex];
UInt64 depthIndex = ~reinterpret_cast<UInt32&>(depth);
UInt64 index = (layerIndex & 0x0F) << 60 |
(depthIndex & 0xFFFFFFFF) << 28;
return index;
});
depthSortedSprites.Sort([&](const SpriteChain& sprites)
{
// RQ index:
// - Layer (4bits)
// - Depth (32bits)
// - ?? (28bits)
float depth = viewerPos.SquaredDistance(sprites.vertices[0].position);
UInt64 layerIndex = m_layerCache[sprites.layerIndex];
UInt64 depthIndex = ~reinterpret_cast<UInt32&>(depth);
UInt64 index = (layerIndex & 0x0F) << 60 |
(depthIndex & 0xFFFFFFFF) << 28;
return index;
});
}
}
}

View File

@@ -21,10 +21,10 @@ namespace Nz
* \param instanceData Data used for instance
*/
void Billboard::AddToRenderQueue(AbstractRenderQueue* renderQueue, const InstanceData& instanceData) const
void Billboard::AddToRenderQueue(AbstractRenderQueue* renderQueue, const InstanceData& instanceData, const Recti& scissorRect) const
{
Nz::Vector3f position = instanceData.transformMatrix.GetTranslation();
renderQueue->AddBillboards(instanceData.renderOrder, GetMaterial(), 1, &position, &m_size, &m_sinCos, &m_color);
renderQueue->AddBillboards(instanceData.renderOrder, GetMaterial(), 1, scissorRect, &position, &m_size, &m_sinCos, &m_color);
}
/*
@@ -33,9 +33,12 @@ namespace Nz
void Billboard::MakeBoundingVolume() const
{
constexpr float sqrt2 = float(M_SQRT2);
// As billboard always face the screen, we must take its maximum size in account on every axis
float maxSize = float(M_SQRT2) * std::max(m_size.x, m_size.y);
m_boundingVolume.Set(Vector3f(0.f), sqrt2 * m_size.x * Vector3f::Right() + sqrt2 * m_size.y * Vector3f::Down());
Nz::Vector3f halfSize = (maxSize * Vector3f::Right() + maxSize * Vector3f::Down() + maxSize * Vector3f::Forward()) / 2.f;
m_boundingVolume.Set(-halfSize, halfSize);
}
BillboardLibrary::LibraryMap Billboard::s_library;

View File

@@ -50,6 +50,7 @@ namespace Nz
ParameterList list;
list.SetParameter("UNIFORM_VERTEX_DEPTH", true);
m_uberShaderInstance = m_uberShader->Get(list);
const Shader* shader = m_uberShaderInstance->GetShader();

View File

@@ -5,16 +5,34 @@
#include <Nazara/Graphics/DeferredGeometryPass.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Core/ErrorFlags.hpp>
#include <Nazara/Core/OffsetOf.hpp>
#include <Nazara/Graphics/AbstractViewer.hpp>
#include <Nazara/Graphics/DeferredRenderTechnique.hpp>
#include <Nazara/Graphics/DeferredProxyRenderQueue.hpp>
#include <Nazara/Graphics/Material.hpp>
#include <Nazara/Graphics/SceneData.hpp>
#include <Nazara/Renderer/Renderer.hpp>
#include <Nazara/Renderer/RenderTexture.hpp>
#include <Nazara/Utility/VertexStruct.hpp>
#include <Nazara/Graphics/Debug.hpp>
namespace Nz
{
namespace
{
struct BillboardPoint
{
Color color;
Vector3f position;
Vector2f size;
Vector2f sinCos; // must follow `size` (both will be sent as a Vector4f)
Vector2f uv;
};
UInt32 s_maxQuads = std::numeric_limits<UInt16>::max() / 6;
UInt32 s_vertexBufferSize = 4 * 1024 * 1024; // 4 MiB
}
/*!
* \ingroup graphics
* \class Nz::DeferredGeometryPass
@@ -25,8 +43,18 @@ namespace Nz
* \brief Constructs a DeferredGeometryPass object by default
*/
DeferredGeometryPass::DeferredGeometryPass()
DeferredGeometryPass::DeferredGeometryPass() :
m_vertexBuffer(BufferType_Vertex)
{
ErrorFlags flags(ErrorFlag_ThrowException, true);
m_whiteTexture = Nz::TextureLibrary::Get("White2D");
m_vertexBuffer.Create(s_vertexBufferSize, DataStorage_Hardware, BufferUsage_Dynamic);
m_billboardPointBuffer.Reset(&s_billboardVertexDeclaration, &m_vertexBuffer);
m_spriteBuffer.Reset(VertexDeclaration::Get(VertexLayout_XYZ_Color_UV), &m_vertexBuffer);
m_clearShader = ShaderLibrary::Get("DeferredGBufferClear");
m_clearStates.depthBuffer = true;
m_clearStates.faceCulling = true;
@@ -57,6 +85,7 @@ namespace Nz
m_GBufferRTT->SetColorTargets({0, 1, 2}); // G-Buffer
Renderer::SetTarget(m_GBufferRTT);
Renderer::SetScissorRect(Recti(0, 0, m_dimensions.x, m_dimensions.y));
Renderer::SetViewport(Recti(0, 0, m_dimensions.x, m_dimensions.y));
Renderer::SetRenderStates(m_clearStates);
@@ -67,131 +96,27 @@ namespace Nz
Renderer::SetMatrix(MatrixType_Projection, sceneData.viewer->GetProjectionMatrix());
Renderer::SetMatrix(MatrixType_View, sceneData.viewer->GetViewMatrix());
const Shader* lastShader = nullptr;
const ShaderUniforms* shaderUniforms = nullptr;
BasicRenderQueue& renderQueue = *m_renderQueue->GetDeferredRenderQueue();
for (auto& layerPair : m_renderQueue->layers)
{
for (auto& pipelinePair : layerPair.second.opaqueModels)
{
const MaterialPipeline* pipeline = pipelinePair.first;
auto& pipelineEntry = pipelinePair.second;
renderQueue.Sort(sceneData.viewer);
if (pipelineEntry.maxInstanceCount > 0)
{
bool instancing = instancingEnabled && (pipelineEntry.maxInstanceCount > NAZARA_GRAPHICS_INSTANCING_MIN_INSTANCES_COUNT);
if (!renderQueue.models.empty())
DrawModels(sceneData, renderQueue, renderQueue.models);
UInt32 flags = ShaderFlags_Deferred;
if (instancing)
flags |= ShaderFlags_Instancing;
if (!renderQueue.basicSprites.empty())
DrawSprites(sceneData, renderQueue, renderQueue.basicSprites);
const MaterialPipeline::Instance& pipelineInstance = pipeline->Apply(flags);
if (!renderQueue.billboards.empty())
DrawBillboards(sceneData, renderQueue, renderQueue.billboards);
const Shader* shader = pipelineInstance.uberInstance->GetShader();
if (!renderQueue.depthSortedModels.empty())
DrawModels(sceneData, renderQueue, renderQueue.depthSortedModels);
// Uniforms are conserved in our program, there's no point to send them back until they change
if (shader != lastShader)
{
// Index of uniforms in the shader
shaderUniforms = GetShaderUniforms(shader);
if (!renderQueue.depthSortedSprites.empty())
DrawSprites(sceneData, renderQueue, renderQueue.depthSortedSprites);
// Ambiant color of the scene
shader->SendColor(shaderUniforms->sceneAmbient, sceneData.ambientColor);
// Position of the camera
shader->SendVector(shaderUniforms->eyePosition, sceneData.viewer->GetEyePosition());
lastShader = shader;
}
for (auto& materialPair : pipelineEntry.materialMap)
{
const Material* material = materialPair.first;
auto& matEntry = materialPair.second;
if (matEntry.enabled)
{
DeferredRenderQueue::MeshInstanceContainer& meshInstances = matEntry.meshMap;
if (!meshInstances.empty())
{
material->Apply(pipelineInstance);
// Meshes
for (auto& meshIt : meshInstances)
{
const MeshData& meshData = meshIt.first;
auto& meshEntry = meshIt.second;
std::vector<Matrix4f>& instances = meshEntry.instances;
if (!instances.empty())
{
const IndexBuffer* indexBuffer = meshData.indexBuffer;
const VertexBuffer* vertexBuffer = meshData.vertexBuffer;
// Handle draw call before rendering loop
Renderer::DrawCall drawFunc;
Renderer::DrawCallInstanced instancedDrawFunc;
unsigned int indexCount;
if (indexBuffer)
{
drawFunc = Renderer::DrawIndexedPrimitives;
instancedDrawFunc = Renderer::DrawIndexedPrimitivesInstanced;
indexCount = indexBuffer->GetIndexCount();
}
else
{
drawFunc = Renderer::DrawPrimitives;
instancedDrawFunc = Renderer::DrawPrimitivesInstanced;
indexCount = vertexBuffer->GetVertexCount();
}
Renderer::SetIndexBuffer(indexBuffer);
Renderer::SetVertexBuffer(vertexBuffer);
if (instancing)
{
// We get the buffer for instance of Renderer and we configure it to work with matrices
VertexBuffer* instanceBuffer = Renderer::GetInstanceBuffer();
instanceBuffer->SetVertexDeclaration(VertexDeclaration::Get(VertexLayout_Matrix4));
const Matrix4f* instanceMatrices = &instances[0];
std::size_t instanceCount = instances.size();
std::size_t maxInstanceCount = instanceBuffer->GetVertexCount(); // The number of matrices that can be hold in the buffer
while (instanceCount > 0)
{
// We compute the number of instances that we will be able to show this time (Depending on the instance buffer size)
std::size_t renderedInstanceCount = std::min(instanceCount, maxInstanceCount);
instanceCount -= renderedInstanceCount;
// We fill the instancing buffer with our world matrices
instanceBuffer->Fill(instanceMatrices, 0, renderedInstanceCount);
instanceMatrices += renderedInstanceCount;
// And we show
instancedDrawFunc(renderedInstanceCount, meshData.primitiveMode, 0, indexCount);
}
}
else
{
// Without instancing, we must do one draw call for each instance
// This may be faster than instancing under a threshold
// Due to the time to modify the instancing buffer
for (const Matrix4f& matrix : instances)
{
Renderer::SetMatrix(MatrixType_World, matrix);
drawFunc(meshData.primitiveMode, 0, indexCount);
}
}
}
}
}
}
}
}
}
}
if (!renderQueue.depthSortedBillboards.empty())
DrawBillboards(sceneData, renderQueue, renderQueue.depthSortedBillboards);
return false; // We only fill the G-Buffer, the work texture are unchanged
}
@@ -266,13 +191,409 @@ namespace Nz
return false;
}
}
void DeferredGeometryPass::DrawBillboards(const SceneData& sceneData, const BasicRenderQueue& renderQueue, const RenderQueue<BasicRenderQueue::Billboard>& billboards) const
{
VertexBuffer* instanceBuffer = Renderer::GetInstanceBuffer();
instanceBuffer->SetVertexDeclaration(&s_billboardInstanceDeclaration);
/*!
* \brief Gets the uniforms of a shader
* \return Uniforms of the shader
*
* \param shader Shader to get uniforms from
*/
Renderer::SetVertexBuffer(&s_quadVertexBuffer);
Nz::BufferMapper<VertexBuffer> instanceBufferMapper;
std::size_t billboardCount = 0;
std::size_t maxBillboardPerDraw = instanceBuffer->GetVertexCount();
auto Commit = [&]()
{
if (billboardCount > 0)
{
instanceBufferMapper.Unmap();
Renderer::DrawPrimitivesInstanced(billboardCount, PrimitiveMode_TriangleStrip, 0, 4);
billboardCount = 0;
}
};
const RenderTarget* renderTarget = sceneData.viewer->GetTarget();
Recti fullscreenScissorRect = Recti(Vector2i(renderTarget->GetSize()));
const Material* lastMaterial = nullptr;
const MaterialPipeline* lastPipeline = nullptr;
const Shader* lastShader = nullptr;
const ShaderUniforms* shaderUniforms = nullptr;
const Texture* lastOverlay = nullptr;
Recti lastScissorRect = Recti(-1, -1);
const MaterialPipeline::Instance* pipelineInstance = nullptr;
for (const BasicRenderQueue::Billboard& billboard : billboards)
{
const Nz::Recti& scissorRect = (billboard.scissorRect.width > 0) ? billboard.scissorRect : fullscreenScissorRect;
if (billboard.material != lastMaterial || (billboard.material->IsScissorTestEnabled() && scissorRect != lastScissorRect))
{
Commit();
const MaterialPipeline* pipeline = billboard.material->GetPipeline();
if (lastPipeline != pipeline)
{
pipelineInstance = &billboard.material->GetPipeline()->Apply(ShaderFlags_Billboard | ShaderFlags_Deferred | ShaderFlags_Instancing | ShaderFlags_VertexColor);
const Shader* shader = pipelineInstance->uberInstance->GetShader();
if (shader != lastShader)
{
// Index of uniforms in the shader
shaderUniforms = GetShaderUniforms(shader);
// Ambient color of the scene
shader->SendColor(shaderUniforms->sceneAmbient, sceneData.ambientColor);
// Position of the camera
shader->SendVector(shaderUniforms->eyePosition, sceneData.viewer->GetEyePosition());
lastShader = shader;
}
lastPipeline = pipeline;
}
if (lastMaterial != billboard.material)
{
billboard.material->Apply(*pipelineInstance);
lastMaterial = billboard.material;
}
if (billboard.material->IsScissorTestEnabled() && scissorRect != lastScissorRect)
{
Renderer::SetScissorRect(scissorRect);
lastScissorRect = scissorRect;
}
}
if (!instanceBufferMapper.GetBuffer())
instanceBufferMapper.Map(instanceBuffer, BufferAccess_DiscardAndWrite);
std::memcpy(static_cast<Nz::UInt8*>(instanceBufferMapper.GetPointer()) + sizeof(BasicRenderQueue::BillboardData) * billboardCount, &billboard.data, sizeof(BasicRenderQueue::BillboardData));
if (++billboardCount >= maxBillboardPerDraw)
Commit();
}
Commit();
}
void DeferredGeometryPass::DrawBillboards(const SceneData& sceneData, const BasicRenderQueue& renderQueue, const RenderQueue<BasicRenderQueue::BillboardChain>& billboards) const
{
VertexBuffer* instanceBuffer = Renderer::GetInstanceBuffer();
instanceBuffer->SetVertexDeclaration(&s_billboardInstanceDeclaration);
Renderer::SetVertexBuffer(&s_quadVertexBuffer);
Nz::BufferMapper<VertexBuffer> instanceBufferMapper;
std::size_t billboardCount = 0;
std::size_t maxBillboardPerDraw = instanceBuffer->GetVertexCount();
auto Commit = [&]()
{
if (billboardCount > 0)
{
instanceBufferMapper.Unmap();
Renderer::DrawPrimitivesInstanced(billboardCount, PrimitiveMode_TriangleStrip, 0, 4);
billboardCount = 0;
}
};
const RenderTarget* renderTarget = sceneData.viewer->GetTarget();
Recti fullscreenScissorRect = Recti(Vector2i(renderTarget->GetSize()));
const Material* lastMaterial = nullptr;
const MaterialPipeline* lastPipeline = nullptr;
const Shader* lastShader = nullptr;
const ShaderUniforms* shaderUniforms = nullptr;
const Texture* lastOverlay = nullptr;
Recti lastScissorRect = Recti(-1, -1);
const MaterialPipeline::Instance* pipelineInstance = nullptr;
for (const BasicRenderQueue::BillboardChain& billboard : billboards)
{
const Nz::Recti& scissorRect = (billboard.scissorRect.width > 0) ? billboard.scissorRect : fullscreenScissorRect;
if (billboard.material != lastMaterial || (billboard.material->IsScissorTestEnabled() && scissorRect != lastScissorRect))
{
Commit();
const MaterialPipeline* pipeline = billboard.material->GetPipeline();
if (lastPipeline != pipeline)
{
pipelineInstance = &billboard.material->GetPipeline()->Apply(ShaderFlags_Billboard | ShaderFlags_Deferred | ShaderFlags_Instancing | ShaderFlags_VertexColor);
const Shader* shader = pipelineInstance->uberInstance->GetShader();
if (shader != lastShader)
{
// Index of uniforms in the shader
shaderUniforms = GetShaderUniforms(shader);
// Ambient color of the scene
shader->SendColor(shaderUniforms->sceneAmbient, sceneData.ambientColor);
// Position of the camera
shader->SendVector(shaderUniforms->eyePosition, sceneData.viewer->GetEyePosition());
lastShader = shader;
}
lastPipeline = pipeline;
}
if (lastMaterial != billboard.material)
{
billboard.material->Apply(*pipelineInstance);
lastMaterial = billboard.material;
}
if (billboard.material->IsScissorTestEnabled() && scissorRect != lastScissorRect)
{
Renderer::SetScissorRect(scissorRect);
lastScissorRect = scissorRect;
}
}
std::size_t billboardRemaining = billboard.billboardCount;
const BasicRenderQueue::BillboardData* billboardData = renderQueue.GetBillboardData(billboard.billboardIndex);
do
{
std::size_t renderedBillboardCount = std::min(billboardRemaining, maxBillboardPerDraw - billboardCount);
billboardRemaining -= renderedBillboardCount;
if (!instanceBufferMapper.GetBuffer())
instanceBufferMapper.Map(instanceBuffer, BufferAccess_DiscardAndWrite);
std::memcpy(static_cast<Nz::UInt8*>(instanceBufferMapper.GetPointer()) + sizeof(BasicRenderQueue::BillboardData) * billboardCount, billboardData, renderedBillboardCount * sizeof(BasicRenderQueue::BillboardData));
billboardCount += renderedBillboardCount;
billboardData += renderedBillboardCount;
if (billboardCount >= maxBillboardPerDraw)
Commit();
}
while (billboardRemaining > 0);
}
Commit();
}
void DeferredGeometryPass::DrawModels(const SceneData& sceneData, const BasicRenderQueue& renderQueue, const Nz::RenderQueue<Nz::BasicRenderQueue::Model>& models) const
{
const RenderTarget* renderTarget = sceneData.viewer->GetTarget();
Recti fullscreenScissorRect = Recti(Vector2i(renderTarget->GetSize()));
const Material* lastMaterial = nullptr;
const MaterialPipeline* lastPipeline = nullptr;
const Shader* lastShader = nullptr;
const ShaderUniforms* shaderUniforms = nullptr;
Recti lastScissorRect = Recti(-1, -1);
const MaterialPipeline::Instance* pipelineInstance = nullptr;
///TODO: Reimplement instancing
for (const BasicRenderQueue::Model& model : models)
{
const MaterialPipeline* pipeline = model.material->GetPipeline();
if (lastPipeline != pipeline)
{
pipelineInstance = &model.material->GetPipeline()->Apply(ShaderFlags_Deferred);
const Shader* shader = pipelineInstance->uberInstance->GetShader();
if (shader != lastShader)
{
// Index of uniforms in the shader
shaderUniforms = GetShaderUniforms(shader);
// Ambient color of the scene
shader->SendColor(shaderUniforms->sceneAmbient, sceneData.ambientColor);
// Position of the camera
shader->SendVector(shaderUniforms->eyePosition, sceneData.viewer->GetEyePosition());
lastShader = shader;
}
lastPipeline = pipeline;
}
if (lastMaterial != model.material)
{
model.material->Apply(*pipelineInstance);
lastMaterial = model.material;
}
if (model.material->IsScissorTestEnabled())
{
const Nz::Recti& scissorRect = (model.scissorRect.width > 0) ? model.scissorRect : fullscreenScissorRect;
if (scissorRect != lastScissorRect)
{
Renderer::SetScissorRect(scissorRect);
lastScissorRect = scissorRect;
}
}
// Handle draw call before rendering loop
Renderer::DrawCall drawFunc;
Renderer::DrawCallInstanced instancedDrawFunc;
unsigned int indexCount;
if (model.meshData.indexBuffer)
{
drawFunc = Renderer::DrawIndexedPrimitives;
instancedDrawFunc = Renderer::DrawIndexedPrimitivesInstanced;
indexCount = model.meshData.indexBuffer->GetIndexCount();
}
else
{
drawFunc = Renderer::DrawPrimitives;
instancedDrawFunc = Renderer::DrawPrimitivesInstanced;
indexCount = model.meshData.vertexBuffer->GetVertexCount();
}
Renderer::SetIndexBuffer(model.meshData.indexBuffer);
Renderer::SetVertexBuffer(model.meshData.vertexBuffer);
Renderer::SetMatrix(MatrixType_World, model.matrix);
drawFunc(model.meshData.primitiveMode, 0, indexCount);
}
}
void DeferredGeometryPass::DrawSprites(const SceneData& sceneData, const BasicRenderQueue& renderQueue, const RenderQueue<BasicRenderQueue::SpriteChain>& spriteList) const
{
const RenderTarget* renderTarget = sceneData.viewer->GetTarget();
Recti fullscreenScissorRect = Recti(Vector2i(renderTarget->GetSize()));
Renderer::SetIndexBuffer(&s_quadIndexBuffer);
Renderer::SetMatrix(MatrixType_World, Matrix4f::Identity());
Renderer::SetVertexBuffer(&m_spriteBuffer);
const unsigned int overlayTextureUnit = Material::GetTextureUnit(TextureMap_Overlay);
const std::size_t maxSpriteCount = std::min<std::size_t>(s_maxQuads, m_spriteBuffer.GetVertexCount() / 4);
m_spriteChains.clear();
auto Commit = [&]()
{
std::size_t spriteChainCount = m_spriteChains.size();
if (spriteChainCount > 0)
{
std::size_t spriteChain = 0; // Which chain of sprites are we treating
std::size_t spriteChainOffset = 0; // Where was the last offset where we stopped in the last chain
do
{
// We open the buffer in writing mode
BufferMapper<VertexBuffer> vertexMapper(m_spriteBuffer, BufferAccess_DiscardAndWrite);
VertexStruct_XYZ_Color_UV* vertices = static_cast<VertexStruct_XYZ_Color_UV*>(vertexMapper.GetPointer());
std::size_t spriteCount = 0;
do
{
const VertexStruct_XYZ_Color_UV* currentChain = m_spriteChains[spriteChain].first;
std::size_t currentChainSpriteCount = m_spriteChains[spriteChain].second;
std::size_t count = std::min(maxSpriteCount - spriteCount, currentChainSpriteCount - spriteChainOffset);
std::memcpy(vertices, currentChain + spriteChainOffset * 4, 4 * count * sizeof(VertexStruct_XYZ_Color_UV));
vertices += count * 4;
spriteCount += count;
spriteChainOffset += count;
// Have we treated the entire chain ?
if (spriteChainOffset == currentChainSpriteCount)
{
spriteChain++;
spriteChainOffset = 0;
}
}
while (spriteCount < maxSpriteCount && spriteChain < spriteChainCount);
vertexMapper.Unmap();
Renderer::DrawIndexedPrimitives(PrimitiveMode_TriangleList, 0, spriteCount * 6);
}
while (spriteChain < spriteChainCount);
}
m_spriteChains.clear();
};
const Material* lastMaterial = nullptr;
const MaterialPipeline* lastPipeline = nullptr;
const Shader* lastShader = nullptr;
const ShaderUniforms* shaderUniforms = nullptr;
const Texture* lastOverlay = nullptr;
Recti lastScissorRect = Recti(-1, -1);
const MaterialPipeline::Instance* pipelineInstance = nullptr;
for (const BasicRenderQueue::SpriteChain& basicSprites : spriteList)
{
const Nz::Recti& scissorRect = (basicSprites.scissorRect.width > 0) ? basicSprites.scissorRect : fullscreenScissorRect;
if (basicSprites.material != lastMaterial || basicSprites.overlay != lastOverlay || (basicSprites.material->IsScissorTestEnabled() && scissorRect != lastScissorRect))
{
Commit();
const MaterialPipeline* pipeline = basicSprites.material->GetPipeline();
if (lastPipeline != pipeline)
{
pipelineInstance = &basicSprites.material->GetPipeline()->Apply(ShaderFlags_Deferred | ShaderFlags_TextureOverlay | ShaderFlags_VertexColor);
const Shader* shader = pipelineInstance->uberInstance->GetShader();
if (shader != lastShader)
{
// Index of uniforms in the shader
shaderUniforms = GetShaderUniforms(shader);
// Ambient color of the scene
shader->SendColor(shaderUniforms->sceneAmbient, sceneData.ambientColor);
// Position of the camera
shader->SendVector(shaderUniforms->eyePosition, sceneData.viewer->GetEyePosition());
// Overlay texture unit
shader->SendInteger(shaderUniforms->textureOverlay, overlayTextureUnit);
lastShader = shader;
}
lastPipeline = pipeline;
}
if (lastMaterial != basicSprites.material)
{
basicSprites.material->Apply(*pipelineInstance);
Renderer::SetTextureSampler(overlayTextureUnit, basicSprites.material->GetDiffuseSampler());
lastMaterial = basicSprites.material;
}
const Nz::Texture* overlayTexture = (basicSprites.overlay) ? basicSprites.overlay.Get() : m_whiteTexture.Get();
if (overlayTexture != lastOverlay)
{
Renderer::SetTexture(overlayTextureUnit, overlayTexture);
lastOverlay = overlayTexture;
}
if (basicSprites.material->IsScissorTestEnabled() && scissorRect != lastScissorRect)
{
Renderer::SetScissorRect(scissorRect);
lastScissorRect = scissorRect;
}
}
m_spriteChains.emplace_back(basicSprites.vertices, basicSprites.spriteCount);
}
Commit();
}
const DeferredGeometryPass::ShaderUniforms* DeferredGeometryPass::GetShaderUniforms(const Shader* shader) const
{
@@ -303,4 +624,73 @@ namespace Nz
{
m_shaderUniforms.erase(shader);
}
bool DeferredGeometryPass::Initialize()
{
try
{
ErrorFlags flags(ErrorFlag_ThrowException, true);
s_quadIndexBuffer.Reset(false, s_maxQuads * 6, DataStorage_Hardware, 0);
BufferMapper<IndexBuffer> mapper(s_quadIndexBuffer, BufferAccess_WriteOnly);
UInt16* indices = static_cast<UInt16*>(mapper.GetPointer());
for (unsigned int i = 0; i < s_maxQuads; ++i)
{
*indices++ = i * 4 + 0;
*indices++ = i * 4 + 2;
*indices++ = i * 4 + 1;
*indices++ = i * 4 + 2;
*indices++ = i * 4 + 3;
*indices++ = i * 4 + 1;
}
mapper.Unmap(); // No point to keep the buffer open any longer
// Quad buffer (used for instancing of billboards and sprites)
//Note: UV are computed in the shader
s_quadVertexBuffer.Reset(VertexDeclaration::Get(VertexLayout_XY), 4, DataStorage_Hardware, 0);
float vertices[2 * 4] = {
-0.5f, -0.5f,
0.5f, -0.5f,
-0.5f, 0.5f,
0.5f, 0.5f,
};
s_quadVertexBuffer.FillRaw(vertices, 0, sizeof(vertices));
// Declaration used when rendering the vertex billboards
s_billboardVertexDeclaration.EnableComponent(VertexComponent_Color, ComponentType_Color, NazaraOffsetOf(BillboardPoint, color));
s_billboardVertexDeclaration.EnableComponent(VertexComponent_Position, ComponentType_Float3, NazaraOffsetOf(BillboardPoint, position));
s_billboardVertexDeclaration.EnableComponent(VertexComponent_TexCoord, ComponentType_Float2, NazaraOffsetOf(BillboardPoint, uv));
s_billboardVertexDeclaration.EnableComponent(VertexComponent_Userdata0, ComponentType_Float4, NazaraOffsetOf(BillboardPoint, size)); // Includes sincos
// Declaration used when rendering the billboards with intancing
// The main advantage is the direct copy (std::memcpy) of data in the RenderQueue to the GPU buffer
s_billboardInstanceDeclaration.EnableComponent(VertexComponent_InstanceData0, ComponentType_Float3, NazaraOffsetOf(BasicRenderQueue::BillboardData, center));
s_billboardInstanceDeclaration.EnableComponent(VertexComponent_InstanceData1, ComponentType_Float4, NazaraOffsetOf(BasicRenderQueue::BillboardData, size)); // Englobe sincos
s_billboardInstanceDeclaration.EnableComponent(VertexComponent_InstanceData2, ComponentType_Color, NazaraOffsetOf(BasicRenderQueue::BillboardData, color));
}
catch (const std::exception& e)
{
NazaraError("Failed to initialise: " + String(e.what()));
return false;
}
return true;
}
void DeferredGeometryPass::Uninitialize()
{
s_quadIndexBuffer.Reset();
s_quadVertexBuffer.Reset();
}
IndexBuffer DeferredGeometryPass::s_quadIndexBuffer;
VertexBuffer DeferredGeometryPass::s_quadVertexBuffer;
VertexDeclaration DeferredGeometryPass::s_billboardInstanceDeclaration;
VertexDeclaration DeferredGeometryPass::s_billboardVertexDeclaration;
}

View File

@@ -5,7 +5,7 @@
#include <Nazara/Graphics/DeferredPhongLightingPass.hpp>
#include <Nazara/Core/Primitive.hpp>
#include <Nazara/Graphics/AbstractViewer.hpp>
#include <Nazara/Graphics/DeferredRenderQueue.hpp>
#include <Nazara/Graphics/DeferredProxyRenderQueue.hpp>
#include <Nazara/Graphics/SceneData.hpp>
#include <Nazara/Renderer/Renderer.hpp>
#include <Nazara/Renderer/RenderTexture.hpp>

View File

@@ -0,0 +1,261 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Engine - Graphics module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Graphics/DeferredProxyRenderQueue.hpp>
#include <Nazara/Graphics/AbstractViewer.hpp>
#include <Nazara/Graphics/BasicRenderQueue.hpp>
#include <Nazara/Graphics/Debug.hpp>
namespace Nz
{
/*!
* \ingroup graphics
* \class Nz::DeferredProxyRenderQueue
* \brief Graphics class sorting the objects into a deferred and forward render queue (depending on blending)
*/
/*!
* \brief Adds multiple billboards to the queue
*
* \param renderOrder Order of rendering
* \param material Material of the billboards
* \param count Number of billboards
* \param positionPtr Position of the billboards
* \param sizePtr Sizes of the billboards
* \param sinCosPtr Rotation of the billboards if null, Vector2f(0.f, 1.f) is used
* \param colorPtr Color of the billboards if null, Color::White is used
*/
void DeferredProxyRenderQueue::AddBillboards(int renderOrder, const Material* material, std::size_t billboardCount, const Recti& scissorRect, SparsePtr<const Vector3f> positionPtr, SparsePtr<const Vector2f> sizePtr, SparsePtr<const Vector2f> sinCosPtr, SparsePtr<const Color> colorPtr)
{
NazaraAssert(material, "Invalid material");
if (!material->IsBlendingEnabled())
m_deferredRenderQueue->AddBillboards(renderOrder, material, billboardCount, scissorRect, positionPtr, sizePtr, sinCosPtr, colorPtr);
else
m_forwardRenderQueue->AddBillboards(renderOrder, material, billboardCount, scissorRect, positionPtr, sizePtr, sinCosPtr, colorPtr);
}
/*!
* \brief Adds multiple billboards to the queue
*
* \param renderOrder Order of rendering
* \param material Material of the billboards
* \param count Number of billboards
* \param positionPtr Position of the billboards
* \param sizePtr Sizes of the billboards
* \param sinCosPtr Rotation of the billboards if null, Vector2f(0.f, 1.f) is used
* \param alphaPtr Alpha parameters of the billboards if null, 1.f is used
*/
void DeferredProxyRenderQueue::AddBillboards(int renderOrder, const Material* material, std::size_t billboardCount, const Recti& scissorRect, SparsePtr<const Vector3f> positionPtr, SparsePtr<const Vector2f> sizePtr, SparsePtr<const Vector2f> sinCosPtr, SparsePtr<const float> alphaPtr)
{
NazaraAssert(material, "Invalid material");
if (!material->IsBlendingEnabled())
m_deferredRenderQueue->AddBillboards(renderOrder, material, billboardCount, scissorRect, positionPtr, sizePtr, sinCosPtr, alphaPtr);
else
m_forwardRenderQueue->AddBillboards(renderOrder, material, billboardCount, scissorRect, positionPtr, sizePtr, sinCosPtr, alphaPtr);
}
/*!
* \brief Adds multiple billboards to the queue
*
* \param renderOrder Order of rendering
* \param material Material of the billboards
* \param count Number of billboards
* \param positionPtr Position of the billboards
* \param sizePtr Sizes of the billboards
* \param anglePtr Rotation of the billboards if null, 0.f is used
* \param colorPtr Color of the billboards if null, Color::White is used
*/
void DeferredProxyRenderQueue::AddBillboards(int renderOrder, const Material* material, std::size_t billboardCount, const Recti& scissorRect, SparsePtr<const Vector3f> positionPtr, SparsePtr<const Vector2f> sizePtr, SparsePtr<const float> anglePtr, SparsePtr<const Color> colorPtr)
{
NazaraAssert(material, "Invalid material");
if (!material->IsBlendingEnabled())
m_deferredRenderQueue->AddBillboards(renderOrder, material, billboardCount, scissorRect, positionPtr, sizePtr, anglePtr, colorPtr);
else
m_forwardRenderQueue->AddBillboards(renderOrder, material, billboardCount, scissorRect, positionPtr, sizePtr, anglePtr, colorPtr);
}
/*!
* \brief Adds multiple billboards to the queue
*
* \param renderOrder Order of rendering
* \param material Material of the billboards
* \param count Number of billboards
* \param positionPtr Position of the billboards
* \param sizePtr Sizes of the billboards
* \param anglePtr Rotation of the billboards if null, 0.f is used
* \param alphaPtr Alpha parameters of the billboards if null, 1.f is used
*/
void DeferredProxyRenderQueue::AddBillboards(int renderOrder, const Material* material, std::size_t billboardCount, const Recti& scissorRect, SparsePtr<const Vector3f> positionPtr, SparsePtr<const Vector2f> sizePtr, SparsePtr<const float> anglePtr, SparsePtr<const float> alphaPtr)
{
NazaraAssert(material, "Invalid material");
if (!material->IsBlendingEnabled())
m_deferredRenderQueue->AddBillboards(renderOrder, material, billboardCount, scissorRect, positionPtr, sizePtr, anglePtr, alphaPtr);
else
m_forwardRenderQueue->AddBillboards(renderOrder, material, billboardCount, scissorRect, positionPtr, sizePtr, anglePtr, alphaPtr);
}
/*!
* \brief Adds multiple billboards to the queue
*
* \param renderOrder Order of rendering
* \param material Material of the billboards
* \param count Number of billboards
* \param positionPtr Position of the billboards
* \param sizePtr Size of the billboards
* \param sinCosPtr Rotation of the billboards if null, Vector2f(0.f, 1.f) is used
* \param colorPtr Color of the billboards if null, Color::White is used
*/
void DeferredProxyRenderQueue::AddBillboards(int renderOrder, const Material* material, std::size_t billboardCount, const Recti& scissorRect, SparsePtr<const Vector3f> positionPtr, SparsePtr<const float> sizePtr, SparsePtr<const Vector2f> sinCosPtr, SparsePtr<const Color> colorPtr)
{
NazaraAssert(material, "Invalid material");
if (!material->IsBlendingEnabled())
m_deferredRenderQueue->AddBillboards(renderOrder, material, billboardCount, scissorRect, positionPtr, sizePtr, sinCosPtr, colorPtr);
else
m_forwardRenderQueue->AddBillboards(renderOrder, material, billboardCount, scissorRect, positionPtr, sizePtr, sinCosPtr, colorPtr);
}
/*!
* \brief Adds multiple billboards to the queue
*
* \param renderOrder Order of rendering
* \param material Material of the billboards
* \param count Number of billboards
* \param positionPtr Position of the billboards
* \param sizePtr Size of the billboards
* \param sinCosPtr Rotation of the billboards if null, Vector2f(0.f, 1.f) is used
* \param alphaPtr Alpha parameters of the billboards if null, 1.f is used
*/
void DeferredProxyRenderQueue::AddBillboards(int renderOrder, const Material* material, std::size_t billboardCount, const Recti& scissorRect, SparsePtr<const Vector3f> positionPtr, SparsePtr<const float> sizePtr, SparsePtr<const Vector2f> sinCosPtr, SparsePtr<const float> alphaPtr)
{
NazaraAssert(material, "Invalid material");
if (!material->IsBlendingEnabled())
m_deferredRenderQueue->AddBillboards(renderOrder, material, billboardCount, scissorRect, positionPtr, sizePtr, sinCosPtr, alphaPtr);
else
m_forwardRenderQueue->AddBillboards(renderOrder, material, billboardCount, scissorRect, positionPtr, sizePtr, sinCosPtr, alphaPtr);
}
/*!
* \brief Adds multiple billboards to the queue
*
* \param renderOrder Order of rendering
* \param material Material of the billboards
* \param count Number of billboards
* \param positionPtr Position of the billboards
* \param sizePtr Size of the billboards
* \param anglePtr Rotation of the billboards if null, 0.f is used
* \param colorPtr Color of the billboards if null, Color::White is used
*/
void DeferredProxyRenderQueue::AddBillboards(int renderOrder, const Material* material, std::size_t billboardCount, const Recti& scissorRect, SparsePtr<const Vector3f> positionPtr, SparsePtr<const float> sizePtr, SparsePtr<const float> anglePtr, SparsePtr<const Color> colorPtr)
{
NazaraAssert(material, "Invalid material");
if (!material->IsBlendingEnabled())
m_deferredRenderQueue->AddBillboards(renderOrder, material, billboardCount, scissorRect, positionPtr, sizePtr, anglePtr, colorPtr);
else
m_forwardRenderQueue->AddBillboards(renderOrder, material, billboardCount, scissorRect, positionPtr, sizePtr, anglePtr, colorPtr);
}
/*!
* \brief Adds multiple billboards to the queue
*
* \param renderOrder Order of rendering
* \param material Material of the billboards
* \param count Number of billboards
* \param positionPtr Position of the billboards
* \param sizePtr Size of the billboards
* \param anglePtr Rotation of the billboards if null, 0.f is used
* \param alphaPtr Alpha parameters of the billboards if null, 1.f is used
*/
void DeferredProxyRenderQueue::AddBillboards(int renderOrder, const Material* material, std::size_t billboardCount, const Recti& scissorRect, SparsePtr<const Vector3f> positionPtr, SparsePtr<const float> sizePtr, SparsePtr<const float> anglePtr, SparsePtr<const float> alphaPtr)
{
NazaraAssert(material, "Invalid material");
if (!material->IsBlendingEnabled())
m_deferredRenderQueue->AddBillboards(renderOrder, material, billboardCount, scissorRect, positionPtr, sizePtr, anglePtr, alphaPtr);
else
m_forwardRenderQueue->AddBillboards(renderOrder, material, billboardCount, scissorRect, positionPtr, sizePtr, anglePtr, alphaPtr);
}
/*!
* \brief Adds drawable to the queue
*
* \param renderOrder Order of rendering
* \param drawable Drawable user defined
*
* \remark Produces a NazaraError if drawable is invalid
*/
void DeferredProxyRenderQueue::AddDrawable(int renderOrder, const Drawable* drawable)
{
m_forwardRenderQueue->AddDrawable(renderOrder, drawable);
}
/*!
* \brief Adds mesh to the queue
*
* \param renderOrder Order of rendering
* \param material Material of the mesh
* \param meshData Data of the mesh
* \param meshAABB Box of the mesh
* \param transformMatrix Matrix of the mesh
*/
void DeferredProxyRenderQueue::AddMesh(int renderOrder, const Material* material, const MeshData& meshData, const Boxf& meshAABB, const Matrix4f& transformMatrix, const Recti& scissorRect)
{
NazaraAssert(material, "Invalid material");
if (!material->IsBlendingEnabled())
m_deferredRenderQueue->AddMesh(renderOrder, material, meshData, meshAABB, transformMatrix, scissorRect);
else
m_forwardRenderQueue->AddMesh(renderOrder, material, meshData, meshAABB, transformMatrix, scissorRect);
}
/*!
* \brief Adds sprites to the queue
*
* \param renderOrder Order of rendering
* \param material Material of the sprites
* \param vertices Buffer of data for the sprites
* \param spriteCount Number of sprites
* \param overlay Texture of the sprites
*/
void DeferredProxyRenderQueue::AddSprites(int renderOrder, const Material* material, const VertexStruct_XYZ_Color_UV* vertices, std::size_t spriteCount, const Recti& scissorRect, const Texture* overlay)
{
NazaraAssert(material, "Invalid material");
if (!material->IsBlendingEnabled())
m_deferredRenderQueue->AddSprites(renderOrder, material, vertices, spriteCount, scissorRect, overlay);
else
m_forwardRenderQueue->AddSprites(renderOrder, material, vertices, spriteCount, scissorRect, overlay);
}
/*!
* \brief Clears the queue
*
* \param fully Should everything be cleared or we can keep layers
*/
void DeferredProxyRenderQueue::Clear(bool fully)
{
AbstractRenderQueue::Clear(fully);
m_deferredRenderQueue->Clear(fully);
m_forwardRenderQueue->Clear(fully);
}
}

View File

@@ -3,8 +3,8 @@
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Graphics/DeferredRenderPass.hpp>
#include <Nazara/Graphics/DeferredProxyRenderQueue.hpp>
#include <Nazara/Graphics/DeferredRenderTechnique.hpp>
#include <Nazara/Graphics/DeferredRenderQueue.hpp>
#include <Nazara/Math/Vector2.hpp>
#include <Nazara/Graphics/Debug.hpp>
@@ -47,7 +47,7 @@ namespace Nz
void DeferredRenderPass::Initialize(DeferredRenderTechnique* technique)
{
m_deferredTechnique = technique;
m_renderQueue = static_cast<DeferredRenderQueue*>(technique->GetRenderQueue());
m_renderQueue = static_cast<DeferredProxyRenderQueue*>(technique->GetRenderQueue());
m_depthStencilTexture = technique->GetDepthStencilTexture();

View File

@@ -1,410 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Engine - Graphics module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Graphics/DeferredRenderQueue.hpp>
#include <Nazara/Graphics/ForwardRenderQueue.hpp>
#include <Nazara/Graphics/Debug.hpp>
///TODO: Render billboards using Deferred Shading if possible
namespace Nz
{
/*!
* \ingroup graphics
* \class Nz::DeferredRenderQueue
* \brief Graphics class that represents the rendering queue for deferred rendering
*/
/*!
* \brief Constructs a DeferredRenderQueue object with the rendering queue of forward rendering
*
* \param forwardQueue Queue of data to render
*/
DeferredRenderQueue::DeferredRenderQueue(ForwardRenderQueue* forwardQueue) :
m_forwardQueue(forwardQueue)
{
}
/*!
* \brief Adds multiple billboards to the queue
*
* \param renderOrder Order of rendering
* \param material Material of the billboards
* \param count Number of billboards
* \param positionPtr Position of the billboards
* \param sizePtr Sizes of the billboards
* \param sinCosPtr Rotation of the billboards if null, Vector2f(0.f, 1.f) is used
* \param colorPtr Color of the billboards if null, Color::White is used
*/
void DeferredRenderQueue::AddBillboards(int renderOrder, const Material* material, unsigned int count, SparsePtr<const Vector3f> positionPtr, SparsePtr<const Vector2f> sizePtr, SparsePtr<const Vector2f> sinCosPtr, SparsePtr<const Color> colorPtr)
{
m_forwardQueue->AddBillboards(renderOrder, material, count, positionPtr, sizePtr, sinCosPtr, colorPtr);
}
/*!
* \brief Adds multiple billboards to the queue
*
* \param renderOrder Order of rendering
* \param material Material of the billboards
* \param count Number of billboards
* \param positionPtr Position of the billboards
* \param sizePtr Sizes of the billboards
* \param sinCosPtr Rotation of the billboards if null, Vector2f(0.f, 1.f) is used
* \param alphaPtr Alpha parameters of the billboards if null, 1.f is used
*/
void DeferredRenderQueue::AddBillboards(int renderOrder, const Material* material, unsigned int count, SparsePtr<const Vector3f> positionPtr, SparsePtr<const Vector2f> sizePtr, SparsePtr<const Vector2f> sinCosPtr, SparsePtr<const float> alphaPtr)
{
m_forwardQueue->AddBillboards(renderOrder, material, count, positionPtr, sizePtr, sinCosPtr, alphaPtr);
}
/*!
* \brief Adds multiple billboards to the queue
*
* \param renderOrder Order of rendering
* \param material Material of the billboards
* \param count Number of billboards
* \param positionPtr Position of the billboards
* \param sizePtr Sizes of the billboards
* \param anglePtr Rotation of the billboards if null, 0.f is used
* \param colorPtr Color of the billboards if null, Color::White is used
*/
void DeferredRenderQueue::AddBillboards(int renderOrder, const Material* material, unsigned int count, SparsePtr<const Vector3f> positionPtr, SparsePtr<const Vector2f> sizePtr, SparsePtr<const float> anglePtr, SparsePtr<const Color> colorPtr)
{
m_forwardQueue->AddBillboards(renderOrder, material, count, positionPtr, sizePtr, anglePtr, colorPtr);
}
/*!
* \brief Adds multiple billboards to the queue
*
* \param renderOrder Order of rendering
* \param material Material of the billboards
* \param count Number of billboards
* \param positionPtr Position of the billboards
* \param sizePtr Sizes of the billboards
* \param anglePtr Rotation of the billboards if null, 0.f is used
* \param alphaPtr Alpha parameters of the billboards if null, 1.f is used
*/
void DeferredRenderQueue::AddBillboards(int renderOrder, const Material* material, unsigned int count, SparsePtr<const Vector3f> positionPtr, SparsePtr<const Vector2f> sizePtr, SparsePtr<const float> anglePtr, SparsePtr<const float> alphaPtr)
{
m_forwardQueue->AddBillboards(renderOrder, material, count, positionPtr, sizePtr, anglePtr, alphaPtr);
}
/*!
* \brief Adds multiple billboards to the queue
*
* \param renderOrder Order of rendering
* \param material Material of the billboards
* \param count Number of billboards
* \param positionPtr Position of the billboards
* \param sizePtr Size of the billboards
* \param sinCosPtr Rotation of the billboards if null, Vector2f(0.f, 1.f) is used
* \param colorPtr Color of the billboards if null, Color::White is used
*/
void DeferredRenderQueue::AddBillboards(int renderOrder, const Material* material, unsigned int count, SparsePtr<const Vector3f> positionPtr, SparsePtr<const float> sizePtr, SparsePtr<const Vector2f> sinCosPtr, SparsePtr<const Color> colorPtr)
{
m_forwardQueue->AddBillboards(renderOrder, material, count, positionPtr, sizePtr, sinCosPtr, colorPtr);
}
/*!
* \brief Adds multiple billboards to the queue
*
* \param renderOrder Order of rendering
* \param material Material of the billboards
* \param count Number of billboards
* \param positionPtr Position of the billboards
* \param sizePtr Size of the billboards
* \param sinCosPtr Rotation of the billboards if null, Vector2f(0.f, 1.f) is used
* \param alphaPtr Alpha parameters of the billboards if null, 1.f is used
*/
void DeferredRenderQueue::AddBillboards(int renderOrder, const Material* material, unsigned int count, SparsePtr<const Vector3f> positionPtr, SparsePtr<const float> sizePtr, SparsePtr<const Vector2f> sinCosPtr, SparsePtr<const float> alphaPtr)
{
m_forwardQueue->AddBillboards(renderOrder, material, count, positionPtr, sizePtr, sinCosPtr, alphaPtr);
}
/*!
* \brief Adds multiple billboards to the queue
*
* \param renderOrder Order of rendering
* \param material Material of the billboards
* \param count Number of billboards
* \param positionPtr Position of the billboards
* \param sizePtr Size of the billboards
* \param anglePtr Rotation of the billboards if null, 0.f is used
* \param colorPtr Color of the billboards if null, Color::White is used
*/
void DeferredRenderQueue::AddBillboards(int renderOrder, const Material* material, unsigned int count, SparsePtr<const Vector3f> positionPtr, SparsePtr<const float> sizePtr, SparsePtr<const float> anglePtr, SparsePtr<const Color> colorPtr)
{
m_forwardQueue->AddBillboards(renderOrder, material, count, positionPtr, sizePtr, anglePtr, colorPtr);
}
/*!
* \brief Adds multiple billboards to the queue
*
* \param renderOrder Order of rendering
* \param material Material of the billboards
* \param count Number of billboards
* \param positionPtr Position of the billboards
* \param sizePtr Size of the billboards
* \param anglePtr Rotation of the billboards if null, 0.f is used
* \param alphaPtr Alpha parameters of the billboards if null, 1.f is used
*/
void DeferredRenderQueue::AddBillboards(int renderOrder, const Material* material, unsigned int count, SparsePtr<const Vector3f> positionPtr, SparsePtr<const float> sizePtr, SparsePtr<const float> anglePtr, SparsePtr<const float> alphaPtr)
{
m_forwardQueue->AddBillboards(renderOrder, material, count, positionPtr, sizePtr, anglePtr, alphaPtr);
}
/*!
* \brief Adds drawable to the queue
*
* \param renderOrder Order of rendering
* \param drawable Drawable user defined
*
* \remark Produces a NazaraError if drawable is invalid
*/
void DeferredRenderQueue::AddDrawable(int renderOrder, const Drawable* drawable)
{
m_forwardQueue->AddDrawable(renderOrder, drawable);
}
/*!
* \brief Adds mesh to the queue
*
* \param renderOrder Order of rendering
* \param material Material of the mesh
* \param meshData Data of the mesh
* \param meshAABB Box of the mesh
* \param transformMatrix Matrix of the mesh
*/
void DeferredRenderQueue::AddMesh(int renderOrder, const Material* material, const MeshData& meshData, const Boxf& meshAABB, const Matrix4f& transformMatrix)
{
if (material->IsBlendingEnabled() || material->IsDepthSortingEnabled()) //< Fixme: Deferred Shading should be able to handle depth sorting
// Deferred Shading cannot handle blended objects, put them in the forward list
m_forwardQueue->AddMesh(renderOrder, material, meshData, meshAABB, transformMatrix);
else
{
Layer& currentLayer = GetLayer(renderOrder);
MeshPipelineBatches& opaqueModels = currentLayer.opaqueModels;
const MaterialPipeline* materialPipeline = material->GetPipeline();
auto pipelineIt = opaqueModels.find(materialPipeline);
if (pipelineIt == opaqueModels.end())
{
BatchedMaterialEntry materialEntry;
pipelineIt = opaqueModels.insert(MeshPipelineBatches::value_type(materialPipeline, std::move(materialEntry))).first;
}
BatchedMaterialEntry& materialEntry = pipelineIt->second;
MeshMaterialBatches& materialMap = materialEntry.materialMap;
auto materialIt = materialMap.find(material);
if (materialIt == materialMap.end())
{
BatchedModelEntry entry;
entry.materialReleaseSlot.Connect(material->OnMaterialRelease, this, &DeferredRenderQueue::OnMaterialInvalidation);
materialIt = materialMap.insert(MeshMaterialBatches::value_type(material, std::move(entry))).first;
}
BatchedModelEntry& entry = materialIt->second;
entry.enabled = true;
MeshInstanceContainer& meshMap = entry.meshMap;
auto it2 = meshMap.find(meshData);
if (it2 == meshMap.end())
{
MeshInstanceEntry instanceEntry;
if (meshData.indexBuffer)
instanceEntry.indexBufferReleaseSlot.Connect(meshData.indexBuffer->OnIndexBufferRelease, this, &DeferredRenderQueue::OnIndexBufferInvalidation);
instanceEntry.vertexBufferReleaseSlot.Connect(meshData.vertexBuffer->OnVertexBufferRelease, this, &DeferredRenderQueue::OnVertexBufferInvalidation);
it2 = meshMap.insert(std::make_pair(meshData, std::move(instanceEntry))).first;
}
std::vector<Matrix4f>& instances = it2->second.instances;
instances.push_back(transformMatrix);
materialEntry.maxInstanceCount = std::max(materialEntry.maxInstanceCount, instances.size());
}
}
/*!
* \brief Adds sprites to the queue
*
* \param renderOrder Order of rendering
* \param material Material of the sprites
* \param vertices Buffer of data for the sprites
* \param spriteCount Number of sprites
* \param overlay Texture of the sprites
*/
void DeferredRenderQueue::AddSprites(int renderOrder, const Material* material, const VertexStruct_XYZ_Color_UV* vertices, std::size_t spriteCount, const Texture* overlay)
{
m_forwardQueue->AddSprites(renderOrder, material, vertices, spriteCount, overlay);
}
/*!
* \brief Clears the queue
*
* \param fully Should everything be cleared or we can keep layers
*/
void DeferredRenderQueue::Clear(bool fully)
{
AbstractRenderQueue::Clear(fully);
if (fully)
layers.clear();
else
{
for (auto it = layers.begin(); it != layers.end();)
{
Layer& layer = it->second;
if (layer.clearCount++ >= 100)
it = layers.erase(it);
else
{
for (auto& pipelinePair : layer.opaqueModels)
{
auto& pipelineEntry = pipelinePair.second;
if (pipelineEntry.maxInstanceCount > 0)
{
for (auto& materialPair : pipelineEntry.materialMap)
{
auto& matEntry = materialPair.second;
if (matEntry.enabled)
{
MeshInstanceContainer& meshInstances = matEntry.meshMap;
for (auto& meshIt : meshInstances)
{
auto& meshEntry = meshIt.second;
meshEntry.instances.clear();
}
matEntry.enabled = false;
}
}
pipelineEntry.maxInstanceCount = 0;
}
}
++it;
}
}
}
m_forwardQueue->Clear(fully);
}
/*!
* \brief Gets the ith layer
* \return Reference to the ith layer for the queue
*
* \param i Index of the layer
*/
DeferredRenderQueue::Layer& DeferredRenderQueue::GetLayer(unsigned int i)
{
auto it = layers.find(i);
if (it == layers.end())
it = layers.insert(std::make_pair(i, Layer())).first;
Layer& layer = it->second;
layer.clearCount = 0;
return layer;
}
/*!
* \brief Handle the invalidation of an index buffer
*
* \param indexBuffer Index buffer being invalidated
*/
void DeferredRenderQueue::OnIndexBufferInvalidation(const IndexBuffer* indexBuffer)
{
for (auto& pair : layers)
{
Layer& layer = pair.second;
for (auto& pipelineEntry : layer.opaqueModels)
{
for (auto& materialEntry : pipelineEntry.second.materialMap)
{
MeshInstanceContainer& meshes = materialEntry.second.meshMap;
for (auto it = meshes.begin(); it != meshes.end();)
{
const MeshData& renderData = it->first;
if (renderData.indexBuffer == indexBuffer)
it = meshes.erase(it);
else
++it;
}
}
}
}
}
/*!
* \brief Handle the invalidation of a material
*
* \param material Material being invalidated
*/
void DeferredRenderQueue::OnMaterialInvalidation(const Material* material)
{
for (auto& pair : layers)
{
Layer& layer = pair.second;
for (auto& pipelineEntry : layer.opaqueModels)
pipelineEntry.second.materialMap.erase(material);
}
}
/*!
* \brief Handle the invalidation of a vertex buffer
*
* \param vertexBuffer Vertex buffer being invalidated
*/
void DeferredRenderQueue::OnVertexBufferInvalidation(const VertexBuffer* vertexBuffer)
{
for (auto& pair : layers)
{
Layer& layer = pair.second;
for (auto& pipelineEntry : layer.opaqueModels)
{
for (auto& materialEntry : pipelineEntry.second.materialMap)
{
MeshInstanceContainer& meshes = materialEntry.second.meshMap;
for (auto it = meshes.begin(); it != meshes.end();)
{
const MeshData& renderData = it->first;
if (renderData.vertexBuffer == vertexBuffer)
it = meshes.erase(it);
else
++it;
}
}
}
}
}
}

View File

@@ -127,7 +127,7 @@ namespace Nz
*/
DeferredRenderTechnique::DeferredRenderTechnique() :
m_renderQueue(static_cast<ForwardRenderQueue*>(m_forwardTechnique.GetRenderQueue())),
m_renderQueue(&m_deferredRenderQueue, static_cast<BasicRenderQueue*>(m_forwardTechnique.GetRenderQueue())),
m_GBufferSize(0U)
{
m_depthStencilTexture = Texture::New();
@@ -455,35 +455,35 @@ namespace Nz
switch (renderPass)
{
case RenderPassType_AA:
smartPtr.reset(new DeferredFXAAPass);
smartPtr = std::make_unique<DeferredFXAAPass>();
break;
case RenderPassType_Bloom:
smartPtr.reset(new DeferredBloomPass);
smartPtr = std::make_unique<DeferredBloomPass>();
break;
case RenderPassType_DOF:
smartPtr.reset(new DeferredDOFPass);
smartPtr = std::make_unique<DeferredDOFPass>();
break;
case RenderPassType_Final:
smartPtr.reset(new DeferredFinalPass);
smartPtr = std::make_unique<DeferredFinalPass>();
break;
case RenderPassType_Fog:
smartPtr.reset(new DeferredFogPass);
smartPtr = std::make_unique<DeferredFogPass>();
break;
case RenderPassType_Forward:
smartPtr.reset(new DeferredForwardPass);
smartPtr = std::make_unique<DeferredForwardPass>();
break;
case RenderPassType_Geometry:
smartPtr.reset(new DeferredGeometryPass);
smartPtr = std::make_unique<DeferredGeometryPass>();
break;
case RenderPassType_Lighting:
smartPtr.reset(new DeferredPhongLightingPass);
smartPtr = std::make_unique<DeferredPhongLightingPass>();
break;
case RenderPassType_SSAO:
@@ -701,6 +701,12 @@ namespace Nz
NazaraWarning("Failed to register gaussian blur shader, certain features will not work: " + error);
}
if (!DeferredGeometryPass::Initialize())
{
NazaraError("Failed to initialize geometry pass");
return false;
}
return true;
}
@@ -710,6 +716,8 @@ namespace Nz
void DeferredRenderTechnique::Uninitialize()
{
DeferredGeometryPass::Uninitialize();
ShaderLibrary::Unregister("DeferredGBufferClear");
ShaderLibrary::Unregister("DeferredDirectionnalLight");
ShaderLibrary::Unregister("DeferredPointSpotLight");

View File

@@ -43,7 +43,7 @@ namespace Nz
* \remark Produces a NazaraAssert if material is invalid
*/
void DepthRenderQueue::AddBillboards(int renderOrder, const Material* material, unsigned int count, SparsePtr<const Vector3f> positionPtr, SparsePtr<const Vector2f> sizePtr, SparsePtr<const Vector2f> sinCosPtr, SparsePtr<const Color> colorPtr)
void DepthRenderQueue::AddBillboards(int renderOrder, const Material* material, std::size_t billboardCount, const Recti& scissorRect, SparsePtr<const Vector3f> positionPtr, SparsePtr<const Vector2f> sizePtr, SparsePtr<const Vector2f> sinCosPtr, SparsePtr<const Color> colorPtr)
{
NazaraAssert(material, "Invalid material");
NazaraUnused(renderOrder);
@@ -56,7 +56,7 @@ namespace Nz
else
material = m_baseMaterial;
ForwardRenderQueue::AddBillboards(0, material, count, positionPtr, sizePtr, sinCosPtr, colorPtr);
BasicRenderQueue::AddBillboards(0, material, billboardCount, scissorRect, positionPtr, sizePtr, sinCosPtr, colorPtr);
}
/*!
@@ -73,7 +73,7 @@ namespace Nz
* \remark Produces a NazaraAssert if material is invalid
*/
void DepthRenderQueue::AddBillboards(int renderOrder, const Material* material, unsigned int count, SparsePtr<const Vector3f> positionPtr, SparsePtr<const Vector2f> sizePtr, SparsePtr<const Vector2f> sinCosPtr, SparsePtr<const float> alphaPtr)
void DepthRenderQueue::AddBillboards(int renderOrder, const Material* material, std::size_t billboardCount, const Recti& scissorRect, SparsePtr<const Vector3f> positionPtr, SparsePtr<const Vector2f> sizePtr, SparsePtr<const Vector2f> sinCosPtr, SparsePtr<const float> alphaPtr)
{
NazaraAssert(material, "Invalid material");
NazaraUnused(renderOrder);
@@ -86,7 +86,7 @@ namespace Nz
else
material = m_baseMaterial;
ForwardRenderQueue::AddBillboards(0, material, count, positionPtr, sizePtr, sinCosPtr, alphaPtr);
BasicRenderQueue::AddBillboards(0, material, billboardCount, scissorRect, positionPtr, sizePtr, sinCosPtr, alphaPtr);
}
/*!
@@ -103,7 +103,7 @@ namespace Nz
* \remark Produces a NazaraAssert if material is invalid
*/
void DepthRenderQueue::AddBillboards(int renderOrder, const Material* material, unsigned int count, SparsePtr<const Vector3f> positionPtr, SparsePtr<const Vector2f> sizePtr, SparsePtr<const float> anglePtr, SparsePtr<const Color> colorPtr)
void DepthRenderQueue::AddBillboards(int renderOrder, const Material* material, std::size_t billboardCount, const Recti& scissorRect, SparsePtr<const Vector3f> positionPtr, SparsePtr<const Vector2f> sizePtr, SparsePtr<const float> anglePtr, SparsePtr<const Color> colorPtr)
{
NazaraAssert(material, "Invalid material");
NazaraUnused(renderOrder);
@@ -116,7 +116,7 @@ namespace Nz
else
material = m_baseMaterial;
ForwardRenderQueue::AddBillboards(0, material, count, positionPtr, sizePtr, anglePtr, colorPtr);
BasicRenderQueue::AddBillboards(0, material, billboardCount, scissorRect, positionPtr, sizePtr, anglePtr, colorPtr);
}
/*!
@@ -133,7 +133,7 @@ namespace Nz
* \remark Produces a NazaraAssert if material is invalid
*/
void DepthRenderQueue::AddBillboards(int renderOrder, const Material* material, unsigned int count, SparsePtr<const Vector3f> positionPtr, SparsePtr<const Vector2f> sizePtr, SparsePtr<const float> anglePtr, SparsePtr<const float> alphaPtr)
void DepthRenderQueue::AddBillboards(int renderOrder, const Material* material, std::size_t billboardCount, const Recti& scissorRect, SparsePtr<const Vector3f> positionPtr, SparsePtr<const Vector2f> sizePtr, SparsePtr<const float> anglePtr, SparsePtr<const float> alphaPtr)
{
NazaraAssert(material, "Invalid material");
NazaraUnused(renderOrder);
@@ -146,7 +146,7 @@ namespace Nz
else
material = m_baseMaterial;
ForwardRenderQueue::AddBillboards(0, material, count, positionPtr, sizePtr, anglePtr, alphaPtr);
BasicRenderQueue::AddBillboards(0, material, billboardCount, scissorRect, positionPtr, sizePtr, anglePtr, alphaPtr);
}
/*!
@@ -163,7 +163,7 @@ namespace Nz
* \remark Produces a NazaraAssert if material is invalid
*/
void DepthRenderQueue::AddBillboards(int renderOrder, const Material* material, unsigned int count, SparsePtr<const Vector3f> positionPtr, SparsePtr<const float> sizePtr, SparsePtr<const Vector2f> sinCosPtr, SparsePtr<const Color> colorPtr)
void DepthRenderQueue::AddBillboards(int renderOrder, const Material* material, std::size_t billboardCount, const Recti& scissorRect, SparsePtr<const Vector3f> positionPtr, SparsePtr<const float> sizePtr, SparsePtr<const Vector2f> sinCosPtr, SparsePtr<const Color> colorPtr)
{
NazaraAssert(material, "Invalid material");
NazaraUnused(renderOrder);
@@ -176,7 +176,7 @@ namespace Nz
else
material = m_baseMaterial;
ForwardRenderQueue::AddBillboards(0, material, count, positionPtr, sizePtr, sinCosPtr, colorPtr);
BasicRenderQueue::AddBillboards(0, material, billboardCount, scissorRect, positionPtr, sizePtr, sinCosPtr, colorPtr);
}
/*!
@@ -193,7 +193,7 @@ namespace Nz
* \remark Produces a NazaraAssert if material is invalid
*/
void DepthRenderQueue::AddBillboards(int renderOrder, const Material* material, unsigned int count, SparsePtr<const Vector3f> positionPtr, SparsePtr<const float> sizePtr, SparsePtr<const Vector2f> sinCosPtr, SparsePtr<const float> alphaPtr)
void DepthRenderQueue::AddBillboards(int renderOrder, const Material* material, std::size_t billboardCount, const Recti& scissorRect, SparsePtr<const Vector3f> positionPtr, SparsePtr<const float> sizePtr, SparsePtr<const Vector2f> sinCosPtr, SparsePtr<const float> alphaPtr)
{
NazaraAssert(material, "Invalid material");
NazaraUnused(renderOrder);
@@ -206,7 +206,7 @@ namespace Nz
else
material = m_baseMaterial;
ForwardRenderQueue::AddBillboards(0, material, count, positionPtr, sizePtr, sinCosPtr, alphaPtr);
BasicRenderQueue::AddBillboards(0, material, billboardCount, scissorRect, positionPtr, sizePtr, sinCosPtr, alphaPtr);
}
/*!
@@ -223,7 +223,7 @@ namespace Nz
* \remark Produces a NazaraAssert if material is invalid
*/
void DepthRenderQueue::AddBillboards(int renderOrder, const Material* material, unsigned int count, SparsePtr<const Vector3f> positionPtr, SparsePtr<const float> sizePtr, SparsePtr<const float> anglePtr, SparsePtr<const Color> colorPtr)
void DepthRenderQueue::AddBillboards(int renderOrder, const Material* material, std::size_t billboardCount, const Recti& scissorRect, SparsePtr<const Vector3f> positionPtr, SparsePtr<const float> sizePtr, SparsePtr<const float> anglePtr, SparsePtr<const Color> colorPtr)
{
NazaraAssert(material, "Invalid material");
NazaraUnused(renderOrder);
@@ -236,7 +236,7 @@ namespace Nz
else
material = m_baseMaterial;
ForwardRenderQueue::AddBillboards(0, material, count, positionPtr, sizePtr, anglePtr, colorPtr);
BasicRenderQueue::AddBillboards(0, material, billboardCount, scissorRect, positionPtr, sizePtr, anglePtr, colorPtr);
}
/*!
@@ -253,7 +253,7 @@ namespace Nz
* \remark Produces a NazaraAssert if material is invalid
*/
void DepthRenderQueue::AddBillboards(int renderOrder, const Material* material, unsigned int count, SparsePtr<const Vector3f> positionPtr, SparsePtr<const float> sizePtr, SparsePtr<const float> anglePtr, SparsePtr<const float> alphaPtr)
void DepthRenderQueue::AddBillboards(int renderOrder, const Material* material, std::size_t billboardCount, const Recti& scissorRect, SparsePtr<const Vector3f> positionPtr, SparsePtr<const float> sizePtr, SparsePtr<const float> anglePtr, SparsePtr<const float> alphaPtr)
{
NazaraAssert(material, "Invalid material");
NazaraUnused(renderOrder);
@@ -266,11 +266,11 @@ namespace Nz
else
material = m_baseMaterial;
ForwardRenderQueue::AddBillboards(0, material, count, positionPtr, sizePtr, anglePtr, alphaPtr);
BasicRenderQueue::AddBillboards(0, material, billboardCount, scissorRect, positionPtr, sizePtr, anglePtr, alphaPtr);
}
/*!
* \brief Adds a direcitonal light to the queue
* \brief Adds a directional light to the queue
*
* \param light Light to add
*
@@ -295,7 +295,7 @@ namespace Nz
* \remark Produces a NazaraAssert if material is invalid
*/
void DepthRenderQueue::AddMesh(int renderOrder, const Material* material, const MeshData& meshData, const Boxf& meshAABB, const Matrix4f& transformMatrix)
void DepthRenderQueue::AddMesh(int renderOrder, const Material* material, const MeshData& meshData, const Boxf& meshAABB, const Matrix4f& transformMatrix, const Recti& scissorRect)
{
NazaraAssert(material, "Invalid material");
NazaraUnused(renderOrder);
@@ -309,7 +309,7 @@ namespace Nz
else
material = m_baseMaterial;
ForwardRenderQueue::AddMesh(0, material, meshData, meshAABB, transformMatrix);
BasicRenderQueue::AddMesh(0, material, meshData, meshAABB, transformMatrix, scissorRect);
}
/*!
@@ -352,7 +352,7 @@ namespace Nz
* \remark Produces a NazaraAssert if material is invalid
*/
void DepthRenderQueue::AddSprites(int renderOrder, const Material* material, const VertexStruct_XYZ_Color_UV* vertices, std::size_t spriteCount, const Texture* overlay)
void DepthRenderQueue::AddSprites(int renderOrder, const Material* material, const VertexStruct_XYZ_Color_UV* vertices, std::size_t spriteCount, const Recti& scissorRect, const Texture* overlay /*= nullptr*/)
{
NazaraAssert(material, "Invalid material");
NazaraUnused(renderOrder);
@@ -366,7 +366,7 @@ namespace Nz
else
material = m_baseMaterial;
ForwardRenderQueue::AddSprites(0, material, vertices, spriteCount, overlay);
BasicRenderQueue::AddSprites(0, material, vertices, spriteCount, scissorRect, overlay);
}
}

View File

@@ -5,11 +5,14 @@
#include <Nazara/Graphics/DepthRenderTechnique.hpp>
#include <Nazara/Core/ErrorFlags.hpp>
#include <Nazara/Core/OffsetOf.hpp>
#include <Nazara/Graphics/AbstractBackground.hpp>
#include <Nazara/Graphics/AbstractViewer.hpp>
#include <Nazara/Graphics/Drawable.hpp>
#include <Nazara/Graphics/Material.hpp>
#include <Nazara/Graphics/SceneData.hpp>
#include <Nazara/Renderer/Config.hpp>
#include <Nazara/Renderer/Renderer.hpp>
#include <Nazara/Renderer/RenderTarget.hpp>
#include <Nazara/Utility/BufferMapper.hpp>
#include <Nazara/Utility/VertexStruct.hpp>
#include <limits>
@@ -47,9 +50,7 @@ namespace Nz
{
ErrorFlags flags(ErrorFlag_ThrowException, true);
std::array<UInt8, 4> whitePixel = { {255, 255, 255, 255} };
m_whiteTexture.Create(ImageType_2D, PixelFormatType_RGBA8, 1, 1);
m_whiteTexture.Update(whitePixel.data());
m_whiteTexture = Nz::TextureLibrary::Get("White2D");
m_vertexBuffer.Create(s_vertexBufferSize, DataStorage_Hardware, BufferUsage_Dynamic);
@@ -63,15 +64,20 @@ namespace Nz
* \param sceneData Data of the scene
*/
void DepthRenderTechnique::Clear(const SceneData& /*sceneData*/) const
void DepthRenderTechnique::Clear(const SceneData& sceneData) const
{
const RenderTarget* renderTarget = sceneData.viewer->GetTarget();
Recti fullscreenScissorRect = Recti(Vector2i(renderTarget->GetSize()));
Renderer::SetScissorRect(fullscreenScissorRect);
Renderer::Enable(RendererParameter_DepthBuffer, true);
Renderer::Enable(RendererParameter_DepthWrite, true);
Renderer::Clear(RendererBuffer_Depth);
// Just in case the background does render depth
//if (sceneData.background)
// sceneData.background->Draw(sceneData.viewer);
if (sceneData.background)
sceneData.background->Draw(sceneData.viewer);
}
/*!
@@ -83,22 +89,28 @@ namespace Nz
bool DepthRenderTechnique::Draw(const SceneData& sceneData) const
{
for (auto& pair : m_renderQueue.layers)
{
ForwardRenderQueue::Layer& layer = pair.second;
m_renderQueue.Sort(sceneData.viewer);
if (!layer.opaqueModels.empty())
DrawOpaqueModels(sceneData, layer);
if (!m_renderQueue.models.empty())
DrawModels(sceneData, m_renderQueue, m_renderQueue.models);
if (!layer.opaqueSprites.empty())
DrawBasicSprites(sceneData, layer);
if (!m_renderQueue.basicSprites.empty())
DrawSprites(sceneData, m_renderQueue, m_renderQueue.basicSprites);
if (!layer.billboards.empty())
DrawBillboards(sceneData, layer);
if (!m_renderQueue.billboards.empty())
DrawBillboards(sceneData, m_renderQueue, m_renderQueue.billboards);
for (const Drawable* drawable : layer.otherDrawables)
drawable->Draw();
}
if (!m_renderQueue.depthSortedModels.empty())
DrawModels(sceneData, m_renderQueue, m_renderQueue.depthSortedModels);
if (!m_renderQueue.depthSortedSprites.empty())
DrawSprites(sceneData, m_renderQueue, m_renderQueue.depthSortedSprites);
if (!m_renderQueue.depthSortedBillboards.empty())
DrawBillboards(sceneData, m_renderQueue, m_renderQueue.depthSortedBillboards);
if (!m_renderQueue.customDrawables.empty())
DrawCustomDrawables(sceneData, m_renderQueue, m_renderQueue.customDrawables);
return true;
}
@@ -175,9 +187,9 @@ namespace Nz
// Declaration utilisée lors du rendu des billboards par instancing
// L'avantage ici est la copie directe (std::memcpy) des données de la RenderQueue vers le buffer GPU
s_billboardInstanceDeclaration.EnableComponent(VertexComponent_InstanceData0, ComponentType_Float3, NazaraOffsetOf(ForwardRenderQueue::BillboardData, center));
s_billboardInstanceDeclaration.EnableComponent(VertexComponent_InstanceData1, ComponentType_Float4, NazaraOffsetOf(ForwardRenderQueue::BillboardData, size)); // Englobe sincos
s_billboardInstanceDeclaration.EnableComponent(VertexComponent_InstanceData2, ComponentType_Color, NazaraOffsetOf(ForwardRenderQueue::BillboardData, color));
s_billboardInstanceDeclaration.EnableComponent(VertexComponent_InstanceData0, ComponentType_Float3, NazaraOffsetOf(BasicRenderQueue::BillboardData, center));
s_billboardInstanceDeclaration.EnableComponent(VertexComponent_InstanceData1, ComponentType_Float4, NazaraOffsetOf(BasicRenderQueue::BillboardData, size)); // Englobe sincos
s_billboardInstanceDeclaration.EnableComponent(VertexComponent_InstanceData2, ComponentType_Color, NazaraOffsetOf(BasicRenderQueue::BillboardData, color));
}
catch (const std::exception& e)
{
@@ -197,411 +209,406 @@ namespace Nz
s_quadIndexBuffer.Reset();
s_quadVertexBuffer.Reset();
}
/*!
* \brief Draws basic sprites
*
* \param sceneData Data of the scene
* \param layer Layer of the rendering
*/
void DepthRenderTechnique::DrawBasicSprites(const SceneData& sceneData, ForwardRenderQueue::Layer& layer) const
void DepthRenderTechnique::DrawBillboards(const SceneData& sceneData, const BasicRenderQueue& renderQueue, const RenderQueue<BasicRenderQueue::Billboard>& billboards) const
{
VertexBuffer* instanceBuffer = Renderer::GetInstanceBuffer();
instanceBuffer->SetVertexDeclaration(&s_billboardInstanceDeclaration);
Renderer::SetVertexBuffer(&s_quadVertexBuffer);
Nz::BufferMapper<VertexBuffer> instanceBufferMapper;
std::size_t billboardCount = 0;
std::size_t maxBillboardPerDraw = instanceBuffer->GetVertexCount();
auto Commit = [&]()
{
if (billboardCount > 0)
{
instanceBufferMapper.Unmap();
Renderer::DrawPrimitivesInstanced(billboardCount, PrimitiveMode_TriangleStrip, 0, 4);
billboardCount = 0;
}
};
const RenderTarget* renderTarget = sceneData.viewer->GetTarget();
Recti fullscreenScissorRect = Recti(Vector2i(renderTarget->GetSize()));
const Material* lastMaterial = nullptr;
const MaterialPipeline* lastPipeline = nullptr;
const Shader* lastShader = nullptr;
const ShaderUniforms* shaderUniforms = nullptr;
const Texture* lastOverlay = nullptr;
Recti lastScissorRect = Recti(-1, -1);
const MaterialPipeline::Instance* pipelineInstance = nullptr;
for (const BasicRenderQueue::Billboard& billboard : billboards)
{
const Nz::Recti& scissorRect = (billboard.scissorRect.width > 0) ? billboard.scissorRect : fullscreenScissorRect;
if (billboard.material != lastMaterial || (billboard.material->IsScissorTestEnabled() && scissorRect != lastScissorRect))
{
Commit();
const MaterialPipeline* pipeline = billboard.material->GetPipeline();
if (lastPipeline != pipeline)
{
pipelineInstance = &billboard.material->GetPipeline()->Apply(ShaderFlags_Billboard | ShaderFlags_Deferred | ShaderFlags_Instancing | ShaderFlags_VertexColor);
const Shader* shader = pipelineInstance->uberInstance->GetShader();
if (shader != lastShader)
{
// Index of uniforms in the shader
shaderUniforms = GetShaderUniforms(shader);
// Ambient color of the scene
shader->SendColor(shaderUniforms->sceneAmbient, sceneData.ambientColor);
lastShader = shader;
}
lastPipeline = pipeline;
}
if (lastMaterial != billboard.material)
{
billboard.material->Apply(*pipelineInstance);
lastMaterial = billboard.material;
}
if (billboard.material->IsScissorTestEnabled() && scissorRect != lastScissorRect)
{
Renderer::SetScissorRect(scissorRect);
lastScissorRect = scissorRect;
}
}
if (!instanceBufferMapper.GetBuffer())
instanceBufferMapper.Map(instanceBuffer, BufferAccess_DiscardAndWrite);
std::memcpy(static_cast<Nz::UInt8*>(instanceBufferMapper.GetPointer()) + sizeof(BasicRenderQueue::BillboardData) * billboardCount, &billboard.data, sizeof(BasicRenderQueue::BillboardData));
if (++billboardCount >= maxBillboardPerDraw)
Commit();
}
Commit();
}
void DepthRenderTechnique::DrawBillboards(const SceneData& sceneData, const BasicRenderQueue& renderQueue, const RenderQueue<BasicRenderQueue::BillboardChain>& billboards) const
{
VertexBuffer* instanceBuffer = Renderer::GetInstanceBuffer();
instanceBuffer->SetVertexDeclaration(&s_billboardInstanceDeclaration);
Renderer::SetVertexBuffer(&s_quadVertexBuffer);
Nz::BufferMapper<VertexBuffer> instanceBufferMapper;
std::size_t billboardCount = 0;
std::size_t maxBillboardPerDraw = instanceBuffer->GetVertexCount();
auto Commit = [&]()
{
if (billboardCount > 0)
{
instanceBufferMapper.Unmap();
Renderer::DrawPrimitivesInstanced(billboardCount, PrimitiveMode_TriangleStrip, 0, 4);
billboardCount = 0;
}
};
const RenderTarget* renderTarget = sceneData.viewer->GetTarget();
Recti fullscreenScissorRect = Recti(Vector2i(renderTarget->GetSize()));
const Material* lastMaterial = nullptr;
const MaterialPipeline* lastPipeline = nullptr;
const Shader* lastShader = nullptr;
const ShaderUniforms* shaderUniforms = nullptr;
const Texture* lastOverlay = nullptr;
Recti lastScissorRect = Recti(-1, -1);
const MaterialPipeline::Instance* pipelineInstance = nullptr;
for (const BasicRenderQueue::BillboardChain& billboard : billboards)
{
const Nz::Recti& scissorRect = (billboard.scissorRect.width > 0) ? billboard.scissorRect : fullscreenScissorRect;
if (billboard.material != lastMaterial || (billboard.material->IsScissorTestEnabled() && scissorRect != lastScissorRect))
{
Commit();
const MaterialPipeline* pipeline = billboard.material->GetPipeline();
if (lastPipeline != pipeline)
{
pipelineInstance = &billboard.material->GetPipeline()->Apply(ShaderFlags_Billboard | ShaderFlags_Deferred | ShaderFlags_Instancing | ShaderFlags_VertexColor);
const Shader* shader = pipelineInstance->uberInstance->GetShader();
if (shader != lastShader)
{
// Index of uniforms in the shader
shaderUniforms = GetShaderUniforms(shader);
// Ambient color of the scene
shader->SendColor(shaderUniforms->sceneAmbient, sceneData.ambientColor);
lastShader = shader;
}
lastPipeline = pipeline;
}
if (lastMaterial != billboard.material)
{
billboard.material->Apply(*pipelineInstance);
lastMaterial = billboard.material;
}
if (billboard.material->IsScissorTestEnabled() && scissorRect != lastScissorRect)
{
Renderer::SetScissorRect(scissorRect);
lastScissorRect = scissorRect;
}
}
std::size_t billboardRemaining = billboard.billboardCount;
const BasicRenderQueue::BillboardData* billboardData = renderQueue.GetBillboardData(billboard.billboardIndex);
do
{
std::size_t renderedBillboardCount = std::min(billboardRemaining, maxBillboardPerDraw - billboardCount);
billboardRemaining -= renderedBillboardCount;
if (!instanceBufferMapper.GetBuffer())
instanceBufferMapper.Map(instanceBuffer, BufferAccess_DiscardAndWrite);
std::memcpy(static_cast<Nz::UInt8*>(instanceBufferMapper.GetPointer()) + sizeof(BasicRenderQueue::BillboardData) * billboardCount, billboardData, renderedBillboardCount * sizeof(BasicRenderQueue::BillboardData));
billboardCount += renderedBillboardCount;
billboardData += renderedBillboardCount;
if (billboardCount >= maxBillboardPerDraw)
Commit();
}
while (billboardRemaining > 0);
}
Commit();
}
void DepthRenderTechnique::DrawCustomDrawables(const SceneData& sceneData, const BasicRenderQueue& renderQueue, const RenderQueue<BasicRenderQueue::CustomDrawable>& customDrawables) const
{
for (const BasicRenderQueue::CustomDrawable& customDrawable : customDrawables)
customDrawable.drawable->Draw();
}
void DepthRenderTechnique::DrawModels(const SceneData& sceneData, const BasicRenderQueue& renderQueue, const Nz::RenderQueue<Nz::BasicRenderQueue::Model>& models) const
{
const RenderTarget* renderTarget = sceneData.viewer->GetTarget();
Recti fullscreenScissorRect = Recti(Vector2i(renderTarget->GetSize()));
const Material* lastMaterial = nullptr;
const MaterialPipeline* lastPipeline = nullptr;
const Shader* lastShader = nullptr;
const ShaderUniforms* shaderUniforms = nullptr;
Recti lastScissorRect = Recti(-1, -1);
const MaterialPipeline::Instance* pipelineInstance = nullptr;
///TODO: Reimplement instancing
for (const BasicRenderQueue::Model& model : models)
{
const MaterialPipeline* pipeline = model.material->GetPipeline();
if (lastPipeline != pipeline)
{
pipelineInstance = &model.material->GetPipeline()->Apply(ShaderFlags_Deferred);
const Shader* shader = pipelineInstance->uberInstance->GetShader();
if (shader != lastShader)
{
// Index of uniforms in the shader
shaderUniforms = GetShaderUniforms(shader);
// Ambient color of the scene
shader->SendColor(shaderUniforms->sceneAmbient, sceneData.ambientColor);
lastShader = shader;
}
lastPipeline = pipeline;
}
if (lastMaterial != model.material)
{
model.material->Apply(*pipelineInstance);
lastMaterial = model.material;
}
if (model.material->IsScissorTestEnabled())
{
const Nz::Recti& scissorRect = (model.scissorRect.width > 0) ? model.scissorRect : fullscreenScissorRect;
if (scissorRect != lastScissorRect)
{
Renderer::SetScissorRect(scissorRect);
lastScissorRect = scissorRect;
}
}
// Handle draw call before rendering loop
Renderer::DrawCall drawFunc;
Renderer::DrawCallInstanced instancedDrawFunc;
unsigned int indexCount;
if (model.meshData.indexBuffer)
{
drawFunc = Renderer::DrawIndexedPrimitives;
instancedDrawFunc = Renderer::DrawIndexedPrimitivesInstanced;
indexCount = model.meshData.indexBuffer->GetIndexCount();
}
else
{
drawFunc = Renderer::DrawPrimitives;
instancedDrawFunc = Renderer::DrawPrimitivesInstanced;
indexCount = model.meshData.vertexBuffer->GetVertexCount();
}
Renderer::SetIndexBuffer(model.meshData.indexBuffer);
Renderer::SetVertexBuffer(model.meshData.vertexBuffer);
Renderer::SetMatrix(MatrixType_World, model.matrix);
drawFunc(model.meshData.primitiveMode, 0, indexCount);
}
}
void DepthRenderTechnique::DrawSprites(const SceneData& sceneData, const BasicRenderQueue& renderQueue, const RenderQueue<BasicRenderQueue::SpriteChain>& spriteList) const
{
const RenderTarget* renderTarget = sceneData.viewer->GetTarget();
Recti fullscreenScissorRect = Recti(Vector2i(renderTarget->GetSize()));
Renderer::SetIndexBuffer(&s_quadIndexBuffer);
Renderer::SetMatrix(MatrixType_World, Matrix4f::Identity());
Renderer::SetVertexBuffer(&m_spriteBuffer);
for (auto& pipelinePair : layer.opaqueSprites)
const unsigned int overlayTextureUnit = Material::GetTextureUnit(TextureMap_Overlay);
const std::size_t maxSpriteCount = std::min<std::size_t>(s_maxQuads, m_spriteBuffer.GetVertexCount() / 4);
m_spriteChains.clear();
auto Commit = [&]()
{
const MaterialPipeline* pipeline = pipelinePair.first;
auto& pipelineEntry = pipelinePair.second;
if (pipelineEntry.enabled)
std::size_t spriteChainCount = m_spriteChains.size();
if (spriteChainCount > 0)
{
const MaterialPipeline::Instance& pipelineInstance = pipeline->Apply(ShaderFlags_TextureOverlay | ShaderFlags_VertexColor);
std::size_t spriteChain = 0; // Which chain of sprites are we treating
std::size_t spriteChainOffset = 0; // Where was the last offset where we stopped in the last chain
const Shader* shader = pipelineInstance.uberInstance->GetShader();
// Uniforms are conserved in our program, there's no point to send them back until they change
if (shader != lastShader)
do
{
// Index of uniforms in the shader
shaderUniforms = GetShaderUniforms(shader);
// We open the buffer in writing mode
BufferMapper<VertexBuffer> vertexMapper(m_spriteBuffer, BufferAccess_DiscardAndWrite);
VertexStruct_XYZ_Color_UV* vertices = static_cast<VertexStruct_XYZ_Color_UV*>(vertexMapper.GetPointer());
// Ambiant color of the scene
shader->SendColor(shaderUniforms->sceneAmbient, sceneData.ambientColor);
std::size_t spriteCount = 0;
lastShader = shader;
}
for (auto& materialPair : pipelineEntry.materialMap)
{
const Material* material = materialPair.first;
auto& matEntry = materialPair.second;
if (matEntry.enabled)
do
{
unsigned int overlayTextureUnit = Material::GetTextureUnit(TextureMap_Overlay);
material->Apply(pipelineInstance);
const VertexStruct_XYZ_Color_UV* currentChain = m_spriteChains[spriteChain].first;
std::size_t currentChainSpriteCount = m_spriteChains[spriteChain].second;
std::size_t count = std::min(maxSpriteCount - spriteCount, currentChainSpriteCount - spriteChainOffset);
std::memcpy(vertices, currentChain + spriteChainOffset * 4, 4 * count * sizeof(VertexStruct_XYZ_Color_UV));
vertices += count * 4;
spriteCount += count;
spriteChainOffset += count;
// Have we treated the entire chain ?
if (spriteChainOffset == currentChainSpriteCount)
{
spriteChain++;
spriteChainOffset = 0;
}
}
while (spriteCount < maxSpriteCount && spriteChain < spriteChainCount);
vertexMapper.Unmap();
Renderer::DrawIndexedPrimitives(PrimitiveMode_TriangleList, 0, spriteCount * 6);
}
while (spriteChain < spriteChainCount);
}
m_spriteChains.clear();
};
const Material* lastMaterial = nullptr;
const MaterialPipeline* lastPipeline = nullptr;
const Shader* lastShader = nullptr;
const ShaderUniforms* shaderUniforms = nullptr;
const Texture* lastOverlay = nullptr;
Recti lastScissorRect = Recti(-1, -1);
const MaterialPipeline::Instance* pipelineInstance = nullptr;
for (const BasicRenderQueue::SpriteChain& basicSprites : spriteList)
{
const Nz::Recti& scissorRect = (basicSprites.scissorRect.width > 0) ? basicSprites.scissorRect : fullscreenScissorRect;
if (basicSprites.material != lastMaterial || basicSprites.overlay != lastOverlay || (basicSprites.material->IsScissorTestEnabled() && scissorRect != lastScissorRect))
{
Commit();
const MaterialPipeline* pipeline = basicSprites.material->GetPipeline();
if (lastPipeline != pipeline)
{
pipelineInstance = &basicSprites.material->GetPipeline()->Apply(ShaderFlags_Deferred | ShaderFlags_TextureOverlay | ShaderFlags_VertexColor);
const Shader* shader = pipelineInstance->uberInstance->GetShader();
if (shader != lastShader)
{
// Index of uniforms in the shader
shaderUniforms = GetShaderUniforms(shader);
// Ambient color of the scene
shader->SendColor(shaderUniforms->sceneAmbient, sceneData.ambientColor);
// Overlay texture unit
shader->SendInteger(shaderUniforms->textureOverlay, overlayTextureUnit);
Renderer::SetTextureSampler(overlayTextureUnit, material->GetDiffuseSampler());
auto& overlayMap = matEntry.overlayMap;
for (auto& overlayIt : overlayMap)
{
const Texture* overlay = overlayIt.first;
auto& spriteChainVector = overlayIt.second.spriteChains;
std::size_t spriteChainCount = spriteChainVector.size();
if (spriteChainCount > 0)
{
Renderer::SetTexture(overlayTextureUnit, (overlay) ? overlay : &m_whiteTexture);
std::size_t spriteChain = 0; // Which chain of sprites are we treating
std::size_t spriteChainOffset = 0; // Where was the last offset where we stopped in the last chain
do
{
// We open the buffer in writing mode
BufferMapper<VertexBuffer> vertexMapper(m_spriteBuffer, BufferAccess_DiscardAndWrite);
VertexStruct_XYZ_Color_UV* vertices = static_cast<VertexStruct_XYZ_Color_UV*>(vertexMapper.GetPointer());
std::size_t spriteCount = 0;
std::size_t maxSpriteCount = std::min(s_maxQuads, m_spriteBuffer.GetVertexCount() / 4);
do
{
ForwardRenderQueue::SpriteChain_XYZ_Color_UV& currentChain = spriteChainVector[spriteChain];
std::size_t count = std::min(maxSpriteCount - spriteCount, currentChain.spriteCount - spriteChainOffset);
std::memcpy(vertices, currentChain.vertices + spriteChainOffset * 4, 4 * count * sizeof(VertexStruct_XYZ_Color_UV));
vertices += count * 4;
spriteCount += count;
spriteChainOffset += count;
// Have we treated the entire chain ?
if (spriteChainOffset == currentChain.spriteCount)
{
spriteChain++;
spriteChainOffset = 0;
}
} while (spriteCount < maxSpriteCount && spriteChain < spriteChainCount);
vertexMapper.Unmap();
Renderer::DrawIndexedPrimitives(PrimitiveMode_TriangleList, 0, spriteCount * 6);
} while (spriteChain < spriteChainCount);
spriteChainVector.clear();
}
}
// We set it back to zero
matEntry.enabled = false;
}
}
pipelineEntry.enabled = false;
}
}
}
/*!
* \brief Draws billboards
*
* \param sceneData Data of the scene
* \param layer Layer of the rendering
*/
void DepthRenderTechnique::DrawBillboards(const SceneData& sceneData, ForwardRenderQueue::Layer& layer) const
{
const Shader* lastShader = nullptr;
const ShaderUniforms* shaderUniforms = nullptr;
if (Renderer::HasCapability(RendererCap_Instancing))
{
VertexBuffer* instanceBuffer = Renderer::GetInstanceBuffer();
instanceBuffer->SetVertexDeclaration(&s_billboardInstanceDeclaration);
Renderer::SetVertexBuffer(&s_quadVertexBuffer);
for (auto& pipelinePair : layer.billboards)
{
const MaterialPipeline* pipeline = pipelinePair.first;
auto& pipelineEntry = pipelinePair.second;
if (pipelineEntry.enabled)
{
const MaterialPipeline::Instance& pipelineInstance = pipeline->Apply(ShaderFlags_Billboard | ShaderFlags_Instancing | ShaderFlags_VertexColor);
const Shader* shader = pipelineInstance.uberInstance->GetShader();
// Uniforms are conserved in our program, there's no point to send them back until they change
if (shader != lastShader)
{
// Index of uniforms in the shader
shaderUniforms = GetShaderUniforms(shader);
// Ambiant color of the scene
shader->SendColor(shaderUniforms->sceneAmbient, sceneData.ambientColor);
lastShader = shader;
}
for (auto& matIt : pipelinePair.second.materialMap)
{
const Material* material = matIt.first;
auto& entry = matIt.second;
auto& billboardVector = entry.billboards;
lastPipeline = pipeline;
}
std::size_t billboardCount = billboardVector.size();
if (billboardCount > 0)
{
// We begin to apply the material (and get the shader activated doing so)
material->Apply(pipelineInstance);
if (lastMaterial != basicSprites.material)
{
basicSprites.material->Apply(*pipelineInstance);
const ForwardRenderQueue::BillboardData* data = &billboardVector[0];
std::size_t maxBillboardPerDraw = instanceBuffer->GetVertexCount();
do
{
std::size_t renderedBillboardCount = std::min(billboardCount, maxBillboardPerDraw);
billboardCount -= renderedBillboardCount;
Renderer::SetTextureSampler(overlayTextureUnit, basicSprites.material->GetDiffuseSampler());
instanceBuffer->Fill(data, 0, renderedBillboardCount);
data += renderedBillboardCount;
lastMaterial = basicSprites.material;
}
Renderer::DrawPrimitivesInstanced(renderedBillboardCount, PrimitiveMode_TriangleStrip, 0, 4);
}
while (billboardCount > 0);
const Nz::Texture* overlayTexture = (basicSprites.overlay) ? basicSprites.overlay.Get() : m_whiteTexture.Get();
if (overlayTexture != lastOverlay)
{
Renderer::SetTexture(overlayTextureUnit, overlayTexture);
lastOverlay = overlayTexture;
}
billboardVector.clear();
}
}
if (basicSprites.material->IsScissorTestEnabled() && scissorRect != lastScissorRect)
{
Renderer::SetScissorRect(scissorRect);
lastScissorRect = scissorRect;
}
}
m_spriteChains.emplace_back(basicSprites.vertices, basicSprites.spriteCount);
}
else
{
Renderer::SetIndexBuffer(&s_quadIndexBuffer);
Renderer::SetVertexBuffer(&m_billboardPointBuffer);
for (auto& pipelinePair : layer.billboards)
{
const MaterialPipeline* pipeline = pipelinePair.first;
auto& pipelineEntry = pipelinePair.second;
if (pipelineEntry.enabled)
{
const MaterialPipeline::Instance& pipelineInstance = pipeline->Apply(ShaderFlags_Billboard | ShaderFlags_VertexColor);
const Shader* shader = pipelineInstance.uberInstance->GetShader();
// Uniforms are conserved in our program, there's no point to send them back until they change
if (shader != lastShader)
{
// Index of uniforms in the shader
shaderUniforms = GetShaderUniforms(shader);
// Ambiant color of the scene
shader->SendColor(shaderUniforms->sceneAmbient, sceneData.ambientColor);
lastShader = shader;
}
for (auto& matIt : pipelinePair.second.materialMap)
{
auto& entry = matIt.second;
auto& billboardVector = entry.billboards;
const ForwardRenderQueue::BillboardData* data = &billboardVector[0];
std::size_t maxBillboardPerDraw = std::min(s_maxQuads, m_billboardPointBuffer.GetVertexCount() / 4);
std::size_t billboardCount = billboardVector.size();
do
{
std::size_t renderedBillboardCount = std::min(billboardCount, maxBillboardPerDraw);
billboardCount -= renderedBillboardCount;
BufferMapper<VertexBuffer> vertexMapper(m_billboardPointBuffer, BufferAccess_DiscardAndWrite, 0, renderedBillboardCount * 4);
BillboardPoint* vertices = static_cast<BillboardPoint*>(vertexMapper.GetPointer());
for (unsigned int i = 0; i < renderedBillboardCount; ++i)
{
const ForwardRenderQueue::BillboardData& billboard = *data++;
vertices->color = billboard.color;
vertices->position = billboard.center;
vertices->sinCos = billboard.sinCos;
vertices->size = billboard.size;
vertices->uv.Set(0.f, 1.f);
vertices++;
vertices->color = billboard.color;
vertices->position = billboard.center;
vertices->sinCos = billboard.sinCos;
vertices->size = billboard.size;
vertices->uv.Set(1.f, 1.f);
vertices++;
vertices->color = billboard.color;
vertices->position = billboard.center;
vertices->sinCos = billboard.sinCos;
vertices->size = billboard.size;
vertices->uv.Set(0.f, 0.f);
vertices++;
vertices->color = billboard.color;
vertices->position = billboard.center;
vertices->sinCos = billboard.sinCos;
vertices->size = billboard.size;
vertices->uv.Set(1.f, 0.f);
vertices++;
}
vertexMapper.Unmap();
Renderer::DrawIndexedPrimitives(PrimitiveMode_TriangleList, 0, renderedBillboardCount * 6);
}
while (billboardCount > 0);
billboardVector.clear();
}
}
}
}
}
/*!
* \brief Draws opaques models
*
* \param sceneData Data of the scene
* \param layer Layer of the rendering
*/
void DepthRenderTechnique::DrawOpaqueModels(const SceneData& sceneData, ForwardRenderQueue::Layer& layer) const
{
const Shader* lastShader = nullptr;
const ShaderUniforms* shaderUniforms = nullptr;
for (auto& pipelinePair : layer.opaqueModels)
{
const MaterialPipeline* pipeline = pipelinePair.first;
auto& pipelineEntry = pipelinePair.second;
if (pipelineEntry.maxInstanceCount > 0)
{
bool instancing = (pipelineEntry.maxInstanceCount > NAZARA_GRAPHICS_INSTANCING_MIN_INSTANCES_COUNT);
const MaterialPipeline::Instance& pipelineInstance = pipeline->Apply((instancing) ? ShaderFlags_Instancing : 0);
const Shader* shader = pipelineInstance.uberInstance->GetShader();
// Uniforms are conserved in our program, there's no point to send them back until they change
if (shader != lastShader)
{
// Index of uniforms in the shader
shaderUniforms = GetShaderUniforms(shader);
// Ambiant color of the scene
shader->SendColor(shaderUniforms->sceneAmbient, sceneData.ambientColor);
lastShader = shader;
}
for (auto& materialPair : pipelineEntry.materialMap)
{
const Material* material = materialPair.first;
auto& matEntry = materialPair.second;
if (matEntry.enabled)
{
material->Apply(pipelineInstance);
ForwardRenderQueue::MeshInstanceContainer& meshInstances = matEntry.meshMap;
// Meshes
for (auto& meshIt : meshInstances)
{
const MeshData& meshData = meshIt.first;
auto& meshEntry = meshIt.second;
std::vector<Matrix4f>& instances = meshEntry.instances;
if (!instances.empty())
{
const IndexBuffer* indexBuffer = meshData.indexBuffer;
const VertexBuffer* vertexBuffer = meshData.vertexBuffer;
// Handle draw call before rendering loop
Renderer::DrawCall drawFunc;
Renderer::DrawCallInstanced instancedDrawFunc;
unsigned int indexCount;
if (indexBuffer)
{
drawFunc = Renderer::DrawIndexedPrimitives;
instancedDrawFunc = Renderer::DrawIndexedPrimitivesInstanced;
indexCount = indexBuffer->GetIndexCount();
}
else
{
drawFunc = Renderer::DrawPrimitives;
instancedDrawFunc = Renderer::DrawPrimitivesInstanced;
indexCount = vertexBuffer->GetVertexCount();
}
Renderer::SetIndexBuffer(indexBuffer);
Renderer::SetVertexBuffer(vertexBuffer);
if (instancing)
{
// We compute the number of instances that we will be able to draw this time (depending on the instancing buffer size)
VertexBuffer* instanceBuffer = Renderer::GetInstanceBuffer();
instanceBuffer->SetVertexDeclaration(VertexDeclaration::Get(VertexLayout_Matrix4));
const Matrix4f* instanceMatrices = &instances[0];
std::size_t instanceCount = instances.size();
std::size_t maxInstanceCount = instanceBuffer->GetVertexCount(); // Maximum number of instance in one batch
while (instanceCount > 0)
{
// We compute the number of instances that we will be able to draw this time (depending on the instancing buffer size)
std::size_t renderedInstanceCount = std::min(instanceCount, maxInstanceCount);
instanceCount -= renderedInstanceCount;
// We fill the instancing buffer with our world matrices
instanceBuffer->Fill(instanceMatrices, 0, renderedInstanceCount);
instanceMatrices += renderedInstanceCount;
// And we draw
instancedDrawFunc(renderedInstanceCount, meshData.primitiveMode, 0, indexCount);
}
}
else
{
// Without instancing, we must do a draw call for each instance
// This may be faster than instancing under a certain number
// Due to the time to modify the instancing buffer
for (const Matrix4f& matrix : instances)
{
Renderer::SetMatrix(MatrixType_World, matrix);
drawFunc(meshData.primitiveMode, 0, indexCount);
}
}
instances.clear();
}
}
matEntry.enabled = false;
}
}
pipelineEntry.maxInstanceCount = 0;
}
}
Commit();
}
/*!

View File

@@ -1,931 +0,0 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Engine - Graphics module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Graphics/ForwardRenderQueue.hpp>
#include <Nazara/Graphics/AbstractViewer.hpp>
#include <Nazara/Utility/VertexStruct.hpp>
#include <Nazara/Graphics/Debug.hpp>
///TODO: Replace sinus/cosinus by a lookup table (which will lead to a speed up about 10x)
namespace Nz
{
/*!
* \ingroup graphics
* \class Nz::ForwardRenderQueue
* \brief Graphics class that represents the rendering queue for forward rendering
*/
/*!
* \brief Adds multiple billboards to the queue
*
* \param renderOrder Order of rendering
* \param material Material of the billboards
* \param count Number of billboards
* \param positionPtr Position of the billboards
* \param sizePtr Sizes of the billboards
* \param sinCosPtr Rotation of the billboards if null, Vector2f(0.f, 1.f) is used
* \param colorPtr Color of the billboards if null, Color::White is used
*
* \remark Produces a NazaraAssert if material is invalid
*/
void ForwardRenderQueue::AddBillboards(int renderOrder, const Material* material, unsigned int count, SparsePtr<const Vector3f> positionPtr, SparsePtr<const Vector2f> sizePtr, SparsePtr<const Vector2f> sinCosPtr, SparsePtr<const Color> colorPtr)
{
NazaraAssert(material, "Invalid material");
Vector2f defaultSinCos(0.f, 1.f); // sin(0) = 0, cos(0) = 1
if (!sinCosPtr)
sinCosPtr.Reset(&defaultSinCos, 0); // The trick here is to put the stride to zero, which leads the pointer to be immobile
if (!colorPtr)
colorPtr.Reset(&Color::White, 0); // Same
BillboardData* billboardData = GetBillboardData(renderOrder, material, count);
for (unsigned int i = 0; i < count; ++i)
{
billboardData->center = *positionPtr++;
billboardData->color = *colorPtr++;
billboardData->sinCos = *sinCosPtr++;
billboardData->size = *sizePtr++;
billboardData++;
}
}
/*!
* \brief Adds multiple billboards to the queue
*
* \param renderOrder Order of rendering
* \param material Material of the billboards
* \param count Number of billboards
* \param positionPtr Position of the billboards
* \param sizePtr Sizes of the billboards
* \param sinCosPtr Rotation of the billboards if null, Vector2f(0.f, 1.f) is used
* \param alphaPtr Alpha parameters of the billboards if null, 1.f is used
*
* \remark Produces a NazaraAssert if material is invalid
*/
void ForwardRenderQueue::AddBillboards(int renderOrder, const Material* material, unsigned int count, SparsePtr<const Vector3f> positionPtr, SparsePtr<const Vector2f> sizePtr, SparsePtr<const Vector2f> sinCosPtr, SparsePtr<const float> alphaPtr)
{
NazaraAssert(material, "Invalid material");
Vector2f defaultSinCos(0.f, 1.f); // sin(0) = 0, cos(0) = 1
if (!sinCosPtr)
sinCosPtr.Reset(&defaultSinCos, 0); // The trick here is to put the stride to zero, which leads the pointer to be immobile
float defaultAlpha = 1.f;
if (!alphaPtr)
alphaPtr.Reset(&defaultAlpha, 0); // Same
BillboardData* billboardData = GetBillboardData(renderOrder, material, count);
for (unsigned int i = 0; i < count; ++i)
{
billboardData->center = *positionPtr++;
billboardData->color = Color(255, 255, 255, static_cast<UInt8>(255.f * (*alphaPtr++)));
billboardData->sinCos = *sinCosPtr++;
billboardData->size = *sizePtr++;
billboardData++;
}
}
/*!
* \brief Adds multiple billboards to the queue
*
* \param renderOrder Order of rendering
* \param material Material of the billboards
* \param count Number of billboards
* \param positionPtr Position of the billboards
* \param sizePtr Sizes of the billboards
* \param anglePtr Rotation of the billboards if null, 0.f is used
* \param colorPtr Color of the billboards if null, Color::White is used
*
* \remark Produces a NazaraAssert if material is invalid
*/
void ForwardRenderQueue::AddBillboards(int renderOrder, const Material* material, unsigned int count, SparsePtr<const Vector3f> positionPtr, SparsePtr<const Vector2f> sizePtr, SparsePtr<const float> anglePtr, SparsePtr<const Color> colorPtr)
{
NazaraAssert(material, "Invalid material");
float defaultRotation = 0.f;
if (!anglePtr)
anglePtr.Reset(&defaultRotation, 0); // The trick here is to put the stride to zero, which leads the pointer to be immobile
if (!colorPtr)
colorPtr.Reset(&Color::White, 0); // Same
BillboardData* billboardData = GetBillboardData(renderOrder, material, count);
for (unsigned int i = 0; i < count; ++i)
{
float sin = std::sin(ToRadians(*anglePtr));
float cos = std::cos(ToRadians(*anglePtr));
anglePtr++;
billboardData->center = *positionPtr++;
billboardData->color = *colorPtr++;
billboardData->sinCos.Set(sin, cos);
billboardData->size = *sizePtr++;
billboardData++;
}
}
/*!
* \brief Adds multiple billboards to the queue
*
* \param renderOrder Order of rendering
* \param material Material of the billboards
* \param count Number of billboards
* \param positionPtr Position of the billboards
* \param sizePtr Sizes of the billboards
* \param anglePtr Rotation of the billboards if null, 0.f is used
* \param alphaPtr Alpha parameters of the billboards if null, 1.f is used
*
* \remark Produces a NazaraAssert if material is invalid
*/
void ForwardRenderQueue::AddBillboards(int renderOrder, const Material* material, unsigned int count, SparsePtr<const Vector3f> positionPtr, SparsePtr<const Vector2f> sizePtr, SparsePtr<const float> anglePtr, SparsePtr<const float> alphaPtr)
{
NazaraAssert(material, "Invalid material");
float defaultRotation = 0.f;
if (!anglePtr)
anglePtr.Reset(&defaultRotation, 0); // The trick here is to put the stride to zero, which leads the pointer to be immobile
float defaultAlpha = 1.f;
if (!alphaPtr)
alphaPtr.Reset(&defaultAlpha, 0); // Same
BillboardData* billboardData = GetBillboardData(renderOrder, material, count);
for (unsigned int i = 0; i < count; ++i)
{
float sin = std::sin(ToRadians(*anglePtr));
float cos = std::cos(ToRadians(*anglePtr));
anglePtr++;
billboardData->center = *positionPtr++;
billboardData->color = Color(255, 255, 255, static_cast<UInt8>(255.f * (*alphaPtr++)));
billboardData->sinCos.Set(sin, cos);
billboardData->size = *sizePtr++;
billboardData++;
}
}
/*!
* \brief Adds multiple billboards to the queue
*
* \param renderOrder Order of rendering
* \param material Material of the billboards
* \param count Number of billboards
* \param positionPtr Position of the billboards
* \param sizePtr Size of the billboards
* \param sinCosPtr Rotation of the billboards if null, Vector2f(0.f, 1.f) is used
* \param colorPtr Color of the billboards if null, Color::White is used
*
* \remark Produces a NazaraAssert if material is invalid
*/
void ForwardRenderQueue::AddBillboards(int renderOrder, const Material* material, unsigned int count, SparsePtr<const Vector3f> positionPtr, SparsePtr<const float> sizePtr, SparsePtr<const Vector2f> sinCosPtr, SparsePtr<const Color> colorPtr)
{
NazaraAssert(material, "Invalid material");
Vector2f defaultSinCos(0.f, 1.f); // sin(0) = 0, cos(0) = 1
if (!sinCosPtr)
sinCosPtr.Reset(&defaultSinCos, 0); // The trick here is to put the stride to zero, which leads the pointer to be immobile
if (!colorPtr)
colorPtr.Reset(&Color::White, 0); // Same
BillboardData* billboardData = GetBillboardData(renderOrder, material, count);
for (unsigned int i = 0; i < count; ++i)
{
billboardData->center = *positionPtr++;
billboardData->color = *colorPtr++;
billboardData->sinCos = *sinCosPtr++;
billboardData->size.Set(*sizePtr++);
billboardData++;
}
}
/*!
* \brief Adds multiple billboards to the queue
*
* \param renderOrder Order of rendering
* \param material Material of the billboards
* \param count Number of billboards
* \param positionPtr Position of the billboards
* \param sizePtr Size of the billboards
* \param sinCosPtr Rotation of the billboards if null, Vector2f(0.f, 1.f) is used
* \param alphaPtr Alpha parameters of the billboards if null, 1.f is used
*
* \remark Produces a NazaraAssert if material is invalid
*/
void ForwardRenderQueue::AddBillboards(int renderOrder, const Material* material, unsigned int count, SparsePtr<const Vector3f> positionPtr, SparsePtr<const float> sizePtr, SparsePtr<const Vector2f> sinCosPtr, SparsePtr<const float> alphaPtr)
{
NazaraAssert(material, "Invalid material");
Vector2f defaultSinCos(0.f, 1.f); // sin(0) = 0, cos(0) = 1
if (!sinCosPtr)
sinCosPtr.Reset(&defaultSinCos, 0); // The trick here is to put the stride to zero, which leads the pointer to be immobile
float defaultAlpha = 1.f;
if (!alphaPtr)
alphaPtr.Reset(&defaultAlpha, 0); // Same
BillboardData* billboardData = GetBillboardData(renderOrder, material, count);
for (unsigned int i = 0; i < count; ++i)
{
billboardData->center = *positionPtr++;
billboardData->color = Color(255, 255, 255, static_cast<UInt8>(255.f * (*alphaPtr++)));
billboardData->sinCos = *sinCosPtr++;
billboardData->size.Set(*sizePtr++);
billboardData++;
}
}
/*!
* \brief Adds multiple billboards to the queue
*
* \param renderOrder Order of rendering
* \param material Material of the billboards
* \param count Number of billboards
* \param positionPtr Position of the billboards
* \param sizePtr Size of the billboards
* \param anglePtr Rotation of the billboards if null, 0.f is used
* \param colorPtr Color of the billboards if null, Color::White is used
*
* \remark Produces a NazaraAssert if material is invalid
*/
void ForwardRenderQueue::AddBillboards(int renderOrder, const Material* material, unsigned int count, SparsePtr<const Vector3f> positionPtr, SparsePtr<const float> sizePtr, SparsePtr<const float> anglePtr, SparsePtr<const Color> colorPtr)
{
NazaraAssert(material, "Invalid material");
float defaultRotation = 0.f;
if (!anglePtr)
anglePtr.Reset(&defaultRotation, 0); // The trick here is to put the stride to zero, which leads the pointer to be immobile
if (!colorPtr)
colorPtr.Reset(&Color::White, 0); // Same
BillboardData* billboardData = GetBillboardData(renderOrder, material, count);
for (unsigned int i = 0; i < count; ++i)
{
float sin = std::sin(ToRadians(*anglePtr));
float cos = std::cos(ToRadians(*anglePtr));
anglePtr++;
billboardData->center = *positionPtr++;
billboardData->color = *colorPtr++;
billboardData->sinCos.Set(sin, cos);
billboardData->size.Set(*sizePtr++);
billboardData++;
}
}
/*!
* \brief Adds multiple billboards to the queue
*
* \param renderOrder Order of rendering
* \param material Material of the billboards
* \param count Number of billboards
* \param positionPtr Position of the billboards
* \param sizePtr Size of the billboards
* \param anglePtr Rotation of the billboards if null, 0.f is used
* \param alphaPtr Alpha parameters of the billboards if null, 1.f is used
*
* \remark Produces a NazaraAssert if material is invalid
*/
void ForwardRenderQueue::AddBillboards(int renderOrder, const Material* material, unsigned int count, SparsePtr<const Vector3f> positionPtr, SparsePtr<const float> sizePtr, SparsePtr<const float> anglePtr, SparsePtr<const float> alphaPtr)
{
NazaraAssert(material, "Invalid material");
float defaultRotation = 0.f;
if (!anglePtr)
anglePtr.Reset(&defaultRotation, 0); // The trick here is to put the stride to zero, which leads the pointer to be immobile
float defaultAlpha = 1.f;
if (!alphaPtr)
alphaPtr.Reset(&defaultAlpha, 0); // Same
BillboardData* billboardData = GetBillboardData(renderOrder, material, count);
for (unsigned int i = 0; i < count; ++i)
{
float sin = std::sin(ToRadians(*anglePtr));
float cos = std::cos(ToRadians(*anglePtr));
anglePtr++;
billboardData->center = *positionPtr++;
billboardData->color = Color(255, 255, 255, static_cast<UInt8>(255.f * (*alphaPtr++)));
billboardData->sinCos.Set(sin, cos);
billboardData->size.Set(*sizePtr++);
billboardData++;
}
}
/*!
* \brief Adds drawable to the queue
*
* \param renderOrder Order of rendering
* \param drawable Drawable user defined
*
* \remark Produces a NazaraError if drawable is invalid
*/
void ForwardRenderQueue::AddDrawable(int renderOrder, const Drawable* drawable)
{
#if NAZARA_GRAPHICS_SAFE
if (!drawable)
{
NazaraError("Invalid drawable");
return;
}
#endif
auto& otherDrawables = GetLayer(renderOrder).otherDrawables;
otherDrawables.push_back(drawable);
}
/*!
* \brief Adds mesh to the queue
*
* \param renderOrder Order of rendering
* \param material Material of the mesh
* \param meshData Data of the mesh
* \param meshAABB Box of the mesh
* \param transformMatrix Matrix of the mesh
*
* \remark Produces a NazaraAssert if material is invalid
*/
void ForwardRenderQueue::AddMesh(int renderOrder, const Material* material, const MeshData& meshData, const Boxf& meshAABB, const Matrix4f& transformMatrix)
{
NazaraAssert(material, "Invalid material");
if (material->IsDepthSortingEnabled())
{
Layer& currentLayer = GetLayer(renderOrder);
auto& transparentMeshes = currentLayer.depthSortedMeshes;
auto& transparentData = currentLayer.depthSortedMeshData;
// The material is marked for depth sorting, we must draw this mesh using another way (after the rendering of opaques objects while sorting them)
std::size_t index = transparentData.size();
transparentData.resize(index+1);
UnbatchedModelData& data = transparentData.back();
data.material = material;
data.meshData = meshData;
data.obbSphere = Spheref(transformMatrix.GetTranslation() + meshAABB.GetCenter(), meshAABB.GetSquaredRadius());
data.transformMatrix = transformMatrix;
transparentMeshes.push_back(index);
}
else
{
Layer& currentLayer = GetLayer(renderOrder);
MeshPipelineBatches& opaqueModels = currentLayer.opaqueModels;
const MaterialPipeline* materialPipeline = material->GetPipeline();
auto pipelineIt = opaqueModels.find(materialPipeline);
if (pipelineIt == opaqueModels.end())
{
BatchedMaterialEntry materialEntry;
pipelineIt = opaqueModels.insert(MeshPipelineBatches::value_type(materialPipeline, std::move(materialEntry))).first;
}
BatchedMaterialEntry& materialEntry = pipelineIt->second;
MeshMaterialBatches& materialMap = materialEntry.materialMap;
auto materialIt = materialMap.find(material);
if (materialIt == materialMap.end())
{
BatchedModelEntry entry;
entry.materialReleaseSlot.Connect(material->OnMaterialRelease, this, &ForwardRenderQueue::OnMaterialInvalidation);
materialIt = materialMap.insert(MeshMaterialBatches::value_type(material, std::move(entry))).first;
}
BatchedModelEntry& entry = materialIt->second;
entry.enabled = true;
MeshInstanceContainer& meshMap = entry.meshMap;
auto it2 = meshMap.find(meshData);
if (it2 == meshMap.end())
{
MeshInstanceEntry instanceEntry;
instanceEntry.squaredBoundingSphere = meshAABB.GetSquaredBoundingSphere();
if (meshData.indexBuffer)
instanceEntry.indexBufferReleaseSlot.Connect(meshData.indexBuffer->OnIndexBufferRelease, this, &ForwardRenderQueue::OnIndexBufferInvalidation);
instanceEntry.vertexBufferReleaseSlot.Connect(meshData.vertexBuffer->OnVertexBufferRelease, this, &ForwardRenderQueue::OnVertexBufferInvalidation);
it2 = meshMap.insert(std::make_pair(meshData, std::move(instanceEntry))).first;
}
std::vector<Matrix4f>& instances = it2->second.instances;
instances.push_back(transformMatrix);
materialEntry.maxInstanceCount = std::max(materialEntry.maxInstanceCount, instances.size());
}
}
/*!
* \brief Adds sprites to the queue
*
* \param renderOrder Order of rendering
* \param material Material of the sprites
* \param vertices Buffer of data for the sprites
* \param spriteCount Number of sprites
* \param overlay Texture of the sprites
*
* \remark Produces a NazaraAssert if material is invalid
*/
void ForwardRenderQueue::AddSprites(int renderOrder, const Material* material, const VertexStruct_XYZ_Color_UV* vertices, std::size_t spriteCount, const Texture* overlay)
{
NazaraAssert(material, "Invalid material");
Layer& currentLayer = GetLayer(renderOrder);
if (material->IsDepthSortingEnabled())
{
auto& transparentSprites = currentLayer.depthSortedSprites;
auto& transparentData = currentLayer.depthSortedSpriteData;
// The material is marked for depth sorting, we must draw this mesh using another way (after the rendering of opaques objects while sorting them)
std::size_t index = transparentData.size();
transparentData.resize(index + 1);
UnbatchedSpriteData& data = transparentData.back();
data.material = material;
data.overlay = overlay;
data.spriteCount = spriteCount;
data.vertices = vertices;
transparentSprites.push_back(index);
}
else
{
SpritePipelineBatches& sprites = currentLayer.opaqueSprites;
const MaterialPipeline* materialPipeline = material->GetPipeline();
auto pipelineIt = sprites.find(materialPipeline);
if (pipelineIt == sprites.end())
{
BatchedSpritePipelineEntry materialEntry;
pipelineIt = sprites.insert(SpritePipelineBatches::value_type(materialPipeline, std::move(materialEntry))).first;
}
BatchedSpritePipelineEntry& pipelineEntry = pipelineIt->second;
pipelineEntry.enabled = true;
SpriteMaterialBatches& materialMap = pipelineEntry.materialMap;
auto matIt = materialMap.find(material);
if (matIt == materialMap.end())
{
BatchedBasicSpriteEntry entry;
entry.materialReleaseSlot.Connect(material->OnMaterialRelease, this, &ForwardRenderQueue::OnMaterialInvalidation);
matIt = materialMap.insert(SpriteMaterialBatches::value_type(material, std::move(entry))).first;
}
BatchedBasicSpriteEntry& entry = matIt->second;
entry.enabled = true;
auto& overlayMap = entry.overlayMap;
auto overlayIt = overlayMap.find(overlay);
if (overlayIt == overlayMap.end())
{
BatchedSpriteEntry overlayEntry;
if (overlay)
overlayEntry.textureReleaseSlot.Connect(overlay->OnTextureRelease, this, &ForwardRenderQueue::OnTextureInvalidation);
overlayIt = overlayMap.insert(std::make_pair(overlay, std::move(overlayEntry))).first;
}
auto& spriteVector = overlayIt->second.spriteChains;
spriteVector.push_back(SpriteChain_XYZ_Color_UV({vertices, spriteCount}));
}
}
/*!
* \brief Clears the queue
*
* \param fully Should everything be cleared or we can keep layers
*/
void ForwardRenderQueue::Clear(bool fully)
{
AbstractRenderQueue::Clear(fully);
if (fully)
layers.clear();
else
{
for (auto it = layers.begin(); it != layers.end();)
{
Layer& layer = it->second;
if (layer.clearCount++ >= 100)
layers.erase(it++);
else
{
for (auto& pipelinePair : layer.billboards)
{
auto& pipelineEntry = pipelinePair.second;
if (pipelineEntry.enabled)
{
for (auto& matIt : pipelinePair.second.materialMap)
{
auto& entry = matIt.second;
auto& billboardVector = entry.billboards;
billboardVector.clear();
}
}
pipelineEntry.enabled = false;
}
for (auto& pipelinePair : layer.opaqueSprites)
{
auto& pipelineEntry = pipelinePair.second;
if (pipelineEntry.enabled)
{
for (auto& materialPair : pipelineEntry.materialMap)
{
auto& matEntry = materialPair.second;
if (matEntry.enabled)
{
auto& overlayMap = matEntry.overlayMap;
for (auto& overlayIt : overlayMap)
{
auto& spriteChainVector = overlayIt.second.spriteChains;
spriteChainVector.clear();
}
matEntry.enabled = false;
}
}
pipelineEntry.enabled = false;
}
}
for (auto& pipelinePair : layer.opaqueModels)
{
auto& pipelineEntry = pipelinePair.second;
if (pipelineEntry.maxInstanceCount > 0)
{
for (auto& materialPair : pipelineEntry.materialMap)
{
auto& matEntry = materialPair.second;
if (matEntry.enabled)
{
MeshInstanceContainer& meshInstances = matEntry.meshMap;
for (auto& meshIt : meshInstances)
{
auto& meshEntry = meshIt.second;
meshEntry.instances.clear();
}
matEntry.enabled = false;
}
}
pipelineEntry.maxInstanceCount = 0;
}
}
layer.depthSortedMeshes.clear();
layer.depthSortedMeshData.clear();
layer.depthSortedSpriteData.clear();
layer.depthSortedSprites.clear();
layer.otherDrawables.clear();
++it;
}
}
}
}
/*!
* \brief Sorts the object according to the viewer position, furthest to nearest
*
* \param viewer Viewer of the scene
*/
void ForwardRenderQueue::Sort(const AbstractViewer* viewer)
{
if (viewer->GetProjectionType() == ProjectionType_Orthogonal)
SortForOrthographic(viewer);
else
SortForPerspective(viewer);
}
/*!
* \brief Gets the billboard data
* \return Pointer to the data of the billboards
*
* \param renderOrder Order of rendering
* \param material Material of the billboard
*/
ForwardRenderQueue::BillboardData* ForwardRenderQueue::GetBillboardData(int renderOrder, const Material* material, unsigned int count)
{
auto& billboards = GetLayer(renderOrder).billboards;
const MaterialPipeline* materialPipeline = material->GetPipeline();
auto pipelineIt = billboards.find(materialPipeline);
if (pipelineIt == billboards.end())
{
BatchedBillboardPipelineEntry pipelineEntry;
pipelineIt = billboards.insert(BillboardPipelineBatches::value_type(materialPipeline, std::move(pipelineEntry))).first;
}
BatchedBillboardPipelineEntry& pipelineEntry = pipelineIt->second;
pipelineEntry.enabled = true;
BatchedBillboardContainer& materialMap = pipelineEntry.materialMap;
auto it = materialMap.find(material);
if (it == materialMap.end())
{
BatchedBillboardEntry entry;
entry.materialReleaseSlot.Connect(material->OnMaterialRelease, this, &ForwardRenderQueue::OnMaterialInvalidation);
it = materialMap.insert(BatchedBillboardContainer::value_type(material, std::move(entry))).first;
}
BatchedBillboardEntry& entry = it->second;
auto& billboardVector = entry.billboards;
std::size_t prevSize = billboardVector.size();
billboardVector.resize(prevSize + count);
return &billboardVector[prevSize];
}
/*!
* \brief Gets the ith layer
* \return Reference to the ith layer for the queue
*
* \param i Index of the layer
*/
ForwardRenderQueue::Layer& ForwardRenderQueue::GetLayer(int i)
{
auto it = layers.find(i);
if (it == layers.end())
it = layers.insert(std::make_pair(i, Layer())).first;
Layer& layer = it->second;
layer.clearCount = 0;
return layer;
}
void ForwardRenderQueue::SortBillboards(Layer& layer, const Planef& nearPlane)
{
for (auto& pipelinePair : layer.billboards)
{
for (auto& matPair : pipelinePair.second.materialMap)
{
const Material* mat = matPair.first;
if (mat->IsDepthSortingEnabled())
{
BatchedBillboardEntry& entry = matPair.second;
auto& billboardVector = entry.billboards;
std::sort(billboardVector.begin(), billboardVector.end(), [&nearPlane] (const BillboardData& data1, const BillboardData& data2)
{
return nearPlane.Distance(data1.center) > nearPlane.Distance(data2.center);
});
}
}
}
}
void ForwardRenderQueue::SortForOrthographic(const AbstractViewer * viewer)
{
Planef nearPlane = viewer->GetFrustum().GetPlane(FrustumPlane_Near);
for (auto& pair : layers)
{
Layer& layer = pair.second;
std::sort(layer.depthSortedMeshes.begin(), layer.depthSortedMeshes.end(), [&layer, &nearPlane] (std::size_t index1, std::size_t index2)
{
const Spheref& sphere1 = layer.depthSortedMeshData[index1].obbSphere;
const Spheref& sphere2 = layer.depthSortedMeshData[index2].obbSphere;
return nearPlane.Distance(sphere1.GetPosition()) < nearPlane.Distance(sphere2.GetPosition());
});
std::sort(layer.depthSortedSprites.begin(), layer.depthSortedSprites.end(), [&layer, &nearPlane] (std::size_t index1, std::size_t index2)
{
const Vector3f& pos1 = layer.depthSortedSpriteData[index1].vertices[0].position;
const Vector3f& pos2 = layer.depthSortedSpriteData[index2].vertices[0].position;
return nearPlane.Distance(pos1) < nearPlane.Distance(pos2);
});
SortBillboards(layer, nearPlane);
}
}
void ForwardRenderQueue::SortForPerspective(const AbstractViewer* viewer)
{
Planef nearPlane = viewer->GetFrustum().GetPlane(FrustumPlane_Near);
Vector3f viewerPos = viewer->GetEyePosition();
for (auto& pair : layers)
{
Layer& layer = pair.second;
std::sort(layer.depthSortedMeshes.begin(), layer.depthSortedMeshes.end(), [&layer, &viewerPos] (std::size_t index1, std::size_t index2)
{
const Spheref& sphere1 = layer.depthSortedMeshData[index1].obbSphere;
const Spheref& sphere2 = layer.depthSortedMeshData[index2].obbSphere;
return viewerPos.SquaredDistance(sphere1.GetPosition()) > viewerPos.SquaredDistance(sphere2.GetPosition());
});
std::sort(layer.depthSortedSprites.begin(), layer.depthSortedSprites.end(), [&layer, &viewerPos] (std::size_t index1, std::size_t index2)
{
const Vector3f& pos1 = layer.depthSortedSpriteData[index1].vertices[0].position;
const Vector3f& pos2 = layer.depthSortedSpriteData[index2].vertices[0].position;
return viewerPos.SquaredDistance(pos1) > viewerPos.SquaredDistance(pos2);
});
SortBillboards(layer, nearPlane);
}
}
/*!
* \brief Handle the invalidation of an index buffer
*
* \param indexBuffer Index buffer being invalidated
*/
void ForwardRenderQueue::OnIndexBufferInvalidation(const IndexBuffer* indexBuffer)
{
for (auto& pair : layers)
{
Layer& layer = pair.second;
for (auto& pipelineEntry : layer.opaqueModels)
{
for (auto& materialEntry : pipelineEntry.second.materialMap)
{
MeshInstanceContainer& meshes = materialEntry.second.meshMap;
for (auto it = meshes.begin(); it != meshes.end();)
{
const MeshData& renderData = it->first;
if (renderData.indexBuffer == indexBuffer)
it = meshes.erase(it);
else
++it;
}
}
}
}
}
/*!
* \brief Handle the invalidation of a material
*
* \param material Material being invalidated
*/
void ForwardRenderQueue::OnMaterialInvalidation(const Material* material)
{
for (auto& pair : layers)
{
Layer& layer = pair.second;
for (auto& pipelineEntry : layer.opaqueSprites)
pipelineEntry.second.materialMap.erase(material);
for (auto& pipelineEntry : layer.billboards)
pipelineEntry.second.materialMap.erase(material);
for (auto& pipelineEntry : layer.opaqueModels)
pipelineEntry.second.materialMap.erase(material);
}
}
/*!
* \brief Handle the invalidation of a texture
*
* \param texture Texture being invalidated
*/
void ForwardRenderQueue::OnTextureInvalidation(const Texture* texture)
{
for (auto& pair : layers)
{
Layer& layer = pair.second;
for (auto& pipelineEntry : layer.opaqueSprites)
{
for (auto& materialEntry : pipelineEntry.second.materialMap)
materialEntry.second.overlayMap.erase(texture);
}
}
}
/*!
* \brief Handle the invalidation of a vertex buffer
*
* \param vertexBuffer Vertex buffer being invalidated
*/
void ForwardRenderQueue::OnVertexBufferInvalidation(const VertexBuffer* vertexBuffer)
{
for (auto& pair : layers)
{
Layer& layer = pair.second;
for (auto& pipelineEntry : layer.opaqueModels)
{
for (auto& materialEntry : pipelineEntry.second.materialMap)
{
MeshInstanceContainer& meshes = materialEntry.second.meshMap;
for (auto it = meshes.begin(); it != meshes.end();)
{
const MeshData& renderData = it->first;
if (renderData.vertexBuffer == vertexBuffer)
it = meshes.erase(it);
else
++it;
}
}
}
}
}
bool ForwardRenderQueue::MaterialComparator::operator()(const Material* mat1, const Material* mat2) const
{
const Texture* diffuseMap1 = mat1->GetDiffuseMap();
const Texture* diffuseMap2 = mat2->GetDiffuseMap();
if (diffuseMap1 != diffuseMap2)
return diffuseMap1 < diffuseMap2;
return mat1 < mat2;
}
bool ForwardRenderQueue::MaterialPipelineComparator::operator()(const MaterialPipeline* pipeline1, const MaterialPipeline* pipeline2) const
{
const Shader* shader1 = pipeline1->GetInstance().renderPipeline.GetInfo().shader;
const Shader* shader2 = pipeline2->GetInstance().renderPipeline.GetInfo().shader;
if (shader1 != shader2)
return shader1 < shader2;
return pipeline1 < pipeline2;
}
/*!
* \brief Functor to compare two mesh data
* \return true If first mesh is "smaller" than the second one
*
* \param data1 First mesh to compare
* \param data2 Second mesh to compare
*/
bool ForwardRenderQueue::MeshDataComparator::operator()(const MeshData& data1, const MeshData& data2) const
{
const Buffer* buffer1;
const Buffer* buffer2;
buffer1 = (data1.indexBuffer) ? data1.indexBuffer->GetBuffer() : nullptr;
buffer2 = (data2.indexBuffer) ? data2.indexBuffer->GetBuffer() : nullptr;
if (buffer1 != buffer2)
return buffer1 < buffer2;
buffer1 = data1.vertexBuffer->GetBuffer();
buffer2 = data2.vertexBuffer->GetBuffer();
if (buffer1 != buffer2)
return buffer1 < buffer2;
return data1.primitiveMode < data2.primitiveMode;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -156,6 +156,21 @@ namespace Nz
Font::SetDefaultAtlas(std::make_shared<GuillotineTextureAtlas>());
// Textures
std::array<UInt8, 6> whitePixels = { { 255, 255, 255, 255, 255, 255 } };
Nz::TextureRef whiteTexture = Nz::Texture::New();
whiteTexture->Create(ImageType_2D, PixelFormatType_L8, 1, 1);
whiteTexture->Update(whitePixels.data());
TextureLibrary::Register("White2D", std::move(whiteTexture));
Nz::TextureRef whiteCubemap = Nz::Texture::New();
whiteCubemap->Create(ImageType_Cubemap, PixelFormatType_L8, 1, 1);
whiteCubemap->Update(whitePixels.data());
TextureLibrary::Register("WhiteCubemap", std::move(whiteCubemap));
onExit.Reset();
NazaraNotice("Initialized: Graphics module");
@@ -217,6 +232,10 @@ namespace Nz
defaultAtlas.reset();
// Textures
TextureLibrary::Unregister("White2D");
TextureLibrary::Unregister("WhiteCubemap");
// Loaders
Loaders::UnregisterMesh();
Loaders::UnregisterTexture();

View File

@@ -160,7 +160,7 @@ namespace Nz
OverrideShader("Shaders/Basic/core.vert", &vertexShader);
#endif
uberShader->SetShader(ShaderStageType_Fragment, fragmentShader, "FLAG_TEXTUREOVERLAY ALPHA_MAPPING ALPHA_TEST AUTO_TEXCOORDS DIFFUSE_MAPPING");
uberShader->SetShader(ShaderStageType_Fragment, fragmentShader, "FLAG_TEXTUREOVERLAY ALPHA_MAPPING ALPHA_TEST AUTO_TEXCOORDS DIFFUSE_MAPPING TEXTURE_MAPPING");
uberShader->SetShader(ShaderStageType_Vertex, vertexShader, "FLAG_BILLBOARD FLAG_INSTANCING FLAG_VERTEXCOLOR TEXTURE_MAPPING TRANSFORM UNIFORM_VERTEX_DEPTH");
UberShaderLibrary::Register("Basic", uberShader);
@@ -188,17 +188,19 @@ namespace Nz
MaterialPipelineInfo pipelineInfo;
pipelineInfo.uberShader = UberShaderLibrary::Get("Basic");
// Basic 2D - No depth write/face culling
// Basic 2D - No depth write/face culling with scissoring
pipelineInfo.depthWrite = false;
pipelineInfo.faceCulling = false;
pipelineInfo.scissorTest = true;
MaterialPipelineLibrary::Register("Basic2D", GetPipeline(pipelineInfo));
// Translucent 2D - Alpha blending with no depth write/face culling
// Translucent 2D - Alpha blending with no depth write/face culling and scissoring
pipelineInfo.blending = true;
pipelineInfo.depthWrite = false;
pipelineInfo.faceCulling = false;
pipelineInfo.depthSorting = true;
pipelineInfo.depthSorting = false;
pipelineInfo.scissorTest = true;
pipelineInfo.dstBlend = BlendFunc_InvSrcAlpha;
pipelineInfo.srcBlend = BlendFunc_SrcAlpha;
@@ -210,6 +212,7 @@ namespace Nz
pipelineInfo.depthWrite = false;
pipelineInfo.faceCulling = false;
pipelineInfo.depthSorting = true;
pipelineInfo.scissorTest = false;
pipelineInfo.dstBlend = BlendFunc_InvSrcAlpha;
pipelineInfo.srcBlend = BlendFunc_SrcAlpha;

View File

@@ -52,7 +52,7 @@ namespace Nz
* \param instanceData Data used for this instance
*/
void Model::AddToRenderQueue(AbstractRenderQueue* renderQueue, const InstanceData& instanceData) const
void Model::AddToRenderQueue(AbstractRenderQueue* renderQueue, const InstanceData& instanceData, const Recti& scissorRect) const
{
unsigned int submeshCount = m_mesh->GetSubMeshCount();
for (unsigned int i = 0; i < submeshCount; ++i)
@@ -65,7 +65,7 @@ namespace Nz
meshData.primitiveMode = mesh->GetPrimitiveMode();
meshData.vertexBuffer = mesh->GetVertexBuffer();
renderQueue->AddMesh(instanceData.renderOrder, material, meshData, mesh->GetAABB(), instanceData.transformMatrix);
renderQueue->AddMesh(instanceData.renderOrder, material, meshData, mesh->GetAABB(), instanceData.transformMatrix, scissorRect);
}
}

View File

@@ -0,0 +1,18 @@
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Engine - Graphics module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Graphics/RenderQueue.hpp>
#include <Nazara/Core/TaskScheduler.hpp>
#include <Nazara/Graphics/Debug.hpp>
namespace Nz
{
void RenderQueueInternal::Sort()
{
std::sort(m_orderedRenderQueue.begin(), m_orderedRenderQueue.end(), [](const RenderDataPair& lhs, const RenderDataPair& rhs)
{
return lhs.first < rhs.first;
});
}
}

View File

@@ -24,7 +24,7 @@ void main()
#if AUTO_TEXCOORDS
vec2 texCoord = gl_FragCoord.xy * InvTargetSize;
#else
#elif TEXTURE_MAPPING
vec2 texCoord = vTexCoord;
#endif

View File

@@ -1 +1 @@
35,105,102,32,69,65,82,76,89,95,70,82,65,71,77,69,78,84,95,84,69,83,84,83,32,38,38,32,33,65,76,80,72,65,95,84,69,83,84,10,108,97,121,111,117,116,40,101,97,114,108,121,95,102,114,97,103,109,101,110,116,95,116,101,115,116,115,41,32,105,110,59,10,35,101,110,100,105,102,10,10,47,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,69,110,116,114,97,110,116,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,47,10,105,110,32,118,101,99,52,32,118,67,111,108,111,114,59,10,105,110,32,118,101,99,50,32,118,84,101,120,67,111,111,114,100,59,10,10,47,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,83,111,114,116,97,110,116,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,47,10,111,117,116,32,118,101,99,52,32,82,101,110,100,101,114,84,97,114,103,101,116,48,59,10,10,47,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,85,110,105,102,111,114,109,101,115,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,47,10,117,110,105,102,111,114,109,32,118,101,99,50,32,73,110,118,84,97,114,103,101,116,83,105,122,101,59,10,117,110,105,102,111,114,109,32,115,97,109,112,108,101,114,50,68,32,77,97,116,101,114,105,97,108,65,108,112,104,97,77,97,112,59,10,117,110,105,102,111,114,109,32,102,108,111,97,116,32,77,97,116,101,114,105,97,108,65,108,112,104,97,84,104,114,101,115,104,111,108,100,59,10,117,110,105,102,111,114,109,32,118,101,99,52,32,77,97,116,101,114,105,97,108,68,105,102,102,117,115,101,59,10,117,110,105,102,111,114,109,32,115,97,109,112,108,101,114,50,68,32,77,97,116,101,114,105,97,108,68,105,102,102,117,115,101,77,97,112,59,10,117,110,105,102,111,114,109,32,115,97,109,112,108,101,114,50,68,32,84,101,120,116,117,114,101,79,118,101,114,108,97,121,59,10,10,47,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,70,111,110,99,116,105,111,110,115,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,47,10,118,111,105,100,32,109,97,105,110,40,41,10,123,10,9,118,101,99,52,32,102,114,97,103,109,101,110,116,67,111,108,111,114,32,61,32,77,97,116,101,114,105,97,108,68,105,102,102,117,115,101,32,42,32,118,67,111,108,111,114,59,10,10,35,105,102,32,65,85,84,79,95,84,69,88,67,79,79,82,68,83,10,9,118,101,99,50,32,116,101,120,67,111,111,114,100,32,61,32,103,108,95,70,114,97,103,67,111,111,114,100,46,120,121,32,42,32,73,110,118,84,97,114,103,101,116,83,105,122,101,59,10,35,101,108,115,101,10,9,118,101,99,50,32,116,101,120,67,111,111,114,100,32,61,32,118,84,101,120,67,111,111,114,100,59,10,35,101,110,100,105,102,10,10,35,105,102,32,68,73,70,70,85,83,69,95,77,65,80,80,73,78,71,10,9,102,114,97,103,109,101,110,116,67,111,108,111,114,32,42,61,32,116,101,120,116,117,114,101,40,77,97,116,101,114,105,97,108,68,105,102,102,117,115,101,77,97,112,44,32,116,101,120,67,111,111,114,100,41,59,10,35,101,110,100,105,102,10,10,35,105,102,32,65,76,80,72,65,95,77,65,80,80,73,78,71,10,9,102,114,97,103,109,101,110,116,67,111,108,111,114,46,97,32,42,61,32,116,101,120,116,117,114,101,40,77,97,116,101,114,105,97,108,65,108,112,104,97,77,97,112,44,32,116,101,120,67,111,111,114,100,41,46,114,59,10,35,101,110,100,105,102,10,10,35,105,102,32,70,76,65,71,95,84,69,88,84,85,82,69,79,86,69,82,76,65,89,10,9,102,114,97,103,109,101,110,116,67,111,108,111,114,32,42,61,32,116,101,120,116,117,114,101,40,84,101,120,116,117,114,101,79,118,101,114,108,97,121,44,32,116,101,120,67,111,111,114,100,41,59,10,35,101,110,100,105,102,10,10,35,105,102,32,65,76,80,72,65,95,84,69,83,84,10,9,105,102,32,40,102,114,97,103,109,101,110,116,67,111,108,111,114,46,97,32,60,32,77,97,116,101,114,105,97,108,65,108,112,104,97,84,104,114,101,115,104,111,108,100,41,10,9,9,100,105,115,99,97,114,100,59,10,35,101,110,100,105,102,10,10,9,82,101,110,100,101,114,84,97,114,103,101,116,48,32,61,32,102,114,97,103,109,101,110,116,67,111,108,111,114,59,10,125,
35,105,102,32,69,65,82,76,89,95,70,82,65,71,77,69,78,84,95,84,69,83,84,83,32,38,38,32,33,65,76,80,72,65,95,84,69,83,84,10,108,97,121,111,117,116,40,101,97,114,108,121,95,102,114,97,103,109,101,110,116,95,116,101,115,116,115,41,32,105,110,59,10,35,101,110,100,105,102,10,10,47,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,69,110,116,114,97,110,116,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,47,10,105,110,32,118,101,99,52,32,118,67,111,108,111,114,59,10,105,110,32,118,101,99,50,32,118,84,101,120,67,111,111,114,100,59,10,10,47,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,83,111,114,116,97,110,116,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,47,10,111,117,116,32,118,101,99,52,32,82,101,110,100,101,114,84,97,114,103,101,116,48,59,10,10,47,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,85,110,105,102,111,114,109,101,115,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,47,10,117,110,105,102,111,114,109,32,118,101,99,50,32,73,110,118,84,97,114,103,101,116,83,105,122,101,59,10,117,110,105,102,111,114,109,32,115,97,109,112,108,101,114,50,68,32,77,97,116,101,114,105,97,108,65,108,112,104,97,77,97,112,59,10,117,110,105,102,111,114,109,32,102,108,111,97,116,32,77,97,116,101,114,105,97,108,65,108,112,104,97,84,104,114,101,115,104,111,108,100,59,10,117,110,105,102,111,114,109,32,118,101,99,52,32,77,97,116,101,114,105,97,108,68,105,102,102,117,115,101,59,10,117,110,105,102,111,114,109,32,115,97,109,112,108,101,114,50,68,32,77,97,116,101,114,105,97,108,68,105,102,102,117,115,101,77,97,112,59,10,117,110,105,102,111,114,109,32,115,97,109,112,108,101,114,50,68,32,84,101,120,116,117,114,101,79,118,101,114,108,97,121,59,10,10,47,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,70,111,110,99,116,105,111,110,115,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,42,47,10,118,111,105,100,32,109,97,105,110,40,41,10,123,10,9,118,101,99,52,32,102,114,97,103,109,101,110,116,67,111,108,111,114,32,61,32,77,97,116,101,114,105,97,108,68,105,102,102,117,115,101,32,42,32,118,67,111,108,111,114,59,10,10,35,105,102,32,65,85,84,79,95,84,69,88,67,79,79,82,68,83,10,9,118,101,99,50,32,116,101,120,67,111,111,114,100,32,61,32,103,108,95,70,114,97,103,67,111,111,114,100,46,120,121,32,42,32,73,110,118,84,97,114,103,101,116,83,105,122,101,59,10,35,101,108,105,102,32,84,69,88,84,85,82,69,95,77,65,80,80,73,78,71,10,9,118,101,99,50,32,116,101,120,67,111,111,114,100,32,61,32,118,84,101,120,67,111,111,114,100,59,10,35,101,110,100,105,102,10,10,35,105,102,32,68,73,70,70,85,83,69,95,77,65,80,80,73,78,71,10,9,102,114,97,103,109,101,110,116,67,111,108,111,114,32,42,61,32,116,101,120,116,117,114,101,40,77,97,116,101,114,105,97,108,68,105,102,102,117,115,101,77,97,112,44,32,116,101,120,67,111,111,114,100,41,59,10,35,101,110,100,105,102,10,10,35,105,102,32,65,76,80,72,65,95,77,65,80,80,73,78,71,10,9,102,114,97,103,109,101,110,116,67,111,108,111,114,46,97,32,42,61,32,116,101,120,116,117,114,101,40,77,97,116,101,114,105,97,108,65,108,112,104,97,77,97,112,44,32,116,101,120,67,111,111,114,100,41,46,114,59,10,35,101,110,100,105,102,10,10,35,105,102,32,70,76,65,71,95,84,69,88,84,85,82,69,79,86,69,82,76,65,89,10,9,102,114,97,103,109,101,110,116,67,111,108,111,114,32,42,61,32,116,101,120,116,117,114,101,40,84,101,120,116,117,114,101,79,118,101,114,108,97,121,44,32,116,101,120,67,111,111,114,100,41,59,10,35,101,110,100,105,102,10,10,35,105,102,32,65,76,80,72,65,95,84,69,83,84,10,9,105,102,32,40,102,114,97,103,109,101,110,116,67,111,108,111,114,46,97,32,60,32,77,97,116,101,114,105,97,108,65,108,112,104,97,84,104,114,101,115,104,111,108,100,41,10,9,9,100,105,115,99,97,114,100,59,10,35,101,110,100,105,102,10,10,9,82,101,110,100,101,114,84,97,114,103,101,116,48,32,61,32,102,114,97,103,109,101,110,116,67,111,108,111,114,59,10,125,

View File

@@ -53,7 +53,7 @@ namespace Nz
* \param instanceData Data for the instance
*/
void SkeletalModel::AddToRenderQueue(AbstractRenderQueue* renderQueue, const InstanceData& instanceData) const
void SkeletalModel::AddToRenderQueue(AbstractRenderQueue* renderQueue, const InstanceData& instanceData, const Recti& scissorRect) const
{
if (!m_mesh)
return;
@@ -69,7 +69,7 @@ namespace Nz
meshData.primitiveMode = mesh->GetPrimitiveMode();
meshData.vertexBuffer = SkinningManager::GetBuffer(mesh, &m_skeleton);
renderQueue->AddMesh(instanceData.renderOrder, material, meshData, m_skeleton.GetAABB(), instanceData.transformMatrix);
renderQueue->AddMesh(instanceData.renderOrder, material, meshData, m_skeleton.GetAABB(), instanceData.transformMatrix, scissorRect);
}
}

View File

@@ -22,10 +22,10 @@ namespace Nz
* \param instanceData Data for the instance
*/
void Sprite::AddToRenderQueue(AbstractRenderQueue* renderQueue, const InstanceData& instanceData) const
void Sprite::AddToRenderQueue(AbstractRenderQueue* renderQueue, const InstanceData& instanceData, const Recti& scissorRect) const
{
const VertexStruct_XYZ_Color_UV* vertices = reinterpret_cast<const VertexStruct_XYZ_Color_UV*>(instanceData.data.data());
renderQueue->AddSprites(instanceData.renderOrder, GetMaterial(), vertices, 1);
renderQueue->AddSprites(instanceData.renderOrder, GetMaterial(), vertices, 1, scissorRect);
}
/*!

View File

@@ -26,7 +26,7 @@ namespace Nz
* \param instanceData Data for the instance
*/
void TextSprite::AddToRenderQueue(AbstractRenderQueue* renderQueue, const InstanceData& instanceData) const
void TextSprite::AddToRenderQueue(AbstractRenderQueue* renderQueue, const InstanceData& instanceData, const Recti& scissorRect) const
{
for (auto& pair : m_renderInfos)
{
@@ -36,7 +36,7 @@ namespace Nz
if (indices.count > 0)
{
const VertexStruct_XYZ_Color_UV* vertices = reinterpret_cast<const VertexStruct_XYZ_Color_UV*>(instanceData.data.data());
renderQueue->AddSprites(instanceData.renderOrder, GetMaterial(), &vertices[indices.first * 4], indices.count, overlay);
renderQueue->AddSprites(instanceData.renderOrder, GetMaterial(), &vertices[indices.first * 4], indices.count, scissorRect, overlay);
}
}
}

View File

@@ -23,7 +23,7 @@ namespace Nz
* \param renderQueue Queue to be added
* \param instanceData Data for the instance
*/
void TileMap::AddToRenderQueue(AbstractRenderQueue* renderQueue, const InstanceData& instanceData) const
void TileMap::AddToRenderQueue(AbstractRenderQueue* renderQueue, const InstanceData& instanceData, const Recti& scissorRect) const
{
const VertexStruct_XYZ_Color_UV* vertices = reinterpret_cast<const VertexStruct_XYZ_Color_UV*>(instanceData.data.data());
@@ -31,7 +31,7 @@ namespace Nz
std::size_t spriteCount = 0;
for (const Layer& layer : m_layers)
{
renderQueue->AddSprites(instanceData.renderOrder, GetMaterial(matCount++), &vertices[spriteCount], layer.tiles.size());
renderQueue->AddSprites(instanceData.renderOrder, GetMaterial(matCount++), &vertices[spriteCount], layer.tiles.size(), scissorRect);
spriteCount += layer.tiles.size();
}

View File

@@ -4,7 +4,7 @@
#include <Nazara/Network/AbstractSocket.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Network/Debug.hpp>
#include <Nazara/Network/Algorithm.hpp>
#if defined(NAZARA_PLATFORM_WINDOWS)
#include <Nazara/Network/Win32/SocketImpl.hpp>
@@ -14,6 +14,8 @@
#error Missing implementation: Socket
#endif
#include <Nazara/Network/Debug.hpp>
namespace Nz
{
/*!
@@ -187,10 +189,23 @@ namespace Nz
{
if (m_handle == SocketImpl::InvalidHandle || m_protocol != protocol)
{
SocketHandle handle = SocketImpl::Create(protocol, m_type, &m_lastError);
SocketHandle handle = SocketImpl::Create((protocol == NetProtocol_Any) ? NetProtocol_IPv6 : protocol, m_type, &m_lastError);
if (handle == SocketImpl::InvalidHandle)
return false;
if (protocol == NetProtocol_Any)
{
if (!SocketImpl::SetIPv6Only(handle, false, &m_lastError))
{
SocketImpl::Close(handle);
NazaraError("Failed to open a dual-stack socket: " + Nz::String(ErrorToString(m_lastError)));
return false;
}
protocol = NetProtocol_IPv6;
}
m_protocol = protocol;
Open(handle);
}

View File

@@ -320,7 +320,7 @@ namespace Nz
bool ENetHost::InitSocket(const IpAddress& address)
{
if (!m_socket.Create(address.GetProtocol()))
if (!m_socket.Create((m_isUsingDualStack) ? NetProtocol_Any : address.GetProtocol()))
return false;
m_socket.EnableBlocking(false);

View File

@@ -59,24 +59,13 @@ namespace Nz
IpAddress::IPv6 convertSockaddr6ToIPv6(const in6_addr& addr)
{
union byteToInt
{
UInt8 b[sizeof(uint32_t)];
uint32_t i;
};
auto& rawIpV6 = addr.s6_addr;
IpAddress::IPv6 ipv6Addr;
IpAddress::IPv6 ipv6;
for (unsigned int i = 0; i < 8; ++i)
ipv6[i] = rawIpV6[i * 2] << 8 | rawIpV6[i * 2 + 1];
for (auto i = 0; i < 4; ++i)
{
byteToInt hostOrder;
hostOrder.i = 0;
std::copy(addr.s6_addr + 4 * i, addr.s6_addr + 4 * (i + 1), hostOrder.b);
ipv6Addr[2 * i] = (hostOrder.b[3] << 8) + hostOrder.b[2];
ipv6Addr[2 * i + 1] = (hostOrder.b[1] << 8) + hostOrder.b[0];
}
return ipv6Addr;
return ipv6;
}
}
@@ -218,9 +207,9 @@ namespace Nz
IpAddress::IPv6 address = ipAddress.ToIPv6();
for (unsigned int i = 0; i < 8; ++i)
{
UInt16 networkOrder = htons(address[i]);
socketAddress->sin6_addr.s6_addr[2 * i] = networkOrder / 256;
socketAddress->sin6_addr.s6_addr[2 * i + 1] = networkOrder % 256;
u_short addressPart = htons(address[i]);
socketAddress->sin6_addr.s6_addr[i * 2 + 0] = addressPart >> 0;
socketAddress->sin6_addr.s6_addr[i * 2 + 1] = addressPart >> 8;
}
return sizeof(sockaddr_in6);

View File

@@ -809,7 +809,7 @@ namespace Nz
{
NazaraAssert(handle != InvalidHandle, "Invalid handle");
bool option = broadcasting;
int option = broadcasting;
if (setsockopt(handle, SOL_SOCKET, SO_BROADCAST, reinterpret_cast<const char*>(&option), sizeof(option)) == SOCKET_ERROR)
{
if (error)
@@ -824,6 +824,25 @@ namespace Nz
return true;
}
bool SocketImpl::SetIPv6Only(SocketHandle handle, bool ipv6Only, SocketError* error)
{
NazaraAssert(handle != InvalidHandle, "Invalid handle");
int option = ipv6Only;
if (setsockopt(handle, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast<const char*>(&option), sizeof(option)) == SOCKET_ERROR)
{
if (error)
*error = TranslateErrnoToResolveError(GetLastErrorCode());
return false; //< Error
}
if (error)
*error = SocketError_NoError;
return true;
}
bool SocketImpl::SetKeepAlive(SocketHandle handle, bool enabled, UInt64 msTime, UInt64 msInterval, SocketError* error)
{
NazaraAssert(handle != InvalidHandle, "Invalid handle");

View File

@@ -72,6 +72,7 @@ namespace Nz
static bool SetBlocking(SocketHandle handle, bool blocking, SocketError* error = nullptr);
static bool SetBroadcasting(SocketHandle handle, bool broadcasting, SocketError* error = nullptr);
static bool SetIPv6Only(SocketHandle handle, bool ipv6only, SocketError* error = nullptr);
static bool SetKeepAlive(SocketHandle handle, bool enabled, UInt64 msTime, UInt64 msInterval, SocketError* error = nullptr);
static bool SetNoDelay(SocketHandle handle, bool nodelay, SocketError* error = nullptr);
static bool SetReceiveBufferSize(SocketHandle handle, std::size_t size, SocketError* error = nullptr);

View File

@@ -93,21 +93,14 @@ namespace Nz
{
sockaddr_in* ipv4 = reinterpret_cast<sockaddr_in*>(info->ai_addr);
auto& rawIpV4 = ipv4->sin_addr;
return IpAddress(rawIpV4.s_net, rawIpV4.s_host, rawIpV4.s_lh, rawIpV4.s_impno, ntohs(ipv4->sin_port));
return FromSockAddr(ipv4);
}
case AF_INET6:
{
sockaddr_in6* ipv6 = reinterpret_cast<sockaddr_in6*>(info->ai_addr);
auto& rawIpV6 = ipv6->sin6_addr.s6_addr;
IpAddress::IPv6 structIpV6;
for (unsigned int i = 0; i < 8; ++i)
structIpV6[i] = UInt16(rawIpV6[i * 2]) << 8 | UInt16(rawIpV6[i * 2 + 1]);
return IpAddress(structIpV6, ntohs(ipv6->sin6_port));
return FromSockAddr(ipv6);
}
}
@@ -164,7 +157,7 @@ namespace Nz
IpAddress::IPv6 ipv6;
for (unsigned int i = 0; i < 8; ++i)
ipv6[i] = rawIpV6[i*2] << 8 | rawIpV6[i*2+1];
ipv6[i] = rawIpV6[i * 2] << 8 | rawIpV6[i * 2 + 1];
return IpAddress(ipv6, ntohs(addressv6->sin6_port));
}
@@ -258,8 +251,9 @@ namespace Nz
IpAddress::IPv6 address = ipAddress.ToIPv6();
for (unsigned int i = 0; i < 8; ++i)
{
socketAddress->sin6_addr.s6_addr[i * 2 + 0] = htons(address[i]) >> 8;
socketAddress->sin6_addr.s6_addr[i * 2 + 1] = htons(address[i]) >> 0;
u_short addressPart = htons(address[i]);
socketAddress->sin6_addr.s6_addr[i * 2 + 0] = addressPart >> 0;
socketAddress->sin6_addr.s6_addr[i * 2 + 1] = addressPart >> 8;
}
return sizeof(sockaddr_in6);

View File

@@ -1,4 +1,4 @@
// Copyright (C) 2017 Jérôme Leclercq
// Copyright (C) 2018 Jérôme Leclercq
// This file is part of the "Nazara Engine - Network module"
// For conditions of distribution and use, see copyright notice in Config.hpp
@@ -10,13 +10,15 @@
// Some compilers (older versions of MinGW) lack Mstcpip.h which defines some structs/defines
#if defined(__has_include)
#define NZ_HAS_MSTCPIP_HEADER __has_include(<Mstcpip.h>)
#define NZ_HAS_MSTCPIP_HEADER __has_include(<mstcpip.h>)
#else
// If this version of MinGW doesn't support __has_include, assume it hasn't Mstcpip.h
#define NZ_HAS_MSTCPIP_HEADER !defined(NAZARA_COMPILER_MINGW)
#endif
#if NZ_HAS_MSTCPIP_HEADER
#include <mstcpip.h>
#else
struct tcp_keepalive
{
u_long onoff;
@@ -25,8 +27,6 @@ struct tcp_keepalive
};
#define SIO_KEEPALIVE_VALS _WSAIOW(IOC_VENDOR,4)
#else
#include <Mstcpip.h>
#endif
#include <Winsock2.h>
@@ -827,6 +827,32 @@ namespace Nz
return true;
}
bool SocketImpl::SetIPv6Only(SocketHandle handle, bool ipv6Only, SocketError* error)
{
#if NAZARA_CORE_WINDOWS_NT6
NazaraAssert(handle != InvalidHandle, "Invalid handle");
DWORD option = ipv6Only;
if (setsockopt(handle, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast<const char*>(&option), sizeof(option)) == SOCKET_ERROR)
{
if (error)
*error = TranslateWSAErrorToSocketError(WSAGetLastError());
return false; //< Error
}
if (error)
*error = SocketError_NoError;
return true;
#else
if (error)
*error = SocketError_NotSupported;
return false;
#endif
}
bool SocketImpl::SetKeepAlive(SocketHandle handle, bool enabled, UInt64 msTime, UInt64 msInterval, SocketError* error)
{
NazaraAssert(handle != InvalidHandle, "Invalid handle");

View File

@@ -72,6 +72,7 @@ namespace Nz
static bool SetBlocking(SocketHandle handle, bool blocking, SocketError* error = nullptr);
static bool SetBroadcasting(SocketHandle handle, bool broadcasting, SocketError* error = nullptr);
static bool SetIPv6Only(SocketHandle handle, bool ipv6Only, SocketError* error = nullptr);
static bool SetKeepAlive(SocketHandle handle, bool enabled, UInt64 msTime, UInt64 msInterval, SocketError* error = nullptr);
static bool SetNoDelay(SocketHandle handle, bool nodelay, SocketError* error = nullptr);
static bool SetReceiveBufferSize(SocketHandle handle, std::size_t size, SocketError* error = nullptr);

View File

@@ -50,7 +50,7 @@ namespace Nz
{
Vector3f min, max;
// Si nous n'avons aucune instance, nous en cr<63>ons une temporaire
// Check for existing collision handles, and create a temporary one if none is available
if (m_handles.empty())
{
PhysWorld3D world;
@@ -61,7 +61,7 @@ namespace Nz
}
NewtonDestroyCollision(collision);
}
else // Sinon on utilise une instance au hasard (elles sont toutes identiques de toute fa<66>on)
else
NewtonCollisionCalculateAABB(m_handles.begin()->second, offsetMatrix, min, max);
return Boxf(scale * min, scale * max);
@@ -72,7 +72,7 @@ namespace Nz
float inertiaMatrix[3];
float origin[3];
// Si nous n'avons aucune instance, nous en cr<63>ons une temporaire
// Check for existing collision handles, and create a temporary one if none is available
if (m_handles.empty())
{
PhysWorld3D world;
@@ -83,7 +83,7 @@ namespace Nz
}
NewtonDestroyCollision(collision);
}
else // Sinon on utilise une instance au hasard (elles sont toutes identiques de toute fa<66>on)
else
NewtonConvexCollisionCalculateInertialMatrix(m_handles.begin()->second, inertiaMatrix, origin);
if (inertia)
@@ -97,7 +97,7 @@ namespace Nz
{
float volume;
// Si nous n'avons aucune instance, nous en cr<63>ons une temporaire
// Check for existing collision handles, and create a temporary one if none is available
if (m_handles.empty())
{
PhysWorld3D world;
@@ -108,12 +108,35 @@ namespace Nz
}
NewtonDestroyCollision(collision);
}
else // Sinon on utilise une instance au hasard (elles sont toutes identiques de toute fa<66>on)
else
volume = NewtonConvexCollisionCalculateVolume(m_handles.begin()->second);
return volume;
}
void Collider3D::ForEachPolygon(const std::function<void(const float* vertices, std::size_t vertexCount)>& callback) const
{
auto newtCallback = [](void* const userData, int vertexCount, const dFloat* const faceArray, int /*faceId*/)
{
const auto& cb = *static_cast<std::add_pointer_t<decltype(callback)>>(userData);
cb(faceArray, vertexCount);
};
// Check for existing collision handles, and create a temporary one if none is available
if (m_handles.empty())
{
PhysWorld3D world;
NewtonCollision* collision = CreateHandle(&world);
{
NewtonCollisionForEachPolygonDo(collision, Nz::Matrix4f::Identity(), newtCallback, const_cast<void*>(static_cast<const void*>(&callback))); //< This isn't that bad; pointer will not be used for writing
}
NewtonDestroyCollision(collision);
}
else
NewtonCollisionForEachPolygonDo(m_handles.begin()->second, Nz::Matrix4f::Identity(), newtCallback, const_cast<void*>(static_cast<const void*>(&callback))); //< This isn't that bad; pointer will not be used for writing
}
NewtonCollision* Collider3D::GetHandle(PhysWorld3D* world) const
{
auto it = m_handles.find(world);
@@ -332,7 +355,7 @@ namespace Nz
ColliderType3D ConvexCollider3D::GetType() const
{
return ColliderType3D_Compound;
return ColliderType3D_ConvexHull;
}
NewtonCollision* ConvexCollider3D::CreateHandle(PhysWorld3D* world) const

View File

@@ -27,7 +27,7 @@ namespace Nz
NewtonDestroy(m_world);
}
int PhysWorld3D::CreateMaterial(Nz::String name)
int PhysWorld3D::CreateMaterial(String name)
{
NazaraAssert(m_materialIds.find(name) == m_materialIds.end(), "Material \"" + name + "\" already exists");
@@ -37,13 +37,12 @@ namespace Nz
return materialId;
}
void PhysWorld3D::ForEachBodyInAABB(const Nz::Boxf& box, const BodyIterator& iterator)
void PhysWorld3D::ForEachBodyInAABB(const Boxf& box, const BodyIterator& iterator)
{
auto NewtonCallback = [](const NewtonBody* const body, void* const userdata) -> int
{
const BodyIterator& iterator = *static_cast<BodyIterator*>(userdata);
RigidBody3D* nzBody = static_cast<RigidBody3D*>(NewtonBodyGetUserData(body));
return iterator(*nzBody);
const BodyIterator& bodyIterator = *static_cast<BodyIterator*>(userdata);
return bodyIterator(*static_cast<RigidBody3D*>(NewtonBodyGetUserData(body)));
};
NewtonWorldForEachBodyInAABBDo(m_world, box.GetMinimum(), box.GetMaximum(), NewtonCallback, const_cast<void*>(static_cast<const void*>(&iterator)));
@@ -59,7 +58,7 @@ namespace Nz
return m_world;
}
int PhysWorld3D::GetMaterial(const Nz::String& name)
int PhysWorld3D::GetMaterial(const String& name)
{
auto it = m_materialIds.find(name);
NazaraAssert(it != m_materialIds.end(), "Material \"" + name + "\" does not exists");
@@ -99,7 +98,7 @@ namespace Nz
void PhysWorld3D::SetMaterialCollisionCallback(int firstMaterial, int secondMaterial, AABBOverlapCallback aabbOverlapCallback, CollisionCallback collisionCallback)
{
static_assert(sizeof(Nz::UInt64) >= 2 * sizeof(int), "Oops");
static_assert(sizeof(UInt64) >= 2 * sizeof(int), "Oops");
auto callbackPtr = std::make_unique<Callback>();
callbackPtr->aabbOverlapCallback = std::move(aabbOverlapCallback);
@@ -107,10 +106,10 @@ namespace Nz
NewtonMaterialSetCollisionCallback(m_world, firstMaterial, secondMaterial, callbackPtr.get(), (callbackPtr->aabbOverlapCallback) ? OnAABBOverlap : nullptr, (callbackPtr->collisionCallback) ? ProcessContact : nullptr);
Nz::UInt64 firstMaterialId(firstMaterial);
Nz::UInt64 secondMaterialId(secondMaterial);
UInt64 firstMaterialId(firstMaterial);
UInt64 secondMaterialId(secondMaterial);
Nz::UInt64 callbackIndex = firstMaterialId << 32 | secondMaterialId;
UInt64 callbackIndex = firstMaterialId << 32 | secondMaterialId;
m_callbacks[callbackIndex] = std::move(callbackPtr);
}
@@ -154,8 +153,8 @@ namespace Nz
int PhysWorld3D::OnAABBOverlap(const NewtonMaterial* const material, const NewtonBody* const body0, const NewtonBody* const body1, int threadIndex)
{
Nz::RigidBody3D* bodyA = static_cast<Nz::RigidBody3D*>(NewtonBodyGetUserData(body0));
Nz::RigidBody3D* bodyB = static_cast<Nz::RigidBody3D*>(NewtonBodyGetUserData(body1));
RigidBody3D* bodyA = static_cast<RigidBody3D*>(NewtonBodyGetUserData(body0));
RigidBody3D* bodyB = static_cast<RigidBody3D*>(NewtonBodyGetUserData(body1));
assert(bodyA && bodyB);
Callback* callbackData = static_cast<Callback*>(NewtonMaterialGetMaterialPairUserData(material));
@@ -167,14 +166,14 @@ namespace Nz
void PhysWorld3D::ProcessContact(const NewtonJoint* const contactJoint, float timestep, int threadIndex)
{
Nz::RigidBody3D* bodyA = static_cast<Nz::RigidBody3D*>(NewtonBodyGetUserData(NewtonJointGetBody0(contactJoint)));
Nz::RigidBody3D* bodyB = static_cast<Nz::RigidBody3D*>(NewtonBodyGetUserData(NewtonJointGetBody1(contactJoint)));
RigidBody3D* bodyA = static_cast<RigidBody3D*>(NewtonBodyGetUserData(NewtonJointGetBody0(contactJoint)));
RigidBody3D* bodyB = static_cast<RigidBody3D*>(NewtonBodyGetUserData(NewtonJointGetBody1(contactJoint)));
assert(bodyA && bodyB);
using ContactJoint = void*;
// Query all joints first, to prevent removing a joint from the list while iterating on it
Nz::StackArray<ContactJoint> contacts = NazaraStackAllocationNoInit(ContactJoint, NewtonContactJointGetContactCount(contactJoint));
StackArray<ContactJoint> contacts = NazaraStackAllocationNoInit(ContactJoint, NewtonContactJointGetContactCount(contactJoint));
std::size_t contactIndex = 0;
for (ContactJoint contact = NewtonContactJointGetFirstContact(contactJoint); contact; contact = NewtonContactJointGetNextContact(contactJoint, contact))
{

View File

@@ -266,7 +266,7 @@ namespace Nz
return NewtonBodyGetSleepState(m_body) != 0;
}
void RigidBody3D::SetAngularDamping(const Nz::Vector3f& angularDamping)
void RigidBody3D::SetAngularDamping(const Vector3f& angularDamping)
{
NewtonBodySetAngularDamping(m_body, angularDamping);
}
@@ -345,7 +345,7 @@ namespace Nz
NewtonBodySetCentreOfMass(m_body, center);
}
void RigidBody3D::SetMaterial(const Nz::String& materialName)
void RigidBody3D::SetMaterial(const String& materialName)
{
SetMaterial(m_world->GetMaterial(materialName));
}

View File

@@ -501,6 +501,7 @@ namespace Nz
event.size.height = size.y;
m_parent->PushEvent(event);
}
break;
}
case WM_KEYDOWN:

View File

@@ -514,8 +514,16 @@ namespace Nz
FontGlyph fontGlyph;
if (ExtractGlyph(characterSize, character, style, &fontGlyph))
{
glyph.atlasRect.width = fontGlyph.image.GetWidth();
glyph.atlasRect.height = fontGlyph.image.GetHeight();
if (fontGlyph.image.IsValid())
{
glyph.atlasRect.width = fontGlyph.image.GetWidth();
glyph.atlasRect.height = fontGlyph.image.GetHeight();
}
else
{
glyph.atlasRect.width = 0;
glyph.atlasRect.height = 0;
}
// Insertion du rectangle dans l'un des atlas
if (glyph.atlasRect.width > 0 && glyph.atlasRect.height > 0) // Si l'image contient quelque chose

View File

@@ -250,6 +250,9 @@ namespace Nz
m_lineCount++;
m_currentLine = m_stream.ReadLine();
if (m_currentLine.IsEmpty())
continue;
m_currentLine = m_currentLine.SubStringTo("//"); // On ignore les commentaires
m_currentLine.Simplify(); // Pour un traitement plus simple
}

View File

@@ -182,6 +182,9 @@ namespace Nz
m_lineCount++;
m_currentLine = m_stream.ReadLine();
if (m_currentLine.IsEmpty())
continue;
m_currentLine = m_currentLine.SubStringTo("//"); // On ignore les commentaires
m_currentLine.Simplify(); // Pour un traitement plus simple
m_currentLine.Trim();

View File

@@ -251,6 +251,32 @@ namespace Nz
currentMaterial->reflectionMap = map;
}
}
else if (keyword == "map_normal" || keyword == "normal")
{
// <!> This is a custom keyword
std::size_t mapPos = m_currentLine.GetWordPosition(1);
if (mapPos != String::npos)
{
String map = m_currentLine.SubString(mapPos);
if (!currentMaterial)
currentMaterial = AddMaterial("default");
currentMaterial->normalMap = map;
}
}
else if (keyword == "map_emissive" || keyword == "emissive")
{
// <!> This is a custom keyword
std::size_t mapPos = m_currentLine.GetWordPosition(1);
if (mapPos != String::npos)
{
String map = m_currentLine.SubString(mapPos);
if (!currentMaterial)
currentMaterial = AddMaterial("default");
currentMaterial->emissiveMap = map;
}
}
else if (keyword == "newmtl")
{
String materialName = m_currentLine.SubString(m_currentLine.GetWordPosition(1));
@@ -424,6 +450,9 @@ namespace Nz
m_lineCount++;
m_currentLine = m_currentStream->ReadLine();
if (m_currentLine.IsEmpty())
continue;
m_currentLine = m_currentLine.SubStringTo("#"); // On ignore les commentaires
m_currentLine.Simplify(); // Pour un traitement plus simple
}

View File

@@ -107,6 +107,24 @@ namespace Nz
data.SetParameter(MaterialData::DiffuseTexturePath, fullPath);
}
if (!mtlMat->emissiveMap.IsEmpty())
{
String fullPath = mtlMat->emissiveMap;
if (!Nz::File::IsAbsolute(fullPath))
fullPath.Prepend(baseDir);
data.SetParameter(MaterialData::EmissiveTexturePath, fullPath);
}
if (!mtlMat->normalMap.IsEmpty())
{
String fullPath = mtlMat->normalMap;
if (!Nz::File::IsAbsolute(fullPath))
fullPath.Prepend(baseDir);
data.SetParameter(MaterialData::NormalTexturePath, fullPath);
}
if (!mtlMat->specularMap.IsEmpty())
{
String fullPath = mtlMat->specularMap;

View File

@@ -617,6 +617,9 @@ namespace Nz
m_lineCount++;
m_currentLine = m_currentStream->ReadLine();
if (m_currentLine.IsEmpty())
continue;
m_currentLine.Simplify(); // Simplify lines (convert multiple blanks into a single space and trims)
}
while (m_currentLine.IsEmpty());

View File

@@ -839,7 +839,7 @@ namespace Nz
if (pixelCount == 0)
return false;
auto seq = workingBitset.Read(GetConstPixels(), info.bitsPerPixel);
auto seq = workingBitset.Write(GetConstPixels(), info.bitsPerPixel);
do
{
workingBitset &= info.alphaMask;
@@ -847,7 +847,7 @@ namespace Nz
return true;
workingBitset.Clear();
workingBitset.Read(seq, info.bitsPerPixel);
workingBitset.Write(seq, info.bitsPerPixel);
}
while (--pixelCount > 0);

View File

@@ -354,42 +354,38 @@ namespace Nz
{
glyph.atlas = nullptr;
glyph.bounds.Set(float(m_drawPos.x), float(0.f), float(advance), float(sizeInfo.lineHeight));
glyph.bounds.Set(float(m_drawPos.x), m_lines.back().bounds.y, float(advance), float(sizeInfo.lineHeight));
glyph.corners[0].Set(glyph.bounds.GetCorner(RectCorner_LeftTop));
glyph.corners[1].Set(glyph.bounds.GetCorner(RectCorner_RightTop));
glyph.corners[2].Set(glyph.bounds.GetCorner(RectCorner_LeftBottom));
glyph.corners[3].Set(glyph.bounds.GetCorner(RectCorner_RightBottom));
switch (character)
{
case '\n':
{
// Extend the line bounding rect to the last glyph it contains, thus extending upon all glyphs of the line
if (!m_glyphs.empty())
{
Glyph& lastGlyph = m_glyphs.back();
m_lines.back().bounds.ExtendTo(lastGlyph.bounds);
}
// Reset cursor
advance = 0;
m_drawPos.x = 0;
m_drawPos.y += sizeInfo.lineHeight;
m_workingBounds.ExtendTo(m_lines.back().bounds);
m_lines.emplace_back(Line{Rectf(0.f, float(sizeInfo.lineHeight * m_lines.size()), 0.f, float(sizeInfo.lineHeight)), m_glyphs.size() + 1});
break;
}
}
}
m_lines.back().bounds.ExtendTo(glyph.bounds);
switch (character)
{
case '\n':
{
// Reset cursor
advance = 0;
m_drawPos.x = 0;
m_drawPos.y += sizeInfo.lineHeight;
m_workingBounds.ExtendTo(m_lines.back().bounds);
m_lines.emplace_back(Line{Rectf(0.f, float(sizeInfo.lineHeight * m_lines.size()), 0.f, float(sizeInfo.lineHeight)), m_glyphs.size() + 1});
break;
}
default:
m_drawPos.x += advance;
break;
}
m_drawPos.x += advance;
m_glyphs.push_back(glyph);
}
m_lines.back().bounds.ExtendTo(m_glyphs.back().bounds);
m_workingBounds.ExtendTo(m_lines.back().bounds);
m_bounds.Set(Rectf(std::floor(m_workingBounds.x), std::floor(m_workingBounds.y), std::ceil(m_workingBounds.width), std::ceil(m_workingBounds.height)));