Merge branch 'master' into NDK-ShadowMapping

Former-commit-id: 83435ab51753299b30a102871fbcd5558d2ac4f1
This commit is contained in:
Lynix
2015-12-09 00:59:07 +01:00
751 changed files with 79400 additions and 71735 deletions

View File

@@ -9,7 +9,10 @@
#include <Nazara/Prerequesites.hpp>
template<typename T> void NzMixToMono(T* input, T* output, unsigned int channelCount, unsigned int frameCount);
namespace Nz
{
template<typename T> void MixToMono(T* input, T* output, unsigned int channelCount, unsigned int frameCount);
}
#include <Nazara/Audio/Algorithm.inl>

View File

@@ -5,21 +5,24 @@
#include <Nazara/Core/Error.hpp>
#include <Nazara/Audio/Debug.hpp>
template<typename T>
void NzMixToMono(T* input, T* output, unsigned int channelCount, unsigned int frameCount)
namespace Nz
{
///DOC: Le buffer d'entrée peut être le même que le buffer de sortie
// Pour éviter l'overflow, on utilise comme accumulateur un type assez grand, (u)int 64 bits pour les entiers, double pour les flottants
typedef typename std::conditional<std::is_unsigned<T>::value, nzUInt64, nzInt64>::type BiggestInt;
typedef typename std::conditional<std::is_integral<T>::value, BiggestInt, double>::type Biggest;
for (unsigned int i = 0; i < frameCount; ++i)
template<typename T>
void MixToMono(T* input, T* output, unsigned int channelCount, unsigned int frameCount)
{
Biggest acc = Biggest(0);
for (unsigned int j = 0; j < channelCount; ++j)
acc += input[i*channelCount + j];
///DOC: Le buffer d'entrée peut être le même que le buffer de sortie
// Pour éviter l'overflow, on utilise comme accumulateur un type assez grand, (u)int 64 bits pour les entiers, double pour les flottants
typedef typename std::conditional<std::is_unsigned<T>::value, UInt64, Int64>::type BiggestInt;
typedef typename std::conditional<std::is_integral<T>::value, BiggestInt, double>::type Biggest;
output[i] = static_cast<T>(acc/channelCount);
for (unsigned int i = 0; i < frameCount; ++i)
{
Biggest acc = Biggest(0);
for (unsigned int j = 0; j < channelCount; ++j)
acc += input[i*channelCount + j];
output[i] = static_cast<T>(acc / channelCount);
}
}
}

View File

@@ -14,41 +14,44 @@
#include <Nazara/Math/Quaternion.hpp>
#include <Nazara/Math/Vector3.hpp>
class NAZARA_AUDIO_API NzAudio
namespace Nz
{
public:
NzAudio() = delete;
~NzAudio() = delete;
class NAZARA_AUDIO_API Audio
{
public:
Audio() = delete;
~Audio() = delete;
static nzAudioFormat GetAudioFormat(unsigned int channelCount);
static float GetDopplerFactor();
static float GetGlobalVolume();
static NzVector3f GetListenerDirection();
static NzVector3f GetListenerPosition();
static NzQuaternionf GetListenerRotation();
static NzVector3f GetListenerVelocity();
static float GetSpeedOfSound();
static AudioFormat GetAudioFormat(unsigned int channelCount);
static float GetDopplerFactor();
static float GetGlobalVolume();
static Vector3f GetListenerDirection();
static Vector3f GetListenerPosition();
static Quaternionf GetListenerRotation();
static Vector3f GetListenerVelocity();
static float GetSpeedOfSound();
static bool Initialize();
static bool Initialize();
static bool IsFormatSupported(nzAudioFormat format);
static bool IsInitialized();
static bool IsFormatSupported(AudioFormat format);
static bool IsInitialized();
static void SetDopplerFactor(float dopplerFactor);
static void SetGlobalVolume(float volume);
static void SetListenerDirection(const NzVector3f& direction);
static void SetListenerDirection(float dirX, float dirY, float dirZ);
static void SetListenerPosition(const NzVector3f& position);
static void SetListenerPosition(float x, float y, float z);
static void SetListenerRotation(const NzQuaternionf& rotation);
static void SetListenerVelocity(const NzVector3f& velocity);
static void SetListenerVelocity(float velX, float velY, float velZ);
static void SetSpeedOfSound(float speed);
static void SetDopplerFactor(float dopplerFactor);
static void SetGlobalVolume(float volume);
static void SetListenerDirection(const Vector3f& direction);
static void SetListenerDirection(float dirX, float dirY, float dirZ);
static void SetListenerPosition(const Vector3f& position);
static void SetListenerPosition(float x, float y, float z);
static void SetListenerRotation(const Quaternionf& rotation);
static void SetListenerVelocity(const Vector3f& velocity);
static void SetListenerVelocity(float velX, float velY, float velZ);
static void SetSpeedOfSound(float speed);
static void Uninitialize();
static void Uninitialize();
private:
static unsigned int s_moduleReferenceCounter;
};
private:
static unsigned int s_moduleReferenceCounter;
};
}
#endif // NAZARA_AUDIO_HPP

View File

@@ -15,7 +15,7 @@
// On force la valeur de MANAGE_MEMORY en mode debug
#if defined(NAZARA_DEBUG) && !NAZARA_AUDIO_MANAGE_MEMORY
#undef NAZARA_AUDIO_MANAGE_MEMORY
#define NAZARA_AUDIO_MANAGE_MEMORY 1
#define NAZARA_AUDIO_MANAGE_MEMORY 0
#endif
NazaraCheckTypeAndVal(NAZARA_AUDIO_STREAMED_BUFFER_COUNT, integral, >, 0, " shall be a strictly positive integer");

View File

@@ -4,29 +4,32 @@
#pragma once
#ifndef NAZARA_ENUMS_HPP
#define NAZARA_ENUMS_HPP
#ifndef NAZARA_ENUMS_AUDIO_HPP
#define NAZARA_ENUMS_AUDIO_HPP
enum nzAudioFormat
namespace Nz
{
nzAudioFormat_Unknown = -1,
enum AudioFormat
{
AudioFormat_Unknown = -1,
// La valeur entière est le nombre de canaux possédés par ce format
nzAudioFormat_Mono = 1,
nzAudioFormat_Stereo = 2,
nzAudioFormat_Quad = 4,
nzAudioFormat_5_1 = 6,
nzAudioFormat_6_1 = 7,
nzAudioFormat_7_1 = 8,
// La valeur entière est le nombre de canaux possédés par ce format
AudioFormat_Mono = 1,
AudioFormat_Stereo = 2,
AudioFormat_Quad = 4,
AudioFormat_5_1 = 6,
AudioFormat_6_1 = 7,
AudioFormat_7_1 = 8,
nzAudioFormat_Max = nzAudioFormat_7_1
};
AudioFormat_Max = AudioFormat_7_1
};
enum nzSoundStatus
{
nzSoundStatus_Playing,
nzSoundStatus_Paused,
nzSoundStatus_Stopped
};
enum SoundStatus
{
SoundStatus_Playing,
SoundStatus_Paused,
SoundStatus_Stopped
};
}
#endif // NAZARA_ENUMS_HPP
#endif // NAZARA_ENUMS_AUDIO_HPP

View File

@@ -13,60 +13,68 @@
#include <Nazara/Core/Resource.hpp>
#include <Nazara/Core/ResourceLoader.hpp>
struct NzMusicParams
namespace Nz
{
bool forceMono = false;
struct MusicParams
{
bool forceMono = false;
bool IsValid() const;
};
bool IsValid() const;
};
class NzMusic;
class NzSoundStream;
class Music;
class SoundStream;
using NzMusicLoader = NzResourceLoader<NzMusic, NzMusicParams>;
using MusicLoader = ResourceLoader<Music, MusicParams>;
struct NzMusicImpl;
struct MusicImpl;
class NAZARA_AUDIO_API NzMusic : public NzResource, public NzSoundEmitter, NzNonCopyable
{
friend NzMusicLoader;
class NAZARA_AUDIO_API Music : public Resource, public SoundEmitter
{
friend MusicLoader;
public:
NzMusic() = default;
~NzMusic();
public:
Music() = default;
Music(const Music&) = delete;
Music(Music&&) = delete; ///TODO
~Music();
bool Create(NzSoundStream* soundStream);
void Destroy();
bool Create(SoundStream* soundStream);
void Destroy();
void EnableLooping(bool loop);
void EnableLooping(bool loop);
nzUInt32 GetDuration() const;
nzAudioFormat GetFormat() const;
nzUInt32 GetPlayingOffset() const;
unsigned int GetSampleCount() const;
unsigned int GetSampleRate() const;
nzSoundStatus GetStatus() const;
UInt32 GetDuration() const;
AudioFormat GetFormat() const;
UInt32 GetPlayingOffset() const;
UInt32 GetSampleCount() const;
UInt32 GetSampleRate() const;
SoundStatus GetStatus() const;
bool IsLooping() const;
bool IsLooping() const;
bool OpenFromFile(const NzString& filePath, const NzMusicParams& params = NzMusicParams());
bool OpenFromMemory(const void* data, std::size_t size, const NzMusicParams& params = NzMusicParams());
bool OpenFromStream(NzInputStream& stream, const NzMusicParams& params = NzMusicParams());
bool OpenFromFile(const String& filePath, const MusicParams& params = MusicParams());
bool OpenFromMemory(const void* data, std::size_t size, const MusicParams& params = MusicParams());
bool OpenFromStream(Stream& stream, const MusicParams& params = MusicParams());
void Pause();
void Play();
void Pause();
void Play();
void SetPlayingOffset(nzUInt32 offset);
void SetPlayingOffset(UInt32 offset);
void Stop();
void Stop();
private:
NzMusicImpl* m_impl = nullptr;
Music& operator=(const Music&) = delete;
Music& operator=(Music&&) = delete; ///TODO
bool FillAndQueueBuffer(unsigned int buffer);
void MusicThread();
private:
MusicImpl* m_impl = nullptr;
static NzMusicLoader::LoaderList s_loaders;
};
bool FillAndQueueBuffer(unsigned int buffer);
void MusicThread();
static MusicLoader::LoaderList s_loaders;
};
}
#endif // NAZARA_MUSIC_HPP

View File

@@ -20,168 +20,171 @@
// Étant donné que les headers OpenAL ne nous permettent pas de n'avoir que les signatures sans les pointeurs de fonctions
// Et que je ne souhaite pas les modifier, je suis contraint de les placer dans un espace de nom différent pour ensuite
// remettre dans l'espace global les choses intéressantes (les typedef notamment)
namespace NzOpenALDetail
namespace OpenALDetail
{
#include <AL/al.h>
#include <AL/alc.h>
}
// Si quelqu'un a une meilleure idée ...
using NzOpenALDetail::ALboolean;
using NzOpenALDetail::ALbyte;
using NzOpenALDetail::ALchar;
using NzOpenALDetail::ALdouble;
using NzOpenALDetail::ALenum;
using NzOpenALDetail::ALfloat;
using NzOpenALDetail::ALint;
using NzOpenALDetail::ALshort;
using NzOpenALDetail::ALsizei;
using NzOpenALDetail::ALubyte;
using NzOpenALDetail::ALuint;
using NzOpenALDetail::ALushort;
using NzOpenALDetail::ALvoid;
using OpenALDetail::ALboolean;
using OpenALDetail::ALbyte;
using OpenALDetail::ALchar;
using OpenALDetail::ALdouble;
using OpenALDetail::ALenum;
using OpenALDetail::ALfloat;
using OpenALDetail::ALint;
using OpenALDetail::ALshort;
using OpenALDetail::ALsizei;
using OpenALDetail::ALubyte;
using OpenALDetail::ALuint;
using OpenALDetail::ALushort;
using OpenALDetail::ALvoid;
using NzOpenALDetail::ALCboolean;
using NzOpenALDetail::ALCbyte;
using NzOpenALDetail::ALCchar;
using NzOpenALDetail::ALCcontext;
using NzOpenALDetail::ALCdevice;
using NzOpenALDetail::ALCdouble;
using NzOpenALDetail::ALCenum;
using NzOpenALDetail::ALCfloat;
using NzOpenALDetail::ALCint;
using NzOpenALDetail::ALCshort;
using NzOpenALDetail::ALCsizei;
using NzOpenALDetail::ALCubyte;
using NzOpenALDetail::ALCuint;
using NzOpenALDetail::ALCushort;
using NzOpenALDetail::ALCvoid;
using OpenALDetail::ALCboolean;
using OpenALDetail::ALCbyte;
using OpenALDetail::ALCchar;
using OpenALDetail::ALCcontext;
using OpenALDetail::ALCdevice;
using OpenALDetail::ALCdouble;
using OpenALDetail::ALCenum;
using OpenALDetail::ALCfloat;
using OpenALDetail::ALCint;
using OpenALDetail::ALCshort;
using OpenALDetail::ALCsizei;
using OpenALDetail::ALCubyte;
using OpenALDetail::ALCuint;
using OpenALDetail::ALCushort;
using OpenALDetail::ALCvoid;
using NzOpenALFunc = void (*)();
class NAZARA_AUDIO_API NzOpenAL
namespace Nz
{
public:
static NzOpenALFunc GetEntry(const NzString& entryPoint);
static NzString GetRendererName();
static NzString GetVendorName();
static unsigned int GetVersion();
using OpenALFunc = void(*)();
static bool Initialize(bool openDevice = true);
class NAZARA_AUDIO_API OpenAL
{
public:
static OpenALFunc GetEntry(const String& entryPoint);
static String GetRendererName();
static String GetVendorName();
static unsigned int GetVersion();
static bool IsInitialized();
static bool Initialize(bool openDevice = true);
static unsigned int QueryInputDevices(std::vector<NzString>& devices);
static unsigned int QueryOutputDevices(std::vector<NzString>& devices);
static bool IsInitialized();
static bool SetDevice(const NzString& deviceName);
static unsigned int QueryInputDevices(std::vector<String>& devices);
static unsigned int QueryOutputDevices(std::vector<String>& devices);
static void Uninitialize();
static bool SetDevice(const String& deviceName);
static ALenum AudioFormat[nzAudioFormat_Max+1];
static void Uninitialize();
private:
static void CloseDevice();
static bool OpenDevice();
static NzOpenALFunc LoadEntry(const char* name, bool throwException = false);
};
static ALenum AudioFormat[AudioFormat_Max + 1];
private:
static void CloseDevice();
static bool OpenDevice();
static OpenALFunc LoadEntry(const char* name, bool throwException = false);
};
}
// al
NAZARA_AUDIO_API extern NzOpenALDetail::LPALBUFFER3F alBuffer3f;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALBUFFER3I alBuffer3i;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALBUFFERDATA alBufferData;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALBUFFERF alBufferf;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALBUFFERFV alBufferfv;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALBUFFERI alBufferi;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALBUFFERIV alBufferiv;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALDELETEBUFFERS alDeleteBuffers;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALDELETESOURCES alDeleteSources;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALDISABLE alDisable;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALDISTANCEMODEL alDistanceModel;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALDOPPLERFACTOR alDopplerFactor;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALDOPPLERVELOCITY alDopplerVelocity;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALENABLE alEnable;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGENBUFFERS alGenBuffers;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGENSOURCES alGenSources;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETBOOLEAN alGetBoolean;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETBOOLEANV alGetBooleanv;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETBUFFER3F alGetBuffer3f;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETBUFFER3I alGetBuffer3i;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETBUFFERF alGetBufferf;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETBUFFERFV alGetBufferfv;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETBUFFERI alGetBufferi;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETBUFFERIV alGetBufferiv;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETDOUBLE alGetDouble;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETDOUBLEV alGetDoublev;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETENUMVALUE alGetEnumValue;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETERROR alGetError;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETFLOAT alGetFloat;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETFLOATV alGetFloatv;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETINTEGER alGetInteger;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETINTEGERV alGetIntegerv;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETLISTENER3F alGetListener3f;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETLISTENER3I alGetListener3i;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETLISTENERF alGetListenerf;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETLISTENERFV alGetListenerfv;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETLISTENERI alGetListeneri;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETLISTENERIV alGetListeneriv;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETPROCADDRESS alGetProcAddress;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETSOURCE3F alGetSource3f;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETSOURCE3I alGetSource3i;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETSOURCEF alGetSourcef;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETSOURCEFV alGetSourcefv;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETSOURCEI alGetSourcei;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETSOURCEIV alGetSourceiv;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALGETSTRING alGetString;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALISBUFFER alIsBuffer;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALISENABLED alIsEnabled;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALISEXTENSIONPRESENT alIsExtensionPresent;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALISSOURCE alIsSource;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALLISTENER3F alListener3f;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALLISTENER3I alListener3i;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALLISTENERF alListenerf;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALLISTENERFV alListenerfv;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALLISTENERI alListeneri;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALLISTENERIV alListeneriv;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALSOURCE3F alSource3f;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALSOURCE3I alSource3i;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALSOURCEF alSourcef;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALSOURCEFV alSourcefv;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALSOURCEI alSourcei;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALSOURCEIV alSourceiv;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALSOURCEPAUSE alSourcePause;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALSOURCEPAUSEV alSourcePausev;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALSOURCEPLAY alSourcePlay;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALSOURCEPLAYV alSourcePlayv;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALSOURCEQUEUEBUFFERS alSourceQueueBuffers;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALSOURCEREWIND alSourceRewind;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALSOURCEREWINDV alSourceRewindv;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALSOURCESTOP alSourceStop;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALSOURCESTOPV alSourceStopv;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALSOURCEUNQUEUEBUFFERS alSourceUnqueueBuffers;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALSPEEDOFSOUND alSpeedOfSound;
NAZARA_AUDIO_API extern OpenALDetail::LPALBUFFER3F alBuffer3f;
NAZARA_AUDIO_API extern OpenALDetail::LPALBUFFER3I alBuffer3i;
NAZARA_AUDIO_API extern OpenALDetail::LPALBUFFERDATA alBufferData;
NAZARA_AUDIO_API extern OpenALDetail::LPALBUFFERF alBufferf;
NAZARA_AUDIO_API extern OpenALDetail::LPALBUFFERFV alBufferfv;
NAZARA_AUDIO_API extern OpenALDetail::LPALBUFFERI alBufferi;
NAZARA_AUDIO_API extern OpenALDetail::LPALBUFFERIV alBufferiv;
NAZARA_AUDIO_API extern OpenALDetail::LPALDELETEBUFFERS alDeleteBuffers;
NAZARA_AUDIO_API extern OpenALDetail::LPALDELETESOURCES alDeleteSources;
NAZARA_AUDIO_API extern OpenALDetail::LPALDISABLE alDisable;
NAZARA_AUDIO_API extern OpenALDetail::LPALDISTANCEMODEL alDistanceModel;
NAZARA_AUDIO_API extern OpenALDetail::LPALDOPPLERFACTOR alDopplerFactor;
NAZARA_AUDIO_API extern OpenALDetail::LPALDOPPLERVELOCITY alDopplerVelocity;
NAZARA_AUDIO_API extern OpenALDetail::LPALENABLE alEnable;
NAZARA_AUDIO_API extern OpenALDetail::LPALGENBUFFERS alGenBuffers;
NAZARA_AUDIO_API extern OpenALDetail::LPALGENSOURCES alGenSources;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETBOOLEAN alGetBoolean;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETBOOLEANV alGetBooleanv;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETBUFFER3F alGetBuffer3f;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETBUFFER3I alGetBuffer3i;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETBUFFERF alGetBufferf;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETBUFFERFV alGetBufferfv;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETBUFFERI alGetBufferi;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETBUFFERIV alGetBufferiv;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETDOUBLE alGetDouble;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETDOUBLEV alGetDoublev;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETENUMVALUE alGetEnumValue;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETERROR alGetError;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETFLOAT alGetFloat;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETFLOATV alGetFloatv;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETINTEGER alGetInteger;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETINTEGERV alGetIntegerv;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETLISTENER3F alGetListener3f;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETLISTENER3I alGetListener3i;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETLISTENERF alGetListenerf;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETLISTENERFV alGetListenerfv;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETLISTENERI alGetListeneri;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETLISTENERIV alGetListeneriv;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETPROCADDRESS alGetProcAddress;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETSOURCE3F alGetSource3f;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETSOURCE3I alGetSource3i;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETSOURCEF alGetSourcef;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETSOURCEFV alGetSourcefv;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETSOURCEI alGetSourcei;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETSOURCEIV alGetSourceiv;
NAZARA_AUDIO_API extern OpenALDetail::LPALGETSTRING alGetString;
NAZARA_AUDIO_API extern OpenALDetail::LPALISBUFFER alIsBuffer;
NAZARA_AUDIO_API extern OpenALDetail::LPALISENABLED alIsEnabled;
NAZARA_AUDIO_API extern OpenALDetail::LPALISEXTENSIONPRESENT alIsExtensionPresent;
NAZARA_AUDIO_API extern OpenALDetail::LPALISSOURCE alIsSource;
NAZARA_AUDIO_API extern OpenALDetail::LPALLISTENER3F alListener3f;
NAZARA_AUDIO_API extern OpenALDetail::LPALLISTENER3I alListener3i;
NAZARA_AUDIO_API extern OpenALDetail::LPALLISTENERF alListenerf;
NAZARA_AUDIO_API extern OpenALDetail::LPALLISTENERFV alListenerfv;
NAZARA_AUDIO_API extern OpenALDetail::LPALLISTENERI alListeneri;
NAZARA_AUDIO_API extern OpenALDetail::LPALLISTENERIV alListeneriv;
NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCE3F alSource3f;
NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCE3I alSource3i;
NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCEF alSourcef;
NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCEFV alSourcefv;
NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCEI alSourcei;
NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCEIV alSourceiv;
NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCEPAUSE alSourcePause;
NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCEPAUSEV alSourcePausev;
NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCEPLAY alSourcePlay;
NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCEPLAYV alSourcePlayv;
NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCEQUEUEBUFFERS alSourceQueueBuffers;
NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCEREWIND alSourceRewind;
NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCEREWINDV alSourceRewindv;
NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCESTOP alSourceStop;
NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCESTOPV alSourceStopv;
NAZARA_AUDIO_API extern OpenALDetail::LPALSOURCEUNQUEUEBUFFERS alSourceUnqueueBuffers;
NAZARA_AUDIO_API extern OpenALDetail::LPALSPEEDOFSOUND alSpeedOfSound;
// alc
NAZARA_AUDIO_API extern NzOpenALDetail::LPALCCAPTURECLOSEDEVICE alcCaptureCloseDevice;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALCCAPTUREOPENDEVICE alcCaptureOpenDevice;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALCCAPTURESAMPLES alcCaptureSamples;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALCCAPTURESTART alcCaptureStart;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALCCAPTURESTOP alcCaptureStop;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALCCLOSEDEVICE alcCloseDevice;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALCCREATECONTEXT alcCreateContext;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALCDESTROYCONTEXT alcDestroyContext;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALCGETCONTEXTSDEVICE alcGetContextsDevice;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALCGETCURRENTCONTEXT alcGetCurrentContext;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALCGETENUMVALUE alcGetEnumValue;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALCGETERROR alcGetError;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALCGETINTEGERV alcGetIntegerv;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALCGETPROCADDRESS alcGetProcAddress;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALCGETSTRING alcGetString;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALCISEXTENSIONPRESENT alcIsExtensionPresent;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALCMAKECONTEXTCURRENT alcMakeContextCurrent;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALCOPENDEVICE alcOpenDevice;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALCPROCESSCONTEXT alcProcessContext;
NAZARA_AUDIO_API extern NzOpenALDetail::LPALCSUSPENDCONTEXT alcSuspendContext;
NAZARA_AUDIO_API extern OpenALDetail::LPALCCAPTURECLOSEDEVICE alcCaptureCloseDevice;
NAZARA_AUDIO_API extern OpenALDetail::LPALCCAPTUREOPENDEVICE alcCaptureOpenDevice;
NAZARA_AUDIO_API extern OpenALDetail::LPALCCAPTURESAMPLES alcCaptureSamples;
NAZARA_AUDIO_API extern OpenALDetail::LPALCCAPTURESTART alcCaptureStart;
NAZARA_AUDIO_API extern OpenALDetail::LPALCCAPTURESTOP alcCaptureStop;
NAZARA_AUDIO_API extern OpenALDetail::LPALCCLOSEDEVICE alcCloseDevice;
NAZARA_AUDIO_API extern OpenALDetail::LPALCCREATECONTEXT alcCreateContext;
NAZARA_AUDIO_API extern OpenALDetail::LPALCDESTROYCONTEXT alcDestroyContext;
NAZARA_AUDIO_API extern OpenALDetail::LPALCGETCONTEXTSDEVICE alcGetContextsDevice;
NAZARA_AUDIO_API extern OpenALDetail::LPALCGETCURRENTCONTEXT alcGetCurrentContext;
NAZARA_AUDIO_API extern OpenALDetail::LPALCGETENUMVALUE alcGetEnumValue;
NAZARA_AUDIO_API extern OpenALDetail::LPALCGETERROR alcGetError;
NAZARA_AUDIO_API extern OpenALDetail::LPALCGETINTEGERV alcGetIntegerv;
NAZARA_AUDIO_API extern OpenALDetail::LPALCGETPROCADDRESS alcGetProcAddress;
NAZARA_AUDIO_API extern OpenALDetail::LPALCGETSTRING alcGetString;
NAZARA_AUDIO_API extern OpenALDetail::LPALCISEXTENSIONPRESENT alcIsExtensionPresent;
NAZARA_AUDIO_API extern OpenALDetail::LPALCMAKECONTEXTCURRENT alcMakeContextCurrent;
NAZARA_AUDIO_API extern OpenALDetail::LPALCOPENDEVICE alcOpenDevice;
NAZARA_AUDIO_API extern OpenALDetail::LPALCPROCESSCONTEXT alcProcessContext;
NAZARA_AUDIO_API extern OpenALDetail::LPALCSUSPENDCONTEXT alcSuspendContext;
#endif // NAZARA_AUDIO_OPENAL

View File

@@ -12,39 +12,46 @@
#include <Nazara/Audio/SoundBuffer.hpp>
#include <Nazara/Audio/SoundEmitter.hpp>
class NAZARA_AUDIO_API NzSound : public NzSoundEmitter
namespace Nz
{
public:
NzSound() = default;
NzSound(const NzSoundBuffer* soundBuffer);
NzSound(const NzSound& sound);
~NzSound();
class NAZARA_AUDIO_API Sound : public SoundEmitter
{
public:
Sound() = default;
Sound(const SoundBuffer* soundBuffer);
Sound(const Sound& sound);
Sound(Sound&&) = default;
~Sound();
void EnableLooping(bool loop);
void EnableLooping(bool loop);
const NzSoundBuffer* GetBuffer() const;
nzUInt32 GetDuration() const;
nzUInt32 GetPlayingOffset() const;
nzSoundStatus GetStatus() const;
const SoundBuffer* GetBuffer() const;
UInt32 GetDuration() const;
UInt32 GetPlayingOffset() const;
SoundStatus GetStatus() const;
bool IsLooping() const;
bool IsPlayable() const;
bool IsPlaying() const;
bool IsLooping() const;
bool IsPlayable() const;
bool IsPlaying() const;
bool LoadFromFile(const NzString& filePath, const NzSoundBufferParams& params = NzSoundBufferParams());
bool LoadFromMemory(const void* data, std::size_t size, const NzSoundBufferParams& params = NzSoundBufferParams());
bool LoadFromStream(NzInputStream& stream, const NzSoundBufferParams& params = NzSoundBufferParams());
bool LoadFromFile(const String& filePath, const SoundBufferParams& params = SoundBufferParams());
bool LoadFromMemory(const void* data, std::size_t size, const SoundBufferParams& params = SoundBufferParams());
bool LoadFromStream(Stream& stream, const SoundBufferParams& params = SoundBufferParams());
void Pause();
void Play();
void Pause();
void Play();
void SetBuffer(const NzSoundBuffer* buffer);
void SetPlayingOffset(nzUInt32 offset);
void SetBuffer(const SoundBuffer* buffer);
void SetPlayingOffset(UInt32 offset);
void Stop();
void Stop();
private:
NzSoundBufferConstRef m_buffer;
};
Sound& operator=(const Sound&) = delete; ///TODO?
Sound& operator=(Sound&&) = default;
private:
SoundBufferConstRef m_buffer;
};
}
#endif // NAZARA_SOUND_HPP

View File

@@ -10,8 +10,6 @@
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Audio/Config.hpp>
#include <Nazara/Audio/Enums.hpp>
#include <Nazara/Core/InputStream.hpp>
#include <Nazara/Core/NonCopyable.hpp>
#include <Nazara/Core/ObjectRef.hpp>
#include <Nazara/Core/ObjectLibrary.hpp>
#include <Nazara/Core/RefCounted.hpp>
@@ -19,73 +17,82 @@
#include <Nazara/Core/ResourceLoader.hpp>
#include <Nazara/Core/ResourceManager.hpp>
#include <Nazara/Core/Signal.hpp>
#include <Nazara/Core/Stream.hpp>
struct NzSoundBufferParams
namespace Nz
{
bool forceMono = false;
bool IsValid() const;
};
class NzSound;
class NzSoundBuffer;
using NzSoundBufferConstRef = NzObjectRef<const NzSoundBuffer>;
using NzSoundBufferLibrary = NzObjectLibrary<NzSoundBuffer>;
using NzSoundBufferLoader = NzResourceLoader<NzSoundBuffer, NzSoundBufferParams>;
using NzSoundBufferManager = NzResourceManager<NzSoundBuffer, NzSoundBufferParams>;
using NzSoundBufferRef = NzObjectRef<NzSoundBuffer>;
struct NzSoundBufferImpl;
class NAZARA_AUDIO_API NzSoundBuffer : public NzRefCounted, public NzResource, NzNonCopyable
{
friend NzSound;
friend NzSoundBufferLibrary;
friend NzSoundBufferLoader;
friend NzSoundBufferManager;
friend class NzAudio;
public:
NzSoundBuffer() = default;
NzSoundBuffer(nzAudioFormat format, unsigned int sampleCount, unsigned int sampleRate, const nzInt16* samples);
~NzSoundBuffer();
bool Create(nzAudioFormat format, unsigned int sampleCount, unsigned int sampleRate, const nzInt16* samples);
void Destroy();
nzUInt32 GetDuration() const;
nzAudioFormat GetFormat() const;
const nzInt16* GetSamples() const;
unsigned int GetSampleCount() const;
unsigned int GetSampleRate() const;
struct SoundBufferParams
{
bool forceMono = false;
bool IsValid() const;
};
bool LoadFromFile(const NzString& filePath, const NzSoundBufferParams& params = NzSoundBufferParams());
bool LoadFromMemory(const void* data, std::size_t size, const NzSoundBufferParams& params = NzSoundBufferParams());
bool LoadFromStream(NzInputStream& stream, const NzSoundBufferParams& params = NzSoundBufferParams());
class Sound;
class SoundBuffer;
static bool IsFormatSupported(nzAudioFormat format);
template<typename... Args> static NzSoundBufferRef New(Args&&... args);
using SoundBufferConstRef = ObjectRef<const SoundBuffer>;
using SoundBufferLibrary = ObjectLibrary<SoundBuffer>;
using SoundBufferLoader = ResourceLoader<SoundBuffer, SoundBufferParams>;
using SoundBufferManager = ResourceManager<SoundBuffer, SoundBufferParams>;
using SoundBufferRef = ObjectRef<SoundBuffer>;
// Signals:
NazaraSignal(OnSoundBufferDestroy, const NzSoundBuffer* /*soundBuffer*/);
NazaraSignal(OnSoundBufferRelease, const NzSoundBuffer* /*soundBuffer*/);
struct SoundBufferImpl;
private:
unsigned int GetOpenALBuffer() const;
class NAZARA_AUDIO_API SoundBuffer : public RefCounted, public Resource
{
friend Sound;
friend SoundBufferLibrary;
friend SoundBufferLoader;
friend SoundBufferManager;
friend class Audio;
static bool Initialize();
static void Uninitialize();
public:
SoundBuffer() = default;
SoundBuffer(AudioFormat format, unsigned int sampleCount, unsigned int sampleRate, const Int16* samples);
SoundBuffer(const SoundBuffer&) = delete;
SoundBuffer(SoundBuffer&&) = delete;
~SoundBuffer();
NzSoundBufferImpl* m_impl = nullptr;
bool Create(AudioFormat format, unsigned int sampleCount, unsigned int sampleRate, const Int16* samples);
void Destroy();
static NzSoundBufferLibrary::LibraryMap s_library;
static NzSoundBufferLoader::LoaderList s_loaders;
static NzSoundBufferManager::ManagerMap s_managerMap;
static NzSoundBufferManager::ManagerParams s_managerParameters;
};
UInt32 GetDuration() const;
AudioFormat GetFormat() const;
const Int16* GetSamples() const;
UInt32 GetSampleCount() const;
UInt32 GetSampleRate() const;
bool IsValid() const;
bool LoadFromFile(const String& filePath, const SoundBufferParams& params = SoundBufferParams());
bool LoadFromMemory(const void* data, std::size_t size, const SoundBufferParams& params = SoundBufferParams());
bool LoadFromStream(Stream& stream, const SoundBufferParams& params = SoundBufferParams());
static bool IsFormatSupported(AudioFormat format);
template<typename... Args> static SoundBufferRef New(Args&&... args);
SoundBuffer& operator=(const SoundBuffer&) = delete;
SoundBuffer& operator=(SoundBuffer&&) = delete; ///TODO
// Signals:
NazaraSignal(OnSoundBufferDestroy, const SoundBuffer* /*soundBuffer*/);
NazaraSignal(OnSoundBufferRelease, const SoundBuffer* /*soundBuffer*/);
private:
unsigned int GetOpenALBuffer() const;
static bool Initialize();
static void Uninitialize();
SoundBufferImpl* m_impl = nullptr;
static SoundBufferLibrary::LibraryMap s_library;
static SoundBufferLoader::LoaderList s_loaders;
static SoundBufferManager::ManagerMap s_managerMap;
static SoundBufferManager::ManagerParams s_managerParameters;
};
}
#include <Nazara/Audio/SoundBuffer.inl>

View File

@@ -5,13 +5,16 @@
#include <memory>
#include <Nazara/Audio/Debug.hpp>
template<typename... Args>
NzSoundBufferRef NzSoundBuffer::New(Args&&... args)
namespace Nz
{
std::unique_ptr<NzSoundBuffer> object(new NzSoundBuffer(std::forward<Args>(args)...));
object->SetPersistent(false);
template<typename... Args>
SoundBufferRef SoundBuffer::New(Args&&... args)
{
std::unique_ptr<SoundBuffer> object(new SoundBuffer(std::forward<Args>(args)...));
object->SetPersistent(false);
return object.release();
return object.release();
}
}
#include <Nazara/Audio/DebugOff.hpp>

View File

@@ -10,54 +10,58 @@
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Audio/Config.hpp>
#include <Nazara/Audio/Enums.hpp>
#include <Nazara/Core/InputStream.hpp>
#include <Nazara/Core/NonCopyable.hpp>
#include <Nazara/Math/Vector3.hpp>
///TODO: Faire hériter SoundEmitter de Node
class NAZARA_AUDIO_API NzSoundEmitter
namespace Nz
{
public:
virtual ~NzSoundEmitter();
class NAZARA_AUDIO_API SoundEmitter
{
public:
virtual ~SoundEmitter();
virtual void EnableLooping(bool loop) = 0;
void EnableSpatialization(bool spatialization);
virtual void EnableLooping(bool loop) = 0;
void EnableSpatialization(bool spatialization);
float GetAttenuation() const;
virtual nzUInt32 GetDuration() const = 0;
float GetMinDistance() const;
float GetPitch() const;
virtual nzUInt32 GetPlayingOffset() const = 0;
NzVector3f GetPosition() const;
NzVector3f GetVelocity() const;
virtual nzSoundStatus GetStatus() const = 0;
float GetVolume() const;
float GetAttenuation() const;
virtual UInt32 GetDuration() const = 0;
float GetMinDistance() const;
float GetPitch() const;
virtual UInt32 GetPlayingOffset() const = 0;
Vector3f GetPosition() const;
Vector3f GetVelocity() const;
virtual SoundStatus GetStatus() const = 0;
float GetVolume() const;
virtual bool IsLooping() const = 0;
bool IsSpatialized() const;
virtual bool IsLooping() const = 0;
bool IsSpatialized() const;
virtual void Pause() = 0;
virtual void Play() = 0;
virtual void Pause() = 0;
virtual void Play() = 0;
void SetAttenuation(float attenuation);
void SetMinDistance(float minDistance);
void SetPitch(float pitch);
void SetPosition(const NzVector3f& position);
void SetPosition(float x, float y, float z);
void SetVelocity(const NzVector3f& velocity);
void SetVelocity(float velX, float velY, float velZ);
void SetVolume(float volume);
void SetAttenuation(float attenuation);
void SetMinDistance(float minDistance);
void SetPitch(float pitch);
void SetPosition(const Vector3f& position);
void SetPosition(float x, float y, float z);
void SetVelocity(const Vector3f& velocity);
void SetVelocity(float velX, float velY, float velZ);
void SetVolume(float volume);
virtual void Stop() = 0;
virtual void Stop() = 0;
protected:
NzSoundEmitter();
NzSoundEmitter(const NzSoundEmitter& emitter);
SoundEmitter& operator=(const SoundEmitter&) = delete; ///TODO
SoundEmitter& operator=(SoundEmitter&&) = delete; ///TODO
nzSoundStatus GetInternalStatus() const;
protected:
SoundEmitter();
SoundEmitter(const SoundEmitter& emitter);
SoundEmitter(SoundEmitter&&) = delete; ///TODO
unsigned int m_source;
};
SoundStatus GetInternalStatus() const;
unsigned int m_source;
};
}
#endif // NAZARA_SOUNDEMITTER_HPP

View File

@@ -11,19 +11,22 @@
#include <Nazara/Audio/Config.hpp>
#include <Nazara/Audio/Enums.hpp>
class NAZARA_AUDIO_API NzSoundStream
namespace Nz
{
public:
NzSoundStream() = default;
virtual ~NzSoundStream();
class NAZARA_AUDIO_API SoundStream
{
public:
SoundStream() = default;
virtual ~SoundStream();
virtual nzUInt32 GetDuration() const = 0;
virtual nzAudioFormat GetFormat() const = 0;
virtual nzUInt64 GetSampleCount() const = 0;
virtual nzUInt32 GetSampleRate() const = 0;
virtual UInt32 GetDuration() const = 0;
virtual AudioFormat GetFormat() const = 0;
virtual UInt32 GetSampleCount() const = 0;
virtual UInt32 GetSampleRate() const = 0;
virtual unsigned int Read(void* buffer, unsigned int sampleCount) = 0;
virtual void Seek(nzUInt32 offset) = 0;
};
virtual unsigned int Read(void* buffer, unsigned int sampleCount) = 0;
virtual void Seek(UInt32 offset) = 0;
};
}
#endif // NAZARA_SOUNDSTREAM_HPP

View File

@@ -1,4 +1,4 @@
// This file was automatically generated on 24 Jun 2015 at 13:55:50
// This file was automatically generated on 20 Nov 2015 at 14:22:32
/*
Nazara Engine - Core module
@@ -49,19 +49,14 @@
#include <Nazara/Core/Functor.hpp>
#include <Nazara/Core/GuillotineBinPack.hpp>
#include <Nazara/Core/HardwareInfo.hpp>
#include <Nazara/Core/Hash.hpp>
#include <Nazara/Core/Hashable.hpp>
#include <Nazara/Core/HashDigest.hpp>
#include <Nazara/Core/Initializer.hpp>
#include <Nazara/Core/InputStream.hpp>
#include <Nazara/Core/LockGuard.hpp>
#include <Nazara/Core/Log.hpp>
#include <Nazara/Core/MemoryHelper.hpp>
#include <Nazara/Core/MemoryManager.hpp>
#include <Nazara/Core/MemoryPool.hpp>
#include <Nazara/Core/MemoryStream.hpp>
#include <Nazara/Core/MemoryView.hpp>
#include <Nazara/Core/Mutex.hpp>
#include <Nazara/Core/NonCopyable.hpp>
#include <Nazara/Core/ObjectLibrary.hpp>
#include <Nazara/Core/ObjectRef.hpp>
#include <Nazara/Core/OffsetOf.hpp>
@@ -74,6 +69,8 @@
#include <Nazara/Core/ResourceLoader.hpp>
#include <Nazara/Core/ResourceManager.hpp>
#include <Nazara/Core/Semaphore.hpp>
#include <Nazara/Core/Serialization.hpp>
#include <Nazara/Core/Serializer.hpp>
#include <Nazara/Core/Signal.hpp>
#include <Nazara/Core/SparsePtr.hpp>
#include <Nazara/Core/Stream.hpp>
@@ -82,6 +79,7 @@
#include <Nazara/Core/TaskScheduler.hpp>
#include <Nazara/Core/Thread.hpp>
#include <Nazara/Core/Unicode.hpp>
#include <Nazara/Core/Unserializer.hpp>
#include <Nazara/Core/Updatable.hpp>
#endif // NAZARA_GLOBAL_CORE_HPP

View File

@@ -8,19 +8,33 @@
#define NAZARA_ABSTRACTHASH_HPP
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/NonCopyable.hpp>
#include <Nazara/Core/Enums.hpp>
#include <memory>
class NzHashDigest;
class NAZARA_CORE_API NzAbstractHash : NzNonCopyable
namespace Nz
{
public:
NzAbstractHash() = default;
virtual ~NzAbstractHash();
class ByteArray;
virtual void Append(const nzUInt8* data, unsigned int len) = 0;
virtual void Begin() = 0;
virtual NzHashDigest End() = 0;
};
class NAZARA_CORE_API AbstractHash
{
public:
AbstractHash() = default;
AbstractHash(const AbstractHash&) = delete;
AbstractHash(AbstractHash&&) = default;
virtual ~AbstractHash();
virtual void Append(const UInt8* data, std::size_t len) = 0;
virtual void Begin() = 0;
virtual ByteArray End() = 0;
virtual std::size_t GetDigestLength() const = 0;
virtual const char* GetHashName() const = 0;
AbstractHash& operator=(const AbstractHash&) = delete;
AbstractHash& operator=(AbstractHash&&) = default;
static std::unique_ptr<AbstractHash> Get(HashType hash);
};
}
#endif // NAZARA_ABSTRACTHASH_HPP

View File

@@ -0,0 +1,9 @@
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp
/*!
* \class Nz::AbstractLogger
* \brief Logger interface
*/

View File

@@ -0,0 +1,31 @@
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#pragma once
#ifndef NAZARA_ABSTRACTLOGGER_HPP
#define NAZARA_ABSTRACTLOGGER_HPP
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/Enums.hpp>
#include <Nazara/Core/String.hpp>
namespace Nz
{
class NAZARA_CORE_API AbstractLogger
{
public:
AbstractLogger() = default;
virtual ~AbstractLogger();
virtual void EnableStdReplication(bool enable) = 0;
virtual bool IsStdReplicationEnabled() = 0;
virtual void Write(const String& string) = 0;
virtual void WriteError(ErrorType type, const String& error, unsigned int line = 0, const char* file = nullptr, const char* function = nullptr);
};
}
#endif // NAZARA_ABSTRACTLOGGER_HPP

View File

@@ -8,15 +8,36 @@
#define NAZARA_ALGORITHM_CORE_HPP
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/Enums.hpp>
#include <Nazara/Core/Serialization.hpp>
#include <functional>
#include <tuple>
#include <type_traits>
template<typename F, typename Tuple> auto NzApply(F&& fn, Tuple&& t);
template<typename O, typename F, typename Tuple> auto NzApply(O& object, F&& fn, Tuple&& t);
template<typename T> void NzHashCombine(std::size_t& seed, const T& v);
namespace Nz
{
class AbstractHash;
class ByteArray;
template<typename T>
struct NzTypeTag {};
template<typename F, typename Tuple> auto Apply(F&& fn, Tuple&& t);
template<typename O, typename F, typename Tuple> auto Apply(O& object, F&& fn, Tuple&& t);
template<typename T> ByteArray ComputeHash(HashType hash, const T& v);
template<typename T> ByteArray ComputeHash(AbstractHash* hash, const T& v);
template<typename T> void HashCombine(std::size_t& seed, const T& v);
template<typename T>
struct TypeTag {};
inline bool Serialize(SerializationContext& context, bool value);
template<typename T>
std::enable_if_t<std::is_arithmetic<T>::value, bool> Serialize(SerializationContext& context, T value);
inline bool Unserialize(UnserializationContext& context, bool* value);
template<typename T>
std::enable_if_t<std::is_arithmetic<T>::value, bool> Unserialize(UnserializationContext& context, T* value);
}
#include <Nazara/Core/Algorithm.inl>

View File

@@ -6,51 +6,152 @@
// Merci à Ryan "FullMetal Alchemist" Lahfa
// Merci aussi à Freedom de siteduzero.com
#include <Nazara/Core/AbstractHash.hpp>
#include <Nazara/Core/ByteArray.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Core/Stream.hpp>
#include <Nazara/Core/Debug.hpp>
// http://www.cppsamples.com/common-tasks/apply-tuple-to-function.html
template<typename F, typename Tuple, size_t... S>
auto NzApplyImplFunc(F&& fn, Tuple&& t, std::index_sequence<S...>)
namespace Nz
{
return std::forward<F>(fn)(std::get<S>(std::forward<Tuple>(t))...);
}
namespace Detail
{
// http://www.cppsamples.com/common-tasks/apply-tuple-to-function.html
template<typename F, typename Tuple, size_t... S>
auto ApplyImplFunc(F&& fn, Tuple&& t, std::index_sequence<S...>)
{
return std::forward<F>(fn)(std::get<S>(std::forward<Tuple>(t))...);
}
template<typename F, typename Tuple>
auto NzApply(F&& fn, Tuple&& t)
{
constexpr std::size_t tSize = std::tuple_size<typename std::remove_reference<Tuple>::type>::value;
template<typename O, typename F, typename Tuple, size_t... S>
auto ApplyImplMethod(O& object, F&& fn, Tuple&& t, std::index_sequence<S...>)
{
return (object .* std::forward<F>(fn))(std::get<S>(std::forward<Tuple>(t))...);
}
}
return NzApplyImplFunc(std::forward<F>(fn), std::forward<Tuple>(t), std::make_index_sequence<tSize>());
}
template<typename F, typename Tuple>
auto Apply(F&& fn, Tuple&& t)
{
constexpr std::size_t tSize = std::tuple_size<typename std::remove_reference<Tuple>::type>::value;
template<typename O, typename F, typename Tuple, size_t... S>
auto NzApplyImplMethod(O& object, F&& fn, Tuple&& t, std::index_sequence<S...>)
{
return (object .* std::forward<F>(fn))(std::get<S>(std::forward<Tuple>(t))...);
}
return Detail::ApplyImplFunc(std::forward<F>(fn), std::forward<Tuple>(t), std::make_index_sequence<tSize>());
}
template<typename O, typename F, typename Tuple>
auto NzApply(O& object, F&& fn, Tuple&& t)
{
constexpr std::size_t tSize = std::tuple_size<typename std::remove_reference<Tuple>::type>::value;
template<typename O, typename F, typename Tuple>
auto Apply(O& object, F&& fn, Tuple&& t)
{
constexpr std::size_t tSize = std::tuple_size<typename std::remove_reference<Tuple>::type>::value;
return NzApplyImplMethod(object, std::forward<F>(fn), std::forward<Tuple>(t), std::make_index_sequence<tSize>());
}
// Algorithme venant de CityHash par Google
// http://stackoverflow.com/questions/8513911/how-to-create-a-good-hash-combine-with-64-bit-output-inspired-by-boosthash-co
template<typename T>
void NzHashCombine(std::size_t& seed, const T& v)
{
const nzUInt64 kMul = 0x9ddfea08eb382d69ULL;
return Detail::ApplyImplMethod(object, std::forward<F>(fn), std::forward<Tuple>(t), std::make_index_sequence<tSize>());
}
std::hash<T> hasher;
nzUInt64 a = (hasher(v) ^ seed) * kMul;
a ^= (a >> 47);
template<typename T>
ByteArray ComputeHash(HashType hash, const T& v)
{
return ComputeHash(AbstractHash::Get(hash).get(), v);
}
nzUInt64 b = (seed ^ a) * kMul;
b ^= (b >> 47);
template<typename T>
ByteArray ComputeHash(AbstractHash* hash, const T& v)
{
hash->Begin();
seed = static_cast<std::size_t>(b * kMul);
HashAppend(hash, v);
return hash->End();
}
// Algorithme venant de CityHash par Google
// http://stackoverflow.com/questions/8513911/how-to-create-a-good-hash-combine-with-64-bit-output-inspired-by-boosthash-co
template<typename T>
void HashCombine(std::size_t& seed, const T& v)
{
const UInt64 kMul = 0x9ddfea08eb382d69ULL;
std::hash<T> hasher;
UInt64 a = (hasher(v) ^ seed) * kMul;
a ^= (a >> 47);
UInt64 b = (seed ^ a) * kMul;
b ^= (b >> 47);
seed = static_cast<std::size_t>(b * kMul);
}
inline bool Serialize(SerializationContext& context, bool value)
{
if (context.currentBitPos == 8)
{
context.currentBitPos = 0;
context.currentByte = 0;
}
if (value)
context.currentByte |= 1 << context.currentBitPos;
if (++context.currentBitPos >= 8)
return Serialize<UInt8>(context, context.currentByte);
else
return true;
}
template<typename T>
std::enable_if_t<std::is_arithmetic<T>::value, bool> Serialize(SerializationContext& context, T value)
{
// Flush bits if a writing is in progress
if (context.currentBitPos != 8)
{
context.currentBitPos = 8;
if (!Serialize<UInt8>(context, context.currentByte))
NazaraWarning("Failed to flush bits");
}
if (context.endianness != Endianness_Unknown && context.endianness != GetPlatformEndianness())
SwapBytes(&value, sizeof(T));
return context.stream->Write(&value, sizeof(T)) == sizeof(T);
}
inline bool Unserialize(UnserializationContext& context, bool* value)
{
NazaraAssert(value, "Invalid data pointer");
if (context.currentBitPos == 8)
{
if (!Unserialize(context, &context.currentByte))
return false;
context.currentBitPos = 0;
}
if (value)
*value = (context.currentByte & (1 << context.currentBitPos)) != 0;
context.currentBitPos++;
return true;
}
template<typename T>
std::enable_if_t<std::is_arithmetic<T>::value, bool> Unserialize(UnserializationContext& context, T* value)
{
NazaraAssert(value, "Invalid data pointer");
// Reset bit position
context.currentBitPos = 8;
if (context.stream->Read(value, sizeof(T)) == sizeof(T))
{
if (context.endianness != Endianness_Unknown && context.endianness != GetPlatformEndianness())
SwapBytes(value, sizeof(T));
return true;
}
else
return false;
}
}
#include <Nazara/Core/DebugOff.hpp>

View File

@@ -12,165 +12,168 @@
#include <memory>
#include <type_traits>
class NzAbstractHash;
template<typename Block = nzUInt32, class Allocator = std::allocator<Block>>
class NzBitset
namespace Nz
{
static_assert(std::is_integral<Block>::value && std::is_unsigned<Block>::value, "Block must be a unsigned integral type");
class AbstractHash;
public:
class Bit;
template<typename Block = UInt32, class Allocator = std::allocator<Block>>
class Bitset
{
static_assert(std::is_integral<Block>::value && std::is_unsigned<Block>::value, "Block must be a unsigned integral type");
NzBitset();
explicit NzBitset(unsigned int bitCount, bool val = false);
explicit NzBitset(const char* bits);
NzBitset(const char* bits, unsigned int bitCount);
NzBitset(const NzBitset& bitset) = default;
explicit NzBitset(const NzString& bits);
NzBitset(NzBitset&& bitset) noexcept = default;
~NzBitset() = default;
public:
class Bit;
void Clear();
unsigned int Count() const;
void Flip();
Bitset();
explicit Bitset(unsigned int bitCount, bool val = false);
explicit Bitset(const char* bits);
Bitset(const char* bits, unsigned int bitCount);
Bitset(const Bitset& bitset) = default;
explicit Bitset(const String& bits);
Bitset(Bitset&& bitset) noexcept = default;
~Bitset() = default;
unsigned int FindFirst() const;
unsigned int FindNext(unsigned int bit) const;
void Clear();
unsigned int Count() const;
void Flip();
Block GetBlock(unsigned int i) const;
unsigned int GetBlockCount() const;
unsigned int GetCapacity() const;
unsigned int GetSize() const;
unsigned int FindFirst() const;
unsigned int FindNext(unsigned int bit) const;
void PerformsAND(const NzBitset& a, const NzBitset& b);
void PerformsNOT(const NzBitset& a);
void PerformsOR(const NzBitset& a, const NzBitset& b);
void PerformsXOR(const NzBitset& a, const NzBitset& b);
Block GetBlock(unsigned int i) const;
unsigned int GetBlockCount() const;
unsigned int GetCapacity() const;
unsigned int GetSize() const;
bool Intersects(const NzBitset& bitset) const;
void PerformsAND(const Bitset& a, const Bitset& b);
void PerformsNOT(const Bitset& a);
void PerformsOR(const Bitset& a, const Bitset& b);
void PerformsXOR(const Bitset& a, const Bitset& b);
void Reserve(unsigned int bitCount);
void Resize(unsigned int bitCount, bool defaultVal = false);
bool Intersects(const Bitset& bitset) const;
void Reset();
void Reset(unsigned int bit);
void Reserve(unsigned int bitCount);
void Resize(unsigned int bitCount, bool defaultVal = false);
void Set(bool val = true);
void Set(unsigned int bit, bool val = true);
void SetBlock(unsigned int i, Block block);
void Reset();
void Reset(unsigned int bit);
void Swap(NzBitset& bitset);
void Set(bool val = true);
void Set(unsigned int bit, bool val = true);
void SetBlock(unsigned int i, Block block);
bool Test(unsigned int bit) const;
bool TestAll() const;
bool TestAny() const;
bool TestNone() const;
void Swap(Bitset& bitset);
template<typename T> T To() const;
NzString ToString() const;
bool Test(unsigned int bit) const;
bool TestAll() const;
bool TestAny() const;
bool TestNone() const;
void UnboundedReset(unsigned int bit);
void UnboundedSet(unsigned int bit, bool val = true);
bool UnboundedTest(unsigned int bit) const;
template<typename T> T To() const;
String ToString() const;
Bit operator[](int index);
bool operator[](int index) const;
void UnboundedReset(unsigned int bit);
void UnboundedSet(unsigned int bit, bool val = true);
bool UnboundedTest(unsigned int bit) const;
NzBitset operator~() const;
Bit operator[](int index);
bool operator[](int index) const;
NzBitset& operator=(const NzBitset& bitset) = default;
NzBitset& operator=(const NzString& bits);
NzBitset& operator=(NzBitset&& bitset) noexcept = default;
Bitset operator~() const;
NzBitset& operator&=(const NzBitset& bitset);
NzBitset& operator|=(const NzBitset& bitset);
NzBitset& operator^=(const NzBitset& bitset);
Bitset& operator=(const Bitset& bitset) = default;
Bitset& operator=(const String& bits);
Bitset& operator=(Bitset&& bitset) noexcept = default;
static Block fullBitMask;
static unsigned int bitsPerBlock;
static unsigned int npos;
Bitset& operator&=(const Bitset& bitset);
Bitset& operator|=(const Bitset& bitset);
Bitset& operator^=(const Bitset& bitset);
private:
unsigned int FindFirstFrom(unsigned int blockIndex) const;
Block GetLastBlockMask() const;
void ResetExtraBits();
static Block fullBitMask;
static unsigned int bitsPerBlock;
static unsigned int npos;
static unsigned int ComputeBlockCount(unsigned int bitCount);
static unsigned int GetBitIndex(unsigned int bit);
static unsigned int GetBlockIndex(unsigned int bit);
private:
unsigned int FindFirstFrom(unsigned int blockIndex) const;
Block GetLastBlockMask() const;
void ResetExtraBits();
std::vector<Block, Allocator> m_blocks;
unsigned int m_bitCount;
};
static unsigned int ComputeBlockCount(unsigned int bitCount);
static unsigned int GetBitIndex(unsigned int bit);
static unsigned int GetBlockIndex(unsigned int bit);
template<typename Block, class Allocator>
bool operator==(const NzBitset<Block, Allocator>& lhs, const NzBitset<Block, Allocator>& rhs);
std::vector<Block, Allocator> m_blocks;
unsigned int m_bitCount;
};
template<typename Block, class Allocator>
bool operator!=(const NzBitset<Block, Allocator>& lhs, const NzBitset<Block, Allocator>& rhs);
template<typename Block, class Allocator>
class Bitset<Block, Allocator>::Bit
{
friend Bitset<Block, Allocator>;
template<typename Block, class Allocator>
bool operator<(const NzBitset<Block, Allocator>& lhs, const NzBitset<Block, Allocator>& rhs);
public:
Bit(const Bit& bit) = default;
template<typename Block, class Allocator>
bool operator<=(const NzBitset<Block, Allocator>& lhs, const NzBitset<Block, Allocator>& rhs);
Bit& Flip();
Bit& Reset();
Bit& Set(bool val = true);
bool Test() const;
template<typename Block, class Allocator>
bool operator>(const NzBitset<Block, Allocator>& lhs, const NzBitset<Block, Allocator>& rhs);
template<bool BadCall = true>
void* operator&() const;
template<typename Block, class Allocator>
bool operator>=(const NzBitset<Block, Allocator>& lhs, const NzBitset<Block, Allocator>& rhs);
operator bool() const;
Bit& operator=(bool val);
Bit& operator=(const Bit& bit);
template<typename Block, class Allocator>
NzBitset<Block, Allocator> operator&(const NzBitset<Block, Allocator>& lhs, const NzBitset<Block, Allocator>& rhs);
Bit& operator|=(bool val);
Bit& operator&=(bool val);
Bit& operator^=(bool val);
Bit& operator-=(bool val);
template<typename Block, class Allocator>
NzBitset<Block, Allocator> operator|(const NzBitset<Block, Allocator>& lhs, const NzBitset<Block, Allocator>& rhs);
private:
Bit(Block& block, Block mask) :
m_block(block),
m_mask(mask)
{
}
template<typename Block, class Allocator>
NzBitset<Block, Allocator> operator^(const NzBitset<Block, Allocator>& lhs, const NzBitset<Block, Allocator>& rhs);
Block& m_block;
Block m_mask;
};
template<typename Block, class Allocator>
class NzBitset<Block, Allocator>::Bit
{
friend NzBitset<Block, Allocator>;
template<typename Block, class Allocator>
bool operator==(const Bitset<Block, Allocator>& lhs, const Nz::Bitset<Block, Allocator>& rhs);
public:
Bit(const Bit& bit) = default;
template<typename Block, class Allocator>
bool operator!=(const Bitset<Block, Allocator>& lhs, const Nz::Bitset<Block, Allocator>& rhs);
Bit& Flip();
Bit& Reset();
Bit& Set(bool val = true);
bool Test() const;
template<typename Block, class Allocator>
bool operator<(const Bitset<Block, Allocator>& lhs, const Nz::Bitset<Block, Allocator>& rhs);
template<bool BadCall = true>
void* operator&() const;
template<typename Block, class Allocator>
bool operator<=(const Bitset<Block, Allocator>& lhs, const Nz::Bitset<Block, Allocator>& rhs);
operator bool() const;
Bit& operator=(bool val);
Bit& operator=(const Bit& bit);
template<typename Block, class Allocator>
bool operator>(const Bitset<Block, Allocator>& lhs, const Nz::Bitset<Block, Allocator>& rhs);
Bit& operator|=(bool val);
Bit& operator&=(bool val);
Bit& operator^=(bool val);
Bit& operator-=(bool val);
template<typename Block, class Allocator>
bool operator>=(const Bitset<Block, Allocator>& lhs, const Nz::Bitset<Block, Allocator>& rhs);
private:
Bit(Block& block, Block mask) :
m_block(block),
m_mask(mask)
{
}
template<typename Block, class Allocator>
Bitset<Block, Allocator> operator&(const Bitset<Block, Allocator>& lhs, const Bitset<Block, Allocator>& rhs);
Block& m_block;
Block m_mask;
};
template<typename Block, class Allocator>
Bitset<Block, Allocator> operator|(const Bitset<Block, Allocator>& lhs, const Bitset<Block, Allocator>& rhs);
template<typename Block, class Allocator>
Bitset<Block, Allocator> operator^(const Bitset<Block, Allocator>& lhs, const Bitset<Block, Allocator>& rhs);
}
namespace std
{
template<typename Block, class Allocator>
void swap(NzBitset<Block, Allocator>& lhs, NzBitset<Block, Allocator>& rhs);
void swap(Nz::Bitset<Block, Allocator>& lhs, Nz::Bitset<Block, Allocator>& rhs);
}
#include <Nazara/Core/Bitset.inl>

File diff suppressed because it is too large Load Diff

View File

@@ -8,130 +8,132 @@
#define NAZARA_BYTEARRAY_HPP
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Core/Hashable.hpp>
#include <Nazara/Core/String.hpp>
#include <vector>
class NzAbstractHash;
class NAZARA_CORE_API NzByteArray : public NzHashable
namespace Nz
{
using Container = std::vector<nzUInt8>;
class AbstractHash;
public:
// types:
using allocator_type = Container::allocator_type;
using const_iterator = Container::const_iterator;
using const_reference = Container::const_reference;
using const_pointer = Container::const_pointer;
using const_reverse_iterator = Container::const_reverse_iterator;
using difference_type = Container::difference_type;
using pointer = Container::pointer;
using iterator = Container::iterator;
using reference = Container::reference;
using reverse_iterator = Container::reverse_iterator;
using size_type = Container::size_type;
using value_type = Container::value_type;
class NAZARA_CORE_API ByteArray
{
using Container = std::vector<UInt8>;
// construct/destroy:
inline NzByteArray() = default;
inline explicit NzByteArray(size_type n);
inline NzByteArray(const void* buffer, size_type n);
inline NzByteArray(size_type n, value_type value);
template <class InputIterator> NzByteArray(InputIterator first, InputIterator last);
NzByteArray(const NzByteArray& other) = default;
NzByteArray(NzByteArray&& other) = default;
~NzByteArray() = default;
public:
// types:
using allocator_type = Container::allocator_type;
using const_iterator = Container::const_iterator;
using const_reference = Container::const_reference;
using const_pointer = Container::const_pointer;
using const_reverse_iterator = Container::const_reverse_iterator;
using difference_type = Container::difference_type;
using pointer = Container::pointer;
using iterator = Container::iterator;
using reference = Container::reference;
using reverse_iterator = Container::reverse_iterator;
using size_type = Container::size_type;
using value_type = Container::value_type;
inline iterator Append(const void* buffer, size_type size);
inline iterator Append(const NzByteArray& other);
template <class InputIterator> void Assign(InputIterator first, InputIterator last);
inline void Assign(size_type n, value_type value);
// construct/destroy:
inline ByteArray() = default;
inline explicit ByteArray(size_type n);
inline ByteArray(const void* buffer, size_type n);
inline ByteArray(size_type n, value_type value);
template <class InputIterator> ByteArray(InputIterator first, InputIterator last);
ByteArray(const ByteArray& other) = default;
ByteArray(ByteArray&& other) = default;
~ByteArray() = default;
inline reference Back();
inline const_reference Back() const;
inline iterator Append(const void* buffer, size_type size);
inline iterator Append(const ByteArray& other);
template <class InputIterator> void Assign(InputIterator first, InputIterator last);
inline void Assign(size_type n, value_type value);
inline void Clear(bool keepBuffer = false);
inline reference Back();
inline const_reference Back() const;
inline iterator Erase(const_iterator pos);
inline iterator Erase(const_iterator first, const_iterator last);
inline void Clear(bool keepBuffer = false);
inline reference Front();
inline const_reference Front() const;
inline iterator Erase(const_iterator pos);
inline iterator Erase(const_iterator first, const_iterator last);
inline allocator_type GetAllocator() const;
inline pointer GetBuffer();
inline size_type GetCapacity() const noexcept;
inline const_pointer GetConstBuffer() const;
inline size_type GetMaxSize() const noexcept;
inline size_type GetSize() const noexcept;
inline NzByteArray GetSubArray(const_iterator startPos, const_iterator endPos) const;
inline reference Front();
inline const_reference Front() const;
inline iterator Insert(const_iterator pos, const void* buffer, size_type n);
inline iterator Insert(const_iterator pos, const NzByteArray& other);
inline iterator Insert(const_iterator pos, size_type n, value_type byte);
template <class InputIterator> iterator Insert(const_iterator pos, InputIterator first, InputIterator last);
inline bool IsEmpty() const noexcept;
inline allocator_type GetAllocator() const;
inline pointer GetBuffer();
inline size_type GetCapacity() const noexcept;
inline const_pointer GetConstBuffer() const;
inline size_type GetMaxSize() const noexcept;
inline size_type GetSize() const noexcept;
inline ByteArray GetSubArray(const_iterator startPos, const_iterator endPos) const;
inline void PopBack();
inline void PopFront();
inline iterator Prepend(const void* buffer, size_type size);
inline iterator Prepend(const NzByteArray& other);
inline void PushBack(value_type byte);
inline void PushFront(value_type byte);
inline iterator Insert(const_iterator pos, const void* buffer, size_type n);
inline iterator Insert(const_iterator pos, const ByteArray& other);
inline iterator Insert(const_iterator pos, size_type n, value_type byte);
template <class InputIterator> iterator Insert(const_iterator pos, InputIterator first, InputIterator last);
inline bool IsEmpty() const noexcept;
inline void Reserve(size_type bufferSize);
inline void Resize(size_type newSize);
inline void Resize(size_type newSize, value_type byte);
inline void PopBack();
inline void PopFront();
inline iterator Prepend(const void* buffer, size_type size);
inline iterator Prepend(const ByteArray& other);
inline void PushBack(value_type byte);
inline void PushFront(value_type byte);
inline void ShrinkToFit();
inline void Swap(NzByteArray& other);
inline void Reserve(size_type bufferSize);
inline void Resize(size_type newSize);
inline void Resize(size_type newSize, value_type byte);
inline NzString ToString() const;
inline void ShrinkToFit();
inline void Swap(ByteArray& other);
// STL interface
inline iterator begin() noexcept;
inline const_iterator begin() const noexcept;
inline bool empty() const noexcept;
inline iterator end() noexcept;
inline const_iterator end() const noexcept;
inline reverse_iterator rbegin() noexcept;
inline const_reverse_iterator rbegin() const noexcept;
inline reverse_iterator rend() noexcept;
inline const_reverse_iterator rend() const noexcept;
inline const_iterator cbegin() const noexcept;
inline const_iterator cend() const noexcept;
inline const_reverse_iterator crbegin() const noexcept;
inline const_reverse_iterator crend() const noexcept;
inline size_type size() const noexcept;
inline String ToHex() const;
inline String ToString() const;
// Operators
inline reference operator[](size_type pos);
inline const_reference operator[](size_type pos) const;
inline NzByteArray& operator=(const NzByteArray& array) = default;
inline NzByteArray& operator=(NzByteArray&& array) = default;
inline NzByteArray operator+(const NzByteArray& array) const;
inline NzByteArray& operator+=(const NzByteArray& array);
// STL interface
inline iterator begin() noexcept;
inline const_iterator begin() const noexcept;
inline bool empty() const noexcept;
inline iterator end() noexcept;
inline const_iterator end() const noexcept;
inline reverse_iterator rbegin() noexcept;
inline const_reverse_iterator rbegin() const noexcept;
inline reverse_iterator rend() noexcept;
inline const_reverse_iterator rend() const noexcept;
inline const_iterator cbegin() const noexcept;
inline const_iterator cend() const noexcept;
inline const_reverse_iterator crbegin() const noexcept;
inline const_reverse_iterator crend() const noexcept;
inline size_type size() const noexcept;
inline bool operator==(const NzByteArray& rhs) const;
inline bool operator!=(const NzByteArray& rhs) const;
inline bool operator<(const NzByteArray& rhs) const;
inline bool operator<=(const NzByteArray& rhs) const;
inline bool operator>(const NzByteArray& rhs) const;
inline bool operator>=(const NzByteArray& rhs) const;
// Operators
NAZARA_CORE_API friend std::ostream& operator<<(std::ostream& out, const Nz::ByteArray& byteArray);
private:
bool FillHash(NzAbstractHash* hash) const;
inline reference operator[](size_type pos);
inline const_reference operator[](size_type pos) const;
inline ByteArray& operator=(const ByteArray& array) = default;
inline ByteArray& operator=(ByteArray&& array) = default;
inline ByteArray operator+(const ByteArray& array) const;
inline ByteArray& operator+=(const ByteArray& array);
Container m_array;
};
inline bool operator==(const ByteArray& rhs) const;
inline bool operator!=(const ByteArray& rhs) const;
inline bool operator<(const ByteArray& rhs) const;
inline bool operator<=(const ByteArray& rhs) const;
inline bool operator>(const ByteArray& rhs) const;
inline bool operator>=(const ByteArray& rhs) const;
NAZARA_CORE_API std::ostream& operator<<(std::ostream& out, const NzByteArray& byteArray);
private:
Container m_array;
};
inline bool HashAppend(AbstractHash* hash, const ByteArray& byteArray);
}
namespace std
{
void swap(NzByteArray& lhs, NzByteArray& rhs);
void swap(Nz::ByteArray& lhs, Nz::ByteArray& rhs);
}
#include <Nazara/Core/ByteArray.inl>

View File

@@ -2,327 +2,356 @@
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp
inline NzByteArray::NzByteArray(size_type n) :
m_array()
#include <Nazara/Core/Error.hpp>
namespace Nz
{
m_array.reserve(n);
}
inline ByteArray::ByteArray(size_type n) :
m_array()
{
m_array.reserve(n);
}
inline NzByteArray::NzByteArray(const void* buffer, size_type n) :
m_array(static_cast<const_pointer>(buffer), static_cast<const_pointer>(buffer) + n)
{
}
inline ByteArray::ByteArray(const void* buffer, size_type n) :
m_array(static_cast<const_pointer>(buffer), static_cast<const_pointer>(buffer) + n)
{
}
inline NzByteArray::NzByteArray(size_type n, const value_type value) :
m_array(n, value)
{
}
inline ByteArray::ByteArray(size_type n, const value_type value) :
m_array(n, value)
{
}
template <class InputIterator>
NzByteArray::NzByteArray(InputIterator first, InputIterator last) :
m_array(first, last)
{
}
template <class InputIterator>
ByteArray::ByteArray(InputIterator first, InputIterator last) :
m_array(first, last)
{
}
inline NzByteArray::iterator NzByteArray::Append(const void* buffer, size_type n)
{
return Insert(end(), static_cast<const_pointer>(buffer), static_cast<const_pointer>(buffer) + n);
}
inline ByteArray::iterator ByteArray::Append(const void* buffer, size_type n)
{
return Insert(end(), static_cast<const_pointer>(buffer), static_cast<const_pointer>(buffer) + n);
}
inline NzByteArray::iterator NzByteArray::Append(const NzByteArray& other)
{
return Insert(end(), other.begin(), other.end());
}
inline ByteArray::iterator ByteArray::Append(const ByteArray& other)
{
return Insert(end(), other.begin(), other.end());
}
inline void NzByteArray::Assign(size_type n, value_type value)
{
m_array.assign(n, value);
}
inline void ByteArray::Assign(size_type n, value_type value)
{
m_array.assign(n, value);
}
template <class InputIterator>
void NzByteArray::Assign(InputIterator first, InputIterator last)
{
m_array.assign(first, last);
}
template <class InputIterator>
void ByteArray::Assign(InputIterator first, InputIterator last)
{
m_array.assign(first, last);
}
inline NzByteArray::reference NzByteArray::Back()
{
return m_array.back();
}
inline ByteArray::reference ByteArray::Back()
{
return m_array.back();
}
inline NzByteArray::const_reference NzByteArray::Back() const
{
return m_array.back();
}
inline ByteArray::const_reference ByteArray::Back() const
{
return m_array.back();
}
inline NzByteArray::iterator NzByteArray::Erase(const_iterator pos)
{
return m_array.erase(pos);
}
inline void ByteArray::Clear(bool keepBuffer)
{
m_array.clear();
if (!keepBuffer)
m_array.shrink_to_fit();
}
inline NzByteArray::iterator NzByteArray::Erase(const_iterator first, const_iterator last)
{
return m_array.erase(first, last);
}
inline ByteArray::iterator ByteArray::Erase(const_iterator pos)
{
return m_array.erase(pos);
}
inline NzByteArray::reference NzByteArray::Front()
{
return m_array.front();
}
inline ByteArray::iterator ByteArray::Erase(const_iterator first, const_iterator last)
{
return m_array.erase(first, last);
}
inline NzByteArray::const_reference NzByteArray::Front() const
{
return m_array.front();
}
inline ByteArray::reference ByteArray::Front()
{
return m_array.front();
}
inline NzByteArray::allocator_type NzByteArray::GetAllocator() const
{
return m_array.get_allocator();
}
inline ByteArray::const_reference ByteArray::Front() const
{
return m_array.front();
}
inline NzByteArray::pointer NzByteArray::GetBuffer()
{
return m_array.data();
}
inline ByteArray::allocator_type ByteArray::GetAllocator() const
{
return m_array.get_allocator();
}
inline NzByteArray::size_type NzByteArray::GetCapacity() const noexcept
{
return m_array.capacity();
}
inline ByteArray::pointer ByteArray::GetBuffer()
{
return m_array.data();
}
inline NzByteArray::const_pointer NzByteArray::GetConstBuffer() const
{
return m_array.data();
}
inline ByteArray::size_type ByteArray::GetCapacity() const noexcept
{
return m_array.capacity();
}
inline NzByteArray::size_type NzByteArray::GetMaxSize() const noexcept
{
return m_array.max_size();
}
inline ByteArray::const_pointer ByteArray::GetConstBuffer() const
{
return m_array.data();
}
inline NzByteArray::size_type NzByteArray::GetSize() const noexcept
{
return m_array.size();
}
inline ByteArray::size_type ByteArray::GetMaxSize() const noexcept
{
return m_array.max_size();
}
inline NzByteArray NzByteArray::GetSubArray(const_iterator startPos, const_iterator endPos) const
{
return NzByteArray(startPos, endPos);
}
inline ByteArray::size_type ByteArray::GetSize() const noexcept
{
return m_array.size();
}
inline NzByteArray::iterator NzByteArray::Insert(const_iterator pos, const void* buffer, size_type n)
{
return m_array.insert(pos, static_cast<const_pointer>(buffer), static_cast<const_pointer>(buffer) + n);
}
inline ByteArray ByteArray::GetSubArray(const_iterator startPos, const_iterator endPos) const
{
return ByteArray(startPos, endPos);
}
inline NzByteArray::iterator NzByteArray::Insert(const_iterator pos, const NzByteArray& other)
{
return m_array.insert(pos, other.begin(), other.end());
}
inline ByteArray::iterator ByteArray::Insert(const_iterator pos, const void* buffer, size_type n)
{
return m_array.insert(pos, static_cast<const_pointer>(buffer), static_cast<const_pointer>(buffer) + n);
}
inline NzByteArray::iterator NzByteArray::Insert(const_iterator pos, size_type n, value_type byte)
{
return m_array.insert(pos, n, byte);
}
inline ByteArray::iterator ByteArray::Insert(const_iterator pos, const ByteArray& other)
{
return m_array.insert(pos, other.begin(), other.end());
}
template <class InputIterator>
NzByteArray::iterator NzByteArray::Insert(const_iterator pos, InputIterator first, InputIterator last)
{
return m_array.insert(pos, first, last);
}
inline ByteArray::iterator ByteArray::Insert(const_iterator pos, size_type n, value_type byte)
{
return m_array.insert(pos, n, byte);
}
inline bool NzByteArray::IsEmpty() const noexcept
{
return m_array.empty();
}
template <class InputIterator>
ByteArray::iterator ByteArray::Insert(const_iterator pos, InputIterator first, InputIterator last)
{
return m_array.insert(pos, first, last);
}
inline void NzByteArray::PopBack()
{
Erase(end() - 1);
}
inline bool ByteArray::IsEmpty() const noexcept
{
return m_array.empty();
}
inline void NzByteArray::PopFront()
{
Erase(begin());
}
inline void ByteArray::PopBack()
{
Erase(end() - 1);
}
inline NzByteArray::iterator NzByteArray::Prepend(const void* buffer, size_type n)
{
return Insert(begin(), buffer, n);
}
inline void ByteArray::PopFront()
{
Erase(begin());
}
inline NzByteArray::iterator NzByteArray::Prepend(const NzByteArray& other)
{
return Insert(begin(), other);
}
inline ByteArray::iterator ByteArray::Prepend(const void* buffer, size_type n)
{
return Insert(begin(), buffer, n);
}
inline void NzByteArray::PushBack(const value_type byte)
{
m_array.push_back(byte);
}
inline ByteArray::iterator ByteArray::Prepend(const ByteArray& other)
{
return Insert(begin(), other);
}
inline void NzByteArray::PushFront(const value_type byte)
{
m_array.insert(begin(), 1, byte);
}
inline void ByteArray::PushBack(const value_type byte)
{
m_array.push_back(byte);
}
inline void NzByteArray::Reserve(size_type bufferSize)
{
m_array.reserve(bufferSize);
}
inline void ByteArray::PushFront(const value_type byte)
{
m_array.insert(begin(), 1, byte);
}
inline void NzByteArray::Resize(size_type newSize)
{
m_array.resize(newSize);
}
inline void ByteArray::Reserve(size_type bufferSize)
{
m_array.reserve(bufferSize);
}
inline void NzByteArray::Resize(size_type newSize, const value_type byte)
{
m_array.resize(newSize, byte);
}
inline void ByteArray::Resize(size_type newSize)
{
m_array.resize(newSize);
}
inline void NzByteArray::ShrinkToFit()
{
m_array.shrink_to_fit();
}
inline void ByteArray::Resize(size_type newSize, const value_type byte)
{
m_array.resize(newSize, byte);
}
inline void NzByteArray::Swap(NzByteArray& other)
{
m_array.swap(other.m_array);
}
inline void ByteArray::ShrinkToFit()
{
m_array.shrink_to_fit();
}
inline NzString NzByteArray::ToString() const
{
return NzString(reinterpret_cast<const char*>(GetConstBuffer()), GetSize());
}
inline void ByteArray::Swap(ByteArray& other)
{
m_array.swap(other.m_array);
}
inline NzByteArray::iterator NzByteArray::begin() noexcept
{
return m_array.begin();
}
inline String ByteArray::ToHex() const
{
std::size_t length = m_array.size() * 2;
inline NzByteArray::const_iterator NzByteArray::begin() const noexcept
{
return m_array.begin();
}
String hexOutput(length, '\0');
for (std::size_t i = 0; i < m_array.size(); ++i)
std::sprintf(&hexOutput[i * 2], "%02x", m_array[i]);
inline NzByteArray::const_iterator NzByteArray::cbegin() const noexcept
{
return m_array.cbegin();
}
return hexOutput;
}
inline NzByteArray::const_iterator NzByteArray::cend() const noexcept
{
return m_array.cend();
}
inline String ByteArray::ToString() const
{
return String(reinterpret_cast<const char*>(GetConstBuffer()), GetSize());
}
inline NzByteArray::const_reverse_iterator NzByteArray::crbegin() const noexcept
{
return m_array.crbegin();
}
inline ByteArray::iterator ByteArray::begin() noexcept
{
return m_array.begin();
}
inline NzByteArray::const_reverse_iterator NzByteArray::crend() const noexcept
{
return m_array.crend();
}
inline ByteArray::const_iterator ByteArray::begin() const noexcept
{
return m_array.begin();
}
inline bool NzByteArray::empty() const noexcept
{
return m_array.empty();
}
inline ByteArray::const_iterator ByteArray::cbegin() const noexcept
{
return m_array.cbegin();
}
inline NzByteArray::iterator NzByteArray::end() noexcept
{
return m_array.end();
}
inline ByteArray::const_iterator ByteArray::cend() const noexcept
{
return m_array.cend();
}
inline NzByteArray::const_iterator NzByteArray::end() const noexcept
{
return m_array.end();
}
inline ByteArray::const_reverse_iterator ByteArray::crbegin() const noexcept
{
return m_array.crbegin();
}
inline NzByteArray::reverse_iterator NzByteArray::rbegin() noexcept
{
return m_array.rbegin();
}
inline ByteArray::const_reverse_iterator ByteArray::crend() const noexcept
{
return m_array.crend();
}
inline NzByteArray::const_reverse_iterator NzByteArray::rbegin() const noexcept
{
return m_array.rbegin();
}
inline bool ByteArray::empty() const noexcept
{
return m_array.empty();
}
inline NzByteArray::reverse_iterator NzByteArray::rend() noexcept
{
return m_array.rend();
}
inline ByteArray::iterator ByteArray::end() noexcept
{
return m_array.end();
}
inline NzByteArray::size_type NzByteArray::size() const noexcept
{
return GetSize();
}
inline ByteArray::const_iterator ByteArray::end() const noexcept
{
return m_array.end();
}
inline NzByteArray::reference NzByteArray::operator[](size_type pos)
{
NazaraAssert(pos < GetSize(), "Index out of range");
inline ByteArray::reverse_iterator ByteArray::rbegin() noexcept
{
return m_array.rbegin();
}
return m_array[pos];
}
inline ByteArray::const_reverse_iterator ByteArray::rbegin() const noexcept
{
return m_array.rbegin();
}
inline NzByteArray::const_reference NzByteArray::operator[](size_type pos) const
{
NazaraAssert(pos < GetSize(), "Index out of range");
inline ByteArray::reverse_iterator ByteArray::rend() noexcept
{
return m_array.rend();
}
return m_array[pos];
}
inline ByteArray::size_type ByteArray::size() const noexcept
{
return GetSize();
}
inline NzByteArray NzByteArray::operator+(const NzByteArray& other) const
{
NzByteArray tmp(*this);
tmp += other;
inline ByteArray::reference ByteArray::operator[](size_type pos)
{
NazaraAssert(pos < GetSize(), "Index out of range");
return tmp;
}
return m_array[pos];
}
inline NzByteArray& NzByteArray::operator+=(const NzByteArray& other)
{
Append(other);
inline ByteArray::const_reference ByteArray::operator[](size_type pos) const
{
NazaraAssert(pos < GetSize(), "Index out of range");
return *this;
}
return m_array[pos];
}
inline bool NzByteArray::operator==(const NzByteArray& rhs) const
{
return m_array == rhs.m_array;
}
inline ByteArray ByteArray::operator+(const ByteArray& other) const
{
ByteArray tmp(*this);
tmp += other;
inline bool NzByteArray::operator!=(const NzByteArray& rhs) const
{
return !operator==(rhs);
}
return tmp;
}
inline bool NzByteArray::operator<(const NzByteArray& rhs) const
{
return m_array < rhs.m_array;
}
inline ByteArray& ByteArray::operator+=(const ByteArray& other)
{
Append(other);
inline bool NzByteArray::operator<=(const NzByteArray& rhs) const
{
return m_array <= rhs.m_array;
}
return *this;
}
inline bool NzByteArray::operator>(const NzByteArray& rhs) const
{
return m_array > rhs.m_array;
}
inline bool ByteArray::operator==(const ByteArray& rhs) const
{
return m_array == rhs.m_array;
}
inline bool NzByteArray::operator>=(const NzByteArray& rhs) const
{
return m_array >= rhs.m_array;
inline bool ByteArray::operator!=(const ByteArray& rhs) const
{
return !operator==(rhs);
}
inline bool ByteArray::operator<(const ByteArray& rhs) const
{
return m_array < rhs.m_array;
}
inline bool ByteArray::operator<=(const ByteArray& rhs) const
{
return m_array <= rhs.m_array;
}
inline bool ByteArray::operator>(const ByteArray& rhs) const
{
return m_array > rhs.m_array;
}
inline bool ByteArray::operator>=(const ByteArray& rhs) const
{
return m_array >= rhs.m_array;
}
inline bool HashAppend(AbstractHash* hash, const ByteArray& byteArray)
{
hash->Append(byteArray.GetConstBuffer(), byteArray.GetSize());
return true;
}
}
namespace std
{
inline void swap(NzByteArray& lhs, NzByteArray& rhs)
inline void swap(Nz::ByteArray& lhs, Nz::ByteArray& rhs)
{
lhs.Swap(rhs);
}

View File

@@ -8,23 +8,30 @@
#define NAZARA_CALLONEXIT_HPP
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/NonCopyable.hpp>
#include <functional>
class NzCallOnExit : NzNonCopyable
namespace Nz
{
using Func = std::function<void()>;
class CallOnExit
{
using Func = std::function<void()>;
public:
NzCallOnExit(Func func = nullptr);
~NzCallOnExit();
public:
CallOnExit(Func func = nullptr);
CallOnExit(const CallOnExit&) = delete;
CallOnExit(CallOnExit&&) = delete;
~CallOnExit();
void CallAndReset(Func func = nullptr);
void Reset(Func func = nullptr);
void CallAndReset(Func func = nullptr);
void Reset(Func func = nullptr);
private:
Func m_func;
};
CallOnExit& operator=(const CallOnExit&) = delete;
CallOnExit& operator=(CallOnExit&&) = default;
private:
Func m_func;
};
}
#include <Nazara/Core/CallOnExit.inl>

View File

@@ -5,28 +5,31 @@
#include <Nazara/Core/Error.hpp>
#include <Nazara/Core/Debug.hpp>
inline NzCallOnExit::NzCallOnExit(Func func) :
m_func(func)
namespace Nz
{
}
inline CallOnExit::CallOnExit(Func func) :
m_func(func)
{
}
inline NzCallOnExit::~NzCallOnExit()
{
if (m_func)
m_func();
}
inline CallOnExit::~CallOnExit()
{
if (m_func)
m_func();
}
inline void NzCallOnExit::CallAndReset(Func func)
{
if (m_func)
m_func();
inline void CallOnExit::CallAndReset(Func func)
{
if (m_func)
m_func();
Reset(func);
}
Reset(func);
}
inline void NzCallOnExit::Reset(Func func)
{
m_func = func;
inline void CallOnExit::Reset(Func func)
{
m_func = func;
}
}
#include <Nazara/Core/DebugOff.hpp>

View File

@@ -15,35 +15,41 @@
#include <Nazara/Core/ThreadSafetyOff.hpp>
#endif
class NAZARA_CORE_API NzClock
namespace Nz
{
public:
NzClock(nzUInt64 startingValue = 0, bool paused = false);
NzClock(const NzClock& clock) = default;
class NAZARA_CORE_API Clock
{
public:
Clock(UInt64 startingValue = 0, bool paused = false);
Clock(const Clock& clock) = default;
Clock(Clock&& clock) = default;
~Clock() = default;
float GetSeconds() const;
nzUInt64 GetMicroseconds() const;
nzUInt64 GetMilliseconds() const;
float GetSeconds() const;
UInt64 GetMicroseconds() const;
UInt64 GetMilliseconds() const;
bool IsPaused() const;
bool IsPaused() const;
void Pause();
void Restart();
void Unpause();
void Pause();
void Restart();
void Unpause();
NzClock& operator=(const NzClock& clock) = default;
Clock& operator=(const Clock& clock) = default;
Clock& operator=(Clock&& clock) = default;
private:
NazaraMutexAttrib(m_mutex, mutable)
private:
NazaraMutexAttrib(m_mutex, mutable)
nzUInt64 m_elapsedTime;
nzUInt64 m_refTime;
bool m_paused;
};
UInt64 m_elapsedTime;
UInt64 m_refTime;
bool m_paused;
};
typedef nzUInt64 (*NzClockFunction)();
typedef UInt64 (*ClockFunction)();
extern NAZARA_CORE_API NzClockFunction NzGetMicroseconds;
extern NAZARA_CORE_API NzClockFunction NzGetMilliseconds;
extern NAZARA_CORE_API ClockFunction GetElapsedMicroseconds;
extern NAZARA_CORE_API ClockFunction GetElapsedMilliseconds;
}
#endif // NAZARA_CLOCK_HPP

View File

@@ -11,57 +11,60 @@
#include <Nazara/Core/String.hpp>
#include <Nazara/Math/Vector3.hpp>
class NzColor
namespace Nz
{
public:
inline NzColor();
inline NzColor(nzUInt8 red, nzUInt8 green, nzUInt8 blue, nzUInt8 alpha = 255);
inline explicit NzColor(nzUInt8 lightness);
inline NzColor(nzUInt8 color[3], nzUInt8 alpha = 255);
inline NzColor(const NzColor& color) = default;
inline ~NzColor() = default;
class Color
{
public:
inline Color();
inline Color(UInt8 red, UInt8 green, UInt8 blue, UInt8 alpha = 255);
inline explicit Color(UInt8 lightness);
inline Color(UInt8 color[3], UInt8 alpha = 255);
inline Color(const Color& color) = default;
inline ~Color() = default;
inline NzString ToString() const;
inline String ToString() const;
inline NzColor operator+(const NzColor& angles) const;
inline NzColor operator*(const NzColor& angles) const;
inline Color operator+(const Color& angles) const;
inline Color operator*(const Color& angles) const;
inline NzColor operator+=(const NzColor& angles);
inline NzColor operator*=(const NzColor& angles);
inline Color operator+=(const Color& angles);
inline Color operator*=(const Color& angles);
inline bool operator==(const NzColor& angles) const;
inline bool operator!=(const NzColor& angles) const;
inline bool operator==(const Color& angles) const;
inline bool operator!=(const Color& angles) const;
static inline NzColor FromCMY(float cyan, float magenta, float yellow);
static inline NzColor FromCMYK(float cyan, float magenta, float yellow, float black);
static inline NzColor FromHSL(nzUInt8 hue, nzUInt8 saturation, nzUInt8 lightness);
static inline NzColor FromHSV(float hue, float saturation, float value);
static inline NzColor FromXYZ(const NzVector3f& vec);
static inline NzColor FromXYZ(float x, float y, float z);
static inline void ToCMY(const NzColor& color, float* cyan, float* magenta, float* yellow);
static inline void ToCMYK(const NzColor& color, float* cyan, float* magenta, float* yellow, float* black);
static inline void ToHSL(const NzColor& color, nzUInt8* hue, nzUInt8* saturation, nzUInt8* lightness);
static inline void ToHSV(const NzColor& color, float* hue, float* saturation, float* value);
static inline void ToXYZ(const NzColor& color, NzVector3f* vec);
static inline void ToXYZ(const NzColor& color, float* x, float* y, float* z);
static inline Color FromCMY(float cyan, float magenta, float yellow);
static inline Color FromCMYK(float cyan, float magenta, float yellow, float black);
static inline Color FromHSL(UInt8 hue, UInt8 saturation, UInt8 lightness);
static inline Color FromHSV(float hue, float saturation, float value);
static inline Color FromXYZ(const Vector3f& vec);
static inline Color FromXYZ(float x, float y, float z);
static inline void ToCMY(const Color& color, float* cyan, float* magenta, float* yellow);
static inline void ToCMYK(const Color& color, float* cyan, float* magenta, float* yellow, float* black);
static inline void ToHSL(const Color& color, UInt8* hue, UInt8* saturation, UInt8* lightness);
static inline void ToHSV(const Color& color, float* hue, float* saturation, float* value);
static inline void ToXYZ(const Color& color, Vector3f* vec);
static inline void ToXYZ(const Color& color, float* x, float* y, float* z);
nzUInt8 r, g, b, a;
UInt8 r, g, b, a;
static NAZARA_CORE_API const NzColor Black;
static NAZARA_CORE_API const NzColor Blue;
static NAZARA_CORE_API const NzColor Cyan;
static NAZARA_CORE_API const NzColor Green;
static NAZARA_CORE_API const NzColor Magenta;
static NAZARA_CORE_API const NzColor Orange;
static NAZARA_CORE_API const NzColor Red;
static NAZARA_CORE_API const NzColor Yellow;
static NAZARA_CORE_API const NzColor White;
static NAZARA_CORE_API const Color Black;
static NAZARA_CORE_API const Color Blue;
static NAZARA_CORE_API const Color Cyan;
static NAZARA_CORE_API const Color Green;
static NAZARA_CORE_API const Color Magenta;
static NAZARA_CORE_API const Color Orange;
static NAZARA_CORE_API const Color Red;
static NAZARA_CORE_API const Color Yellow;
static NAZARA_CORE_API const Color White;
private:
static float Hue2RGB(float v1, float v2, float vH);
};
private:
static float Hue2RGB(float v1, float v2, float vH);
};
}
std::ostream& operator<<(std::ostream& out, const NzColor& color);
std::ostream& operator<<(std::ostream& out, const Nz::Color& color);
#include <Nazara/Core/Color.inl>

View File

@@ -9,411 +9,416 @@
#include <stdexcept>
#include <Nazara/Core/Debug.hpp>
inline NzColor::NzColor()
namespace Nz
{
}
inline NzColor::NzColor(nzUInt8 red, nzUInt8 green, nzUInt8 blue, nzUInt8 alpha) :
r(red),
g(green),
b(blue),
a(alpha)
{
}
inline NzColor::NzColor(nzUInt8 lightness) :
r(lightness),
g(lightness),
b(lightness),
a(255)
{
}
inline NzColor::NzColor(nzUInt8 vec[3], nzUInt8 alpha) :
r(vec[0]),
g(vec[1]),
b(vec[2]),
a(alpha)
{
}
inline NzString NzColor::ToString() const
{
NzStringStream ss;
ss << "Color(" << static_cast<int>(r) << ", " << static_cast<int>(g) << ", " << static_cast<int>(b);
if (a != 255)
ss << ", " << static_cast<int>(a);
ss << ')';
return ss;
}
inline NzColor NzColor::operator+(const NzColor& color) const
{
NzColor c;
c.r = std::min(static_cast<unsigned int>(r) + static_cast<unsigned int>(color.r), 255U);
c.g = std::min(static_cast<unsigned int>(g) + static_cast<unsigned int>(color.g), 255U);
c.b = std::min(static_cast<unsigned int>(b) + static_cast<unsigned int>(color.b), 255U);
c.a = std::min(static_cast<unsigned int>(a) + static_cast<unsigned int>(color.a), 255U);
return c;
}
inline NzColor NzColor::operator*(const NzColor& color) const
{
NzColor c;
c.r = (static_cast<unsigned int>(r) * static_cast<unsigned int>(color.r)) / 255U;
c.g = (static_cast<unsigned int>(g) * static_cast<unsigned int>(color.g)) / 255U;
c.b = (static_cast<unsigned int>(b) * static_cast<unsigned int>(color.b)) / 255U;
c.a = (static_cast<unsigned int>(a) * static_cast<unsigned int>(color.a)) / 255U;
return c;
}
inline NzColor NzColor::operator+=(const NzColor& color)
{
return operator=(operator+(color));
}
inline NzColor NzColor::operator*=(const NzColor& color)
{
return operator=(operator*(color));
}
inline bool NzColor::operator==(const NzColor& color) const
{
return r == color.r && g == color.g && b == color.b && a == color.a;
}
inline bool NzColor::operator!=(const NzColor& color) const
{
return !operator==(color);
}
// Algorithmes venant de http://www.easyrgb.com/index.php?X=MATH
inline NzColor NzColor::FromCMY(float cyan, float magenta, float yellow)
{
return NzColor(static_cast<nzUInt8>((1.f-cyan)*255.f), static_cast<nzUInt8>((1.f-magenta)*255.f), static_cast<nzUInt8>((1.f-yellow)*255.f));
}
inline NzColor NzColor::FromCMYK(float cyan, float magenta, float yellow, float black)
{
return FromCMY(cyan * (1.f - black) + black,
magenta * (1.f - black) + black,
yellow * (1.f - black) + black);
}
inline NzColor NzColor::FromHSL(nzUInt8 hue, nzUInt8 saturation, nzUInt8 lightness)
{
if (saturation == 0)
inline Color::Color()
{
// RGB results from 0 to 255
return NzColor(lightness * 255,
lightness * 255,
lightness * 255);
}
else
inline Color::Color(UInt8 red, UInt8 green, UInt8 blue, UInt8 alpha) :
r(red),
g(green),
b(blue),
a(alpha)
{
// Norme Windows
float l = lightness/240.f;
float h = hue/240.f;
float s = saturation/240.f;
float v2;
if (l < 0.5f)
v2 = l * (1.f + s);
else
v2 = (l + s) - (s*l);
float v1 = 2.f * l - v2;
return NzColor(static_cast<nzUInt8>(255.f * Hue2RGB(v1, v2, h + (1.f/3.f))),
static_cast<nzUInt8>(255.f * Hue2RGB(v1, v2, h)),
static_cast<nzUInt8>(255.f * Hue2RGB(v1, v2, h - (1.f/3.f))));
}
}
inline NzColor NzColor::FromHSV(float hue, float saturation, float value)
{
if (NzNumberEquals(saturation, 0.f))
return NzColor(static_cast<nzUInt8>(value * 255.f));
else
inline Color::Color(UInt8 lightness) :
r(lightness),
g(lightness),
b(lightness),
a(255)
{
float h = hue/360.f * 6.f;
float s = saturation/360.f;
}
if (NzNumberEquals(h, 6.f))
h = 0; // hue must be < 1
inline Color::Color(UInt8 vec[3], UInt8 alpha) :
r(vec[0]),
g(vec[1]),
b(vec[2]),
a(alpha)
{
}
int i = static_cast<unsigned int>(h);
float v1 = value * (1.f - s);
float v2 = value * (1.f - s * (h - i));
float v3 = value * (1.f - s * (1.f - (h - i)));
inline String Color::ToString() const
{
StringStream ss;
ss << "Color(" << static_cast<int>(r) << ", " << static_cast<int>(g) << ", " << static_cast<int>(b);
float r, g, b;
switch (i)
if (a != 255)
ss << ", " << static_cast<int>(a);
ss << ')';
return ss;
}
inline Color Color::operator+(const Color& color) const
{
///TODO: Improve this shit
Color c;
c.r = static_cast<UInt8>(std::min(static_cast<unsigned int>(r) + static_cast<unsigned int>(color.r), 255U));
c.g = static_cast<UInt8>(std::min(static_cast<unsigned int>(g) + static_cast<unsigned int>(color.g), 255U));
c.b = static_cast<UInt8>(std::min(static_cast<unsigned int>(b) + static_cast<unsigned int>(color.b), 255U));
c.a = static_cast<UInt8>(std::min(static_cast<unsigned int>(a) + static_cast<unsigned int>(color.a), 255U));
return c;
}
inline Color Color::operator*(const Color& color) const
{
///TODO: Improve this shit
Color c;
c.r = static_cast<UInt8>((static_cast<unsigned int>(r) * static_cast<unsigned int>(color.r)) / 255U);
c.g = static_cast<UInt8>((static_cast<unsigned int>(g) * static_cast<unsigned int>(color.g)) / 255U);
c.b = static_cast<UInt8>((static_cast<unsigned int>(b) * static_cast<unsigned int>(color.b)) / 255U);
c.a = static_cast<UInt8>((static_cast<unsigned int>(a) * static_cast<unsigned int>(color.a)) / 255U);
return c;
}
inline Color Color::operator+=(const Color& color)
{
return operator=(operator+(color));
}
inline Color Color::operator*=(const Color& color)
{
return operator=(operator*(color));
}
inline bool Color::operator==(const Color& color) const
{
return r == color.r && g == color.g && b == color.b && a == color.a;
}
inline bool Color::operator!=(const Color& color) const
{
return !operator==(color);
}
// Algorithmes venant de http://www.easyrgb.com/index.php?X=MATH
inline Color Color::FromCMY(float cyan, float magenta, float yellow)
{
return Color(static_cast<UInt8>((1.f-cyan)*255.f), static_cast<UInt8>((1.f-magenta)*255.f), static_cast<UInt8>((1.f-yellow)*255.f));
}
inline Color Color::FromCMYK(float cyan, float magenta, float yellow, float black)
{
return FromCMY(cyan * (1.f - black) + black,
magenta * (1.f - black) + black,
yellow * (1.f - black) + black);
}
inline Color Color::FromHSL(UInt8 hue, UInt8 saturation, UInt8 lightness)
{
if (saturation == 0)
{
case 0:
r = value;
g = v3;
b = v1;
break;
// RGB results from 0 to 255
return Color(lightness * 255,
lightness * 255,
lightness * 255);
}
else
{
// Norme Windows
float l = lightness/240.f;
float h = hue/240.f;
float s = saturation/240.f;
case 1:
r = v2;
g = value;
b = v1;
break;
float v2;
if (l < 0.5f)
v2 = l * (1.f + s);
else
v2 = (l + s) - (s*l);
case 2:
r = v1;
g = value;
b = v3;
break;
float v1 = 2.f * l - v2;
case 3:
r = v1;
g = v2;
b = value;
break;
return Color(static_cast<UInt8>(255.f * Hue2RGB(v1, v2, h + (1.f/3.f))),
static_cast<UInt8>(255.f * Hue2RGB(v1, v2, h)),
static_cast<UInt8>(255.f * Hue2RGB(v1, v2, h - (1.f/3.f))));
}
}
case 4:
r = v3;
g = v1;
b = value;
break;
inline Color Color::FromHSV(float hue, float saturation, float value)
{
if (NumberEquals(saturation, 0.f))
return Color(static_cast<UInt8>(value * 255.f));
else
{
float h = hue/360.f * 6.f;
float s = saturation/360.f;
default:
r = value;
g = v1;
b = v2;
break;
if (NumberEquals(h, 6.f))
h = 0; // hue must be < 1
int i = static_cast<unsigned int>(h);
float v1 = value * (1.f - s);
float v2 = value * (1.f - s * (h - i));
float v3 = value * (1.f - s * (1.f - (h - i)));
float r, g, b;
switch (i)
{
case 0:
r = value;
g = v3;
b = v1;
break;
case 1:
r = v2;
g = value;
b = v1;
break;
case 2:
r = v1;
g = value;
b = v3;
break;
case 3:
r = v1;
g = v2;
b = value;
break;
case 4:
r = v3;
g = v1;
b = value;
break;
default:
r = value;
g = v1;
b = v2;
break;
}
// RGB results from 0 to 255
return Color(static_cast<UInt8>(r*255.f), static_cast<UInt8>(g*255.f), static_cast<UInt8>(b*255.f));
}
}
inline Color Color::FromXYZ(const Vector3f& vec)
{
return FromXYZ(vec.x, vec.y, vec.z);
}
inline Color Color::FromXYZ(float x, float y, float z)
{
x /= 100.f; // X from 0 to 95.047
y /= 100.f; // Y from 0 to 100.000
z /= 100.f; // Z from 0 to 108.883
float r = x * 3.2406f + y * -1.5372f + z * -0.4986f;
float g = x * -0.9689f + y * 1.8758f + z * 0.0415f;
float b = x * 0.0557f + y * -0.2040f + z * 1.0570f;
if (r > 0.0031308f)
r = 1.055f * (std::pow(r, 1.f/2.4f)) - 0.055f;
else
r *= 12.92f;
if (g > 0.0031308f)
g = 1.055f * (std::pow(r, 1.f/2.4f)) - 0.055f;
else
g *= 12.92f;
if (b > 0.0031308f)
b = 1.055f * (std::pow(r, 1.f/2.4f)) - 0.055f;
else
b *= 12.92f;
return Color(static_cast<UInt8>(r * 255.f), static_cast<UInt8>(g * 255.f), static_cast<UInt8>(b * 255.f));
}
inline void Color::ToCMY(const Color& color, float* cyan, float* magenta, float* yellow)
{
*cyan = 1.f - color.r/255.f;
*magenta = 1.f - color.g/255.f;
*yellow = 1.f - color.b/255.f;
}
inline void Color::ToCMYK(const Color& color, float* cyan, float* magenta, float* yellow, float* black)
{
float c, m, y;
ToCMY(color, &c, &m, &y);
float k = std::min({1.f, c, m, y});
if (NumberEquals(k, 1.f))
{
//Black
*cyan = 0.f;
*magenta = 0.f;
*yellow = 0.f;
}
else
{
*cyan = (c-k)/(1.f-k);
*magenta = (m-k)/(1.f-k);
*yellow = (y-k)/(1.f-k);
}
// RGB results from 0 to 255
return NzColor(static_cast<nzUInt8>(r*255.f), static_cast<nzUInt8>(g*255.f), static_cast<nzUInt8>(b*255.f));
}
}
inline NzColor NzColor::FromXYZ(const NzVector3f& vec)
{
return FromXYZ(vec.x, vec.y, vec.z);
}
inline NzColor NzColor::FromXYZ(float x, float y, float z)
{
x /= 100.f; // X from 0 to 95.047
y /= 100.f; // Y from 0 to 100.000
z /= 100.f; // Z from 0 to 108.883
float r = x * 3.2406f + y * -1.5372f + z * -0.4986f;
float g = x * -0.9689f + y * 1.8758f + z * 0.0415f;
float b = x * 0.0557f + y * -0.2040f + z * 1.0570f;
if (r > 0.0031308f)
r = 1.055f * (std::pow(r, 1.f/2.4f)) - 0.055f;
else
r *= 12.92f;
if (g > 0.0031308f)
g = 1.055f * (std::pow(r, 1.f/2.4f)) - 0.055f;
else
g *= 12.92f;
if (b > 0.0031308f)
b = 1.055f * (std::pow(r, 1.f/2.4f)) - 0.055f;
else
b *= 12.92f;
return NzColor(static_cast<nzUInt8>(r * 255.f), static_cast<nzUInt8>(g * 255.f), static_cast<nzUInt8>(b * 255.f));
}
inline void NzColor::ToCMY(const NzColor& color, float* cyan, float* magenta, float* yellow)
{
*cyan = 1.f - color.r/255.f;
*magenta = 1.f - color.g/255.f;
*yellow = 1.f - color.b/255.f;
}
inline void NzColor::ToCMYK(const NzColor& color, float* cyan, float* magenta, float* yellow, float* black)
{
float c, m, y;
ToCMY(color, &c, &m, &y);
float k = std::min({1.f, c, m, y});
if (NzNumberEquals(k, 1.f))
{
//Black
*cyan = 0.f;
*magenta = 0.f;
*yellow = 0.f;
}
else
{
*cyan = (c-k)/(1.f-k);
*magenta = (m-k)/(1.f-k);
*yellow = (y-k)/(1.f-k);
*black = k;
}
*black = k;
}
inline void NzColor::ToHSL(const NzColor& color, nzUInt8* hue, nzUInt8* saturation, nzUInt8* lightness)
{
float r = color.r / 255.f;
float g = color.g / 255.f;
float b = color.b / 255.f;
float min = std::min({r, g, b}); // Min. value of RGB
float max = std::max({r, g, b}); // Max. value of RGB
float deltaMax = max - min; //Delta RGB value
float l = (max + min)/2.f;
if (NzNumberEquals(deltaMax, 0.f))
inline void Color::ToHSL(const Color& color, UInt8* hue, UInt8* saturation, UInt8* lightness)
{
//This is a gray, no chroma...
*hue = 0; //HSL results from 0 to 1
*saturation = 0;
}
else
{
//Chromatic data...
if (l < 0.5f)
*saturation = static_cast<nzUInt8>(deltaMax/(max+min)*240.f);
float r = color.r / 255.f;
float g = color.g / 255.f;
float b = color.b / 255.f;
float min = std::min({r, g, b}); // Min. value of RGB
float max = std::max({r, g, b}); // Max. value of RGB
float deltaMax = max - min; //Delta RGB value
float l = (max + min)/2.f;
if (NumberEquals(deltaMax, 0.f))
{
//This is a gray, no chroma...
*hue = 0; //HSL results from 0 to 1
*saturation = 0;
}
else
*saturation = static_cast<nzUInt8>(deltaMax/(2.f-max-min)*240.f);
{
//Chromatic data...
if (l < 0.5f)
*saturation = static_cast<UInt8>(deltaMax/(max+min)*240.f);
else
*saturation = static_cast<UInt8>(deltaMax/(2.f-max-min)*240.f);
*lightness = static_cast<nzUInt8>(l*240.f);
*lightness = static_cast<UInt8>(l*240.f);
float deltaR = ((max - r)/6.f + deltaMax/2.f)/deltaMax;
float deltaG = ((max - g)/6.f + deltaMax/2.f)/deltaMax;
float deltaB = ((max - b)/6.f + deltaMax/2.f)/deltaMax;
float deltaR = ((max - r)/6.f + deltaMax/2.f)/deltaMax;
float deltaG = ((max - g)/6.f + deltaMax/2.f)/deltaMax;
float deltaB = ((max - b)/6.f + deltaMax/2.f)/deltaMax;
float h;
if (NzNumberEquals(r, max))
h = deltaB - deltaG;
else if (NzNumberEquals(g, max))
h = (1.f/3.f) + deltaR - deltaB;
else
h = (2.f/3.f) + deltaG - deltaR;
float h;
if (NumberEquals(r, max))
h = deltaB - deltaG;
else if (NumberEquals(g, max))
h = (1.f/3.f) + deltaR - deltaB;
else
h = (2.f/3.f) + deltaG - deltaR;
if (h < 0.f)
h += 1.f;
else if (h > 1.f)
h -= 1.f;
if (h < 0.f)
h += 1.f;
else if (h > 1.f)
h -= 1.f;
*hue = static_cast<nzUInt8>(h*240.f);
*hue = static_cast<UInt8>(h*240.f);
}
}
}
inline void NzColor::ToHSV(const NzColor& color, float* hue, float* saturation, float* value)
{
float r = color.r / 255.f;
float g = color.g / 255.f;
float b = color.b / 255.f;
float min = std::min({r, g, b}); //Min. value of RGB
float max = std::max({r, g, b}); //Max. value of RGB
float deltaMax = max - min; //Delta RGB value
*value = max;
if (NzNumberEquals(deltaMax, 0.f))
inline void Color::ToHSV(const Color& color, float* hue, float* saturation, float* value)
{
//This is a gray, no chroma...
*hue = 0; //HSV results from 0 to 1
*saturation = 0;
}
else
{
//Chromatic data...
*saturation = deltaMax/max*360.f;
float r = color.r / 255.f;
float g = color.g / 255.f;
float b = color.b / 255.f;
float deltaR = ((max - r)/6.f + deltaMax/2.f)/deltaMax;
float deltaG = ((max - g)/6.f + deltaMax/2.f)/deltaMax;
float deltaB = ((max - b)/6.f + deltaMax/2.f)/deltaMax;
float min = std::min({r, g, b}); //Min. value of RGB
float max = std::max({r, g, b}); //Max. value of RGB
float h;
float deltaMax = max - min; //Delta RGB value
if (NzNumberEquals(r, max))
h = deltaB - deltaG;
else if (NzNumberEquals(g, max))
h = (1.f/3.f) + deltaR - deltaB;
*value = max;
if (NumberEquals(deltaMax, 0.f))
{
//This is a gray, no chroma...
*hue = 0; //HSV results from 0 to 1
*saturation = 0;
}
else
h = (2.f/3.f) + deltaG - deltaR;
{
//Chromatic data...
*saturation = deltaMax/max*360.f;
if (h < 0.f)
h += 1.f;
else if (h > 1.f)
h -= 1.f;
float deltaR = ((max - r)/6.f + deltaMax/2.f)/deltaMax;
float deltaG = ((max - g)/6.f + deltaMax/2.f)/deltaMax;
float deltaB = ((max - b)/6.f + deltaMax/2.f)/deltaMax;
*hue = h*360.f;
float h;
if (NumberEquals(r, max))
h = deltaB - deltaG;
else if (NumberEquals(g, max))
h = (1.f/3.f) + deltaR - deltaB;
else
h = (2.f/3.f) + deltaG - deltaR;
if (h < 0.f)
h += 1.f;
else if (h > 1.f)
h -= 1.f;
*hue = h*360.f;
}
}
inline void Color::ToXYZ(const Color& color, Vector3f* vec)
{
return ToXYZ(color, &vec->x, &vec->y, &vec->z);
}
inline void Color::ToXYZ(const Color& color, float* x, float* y, float* z)
{
float r = color.r/255.f; //R from 0 to 255
float g = color.g/255.f; //G from 0 to 255
float b = color.b/255.f; //B from 0 to 255
if (r > 0.04045f)
r = std::pow((r + 0.055f)/1.055f, 2.4f);
else
r /= 12.92f;
if (g > 0.04045f)
g = std::pow((g + 0.055f)/1.055f, 2.4f);
else
g /= 12.92f;
if (b > 0.04045f)
b = std::pow((b + 0.055f)/1.055f, 2.4f);
else
b /= 12.92f;
r *= 100.f;
g *= 100.f;
b *= 100.f;
//Observer. = 2°, Illuminant = D65
*x = r*0.4124f + g*0.3576f + b*0.1805f;
*y = r*0.2126f + g*0.7152f + b*0.0722f;
*z = r*0.0193f + g*0.1192f + b*0.9505f;
}
inline float Color::Hue2RGB(float v1, float v2, float vH)
{
if (vH < 0.f)
vH += 1;
if (vH > 1.f)
vH -= 1;
if ((6.f * vH) < 1.f)
return v1 + (v2-v1)*6*vH;
if ((2.f * vH) < 1.f)
return v2;
if ((3.f * vH) < 2.f)
return v1 + (v2 - v1)*(2.f/3.f - vH)*6;
return v1;
}
}
inline void NzColor::ToXYZ(const NzColor& color, NzVector3f* vec)
{
return ToXYZ(color, &vec->x, &vec->y, &vec->z);
}
inline void NzColor::ToXYZ(const NzColor& color, float* x, float* y, float* z)
{
float r = color.r/255.f; //R from 0 to 255
float g = color.g/255.f; //G from 0 to 255
float b = color.b/255.f; //B from 0 to 255
if (r > 0.04045f)
r = std::pow((r + 0.055f)/1.055f, 2.4f);
else
r /= 12.92f;
if (g > 0.04045f)
g = std::pow((g + 0.055f)/1.055f, 2.4f);
else
g /= 12.92f;
if (b > 0.04045f)
b = std::pow((b + 0.055f)/1.055f, 2.4f);
else
b /= 12.92f;
r *= 100.f;
g *= 100.f;
b *= 100.f;
//Observer. = 2°, Illuminant = D65
*x = r*0.4124f + g*0.3576f + b*0.1805f;
*y = r*0.2126f + g*0.7152f + b*0.0722f;
*z = r*0.0193f + g*0.1192f + b*0.9505f;
}
inline float NzColor::Hue2RGB(float v1, float v2, float vH)
{
if (vH < 0.f)
vH += 1;
if (vH > 1.f)
vH -= 1;
if ((6.f * vH) < 1.f)
return v1 + (v2-v1)*6*vH;
if ((2.f * vH) < 1.f)
return v2;
if ((3.f * vH) < 2.f)
return v1 + (v2 - v1)*(2.f/3.f - vH)*6;
return v1;
}
inline std::ostream& operator<<(std::ostream& out, const NzColor& color)
inline std::ostream& operator<<(std::ostream& out, const Nz::Color& color)
{
return out << color.ToString();
}

View File

@@ -8,25 +8,32 @@
#define NAZARA_CONDITIONVARIABLE_HPP
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/NonCopyable.hpp>
class NzConditionVariableImpl;
class NzMutex;
class NAZARA_CORE_API NzConditionVariable : NzNonCopyable
namespace Nz
{
public:
NzConditionVariable();
~NzConditionVariable();
class ConditionVariableImpl;
class Mutex;
void Signal();
void SignalAll();
class NAZARA_CORE_API ConditionVariable
{
public:
ConditionVariable();
ConditionVariable(const ConditionVariable&) = delete;
ConditionVariable(ConditionVariable&&) = delete; ///TODO
~ConditionVariable();
void Wait(NzMutex* mutex);
bool Wait(NzMutex* mutex, nzUInt32 timeout);
void Signal();
void SignalAll();
private:
NzConditionVariableImpl* m_impl;
};
void Wait(Mutex* mutex);
bool Wait(Mutex* mutex, UInt32 timeout);
ConditionVariable& operator=(const ConditionVariable&) = delete;
ConditionVariable& operator=(ConditionVariable&&) = delete; ///TODO
private:
ConditionVariableImpl* m_impl;
};
}
#endif // NAZARA_CONDITIONVARIABLE_HPP

View File

@@ -44,7 +44,7 @@
// Taille du buffer lors d'une lecture complète d'un fichier (ex: Hash)
#define NAZARA_CORE_FILE_BUFFERSIZE 4096
// Incorpore la table Unicode Character Data (Nécessaires pour faire fonctionner le flag NzString::HandleUTF8)
// Incorpore la table Unicode Character Data (Nécessaires pour faire fonctionner le flag String::HandleUTF8)
#define NAZARA_CORE_INCLUDE_UNICODEDATA 0
// Utilise le MemoryManager pour gérer les allocations dynamiques (détecte les leaks au prix d'allocations/libérations dynamiques plus lentes)
@@ -57,12 +57,12 @@
#define NAZARA_CORE_THREADSAFE 1
// Les classes à protéger des accès concurrentiels
#define NAZARA_THREADSAFETY_CLOCK 0 // NzClock
#define NAZARA_THREADSAFETY_DIRECTORY 1 // NzDirectory
#define NAZARA_THREADSAFETY_DYNLIB 1 // NzDynLib
#define NAZARA_THREADSAFETY_FILE 1 // NzFile
#define NAZARA_THREADSAFETY_LOG 1 // NzLog
#define NAZARA_THREADSAFETY_REFCOUNTED 1 // NzRefCounted
#define NAZARA_THREADSAFETY_CLOCK 0 // Clock
#define NAZARA_THREADSAFETY_DIRECTORY 1 // Directory
#define NAZARA_THREADSAFETY_DYNLIB 1 // DynLib
#define NAZARA_THREADSAFETY_FILE 1 // File
#define NAZARA_THREADSAFETY_LOG 1 // Log
#define NAZARA_THREADSAFETY_REFCOUNTED 1 // RefCounted
// Le nombre de spinlocks à utiliser avec les sections critiques de Windows (0 pour désactiver)
#define NAZARA_CORE_WINDOWS_CS_SPINLOCKS 4096

View File

@@ -10,20 +10,23 @@
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/Initializer.hpp>
class NAZARA_CORE_API NzCore
namespace Nz
{
public:
NzCore() = delete;
~NzCore() = delete;
class NAZARA_CORE_API Core
{
public:
Core() = delete;
~Core() = delete;
static bool Initialize();
static bool Initialize();
static bool IsInitialized();
static bool IsInitialized();
static void Uninitialize();
static void Uninitialize();
private:
static unsigned int s_moduleReferenceCounter;
};
private:
static unsigned int s_moduleReferenceCounter;
};
}
#endif // NAZARA_CORE_HPP

View File

@@ -21,7 +21,7 @@ NAZARA_CORE_API void operator delete[](void* ptr, const char* file, unsigned int
#endif // NAZARA_DEBUG_NEWREDEFINITION_HPP
#ifndef NAZARA_DEBUG_NEWREDEFINITION_DISABLE_REDEFINITION
#define delete NzMemoryManager::NextFree(__FILE__, __LINE__), delete
#define delete MemoryManager::NextFree(__FILE__, __LINE__), delete
#define new new(__FILE__, __LINE__)
#endif

View File

@@ -8,7 +8,6 @@
#define NAZARA_DIRECTORY_HPP
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/NonCopyable.hpp>
#include <Nazara/Core/String.hpp>
#if defined(NAZARA_PLATFORM_WINDOWS)
@@ -26,49 +25,57 @@
#include <Nazara/Core/ThreadSafetyOff.hpp>
#endif
class NzDirectoryImpl;
class NAZARA_CORE_API NzDirectory : NzNonCopyable
namespace Nz
{
public:
NzDirectory();
NzDirectory(const NzString& dirPath);
~NzDirectory();
class DirectoryImpl;
void Close();
class NAZARA_CORE_API Directory
{
public:
Directory();
Directory(const String& dirPath);
Directory(const Directory&) = delete;
Directory(Directory&&) = delete; ///TODO
~Directory();
bool Exists() const;
void Close();
NzString GetPath() const;
NzString GetPattern() const;
NzString GetResultName() const;
NzString GetResultPath() const;
nzUInt64 GetResultSize() const;
bool Exists() const;
bool IsOpen() const;
bool IsResultDirectory() const;
String GetPath() const;
String GetPattern() const;
String GetResultName() const;
String GetResultPath() const;
UInt64 GetResultSize() const;
bool NextResult(bool skipDots = true);
bool IsOpen() const;
bool IsResultDirectory() const;
bool Open();
bool NextResult(bool skipDots = true);
void SetPath(const NzString& dirPath);
void SetPattern(const NzString& pattern);
bool Open();
static bool Copy(const NzString& sourcePath, const NzString& destPath);
static bool Create(const NzString& dirPath, bool recursive = false);
static bool Exists(const NzString& dirPath);
static NzString GetCurrent();
static const char* GetCurrentFileRelativeToEngine(const char* currentFile);
static bool Remove(const NzString& dirPath, bool emptyDirectory = false);
static bool SetCurrent(const NzString& dirPath);
void SetPath(const String& dirPath);
void SetPattern(const String& pattern);
private:
NazaraMutexAttrib(m_mutex, mutable)
static bool Copy(const String& sourcePath, const String& destPath);
static bool Create(const String& dirPath, bool recursive = false);
static bool Exists(const String& dirPath);
static String GetCurrent();
static const char* GetCurrentFileRelativeToEngine(const char* currentFile);
static bool Remove(const String& dirPath, bool emptyDirectory = false);
static bool SetCurrent(const String& dirPath);
NzString m_dirPath;
NzString m_pattern;
NzDirectoryImpl* m_impl;
};
Directory& operator=(const Directory&) = delete;
Directory& operator=(Directory&&) = delete; ///TODO
private:
NazaraMutexAttrib(m_mutex, mutable)
String m_dirPath;
String m_pattern;
DirectoryImpl* m_impl;
};
}
#endif // NAZARA_DIRECTORY_HPP

View File

@@ -8,7 +8,6 @@
#define NAZARA_DYNLIB_HPP
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/NonCopyable.hpp>
#include <Nazara/Core/String.hpp>
#if defined(NAZARA_PLATFORM_WINDOWS)
@@ -27,32 +26,37 @@
#include <Nazara/Core/ThreadSafetyOff.hpp>
#endif
using NzDynLibFunc = int (*)(); // Type "générique" de pointeur sur fonction
class NzDynLibImpl;
class NAZARA_CORE_API NzDynLib : NzNonCopyable
namespace Nz
{
public:
NzDynLib();
NzDynLib(NzDynLib&& lib);
~NzDynLib();
using DynLibFunc = int (*)(); // Type "générique" de pointeur sur fonction
NzString GetLastError() const;
NzDynLibFunc GetSymbol(const NzString& symbol) const;
class DynLibImpl;
bool IsLoaded() const;
class NAZARA_CORE_API DynLib
{
public:
DynLib();
DynLib(const DynLib&) = delete;
DynLib(DynLib&& lib);
~DynLib();
bool Load(const NzString& libraryPath);
void Unload();
String GetLastError() const;
DynLibFunc GetSymbol(const String& symbol) const;
NzDynLib& operator=(NzDynLib&& lib);
bool IsLoaded() const;
private:
NazaraMutexAttrib(m_mutex, mutable)
bool Load(const String& libraryPath);
void Unload();
mutable NzString m_lastError;
NzDynLibImpl* m_impl;
DynLib& operator=(const DynLib&) = delete;
DynLib& operator=(DynLib&& lib);
private:
NazaraMutexAttrib(m_mutex, mutable)
mutable String m_lastError;
DynLibImpl* m_impl;
};
}
#endif // NAZARA_DYNLIB_HPP

View File

@@ -25,8 +25,11 @@
#error You cannot define both NAZARA_BIG_ENDIAN and NAZARA_LITTLE_ENDIAN
#endif
inline void NzByteSwap(void* buffer, unsigned int size);
inline nzEndianness NzGetPlatformEndianness();
namespace Nz
{
inline constexpr Endianness GetPlatformEndianness();
inline void SwapBytes(void* buffer, unsigned int size);
}
#include <Nazara/Core/Endianness.inl>

View File

@@ -5,23 +5,26 @@
#include <algorithm>
#include <Nazara/Core/Debug.hpp>
inline void NzByteSwap(void* buffer, unsigned int size)
namespace Nz
{
nzUInt8* bytes = reinterpret_cast<nzUInt8*>(buffer);
unsigned int i = 0;
unsigned int j = size-1;
inline constexpr Endianness GetPlatformEndianness()
{
#if defined(NAZARA_BIG_ENDIAN)
return Endianness_BigEndian;
#elif defined(NAZARA_LITTLE_ENDIAN)
return Endianness_LittleEndian;
#endif
}
while (i < j)
std::swap(bytes[i++], bytes[j--]);
}
inline void SwapBytes(void* buffer, unsigned int size)
{
UInt8* bytes = reinterpret_cast<UInt8*>(buffer);
unsigned int i = 0;
unsigned int j = size-1;
inline nzEndianness NzGetPlatformEndianness()
{
#if defined(NAZARA_BIG_ENDIAN)
return nzEndianness_BigEndian;
#elif defined(NAZARA_LITTLE_ENDIAN)
return nzEndianness_LittleEndian;
#endif
while (i < j)
std::swap(bytes[i++], bytes[j--]);
}
}
#include <Nazara/Core/DebugOff.hpp>

View File

@@ -7,182 +7,187 @@
#ifndef NAZARA_ENUMS_CORE_HPP
#define NAZARA_ENUMS_CORE_HPP
enum nzCoordSys
namespace Nz
{
nzCoordSys_Global,
nzCoordSys_Local,
enum CoordSys
{
CoordSys_Global,
CoordSys_Local,
nzCoordSys_Max = nzCoordSys_Local
};
CoordSys_Max = CoordSys_Local
};
enum nzCursorPosition
{
nzCursorPosition_AtBegin, // Début du fichier
nzCursorPosition_AtCurrent, // Position du pointeur
nzCursorPosition_AtEnd, // Fin du fichier
enum CursorPosition
{
CursorPosition_AtBegin, // Début du fichier
CursorPosition_AtCurrent, // Position du pointeur
CursorPosition_AtEnd, // Fin du fichier
nzCursorPosition_Max = nzCursorPosition_AtEnd
};
CursorPosition_Max = CursorPosition_AtEnd
};
enum nzEndianness
{
nzEndianness_Unknown = -1,
enum Endianness
{
Endianness_Unknown = -1,
nzEndianness_BigEndian,
nzEndianness_LittleEndian,
Endianness_BigEndian,
Endianness_LittleEndian,
nzEndianness_Max = nzEndianness_LittleEndian
};
Endianness_Max = Endianness_LittleEndian
};
enum nzErrorFlag
{
nzErrorFlag_None = 0,
enum ErrorFlag
{
ErrorFlag_None = 0,
nzErrorFlag_Silent = 0x1,
nzErrorFlag_SilentDisabled = 0x2,
nzErrorFlag_ThrowException = 0x4,
nzErrorFlag_ThrowExceptionDisabled = 0x8,
ErrorFlag_Silent = 0x1,
ErrorFlag_SilentDisabled = 0x2,
ErrorFlag_ThrowException = 0x4,
ErrorFlag_ThrowExceptionDisabled = 0x8,
nzErrorFlag_Max = nzErrorFlag_ThrowExceptionDisabled*2-1
};
ErrorFlag_Max = ErrorFlag_ThrowExceptionDisabled*2-1
};
enum nzErrorType
{
nzErrorType_AssertFailed,
nzErrorType_Internal,
nzErrorType_Normal,
nzErrorType_Warning,
enum ErrorType
{
ErrorType_AssertFailed,
ErrorType_Internal,
ErrorType_Normal,
ErrorType_Warning,
nzErrorType_Max = nzErrorType_Warning
};
ErrorType_Max = ErrorType_Warning
};
enum nzHash
{
nzHash_CRC32,
nzHash_Fletcher16,
nzHash_MD5,
nzHash_SHA1,
nzHash_SHA224,
nzHash_SHA256,
nzHash_SHA384,
nzHash_SHA512,
nzHash_Whirlpool,
enum HashType
{
HashType_CRC32,
HashType_Fletcher16,
HashType_MD5,
HashType_SHA1,
HashType_SHA224,
HashType_SHA256,
HashType_SHA384,
HashType_SHA512,
HashType_Whirlpool,
nzHash_Max = nzHash_Whirlpool
};
HashType_Max = HashType_Whirlpool
};
enum nzOpenModeFlags
{
nzOpenMode_Current = 0x00, // Utilise le mode d'ouverture actuel
enum OpenModeFlags
{
OpenMode_NotOpen = 0x00, // Utilise le mode d'ouverture actuel
nzOpenMode_Append = 0x01, // Empêche l'écriture sur la partie déjà existante et met le curseur à la fin
nzOpenMode_Lock = 0x02, // Empêche le fichier d'être modifié tant qu'il est ouvert
nzOpenMode_ReadOnly = 0x04, // Ouvre uniquement en lecture
nzOpenMode_ReadWrite = 0x08, // Ouvre en lecture/écriture
nzOpenMode_Text = 0x10, // Ouvre en mode texte
nzOpenMode_Truncate = 0x20, // Créé le fichier s'il n'existe pas et le vide s'il existe
nzOpenMode_WriteOnly = 0x40, // Ouvre uniquement en écriture, créé le fichier s'il n'existe pas
OpenMode_Append = 0x01, // Empêche l'écriture sur la partie déjà existante et met le curseur à la fin
OpenMode_Lock = 0x02, // Empêche le fichier d'être modifié tant qu'il est ouvert
OpenMode_ReadOnly = 0x04, // Ouvre uniquement en lecture
OpenMode_Text = 0x10, // Ouvre en mode texte
OpenMode_Truncate = 0x20, // Créé le fichier s'il n'existe pas et le vide s'il existe
OpenMode_WriteOnly = 0x40, // Ouvre uniquement en écriture, créé le fichier s'il n'existe pas
nzOpenMode_Max = nzOpenMode_WriteOnly
};
OpenMode_ReadWrite = OpenMode_ReadOnly | OpenMode_WriteOnly, // Ouvre en lecture/écriture
enum nzParameterType
{
nzParameterType_Boolean,
nzParameterType_Float,
nzParameterType_Integer,
nzParameterType_None,
nzParameterType_Pointer,
nzParameterType_String,
nzParameterType_Userdata,
OpenMode_Max = OpenMode_WriteOnly
};
nzParameterType_Max = nzParameterType_Userdata
};
enum ParameterType
{
ParameterType_Boolean,
ParameterType_Float,
ParameterType_Integer,
ParameterType_None,
ParameterType_Pointer,
ParameterType_String,
ParameterType_Userdata,
enum nzPlugin
{
nzPlugin_Assimp,
nzPlugin_FreeType
};
ParameterType_Max = ParameterType_Userdata
};
enum nzPrimitiveType
{
nzPrimitiveType_Box,
nzPrimitiveType_Cone,
nzPrimitiveType_Plane,
nzPrimitiveType_Sphere,
enum Plugin
{
Plugin_Assimp,
Plugin_FreeType
};
nzPrimitiveType_Max = nzPrimitiveType_Sphere
};
enum PrimitiveType
{
PrimitiveType_Box,
PrimitiveType_Cone,
PrimitiveType_Plane,
PrimitiveType_Sphere,
enum nzProcessorCap
{
nzProcessorCap_x64,
nzProcessorCap_AVX,
nzProcessorCap_FMA3,
nzProcessorCap_FMA4,
nzProcessorCap_MMX,
nzProcessorCap_XOP,
nzProcessorCap_SSE,
nzProcessorCap_SSE2,
nzProcessorCap_SSE3,
nzProcessorCap_SSSE3,
nzProcessorCap_SSE41,
nzProcessorCap_SSE42,
nzProcessorCap_SSE4a,
PrimitiveType_Max = PrimitiveType_Sphere
};
nzProcessorCap_Max = nzProcessorCap_SSE4a
};
enum ProcessorCap
{
ProcessorCap_x64,
ProcessorCap_AVX,
ProcessorCap_FMA3,
ProcessorCap_FMA4,
ProcessorCap_MMX,
ProcessorCap_XOP,
ProcessorCap_SSE,
ProcessorCap_SSE2,
ProcessorCap_SSE3,
ProcessorCap_SSSE3,
ProcessorCap_SSE41,
ProcessorCap_SSE42,
ProcessorCap_SSE4a,
enum nzProcessorVendor
{
nzProcessorVendor_Unknown = -1,
ProcessorCap_Max = ProcessorCap_SSE4a
};
nzProcessorVendor_AMD,
nzProcessorVendor_Centaur,
nzProcessorVendor_Cyrix,
nzProcessorVendor_Intel,
nzProcessorVendor_KVM,
nzProcessorVendor_HyperV,
nzProcessorVendor_NSC,
nzProcessorVendor_NexGen,
nzProcessorVendor_Rise,
nzProcessorVendor_SIS,
nzProcessorVendor_Transmeta,
nzProcessorVendor_UMC,
nzProcessorVendor_VIA,
nzProcessorVendor_VMware,
nzProcessorVendor_Vortex,
nzProcessorVendor_XenHVM,
enum ProcessorVendor
{
ProcessorVendor_Unknown = -1,
nzProcessorVendor_Max = nzProcessorVendor_XenHVM
};
ProcessorVendor_AMD,
ProcessorVendor_Centaur,
ProcessorVendor_Cyrix,
ProcessorVendor_Intel,
ProcessorVendor_KVM,
ProcessorVendor_HyperV,
ProcessorVendor_NSC,
ProcessorVendor_NexGen,
ProcessorVendor_Rise,
ProcessorVendor_SIS,
ProcessorVendor_Transmeta,
ProcessorVendor_UMC,
ProcessorVendor_VIA,
ProcessorVendor_VMware,
ProcessorVendor_Vortex,
ProcessorVendor_XenHVM,
enum nzSphereType
{
nzSphereType_Cubic,
nzSphereType_Ico,
nzSphereType_UV,
ProcessorVendor_Max = ProcessorVendor_XenHVM
};
nzSphereType_Max = nzSphereType_UV
};
enum SphereType
{
SphereType_Cubic,
SphereType_Ico,
SphereType_UV,
enum nzStreamOptionFlags
{
nzStreamOption_None = 0,
SphereType_Max = SphereType_UV
};
nzStreamOption_Text = 0x1,
enum StreamOptionFlags
{
StreamOption_None = 0,
nzStreamOption_Max = nzStreamOption_Text*2-1
};
StreamOption_Sequential = 0x1,
StreamOption_Text = 0x2,
enum nzTernary
{
nzTernary_False,
nzTernary_True,
nzTernary_Unknown,
StreamOption_Max = StreamOption_Text*2-1
};
nzTernary_Max = nzTernary_Unknown
};
enum Ternary
{
Ternary_False,
Ternary_True,
Ternary_Unknown,
Ternary_Max = Ternary_Unknown
};
}
#endif // NAZARA_ENUMS_CORE_HPP

View File

@@ -14,37 +14,40 @@
#include <Nazara/Core/String.hpp>
#if NAZARA_CORE_ENABLE_ASSERTS || defined(NAZARA_DEBUG)
#define NazaraAssert(a, err) if (!(a)) NzError::Error(nzErrorType_AssertFailed, err, __LINE__, NzDirectory::GetCurrentFileRelativeToEngine(__FILE__), NAZARA_FUNCTION)
#define NazaraAssert(a, err) if (!(a)) Nz::Error::Trigger(Nz::ErrorType_AssertFailed, err, __LINE__, Nz::Directory::GetCurrentFileRelativeToEngine(__FILE__), NAZARA_FUNCTION)
#else
#define NazaraAssert(a, err)
#define NazaraAssert(a, err) for (;;) break
#endif
#define NazaraError(err) NzError::Error(nzErrorType_Normal, err, __LINE__, NzDirectory::GetCurrentFileRelativeToEngine(__FILE__), NAZARA_FUNCTION)
#define NazaraInternalError(err) NzError::Error(nzErrorType_Internal, err, __LINE__, NzDirectory::GetCurrentFileRelativeToEngine(__FILE__), NAZARA_FUNCTION)
#define NazaraWarning(err) NzError::Error(nzErrorType_Warning, err, __LINE__, NzDirectory::GetCurrentFileRelativeToEngine(__FILE__), NAZARA_FUNCTION)
#define NazaraError(err) Nz::Error::Trigger(Nz::ErrorType_Normal, err, __LINE__, Nz::Directory::GetCurrentFileRelativeToEngine(__FILE__), NAZARA_FUNCTION)
#define NazaraInternalError(err) Nz::Error::Trigger(Nz::ErrorType_Internal, err, __LINE__, Nz::Directory::GetCurrentFileRelativeToEngine(__FILE__), NAZARA_FUNCTION)
#define NazaraWarning(err) Nz::Error::Trigger(Nz::ErrorType_Warning, err, __LINE__, Nz::Directory::GetCurrentFileRelativeToEngine(__FILE__), NAZARA_FUNCTION)
class NAZARA_CORE_API NzError
namespace Nz
{
public:
NzError() = delete;
~NzError() = delete;
class NAZARA_CORE_API Error
{
public:
Error() = delete;
~Error() = delete;
static void Error(nzErrorType type, const NzString& error);
static void Error(nzErrorType type, const NzString& error, unsigned int line, const char* file, const char* function);
static UInt32 GetFlags();
static String GetLastError(const char** file = nullptr, unsigned int* line = nullptr, const char** function = nullptr);
static unsigned int GetLastSystemErrorCode();
static String GetLastSystemError(unsigned int code = GetLastSystemErrorCode());
static nzUInt32 GetFlags();
static NzString GetLastError(const char** file = nullptr, unsigned int* line = nullptr, const char** function = nullptr);
static unsigned int GetLastSystemErrorCode();
static NzString GetLastSystemError(unsigned int code = GetLastSystemErrorCode());
static void SetFlags(UInt32 flags);
static void SetFlags(nzUInt32 flags);
static void Trigger(ErrorType type, const String& error);
static void Trigger(ErrorType type, const String& error, unsigned int line, const char* file, const char* function);
private:
static nzUInt32 s_flags;
static NzString s_lastError;
static const char* s_lastErrorFunction;
static const char* s_lastErrorFile;
static unsigned int s_lastErrorLine;
};
private:
static UInt32 s_flags;
static String s_lastError;
static const char* s_lastErrorFunction;
static const char* s_lastErrorFile;
static unsigned int s_lastErrorLine;
};
}
#endif // NAZARA_ERROR_HPP

View File

@@ -9,20 +9,27 @@
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/Enums.hpp>
#include <Nazara/Core/NonCopyable.hpp>
class NAZARA_CORE_API NzErrorFlags : NzNonCopyable
namespace Nz
{
public:
NzErrorFlags(nzUInt32 flags, bool replace = false);
~NzErrorFlags();
class NAZARA_CORE_API ErrorFlags
{
public:
ErrorFlags(UInt32 flags, bool replace = false);
ErrorFlags(const ErrorFlags&) = delete;
ErrorFlags(ErrorFlags&&) = delete;
~ErrorFlags();
nzUInt32 GetPreviousFlags() const;
UInt32 GetPreviousFlags() const;
void SetFlags(nzUInt32 flags, bool replace = false);
void SetFlags(UInt32 flags, bool replace = false);
private:
nzUInt32 m_previousFlags;
};
ErrorFlags& operator=(const ErrorFlags&) = delete;
ErrorFlags& operator=(ErrorFlags&&) = delete;
private:
UInt32 m_previousFlags;
};
}
#endif // NAZARA_ERRORFLAGS_HPP

View File

@@ -11,10 +11,7 @@
#include <Nazara/Core/ByteArray.hpp>
#include <Nazara/Core/Directory.hpp>
#include <Nazara/Core/Endianness.hpp>
#include <Nazara/Core/Hashable.hpp>
#include <Nazara/Core/HashDigest.hpp>
#include <Nazara/Core/InputStream.hpp>
#include <Nazara/Core/NonCopyable.hpp>
#include <Nazara/Core/Stream.hpp>
#include <Nazara/Core/String.hpp>
#if NAZARA_CORE_THREADSAFE && NAZARA_THREADSAFETY_FILE
@@ -25,85 +22,84 @@
#include <ctime>
class NzFileImpl;
class NAZARA_CORE_API NzFile : public NzHashable, public NzInputStream, NzNonCopyable
namespace Nz
{
public:
NzFile();
NzFile(const NzString& filePath);
NzFile(const NzString& filePath, unsigned int openMode);
NzFile(NzFile&& file) noexcept;
~NzFile();
class FileImpl;
bool Copy(const NzString& newFilePath);
void Close();
class NAZARA_CORE_API File : public Stream
{
public:
File();
File(const String& filePath);
File(const String& filePath, UInt32 openMode);
File(const File&) = delete;
File(File&& file) noexcept;
~File();
bool Delete();
bool Copy(const String& newFilePath);
void Close();
bool EndOfFile() const;
bool EndOfStream() const;
bool Delete();
bool Exists() const;
bool EndOfFile() const;
bool EndOfStream() const override;
void Flush();
bool Exists() const;
time_t GetCreationTime() const;
nzUInt64 GetCursorPos() const;
NzString GetDirectory() const;
NzString GetFileName() const;
time_t GetLastAccessTime() const;
time_t GetLastWriteTime() const;
NzString GetPath() const;
nzUInt64 GetSize() const;
time_t GetCreationTime() const;
UInt64 GetCursorPos() const override;
String GetDirectory() const override;
String GetFileName() const;
time_t GetLastAccessTime() const;
time_t GetLastWriteTime() const;
String GetPath() const override;
UInt64 GetSize() const override;
bool IsOpen() const;
bool IsOpen() const;
bool Open(unsigned int openMode = nzOpenMode_Current);
bool Open(const NzString& filePath, unsigned int openMode = nzOpenMode_Current);
bool Open(unsigned int openMode = OpenMode_NotOpen);
bool Open(const String& filePath, unsigned int openMode = OpenMode_NotOpen);
std::size_t Read(void* buffer, std::size_t size);
std::size_t Read(void* buffer, std::size_t typeSize, unsigned int count);
bool Rename(const NzString& newFilePath);
bool Rename(const String& newFilePath);
bool SetCursorPos(nzCursorPosition pos, nzInt64 offset = 0);
bool SetCursorPos(nzUInt64 offset);
void SetEndianness(nzEndianness endianness);
bool SetFile(const NzString& filePath);
bool SetOpenMode(unsigned int openMode);
bool SetCursorPos(CursorPosition pos, Int64 offset = 0);
bool SetCursorPos(UInt64 offset) override;
bool SetFile(const String& filePath);
bool Write(const NzByteArray& byteArray);
bool Write(const NzString& string);
std::size_t Write(const void* buffer, std::size_t typeSize, unsigned int count);
File& operator=(const String& filePath);
File& operator=(const File&) = delete;
File& operator=(File&& file) noexcept;
NzFile& operator=(const NzString& filePath);
NzFile& operator=(NzFile&& file) noexcept;
static String AbsolutePath(const String& filePath);
static inline ByteArray ComputeHash(HashType hash, const String& filePath);
static inline ByteArray ComputeHash(AbstractHash* hash, const String& filePath);
static bool Copy(const String& sourcePath, const String& targetPath);
static bool Delete(const String& filePath);
static bool Exists(const String& filePath);
static time_t GetCreationTime(const String& filePath);
static String GetDirectory(const String& filePath);
static time_t GetLastAccessTime(const String& filePath);
static time_t GetLastWriteTime(const String& filePath);
static UInt64 GetSize(const String& filePath);
static bool IsAbsolute(const String& filePath);
static String NormalizePath(const String& filePath);
static String NormalizeSeparators(const String& filePath);
static bool Rename(const String& sourcePath, const String& targetPath);
static NzString AbsolutePath(const NzString& filePath);
static bool Copy(const NzString& sourcePath, const NzString& targetPath);
static bool Delete(const NzString& filePath);
static bool Exists(const NzString& filePath);
static time_t GetCreationTime(const NzString& filePath);
static NzString GetDirectory(const NzString& filePath);
static time_t GetLastAccessTime(const NzString& filePath);
static time_t GetLastWriteTime(const NzString& filePath);
static NzHashDigest GetHash(const NzString& filePath, nzHash hash);
static NzHashDigest GetHash(const NzString& filePath, NzAbstractHash* hash);
static nzUInt64 GetSize(const NzString& filePath);
static bool IsAbsolute(const NzString& filePath);
static NzString NormalizePath(const NzString& filePath);
static NzString NormalizeSeparators(const NzString& filePath);
static bool Rename(const NzString& sourcePath, const NzString& targetPath);
private:
NazaraMutexAttrib(m_mutex, mutable)
private:
bool FillHash(NzAbstractHash* hash) const;
void FlushStream() override;
std::size_t ReadBlock(void* buffer, std::size_t size) override;
std::size_t WriteBlock(const void* buffer, std::size_t size) override;
NazaraMutexAttrib(m_mutex, mutable)
String m_filePath;
FileImpl* m_impl;
};
nzEndianness m_endianness;
NzString m_filePath;
NzFileImpl* m_impl;
unsigned int m_openMode;
};
NAZARA_CORE_API bool HashAppend(AbstractHash* hash, const File& originalFile);
}
#include <Nazara/Core/File.inl>
#endif // NAZARA_FILE_HPP

View File

@@ -0,0 +1,22 @@
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Core/AbstractHash.hpp>
#include <Nazara/Core/Algorithm.hpp>
#include <Nazara/Core/Debug.hpp>
namespace Nz
{
inline ByteArray File::ComputeHash(HashType hash, const String& filePath)
{
return ComputeHash(AbstractHash::Get(hash).get(), filePath);
}
inline ByteArray File::ComputeHash(AbstractHash* hash, const String& filePath)
{
return Nz::ComputeHash(hash, File(filePath));
}
}
#include <Nazara/Core/DebugOff.hpp>

View File

@@ -0,0 +1,46 @@
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#pragma once
#ifndef NAZARA_FILELOGGER_HPP
#define NAZARA_FILELOGGER_HPP
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/AbstractLogger.hpp>
#include <Nazara/Core/File.hpp>
#include <Nazara/Core/StdLogger.hpp>
namespace Nz
{
class NAZARA_CORE_API FileLogger : public AbstractLogger
{
public:
FileLogger(const String& logPath = "NazaraLog.log");
FileLogger(const FileLogger&) = default;
FileLogger(FileLogger&&) = default;
~FileLogger();
void EnableTimeLogging(bool enable);
void EnableStdReplication(bool enable) override;
bool IsStdReplicationEnabled() override;
bool IsTimeLoggingEnabled();
void Write(const String& string) override;
void WriteError(ErrorType type, const String& error, unsigned int line = 0, const char* file = nullptr, const char* function = nullptr) override;
FileLogger& operator=(const FileLogger&) = default;
FileLogger& operator=(FileLogger&&) = default;
private:
File m_outputFile;
StdLogger m_stdLogger;
bool m_forceStdOutput;
bool m_stdReplicationEnabled;
bool m_timeLoggingEnabled;
};
}
#endif // NAZARA_FILELOGGER_HPP

View File

@@ -11,47 +11,50 @@
// Inspiré du code de la SFML par Laurent Gomila
struct NzFunctor
namespace Nz
{
virtual ~NzFunctor() {}
struct Functor
{
virtual ~Functor() {}
virtual void Run() = 0;
};
virtual void Run() = 0;
};
template<typename F>
struct NzFunctorWithoutArgs : NzFunctor
{
NzFunctorWithoutArgs(F func);
template<typename F>
struct FunctorWithoutArgs : Functor
{
FunctorWithoutArgs(F func);
void Run();
void Run();
private:
F m_func;
};
private:
F m_func;
};
template<typename F, typename... Args>
struct NzFunctorWithArgs : NzFunctor
{
NzFunctorWithArgs(F func, Args&&... args);
template<typename F, typename... Args>
struct FunctorWithArgs : Functor
{
FunctorWithArgs(F func, Args&&... args);
void Run();
void Run();
private:
F m_func;
std::tuple<Args...> m_args;
};
private:
F m_func;
std::tuple<Args...> m_args;
};
template<typename C>
struct NzMemberWithoutArgs : NzFunctor
{
NzMemberWithoutArgs(void (C::*func)(), C* object);
template<typename C>
struct MemberWithoutArgs : Functor
{
MemberWithoutArgs(void (C::*func)(), C* object);
void Run();
void Run();
private:
void (C::*m_func)();
C* m_object;
};
private:
void (C::*m_func)();
C* m_object;
};
}
#include <Nazara/Core/Functor.inl>

View File

@@ -4,41 +4,44 @@
#include <utility>
template<typename F>
NzFunctorWithoutArgs<F>::NzFunctorWithoutArgs(F func) :
m_func(func)
namespace Nz
{
}
template<typename F>
FunctorWithoutArgs<F>::FunctorWithoutArgs(F func) :
m_func(func)
{
}
template<typename F>
void NzFunctorWithoutArgs<F>::Run()
{
m_func();
}
template<typename F>
void FunctorWithoutArgs<F>::Run()
{
m_func();
}
template<typename F, typename... Args>
NzFunctorWithArgs<F, Args...>::NzFunctorWithArgs(F func, Args&&... args) :
m_func(func),
m_args(std::forward<Args>(args)...)
{
}
template<typename F, typename... Args>
FunctorWithArgs<F, Args...>::FunctorWithArgs(F func, Args&&... args) :
m_func(func),
m_args(std::forward<Args>(args)...)
{
}
template<typename F, typename... Args>
void NzFunctorWithArgs<F, Args...>::Run()
{
NzApply(m_func, m_args);
}
template<typename F, typename... Args>
void FunctorWithArgs<F, Args...>::Run()
{
Apply(m_func, m_args);
}
template<typename C>
NzMemberWithoutArgs<C>::NzMemberWithoutArgs(void (C::*func)(), C* object) :
m_func(func),
m_object(object)
{
}
template<typename C>
MemberWithoutArgs<C>::MemberWithoutArgs(void (C::*func)(), C* object) :
m_func(func),
m_object(object)
{
}
template<typename C>
void NzMemberWithoutArgs<C>::Run()
{
(m_object->*m_func)();
template<typename C>
void MemberWithoutArgs<C>::Run()
{
(m_object->*m_func)();
}
}

View File

@@ -15,74 +15,77 @@
#include <Nazara/Math/Rect.hpp>
#include <vector>
class NAZARA_CORE_API NzGuillotineBinPack
namespace Nz
{
public:
enum FreeRectChoiceHeuristic : int;
enum GuillotineSplitHeuristic : int;
class NAZARA_CORE_API GuillotineBinPack
{
public:
enum FreeRectChoiceHeuristic : int;
enum GuillotineSplitHeuristic : int;
NzGuillotineBinPack();
NzGuillotineBinPack(unsigned int width, unsigned int height);
NzGuillotineBinPack(const NzVector2ui& size);
NzGuillotineBinPack(const NzGuillotineBinPack&) = default;
NzGuillotineBinPack(NzGuillotineBinPack&&) = default;
~NzGuillotineBinPack() = default;
GuillotineBinPack();
GuillotineBinPack(unsigned int width, unsigned int height);
GuillotineBinPack(const Vector2ui& size);
GuillotineBinPack(const GuillotineBinPack&) = default;
GuillotineBinPack(GuillotineBinPack&&) = default;
~GuillotineBinPack() = default;
void Clear();
void Clear();
void Expand(unsigned int newWidth, unsigned newHeight);
void Expand(const NzVector2ui& newSize);
void Expand(unsigned int newWidth, unsigned newHeight);
void Expand(const Vector2ui& newSize);
void FreeRectangle(const NzRectui& rect);
void FreeRectangle(const Rectui& rect);
unsigned int GetHeight() const;
float GetOccupancy() const;
NzVector2ui GetSize() const;
unsigned int GetWidth() const;
unsigned int GetHeight() const;
float GetOccupancy() const;
Vector2ui GetSize() const;
unsigned int GetWidth() const;
bool Insert(NzRectui* rects, unsigned int count, bool merge, FreeRectChoiceHeuristic rectChoice, GuillotineSplitHeuristic splitMethod);
bool Insert(NzRectui* rects, bool* flipped, unsigned int count, bool merge, FreeRectChoiceHeuristic rectChoice, GuillotineSplitHeuristic splitMethod);
bool Insert(NzRectui* rects, bool* flipped, bool* inserted, unsigned int count, bool merge, FreeRectChoiceHeuristic rectChoice, GuillotineSplitHeuristic splitMethod);
bool Insert(Rectui* rects, unsigned int count, bool merge, FreeRectChoiceHeuristic rectChoice, GuillotineSplitHeuristic splitMethod);
bool Insert(Rectui* rects, bool* flipped, unsigned int count, bool merge, FreeRectChoiceHeuristic rectChoice, GuillotineSplitHeuristic splitMethod);
bool Insert(Rectui* rects, bool* flipped, bool* inserted, unsigned int count, bool merge, FreeRectChoiceHeuristic rectChoice, GuillotineSplitHeuristic splitMethod);
bool MergeFreeRectangles();
bool MergeFreeRectangles();
void Reset();
void Reset(unsigned int width, unsigned int height);
void Reset(const NzVector2ui& size);
void Reset();
void Reset(unsigned int width, unsigned int height);
void Reset(const Vector2ui& size);
NzGuillotineBinPack& operator=(const NzGuillotineBinPack&) = default;
NzGuillotineBinPack& operator=(NzGuillotineBinPack&&) = default;
GuillotineBinPack& operator=(const GuillotineBinPack&) = default;
GuillotineBinPack& operator=(GuillotineBinPack&&) = default;
enum FreeRectChoiceHeuristic : int
{
RectBestAreaFit,
RectBestLongSideFit,
RectBestShortSideFit,
RectWorstAreaFit,
RectWorstLongSideFit,
RectWorstShortSideFit
};
enum FreeRectChoiceHeuristic : int
{
RectBestAreaFit,
RectBestLongSideFit,
RectBestShortSideFit,
RectWorstAreaFit,
RectWorstLongSideFit,
RectWorstShortSideFit
};
enum GuillotineSplitHeuristic : int
{
SplitLongerAxis,
SplitLongerLeftoverAxis,
SplitMaximizeArea,
SplitMinimizeArea,
SplitShorterAxis,
SplitShorterLeftoverAxis
};
enum GuillotineSplitHeuristic : int
{
SplitLongerAxis,
SplitLongerLeftoverAxis,
SplitMaximizeArea,
SplitMinimizeArea,
SplitShorterAxis,
SplitShorterLeftoverAxis
};
private:
void SplitFreeRectAlongAxis(const NzRectui& freeRect, const NzRectui& placedRect, bool splitHorizontal);
void SplitFreeRectByHeuristic(const NzRectui& freeRect, const NzRectui& placedRect, GuillotineSplitHeuristic method);
private:
void SplitFreeRectAlongAxis(const Rectui& freeRect, const Rectui& placedRect, bool splitHorizontal);
void SplitFreeRectByHeuristic(const Rectui& freeRect, const Rectui& placedRect, GuillotineSplitHeuristic method);
static int ScoreByHeuristic(int width, int height, const NzRectui& freeRect, FreeRectChoiceHeuristic rectChoice);
static int ScoreByHeuristic(int width, int height, const Rectui& freeRect, FreeRectChoiceHeuristic rectChoice);
std::vector<NzRectui> m_freeRectangles;
unsigned int m_height;
unsigned int m_usedArea;
unsigned int m_width;
};
std::vector<Rectui> m_freeRectangles;
unsigned int m_height;
unsigned int m_usedArea;
unsigned int m_width;
};
}
#endif // NAZARA_GUILLOTINEBINPACK_HPP

View File

@@ -11,25 +11,31 @@
#include <Nazara/Core/Enums.hpp>
#include <Nazara/Core/String.hpp>
class NAZARA_CORE_API NzHardwareInfo
namespace Nz
{
public:
static void Cpuid(nzUInt32 functionId, nzUInt32 subFunctionId, nzUInt32 result[4]);
class NAZARA_CORE_API HardwareInfo
{
public:
HardwareInfo() = delete;
~HardwareInfo() = delete;
static NzString GetProcessorBrandString();
static unsigned int GetProcessorCount();
static nzProcessorVendor GetProcessorVendor();
static NzString GetProcessorVendorName();
static nzUInt64 GetTotalMemory();
static void Cpuid(UInt32 functionId, UInt32 subFunctionId, UInt32 result[4]);
static bool HasCapability(nzProcessorCap capability);
static String GetProcessorBrandString();
static unsigned int GetProcessorCount();
static ProcessorVendor GetProcessorVendor();
static String GetProcessorVendorName();
static UInt64 GetTotalMemory();
static bool Initialize();
static bool HasCapability(ProcessorCap capability);
static bool IsCpuidSupported();
static bool IsInitialized();
static bool Initialize();
static void Uninitialize();
};
static bool IsCpuidSupported();
static bool IsInitialized();
static void Uninitialize();
};
}
#endif // NAZARA_HARDWAREINFO_HPP

View File

@@ -1,29 +0,0 @@
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#pragma once
#ifndef NAZARA_HASH_HPP
#define NAZARA_HASH_HPP
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/AbstractHash.hpp>
#include <Nazara/Core/Hashable.hpp>
#include <Nazara/Core/HashDigest.hpp>
#include <Nazara/Core/NonCopyable.hpp>
class NAZARA_CORE_API NzHash : NzNonCopyable
{
public:
NzHash(nzHash hash);
NzHash(NzAbstractHash* hashImpl);
~NzHash();
NzHashDigest Hash(const NzHashable& hashable);
private:
NzAbstractHash* m_impl;
};
#endif // NAZARA_HASH_HPP

View File

@@ -9,25 +9,28 @@
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/AbstractHash.hpp>
#include <Nazara/Core/HashDigest.hpp>
#include <Nazara/Core/ByteArray.hpp>
struct NzHashCRC32_state;
class NAZARA_CORE_API NzHashCRC32 : public NzAbstractHash
namespace Nz
{
public:
NzHashCRC32(nzUInt32 polynomial = 0x04c11db7);
virtual ~NzHashCRC32();
struct HashCRC32_state;
void Append(const nzUInt8* data, unsigned int len);
void Begin();
NzHashDigest End();
class NAZARA_CORE_API HashCRC32 : public AbstractHash
{
public:
HashCRC32(UInt32 polynomial = 0x04c11db7);
virtual ~HashCRC32();
static unsigned int GetDigestLength();
static NzString GetHashName();
void Append(const UInt8* data, std::size_t len) override;
void Begin() override;
ByteArray End() override;
private:
NzHashCRC32_state* m_state;
};
std::size_t GetDigestLength() const override;
const char* GetHashName() const override;
private:
HashCRC32_state* m_state;
};
}
#endif // NAZARA_HASH_CRC32_HPP

View File

@@ -9,26 +9,29 @@
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/AbstractHash.hpp>
#include <Nazara/Core/HashDigest.hpp>
#include <Nazara/Core/ByteArray.hpp>
#include <Nazara/Core/String.hpp>
struct NzHashFletcher16_state;
class NAZARA_CORE_API NzHashFletcher16 : public NzAbstractHash
namespace Nz
{
public:
NzHashFletcher16();
virtual ~NzHashFletcher16();
struct HashFletcher16_state;
void Append(const nzUInt8* data, unsigned int len);
void Begin();
NzHashDigest End();
class NAZARA_CORE_API HashFletcher16 : public AbstractHash
{
public:
HashFletcher16();
virtual ~HashFletcher16();
static unsigned int GetDigestLength();
static NzString GetHashName();
void Append(const UInt8* data, std::size_t len) override;
void Begin() override;
ByteArray End() override;
private:
NzHashFletcher16_state* m_state;
};
std::size_t GetDigestLength() const override;
const char* GetHashName() const override;
private:
HashFletcher16_state* m_state;
};
}
#endif // NAZARA_HASH_FLETCHER16_HPP

View File

@@ -9,25 +9,28 @@
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/AbstractHash.hpp>
#include <Nazara/Core/HashDigest.hpp>
#include <Nazara/Core/ByteArray.hpp>
struct NzHashMD5_state;
class NAZARA_CORE_API NzHashMD5 : public NzAbstractHash
namespace Nz
{
public:
NzHashMD5();
virtual ~NzHashMD5();
struct HashMD5_state;
void Append(const nzUInt8* data, unsigned int len);
void Begin();
NzHashDigest End();
class NAZARA_CORE_API HashMD5 : public AbstractHash
{
public:
HashMD5();
virtual ~HashMD5();
static unsigned int GetDigestLength();
static NzString GetHashName();
void Append(const UInt8* data, std::size_t len) override;
void Begin() override;
ByteArray End() override;
private:
NzHashMD5_state* m_state;
};
std::size_t GetDigestLength() const override;
const char* GetHashName() const override;
private:
HashMD5_state* m_state;
};
}
#endif // NAZARA_HASH_MD5_HPP

View File

@@ -9,25 +9,28 @@
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/AbstractHash.hpp>
#include <Nazara/Core/HashDigest.hpp>
#include <Nazara/Core/ByteArray.hpp>
union SHA_CTX;
class NAZARA_CORE_API NzHashSHA1 : public NzAbstractHash
namespace Nz
{
public:
NzHashSHA1();
virtual ~NzHashSHA1();
union SHA_CTX;
void Append(const nzUInt8* data, unsigned int len);
void Begin();
NzHashDigest End();
class NAZARA_CORE_API HashSHA1 : public AbstractHash
{
public:
HashSHA1();
virtual ~HashSHA1();
static unsigned int GetDigestLength();
static NzString GetHashName();
void Append(const UInt8* data, std::size_t len) override;
void Begin() override;
ByteArray End() override;
private:
SHA_CTX* m_state;
};
std::size_t GetDigestLength() const override;
const char* GetHashName() const override;
private:
SHA_CTX* m_state;
};
}
#endif // NAZARA_HASH_SHA1_HPP

View File

@@ -9,25 +9,28 @@
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/AbstractHash.hpp>
#include <Nazara/Core/HashDigest.hpp>
#include <Nazara/Core/ByteArray.hpp>
union SHA_CTX;
class NAZARA_CORE_API NzHashSHA224 : public NzAbstractHash
namespace Nz
{
public:
NzHashSHA224();
virtual ~NzHashSHA224();
union SHA_CTX;
void Append(const nzUInt8* data, unsigned int len);
void Begin();
NzHashDigest End();
class NAZARA_CORE_API HashSHA224 : public AbstractHash
{
public:
HashSHA224();
virtual ~HashSHA224();
static unsigned int GetDigestLength();
static NzString GetHashName();
void Append(const UInt8* data, std::size_t len) override;
void Begin() override;
ByteArray End() override;
private:
SHA_CTX* m_state;
};
std::size_t GetDigestLength() const override;
const char* GetHashName() const override;
private:
SHA_CTX* m_state;
};
}
#endif // NAZARA_HASH_SHA224_HPP

View File

@@ -9,25 +9,28 @@
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/AbstractHash.hpp>
#include <Nazara/Core/HashDigest.hpp>
#include <Nazara/Core/ByteArray.hpp>
union SHA_CTX;
class NAZARA_CORE_API NzHashSHA256 : public NzAbstractHash
namespace Nz
{
public:
NzHashSHA256();
virtual ~NzHashSHA256();
union SHA_CTX;
void Append(const nzUInt8* data, unsigned int len);
void Begin();
NzHashDigest End();
class NAZARA_CORE_API HashSHA256 : public AbstractHash
{
public:
HashSHA256();
virtual ~HashSHA256();
static unsigned int GetDigestLength();
static NzString GetHashName();
void Append(const UInt8* data, std::size_t len) override;
void Begin() override;
ByteArray End() override;
private:
SHA_CTX* m_state;
};
std::size_t GetDigestLength() const override;
const char* GetHashName() const override;
private:
SHA_CTX* m_state;
};
}
#endif // NAZARA_HASH_SHA256_HPP

View File

@@ -9,25 +9,28 @@
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/AbstractHash.hpp>
#include <Nazara/Core/HashDigest.hpp>
#include <Nazara/Core/ByteArray.hpp>
union SHA_CTX;
class NAZARA_CORE_API NzHashSHA384 : public NzAbstractHash
namespace Nz
{
public:
NzHashSHA384();
virtual ~NzHashSHA384();
union SHA_CTX;
void Append(const nzUInt8* data, unsigned int len);
void Begin();
NzHashDigest End();
class NAZARA_CORE_API HashSHA384 : public AbstractHash
{
public:
HashSHA384();
virtual ~HashSHA384();
static unsigned int GetDigestLength();
static NzString GetHashName();
void Append(const UInt8* data, std::size_t len) override;
void Begin() override;
ByteArray End() override;
private:
SHA_CTX* m_state;
};
std::size_t GetDigestLength() const override;
const char* GetHashName() const override;
private:
SHA_CTX* m_state;
};
}
#endif // NAZARA_HASH_SHA384_HPP

View File

@@ -9,25 +9,28 @@
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/AbstractHash.hpp>
#include <Nazara/Core/HashDigest.hpp>
#include <Nazara/Core/ByteArray.hpp>
union SHA_CTX;
class NAZARA_CORE_API NzHashSHA512 : public NzAbstractHash
namespace Nz
{
public:
NzHashSHA512();
virtual ~NzHashSHA512();
union SHA_CTX;
void Append(const nzUInt8* data, unsigned int len);
void Begin();
NzHashDigest End();
class NAZARA_CORE_API HashSHA512 : public AbstractHash
{
public:
HashSHA512();
virtual ~HashSHA512();
static unsigned int GetDigestLength();
static NzString GetHashName();
void Append(const UInt8* data, std::size_t len) override;
void Begin() override;
ByteArray End() override;
private:
SHA_CTX* m_state;
};
std::size_t GetDigestLength() const override;
const char* GetHashName() const override;
private:
SHA_CTX* m_state;
};
}
#endif // NAZARA_HASH_SHA512_HPP

View File

@@ -7,25 +7,28 @@
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/AbstractHash.hpp>
#include <Nazara/Core/HashDigest.hpp>
#include <Nazara/Core/ByteArray.hpp>
struct NzHashWhirlpool_state;
class NAZARA_CORE_API NzHashWhirlpool : public NzAbstractHash
namespace Nz
{
public:
NzHashWhirlpool();
virtual ~NzHashWhirlpool();
struct HashWhirlpool_state;
void Append(const nzUInt8* data, unsigned int len);
void Begin();
NzHashDigest End();
class NAZARA_CORE_API HashWhirlpool : public AbstractHash
{
public:
HashWhirlpool();
virtual ~HashWhirlpool();
static unsigned int GetDigestLength();
static NzString GetHashName();
void Append(const UInt8* data, std::size_t len) override;
void Begin() override;
ByteArray End() override;
private:
NzHashWhirlpool_state* m_state;
};
std::size_t GetDigestLength() const;
const char* GetHashName() const;
private:
HashWhirlpool_state* m_state;
};
}
#endif // NAZARA_HASH_WHIRLPOOL_HPP

View File

@@ -1,53 +0,0 @@
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#pragma once
#ifndef NAZARA_HASHDIGEST_HPP
#define NAZARA_HASHDIGEST_HPP
///TODO: Remplacer par ByteArray
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/String.hpp>
#include <iosfwd>
class NAZARA_CORE_API NzHashDigest
{
public:
NzHashDigest();
NzHashDigest(const NzString& hashName, const nzUInt8* digest, unsigned int length);
NzHashDigest(const NzHashDigest& rhs);
NzHashDigest(NzHashDigest&& rhs) noexcept;
~NzHashDigest();
bool IsValid() const;
const nzUInt8* GetDigest() const;
unsigned int GetDigestLength() const;
NzString GetHashName() const;
NzString ToHex() const;
nzUInt8 operator[](unsigned int pos) const;
NzHashDigest& operator=(const NzHashDigest& rhs);
NzHashDigest& operator=(NzHashDigest&& rhs) noexcept;
bool operator==(const NzHashDigest& rhs) const;
bool operator!=(const NzHashDigest& rhs) const;
bool operator<(const NzHashDigest& rhs) const;
bool operator<=(const NzHashDigest& rhs) const;
bool operator>(const NzHashDigest& rhs) const;
bool operator>=(const NzHashDigest& rhs) const;
NAZARA_CORE_API friend std::ostream& operator<<(std::ostream& out, const NzHashDigest& string);
private:
NzString m_hashName;
nzUInt8* m_digest;
unsigned int m_digestLength;
};
#endif // NAZARA_HASHDIGEST_HPP

View File

@@ -1,31 +0,0 @@
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#pragma once
#ifndef HASHABLE_HPP_INCLUDED
#define HASHABLE_HPP_INCLUDED
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/Enums.hpp>
class NzAbstractHash;
class NzHashDigest;
class NAZARA_CORE_API NzHashable
{
friend class NzHash;
public:
NzHashable() = default;
virtual ~NzHashable();
NzHashDigest GetHash(nzHash hash) const;
NzHashDigest GetHash(NzAbstractHash* impl) const;
private:
virtual bool FillHash(NzAbstractHash* impl) const = 0;
};
#endif // HASHABLE_HPP_INCLUDED

View File

@@ -9,22 +9,30 @@
#include <Nazara/Prerequesites.hpp>
template<typename... Args>
class NzInitializer
namespace Nz
{
public:
NzInitializer(bool initialize = true);
~NzInitializer();
template<typename... Args>
class Initializer
{
public:
Initializer(bool initialize = true);
Initializer(const Initializer&) = delete;
Initializer(Initializer&&) = delete; ///TODO
~Initializer();
bool Initialize();
bool IsInitialized() const;
void Uninitialize();
bool Initialize();
bool IsInitialized() const;
void Uninitialize();
operator bool() const;
operator bool() const;
private:
bool m_initialized;
};
Initializer& operator=(const Initializer&) = delete;
Initializer& operator=(Initializer&&) = delete; ///TODO
private:
bool m_initialized;
};
}
#include <Nazara/Core/Initializer.inl>

View File

@@ -4,84 +4,91 @@
#include <Nazara/Core/Debug.hpp>
template<typename...> struct NzImplInitializer;
template<typename T, typename... Rest>
struct NzImplInitializer<T, Rest...>
namespace Nz
{
static bool Init()
namespace Detail
{
if (T::Initialize())
template<typename...> struct Initializer;
template<typename T, typename... Rest>
struct Initializer<T, Rest...>
{
if (NzImplInitializer<Rest...>::Init())
return true;
else
static bool Init()
{
if (T::Initialize())
{
if (Initializer<Rest...>::Init())
return true;
else
T::Uninitialize();
}
return false;
}
static void Uninit()
{
Initializer<Rest...>::Uninit();
T::Uninitialize();
}
}
};
return false;
template<>
struct Initializer<>
{
static bool Init()
{
return true;
}
static void Uninit()
{
}
};
}
static void Uninit()
template<typename... Args>
Initializer<Args...>::Initializer(bool initialize) :
m_initialized(false)
{
NzImplInitializer<Rest...>::Uninit();
T::Uninitialize();
if (initialize)
Initialize();
}
};
template<>
struct NzImplInitializer<>
{
static bool Init()
template<typename... Args>
Initializer<Args...>::~Initializer()
{
return true;
Uninitialize();
}
static void Uninit()
template<typename... Args>
bool Initializer<Args...>::Initialize()
{
if (!m_initialized)
m_initialized = Detail::Initializer<Args...>::Init();
return m_initialized;
}
};
template<typename... Args>
NzInitializer<Args...>::NzInitializer(bool initialize) :
m_initialized(false)
{
if (initialize)
Initialize();
}
template<typename... Args>
bool Initializer<Args...>::IsInitialized() const
{
return m_initialized;
}
template<typename... Args>
NzInitializer<Args...>::~NzInitializer()
{
Uninitialize();
}
template<typename... Args>
void Initializer<Args...>::Uninitialize()
{
if (m_initialized)
Detail::Initializer<Args...>::Uninit();
}
template<typename... Args>
bool NzInitializer<Args...>::Initialize()
{
if (!m_initialized)
m_initialized = NzImplInitializer<Args...>::Init();
return m_initialized;
}
template<typename... Args>
bool NzInitializer<Args...>::IsInitialized() const
{
return m_initialized;
}
template<typename... Args>
void NzInitializer<Args...>::Uninitialize()
{
if (m_initialized)
NzImplInitializer<Args...>::Uninit();
}
template<typename... Args>
NzInitializer<Args...>::operator bool() const
{
return IsInitialized();
template<typename... Args>
Initializer<Args...>::operator bool() const
{
return IsInitialized();
}
}
#include <Nazara/Core/DebugOff.hpp>

View File

@@ -1,26 +0,0 @@
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#pragma once
#ifndef NAZARA_INPUTSTREAM_HPP
#define NAZARA_INPUTSTREAM_HPP
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/Stream.hpp>
class NAZARA_CORE_API NzInputStream : public NzStream
{
public:
virtual ~NzInputStream();
virtual bool EndOfStream() const = 0;
virtual nzUInt64 GetSize() const = 0;
virtual std::size_t Read(void* buffer, std::size_t size) = 0;
virtual NzString ReadLine(unsigned int lineSize = 0);
};
#endif // NAZARA_INPUTSTREAM_HPP

View File

@@ -9,16 +9,19 @@
#include <Nazara/Prerequesites.hpp>
class NzMutex;
class NAZARA_CORE_API NzLockGuard
namespace Nz
{
public:
NzLockGuard(NzMutex& mutex);
~NzLockGuard();
class Mutex;
private:
NzMutex& m_mutex;
};
class NAZARA_CORE_API LockGuard
{
public:
LockGuard(Mutex& mutex);
~LockGuard();
private:
Mutex& m_mutex;
};
}
#endif // NAZARA_LOCKGUARD_HPP

View File

@@ -9,8 +9,9 @@
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Core/NonCopyable.hpp>
#include <Nazara/Core/Signal.hpp>
#include <Nazara/Core/String.hpp>
#include <memory>
#if NAZARA_CORE_THREADSAFE && NAZARA_THREADSAFETY_LOG
#include <Nazara/Core/ThreadSafety.hpp>
@@ -24,41 +25,38 @@
#define NazaraDebug(txt)
#endif
#define NazaraLog NzLog::Instance()
#define NazaraNotice(txt) NazaraLog->Write(txt)
#define NazaraNotice(txt) Nz::Log::Write(txt)
class NzFile;
class NAZARA_CORE_API NzLog : NzNonCopyable
namespace Nz
{
public:
void Enable(bool enable);
void EnableAppend(bool enable);
void EnableDateTime(bool enable);
class AbstractLogger;
NzString GetFile() const;
class NAZARA_CORE_API Log
{
friend class Core;
bool IsEnabled() const;
public:
static void Enable(bool enable);
void SetFile(const NzString& filePath);
static AbstractLogger* GetLogger();
void Write(const NzString& string);
void WriteError(nzErrorType type, const NzString& error);
void WriteError(nzErrorType type, const NzString& error, unsigned int line, const NzString& file, const NzString& func);
static bool IsEnabled();
static NzLog* Instance();
static void SetLogger(AbstractLogger* logger);
private:
NzLog();
~NzLog();
static void Write(const String& string);
static void WriteError(ErrorType type, const String& error, unsigned int line = 0, const char* file = nullptr, const char* function = nullptr);
NazaraMutexAttrib(m_mutex, mutable)
NazaraStaticSignal(OnLogWrite, const String& /*string*/);
NazaraStaticSignal(OnLogWriteError, ErrorType /*type*/, const String& /*error*/, unsigned int /*line*/, const char* /*file*/, const char* /*function*/);
NzString m_filePath;
NzFile* m_file;
bool m_append;
bool m_enabled;
bool m_writeTime;
};
private:
static bool Initialize();
static void Uninitialize();
static AbstractLogger* s_logger;
static bool s_enabled;
};
}
#endif // NAZARA_LOGGER_HPP

View File

@@ -9,11 +9,14 @@
#include <cstddef>
void NzOperatorDelete(void* ptr);
void* NzOperatorNew(std::size_t size);
namespace Nz
{
void OperatorDelete(void* ptr);
void* OperatorNew(std::size_t size);
template<typename T, typename... Args>
T* NzPlacementNew(void* ptr, Args&&... args);
template<typename T, typename... Args>
T* PlacementNew(void* ptr, Args&&... args);
}
#include <Nazara/Core/MemoryHelper.inl>

View File

@@ -14,28 +14,31 @@
#include <utility>
#include <Nazara/Core/Debug.hpp>
inline void NzOperatorDelete(void* ptr)
namespace Nz
{
#if NAZARA_CORE_MANAGE_MEMORY
NzMemoryManager::Free(ptr);
#else
operator delete(ptr);
#endif
}
inline void OperatorDelete(void* ptr)
{
#if NAZARA_CORE_MANAGE_MEMORY
MemoryManager::Free(ptr);
#else
operator delete(ptr);
#endif
}
inline void* NzOperatorNew(std::size_t size)
{
#if NAZARA_CORE_MANAGE_MEMORY
return NzMemoryManager::Allocate(size);
#else
return operator new(size);
#endif
}
inline void* OperatorNew(std::size_t size)
{
#if NAZARA_CORE_MANAGE_MEMORY
return MemoryManager::Allocate(size);
#else
return operator new(size);
#endif
}
template<typename T, typename... Args>
T* NzPlacementNew(void* ptr, Args&&... args)
{
return new (ptr) T(std::forward<Args>(args)...);
template<typename T, typename... Args>
T* PlacementNew(void* ptr, Args&&... args)
{
return new (ptr) T(std::forward<Args>(args)...);
}
}
#include <Nazara/Core/DebugOff.hpp>

View File

@@ -11,32 +11,35 @@
#include <cstdio>
#include <cstring>
class NAZARA_CORE_API NzMemoryManager
namespace Nz
{
public:
static void* Allocate(std::size_t size, bool multi = false, const char* file = nullptr, unsigned int line = 0);
class NAZARA_CORE_API MemoryManager
{
public:
static void* Allocate(std::size_t size, bool multi = false, const char* file = nullptr, unsigned int line = 0);
static void EnableAllocationFilling(bool allocationFilling);
static void EnableAllocationLogging(bool logAllocations);
static void EnableAllocationFilling(bool allocationFilling);
static void EnableAllocationLogging(bool logAllocations);
static void Free(void* pointer, bool multi = false);
static void Free(void* pointer, bool multi = false);
static unsigned int GetAllocatedBlockCount();
static std::size_t GetAllocatedSize();
static unsigned int GetAllocationCount();
static unsigned int GetAllocatedBlockCount();
static std::size_t GetAllocatedSize();
static unsigned int GetAllocationCount();
static bool IsAllocationFillingEnabled();
static bool IsAllocationLoggingEnabled();
static bool IsAllocationFillingEnabled();
static bool IsAllocationLoggingEnabled();
static void NextFree(const char* file, unsigned int line);
static void NextFree(const char* file, unsigned int line);
private:
NzMemoryManager();
~NzMemoryManager();
private:
MemoryManager();
~MemoryManager();
static void Initialize();
static void TimeInfo(char buffer[23]);
static void Uninitialize();
};
static void Initialize();
static void TimeInfo(char buffer[23]);
static void Uninitialize();
};
}
#endif // NAZARA_MEMORYMANAGER_HPP

View File

@@ -11,39 +11,42 @@
#include <atomic>
#include <memory>
class NzMemoryPool
namespace Nz
{
public:
NzMemoryPool(unsigned int blockSize, unsigned int size = 1024, bool canGrow = true);
NzMemoryPool(const NzMemoryPool&) = delete;
NzMemoryPool(NzMemoryPool&& pool) noexcept;
~NzMemoryPool() = default;
class MemoryPool
{
public:
MemoryPool(unsigned int blockSize, unsigned int size = 1024, bool canGrow = true);
MemoryPool(const MemoryPool&) = delete;
MemoryPool(MemoryPool&& pool) noexcept;
~MemoryPool() = default;
void* Allocate(unsigned int size);
template<typename T> void Delete(T* ptr);
void Free(void* ptr);
void* Allocate(unsigned int size);
template<typename T> void Delete(T* ptr);
void Free(void* ptr);
unsigned int GetBlockSize() const;
unsigned int GetFreeBlocks() const;
unsigned int GetSize() const;
unsigned int GetBlockSize() const;
unsigned int GetFreeBlocks() const;
unsigned int GetSize() const;
template<typename T, typename... Args> T* New(Args&&... args);
template<typename T, typename... Args> T* New(Args&&... args);
NzMemoryPool& operator=(const NzMemoryPool&) = delete;
NzMemoryPool& operator=(NzMemoryPool&& pool) noexcept;
MemoryPool& operator=(const MemoryPool&) = delete;
MemoryPool& operator=(MemoryPool&& pool) noexcept;
private:
NzMemoryPool(NzMemoryPool* pool);
private:
MemoryPool(MemoryPool* pool);
std::unique_ptr<void*[]> m_freeList;
std::unique_ptr<nzUInt8[]> m_pool;
std::unique_ptr<NzMemoryPool> m_next;
std::atomic_uint m_freeCount;
NzMemoryPool* m_previous;
bool m_canGrow;
unsigned int m_blockSize;
unsigned int m_size;
};
std::unique_ptr<void*[]> m_freeList;
std::unique_ptr<UInt8[]> m_pool;
std::unique_ptr<MemoryPool> m_next;
std::atomic_uint m_freeCount;
MemoryPool* m_previous;
bool m_canGrow;
unsigned int m_blockSize;
unsigned int m_size;
};
}
#include <Nazara/Core/MemoryPool.inl>

View File

@@ -6,140 +6,143 @@
#include <utility>
#include <Nazara/Core/Debug.hpp>
inline NzMemoryPool::NzMemoryPool(unsigned int blockSize, unsigned int size, bool canGrow) :
m_freeCount(size),
m_previous(nullptr),
m_canGrow(canGrow),
m_blockSize(blockSize),
m_size(size)
namespace Nz
{
m_pool.reset(new nzUInt8[blockSize * size]);
m_freeList.reset(new void*[size]);
// Remplissage de la free list
for (unsigned int i = 0; i < size; ++i)
m_freeList[i] = &m_pool[m_blockSize * (size-i-1)];
}
inline NzMemoryPool::NzMemoryPool(NzMemoryPool&& pool) noexcept
{
operator=(std::move(pool));
}
inline NzMemoryPool::NzMemoryPool(NzMemoryPool* pool) :
NzMemoryPool(pool->m_blockSize, pool->m_size, pool->m_canGrow)
{
m_previous = pool;
}
inline void* NzMemoryPool::Allocate(unsigned int size)
{
///DOC: Si la taille est supérieure à celle d'un bloc du pool, l'opérateur new est utilisé
if (size <= m_blockSize)
inline MemoryPool::MemoryPool(unsigned int blockSize, unsigned int size, bool canGrow) :
m_freeCount(size),
m_previous(nullptr),
m_canGrow(canGrow),
m_blockSize(blockSize),
m_size(size)
{
if (m_freeCount > 0)
return m_freeList[--m_freeCount];
else if (m_canGrow)
{
if (!m_next)
m_next.reset(new NzMemoryPool(this));
m_pool.reset(new UInt8[blockSize * size]);
m_freeList.reset(new void*[size]);
return m_next->Allocate(size);
}
// Remplissage de la free list
for (unsigned int i = 0; i < size; ++i)
m_freeList[i] = &m_pool[m_blockSize * (size-i-1)];
}
return NzOperatorNew(size);
}
template<typename T>
inline void NzMemoryPool::Delete(T* ptr)
{
///DOC: Va appeler le destructeur de l'objet avant de le libérer
if (ptr)
inline MemoryPool::MemoryPool(MemoryPool&& pool) noexcept
{
ptr->~T();
Free(ptr);
operator=(std::move(pool));
}
}
inline void NzMemoryPool::Free(void* ptr)
{
///DOC: Si appelé avec un pointeur ne faisant pas partie du pool, l'opérateur delete est utilisé
if (ptr)
inline MemoryPool::MemoryPool(MemoryPool* pool) :
MemoryPool(pool->m_blockSize, pool->m_size, pool->m_canGrow)
{
// Le pointeur nous appartient-il ?
nzUInt8* freePtr = static_cast<nzUInt8*>(ptr);
nzUInt8* poolPtr = m_pool.get();
if (freePtr >= poolPtr && freePtr < poolPtr + m_blockSize*m_size)
m_previous = pool;
}
inline void* MemoryPool::Allocate(unsigned int size)
{
///DOC: Si la taille est supérieure à celle d'un bloc du pool, l'opérateur new est utilisé
if (size <= m_blockSize)
{
#if NAZARA_CORE_SAFE
if ((freePtr - poolPtr) % m_blockSize != 0)
throw std::runtime_error("Invalid pointer (does not point to an element of the pool)");
#endif
m_freeList[m_freeCount++] = ptr;
// Si nous sommes vide et l'extension d'un autre pool, nous nous suicidons
if (m_freeCount == m_size && m_previous && !m_next)
if (m_freeCount > 0)
return m_freeList[--m_freeCount];
else if (m_canGrow)
{
m_previous->m_next.release();
delete this; // Suicide
if (!m_next)
m_next.reset(new MemoryPool(this));
return m_next->Allocate(size);
}
}
else
return OperatorNew(size);
}
template<typename T>
inline void MemoryPool::Delete(T* ptr)
{
///DOC: Va appeler le destructeur de l'objet avant de le libérer
if (ptr)
{
if (m_next)
m_next->Free(ptr);
else
NzOperatorDelete(ptr);
ptr->~T();
Free(ptr);
}
}
}
inline unsigned int NzMemoryPool::GetBlockSize() const
{
return m_blockSize;
}
inline unsigned int NzMemoryPool::GetFreeBlocks() const
{
return m_freeCount;
}
inline unsigned int NzMemoryPool::GetSize() const
{
return m_size;
}
template<typename T, typename... Args>
inline T* NzMemoryPool::New(Args&&... args)
{
///DOC: Permet de construire un objet directement dans le pook
T* object = static_cast<T*>(Allocate(sizeof(T)));
NzPlacementNew<T>(object, std::forward<Args>(args)...);
return object;
}
inline NzMemoryPool& NzMemoryPool::operator=(NzMemoryPool&& pool) noexcept
{
m_blockSize = pool.m_blockSize;
m_canGrow = pool.m_canGrow;
m_freeCount = pool.m_freeCount.load(std::memory_order_relaxed);
m_freeList = std::move(pool.m_freeList);
m_pool = std::move(pool.m_pool);
m_previous = pool.m_previous;
m_next = std::move(pool.m_next);
m_size = pool.m_size;
// Si nous avons été créés par un autre pool, nous devons le faire pointer vers nous de nouveau
if (m_previous)
inline void MemoryPool::Free(void* ptr)
{
m_previous->m_next.release();
m_previous->m_next.reset(this);
///DOC: Si appelé avec un pointeur ne faisant pas partie du pool, l'opérateur delete est utilisé
if (ptr)
{
// Le pointeur nous appartient-il ?
UInt8* freePtr = static_cast<UInt8*>(ptr);
UInt8* poolPtr = m_pool.get();
if (freePtr >= poolPtr && freePtr < poolPtr + m_blockSize*m_size)
{
#if NAZARA_CORE_SAFE
if ((freePtr - poolPtr) % m_blockSize != 0)
throw std::runtime_error("Invalid pointer (does not point to an element of the pool)");
#endif
m_freeList[m_freeCount++] = ptr;
// Si nous sommes vide et l'extension d'un autre pool, nous nous suicidons
if (m_freeCount == m_size && m_previous && !m_next)
{
m_previous->m_next.release();
delete this; // Suicide
}
}
else
{
if (m_next)
m_next->Free(ptr);
else
OperatorDelete(ptr);
}
}
}
return *this;
inline unsigned int MemoryPool::GetBlockSize() const
{
return m_blockSize;
}
inline unsigned int MemoryPool::GetFreeBlocks() const
{
return m_freeCount;
}
inline unsigned int MemoryPool::GetSize() const
{
return m_size;
}
template<typename T, typename... Args>
inline T* MemoryPool::New(Args&&... args)
{
///DOC: Permet de construire un objet directement dans le pook
T* object = static_cast<T*>(Allocate(sizeof(T)));
PlacementNew<T>(object, std::forward<Args>(args)...);
return object;
}
inline MemoryPool& MemoryPool::operator=(MemoryPool&& pool) noexcept
{
m_blockSize = pool.m_blockSize;
m_canGrow = pool.m_canGrow;
m_freeCount = pool.m_freeCount.load(std::memory_order_relaxed);
m_freeList = std::move(pool.m_freeList);
m_pool = std::move(pool.m_pool);
m_previous = pool.m_previous;
m_next = std::move(pool.m_next);
m_size = pool.m_size;
// Si nous avons été créés par un autre pool, nous devons le faire pointer vers nous de nouveau
if (m_previous)
{
m_previous->m_next.release();
m_previous->m_next.reset(this);
}
return *this;
}
}
#include <Nazara/Core/DebugOff.hpp>

View File

@@ -1,34 +0,0 @@
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#pragma once
#ifndef NAZARA_MEMORYSTREAM_HPP
#define NAZARA_MEMORYSTREAM_HPP
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/InputStream.hpp>
class NAZARA_CORE_API NzMemoryStream : public NzInputStream
{
public:
NzMemoryStream(const void* ptr, nzUInt64 size);
~NzMemoryStream();
bool EndOfStream() const;
nzUInt64 GetCursorPos() const;
nzUInt64 GetSize() const;
std::size_t Read(void* buffer, std::size_t size);
bool SetCursorPos(nzUInt64 offset);
private:
const nzUInt8* m_ptr;
nzUInt64 m_pos;
nzUInt64 m_size;
};
#endif // NAZARA_MEMORYSTREAM_HPP

View File

@@ -0,0 +1,44 @@
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#pragma once
#ifndef NAZARA_MEMORYVIEW_HPP
#define NAZARA_MEMORYVIEW_HPP
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/Stream.hpp>
namespace Nz
{
class NAZARA_CORE_API MemoryView : public Stream
{
public:
MemoryView(const void* ptr, UInt64 size);
MemoryView(const MemoryView&) = delete;
MemoryView(MemoryView&&) = delete; ///TODO
~MemoryView() = default;
bool EndOfStream() const override;
UInt64 GetCursorPos() const override;
UInt64 GetSize() const override;
bool SetCursorPos(UInt64 offset) override;
MemoryView& operator=(const MemoryView&) = delete;
MemoryView& operator=(MemoryView&&) = delete; ///TODO
private:
void FlushStream() override;
std::size_t ReadBlock(void* buffer, std::size_t size) override;
std::size_t WriteBlock(const void* buffer, std::size_t size) override;
const UInt8* m_ptr;
UInt64 m_pos;
UInt64 m_size;
};
}
#endif // NAZARA_MEMORYVIEW_HPP

View File

@@ -8,26 +8,31 @@
#define NAZARA_MUTEX_HPP
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/NonCopyable.hpp>
class NzMutexImpl;
class NAZARA_CORE_API NzMutex : NzNonCopyable
namespace Nz
{
friend class NzConditionVariable;
class MutexImpl;
public:
NzMutex();
~NzMutex();
class NAZARA_CORE_API Mutex
{
friend class ConditionVariable;
void Lock();
public:
Mutex();
Mutex(const Mutex&) = delete;
Mutex(Mutex&&) = delete; ///TODO
~Mutex();
bool TryLock();
void Lock();
bool TryLock();
void Unlock();
void Unlock();
Mutex& operator=(const Mutex&) = delete;
Mutex& operator=(Mutex&&) = delete; ///TODO
private:
NzMutexImpl* m_impl;
};
private:
MutexImpl* m_impl;
};
}
#endif // NAZARA_MUTEX_HPP

View File

@@ -1,20 +0,0 @@
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#pragma once
#ifndef NAZARA_NONCOPYABLE_HPP
#define NAZARA_NONCOPYABLE_HPP
#include <Nazara/Prerequesites.hpp>
class NAZARA_CORE_API NzNonCopyable
{
protected:
NzNonCopyable() = default;
NzNonCopyable(const NzNonCopyable&) = delete;
NzNonCopyable& operator=(const NzNonCopyable&) = delete;
};
#endif // NAZARA_NONCOPYABLE_HPP

View File

@@ -12,28 +12,31 @@
#include <Nazara/Core/String.hpp>
#include <unordered_map>
template<typename Type>
class NzObjectLibrary
namespace Nz
{
friend Type;
template<typename Type>
class ObjectLibrary
{
friend Type;
public:
NzObjectLibrary() = delete;
~NzObjectLibrary() = delete;
public:
ObjectLibrary() = delete;
~ObjectLibrary() = delete;
static NzObjectRef<Type> Get(const NzString& name);
static bool Has(const NzString& name);
static ObjectRef<Type> Get(const String& name);
static bool Has(const String& name);
static void Register(const NzString& name, NzObjectRef<Type> object);
static NzObjectRef<Type> Query(const NzString& name);
static void Unregister(const NzString& name);
static void Register(const String& name, ObjectRef<Type> object);
static ObjectRef<Type> Query(const String& name);
static void Unregister(const String& name);
private:
static bool Initialize();
static void Uninitialize();
private:
static bool Initialize();
static void Uninitialize();
using LibraryMap = std::unordered_map<NzString, NzObjectRef<Type>>;
};
using LibraryMap = std::unordered_map<String, ObjectRef<Type>>;
};
}
#include <Nazara/Core/ObjectLibrary.inl>

View File

@@ -5,54 +5,57 @@
#include <Nazara/Core/Error.hpp>
#include <Nazara/Core/Debug.hpp>
template<typename Type>
NzObjectRef<Type> NzObjectLibrary<Type>::Get(const NzString& name)
namespace Nz
{
NzObjectRef<Type> ref = Query(name);
if (!ref)
NazaraError("Object \"" + name + "\" is not present");
template<typename Type>
ObjectRef<Type> ObjectLibrary<Type>::Get(const String& name)
{
ObjectRef<Type> ref = Query(name);
if (!ref)
NazaraError("Object \"" + name + "\" is not present");
return ref;
}
return ref;
}
template<typename Type>
bool NzObjectLibrary<Type>::Has(const NzString& name)
{
return Type::s_library.find(name) != Type::s_library.end();
}
template<typename Type>
bool ObjectLibrary<Type>::Has(const String& name)
{
return Type::s_library.find(name) != Type::s_library.end();
}
template<typename Type>
void NzObjectLibrary<Type>::Register(const NzString& name, NzObjectRef<Type> object)
{
Type::s_library.emplace(name, object);
}
template<typename Type>
void ObjectLibrary<Type>::Register(const String& name, ObjectRef<Type> object)
{
Type::s_library.emplace(name, object);
}
template<typename Type>
NzObjectRef<Type> NzObjectLibrary<Type>::Query(const NzString& name)
{
auto it = Type::s_library.find(name);
if (it != Type::s_library.end())
return it->second;
else
return nullptr;
}
template<typename Type>
ObjectRef<Type> ObjectLibrary<Type>::Query(const String& name)
{
auto it = Type::s_library.find(name);
if (it != Type::s_library.end())
return it->second;
else
return nullptr;
}
template<typename Type>
void NzObjectLibrary<Type>::Unregister(const NzString& name)
{
Type::s_library.erase(name);
}
template<typename Type>
void ObjectLibrary<Type>::Unregister(const String& name)
{
Type::s_library.erase(name);
}
template<typename Type>
bool NzObjectLibrary<Type>::Initialize()
{
return true; // Que faire
}
template<typename Type>
bool ObjectLibrary<Type>::Initialize()
{
return true; // Que faire
}
template<typename Type>
void NzObjectLibrary<Type>::Uninitialize()
{
Type::s_library.clear();
template<typename Type>
void ObjectLibrary<Type>::Uninitialize()
{
Type::s_library.clear();
}
}
#include <Nazara/Core/DebugOff.hpp>

View File

@@ -11,35 +11,38 @@
#include <Nazara/Core/RefCounted.hpp>
#include <type_traits>
template<typename T>
class NzObjectRef
namespace Nz
{
public:
NzObjectRef();
NzObjectRef(T* object);
NzObjectRef(const NzObjectRef& ref);
template<typename U> NzObjectRef(const NzObjectRef<U>& ref);
NzObjectRef(NzObjectRef&& ref) noexcept;
~NzObjectRef();
template<typename T>
class ObjectRef
{
public:
ObjectRef();
ObjectRef(T* object);
ObjectRef(const ObjectRef& ref);
template<typename U> ObjectRef(const ObjectRef<U>& ref);
ObjectRef(ObjectRef&& ref) noexcept;
~ObjectRef();
T* Get() const;
bool IsValid() const;
T* Release();
bool Reset(T* object = nullptr);
NzObjectRef& Swap(NzObjectRef& ref);
T* Get() const;
bool IsValid() const;
T* Release();
bool Reset(T* object = nullptr);
ObjectRef& Swap(ObjectRef& ref);
operator bool() const;
operator T*() const;
T* operator->() const;
operator bool() const;
operator T*() const;
T* operator->() const;
NzObjectRef& operator=(T* object);
NzObjectRef& operator=(const NzObjectRef& ref);
template<typename U> NzObjectRef& operator=(const NzObjectRef<U>& ref);
NzObjectRef& operator=(NzObjectRef&& ref) noexcept;
ObjectRef& operator=(T* object);
ObjectRef& operator=(const ObjectRef& ref);
template<typename U> ObjectRef& operator=(const ObjectRef<U>& ref);
ObjectRef& operator=(ObjectRef&& ref) noexcept;
private:
T* m_object;
};
private:
T* m_object;
};
}
#include <Nazara/Core/ObjectRef.inl>

View File

@@ -5,148 +5,151 @@
#include <Nazara/Core/Initializer.hpp>
#include <Nazara/Core/Debug.hpp>
template<typename T>
NzObjectRef<T>::NzObjectRef() :
m_object(nullptr)
namespace Nz
{
}
template<typename T>
NzObjectRef<T>::NzObjectRef(T* object) :
m_object(object)
{
if (m_object)
m_object->AddReference();
}
template<typename T>
NzObjectRef<T>::NzObjectRef(const NzObjectRef& ref) :
m_object(ref.m_object)
{
if (m_object)
m_object->AddReference();
}
template<typename T>
template<typename U>
NzObjectRef<T>::NzObjectRef(const NzObjectRef<U>& ref) :
NzObjectRef(ref.Get())
{
}
template<typename T>
NzObjectRef<T>::NzObjectRef(NzObjectRef&& ref) noexcept :
m_object(ref.m_object)
{
ref.m_object = nullptr; // On vole la référence
}
template<typename T>
NzObjectRef<T>::~NzObjectRef()
{
if (m_object)
m_object->RemoveReference();
}
template<typename T>
T* NzObjectRef<T>::Get() const
{
return m_object;
}
template<typename T>
bool NzObjectRef<T>::IsValid() const
{
return m_object != nullptr;
}
template<typename T>
T* NzObjectRef<T>::Release()
{
T* object = m_object;
m_object = nullptr;
return object;
}
template<typename T>
bool NzObjectRef<T>::Reset(T* object)
{
bool destroyed = false;
if (m_object != object)
template<typename T>
ObjectRef<T>::ObjectRef() :
m_object(nullptr)
{
if (m_object)
destroyed = m_object->RemoveReference();
}
m_object = object;
template<typename T>
ObjectRef<T>::ObjectRef(T* object) :
m_object(object)
{
if (m_object)
m_object->AddReference();
}
return destroyed;
}
template<typename T>
ObjectRef<T>::ObjectRef(const ObjectRef& ref) :
m_object(ref.m_object)
{
if (m_object)
m_object->AddReference();
}
template<typename T>
NzObjectRef<T>& NzObjectRef<T>::Swap(NzObjectRef& ref)
{
std::swap(m_object, ref.m_object);
template<typename T>
template<typename U>
ObjectRef<T>::ObjectRef(const ObjectRef<U>& ref) :
ObjectRef(ref.Get())
{
}
return *this;
}
template<typename T>
ObjectRef<T>::ObjectRef(ObjectRef&& ref) noexcept :
m_object(ref.m_object)
{
ref.m_object = nullptr; // On vole la référence
}
template<typename T>
NzObjectRef<T>::operator bool() const
{
return IsValid();
}
template<typename T>
ObjectRef<T>::~ObjectRef()
{
if (m_object)
m_object->RemoveReference();
}
template<typename T>
NzObjectRef<T>::operator T*() const
{
return m_object;
}
template<typename T>
T* ObjectRef<T>::Get() const
{
return m_object;
}
template<typename T>
T* NzObjectRef<T>::operator->() const
{
return m_object;
}
template<typename T>
bool ObjectRef<T>::IsValid() const
{
return m_object != nullptr;
}
template<typename T>
NzObjectRef<T>& NzObjectRef<T>::operator=(T* object)
{
Reset(object);
template<typename T>
T* ObjectRef<T>::Release()
{
T* object = m_object;
m_object = nullptr;
return *this;
}
return object;
}
template<typename T>
NzObjectRef<T>& NzObjectRef<T>::operator=(const NzObjectRef& ref)
{
Reset(ref.m_object);
template<typename T>
bool ObjectRef<T>::Reset(T* object)
{
bool destroyed = false;
if (m_object != object)
{
if (m_object)
destroyed = m_object->RemoveReference();
return *this;
}
m_object = object;
if (m_object)
m_object->AddReference();
}
template<typename T>
template<typename U>
NzObjectRef<T>& NzObjectRef<T>::operator=(const NzObjectRef<U>& ref)
{
static_assert(std::is_convertible<U*, T*>::value, "U is not implicitly convertible to T");
return destroyed;
}
Reset(ref.Get());
template<typename T>
ObjectRef<T>& ObjectRef<T>::Swap(ObjectRef& ref)
{
std::swap(m_object, ref.m_object);
return *this;
}
return *this;
}
template<typename T>
NzObjectRef<T>& NzObjectRef<T>::operator=(NzObjectRef&& ref) noexcept
{
Reset();
template<typename T>
ObjectRef<T>::operator bool() const
{
return IsValid();
}
std::swap(m_object, ref.m_object);
template<typename T>
ObjectRef<T>::operator T*() const
{
return m_object;
}
return *this;
template<typename T>
T* ObjectRef<T>::operator->() const
{
return m_object;
}
template<typename T>
ObjectRef<T>& ObjectRef<T>::operator=(T* object)
{
Reset(object);
return *this;
}
template<typename T>
ObjectRef<T>& ObjectRef<T>::operator=(const ObjectRef& ref)
{
Reset(ref.m_object);
return *this;
}
template<typename T>
template<typename U>
ObjectRef<T>& ObjectRef<T>::operator=(const ObjectRef<U>& ref)
{
static_assert(std::is_convertible<U*, T*>::value, "U is not implicitly convertible to T");
Reset(ref.Get());
return *this;
}
template<typename T>
ObjectRef<T>& ObjectRef<T>::operator=(ObjectRef&& ref) noexcept
{
Reset();
std::swap(m_object, ref.m_object);
return *this;
}
}
#include <Nazara/Core/DebugOff.hpp>

View File

@@ -10,16 +10,21 @@
// Par "Jesse Good" de SO:
// http://stackoverflow.com/questions/12811330/c-compile-time-offsetof-inside-a-template?answertab=votes#tab-top
template <typename T, typename M> T NzImplGetClassType(M T::*);
template <typename T, typename M> M NzImplGetMemberType(M T::*);
template <typename T, typename R, R T::*M>
std::size_t NzImplOffsetOf()
namespace Nz
{
///FIXME: reinterpret_cast is not allowed in constexpr functions
return reinterpret_cast<std::size_t>(&((static_cast<T*>(0))->*M));
namespace Detail
{
template <typename T, typename M> T GetClassType(M T::*);
template <typename T, typename M> M GetMemberType(M T::*);
template <typename T, typename R, R T::*M>
constexpr std::size_t OffsetOf()
{
return reinterpret_cast<std::size_t>(&((static_cast<T*>(0))->*M));
}
}
}
#define NzOffsetOf(type, member) NzImplOffsetOf<decltype(NzImplGetClassType(&type::member)), decltype(NzImplGetMemberType(&type::member)), &type::member>()
#define NazaraOffsetOf(type, member) Nz::Detail::OffsetOf<decltype(Nz::Detail::GetClassType(&type::member)), decltype(Nz::Detail::GetMemberType(&type::member)), &type::member>()
#endif // NAZARA_OFFSETOF_HPP

View File

@@ -12,83 +12,86 @@
#include <atomic>
#include <unordered_map>
class NAZARA_CORE_API NzParameterList
namespace Nz
{
public:
using Destructor = void (*)(void* value);
class NAZARA_CORE_API ParameterList
{
public:
using Destructor = void (*)(void* value);
NzParameterList() = default;
NzParameterList(const NzParameterList& list);
NzParameterList(NzParameterList&& list);
~NzParameterList();
ParameterList() = default;
ParameterList(const ParameterList& list);
ParameterList(ParameterList&&) = default;
~ParameterList();
void Clear();
void Clear();
bool GetBooleanParameter(const NzString& name, bool* value) const;
bool GetFloatParameter(const NzString& name, float* value) const;
bool GetIntegerParameter(const NzString& name, int* value) const;
bool GetParameterType(const NzString& name, nzParameterType* type) const;
bool GetPointerParameter(const NzString& name, void** value) const;
bool GetStringParameter(const NzString& name, NzString* value) const;
bool GetUserdataParameter(const NzString& name, void** value) const;
bool GetBooleanParameter(const String& name, bool* value) const;
bool GetFloatParameter(const String& name, float* value) const;
bool GetIntegerParameter(const String& name, int* value) const;
bool GetParameterType(const String& name, ParameterType* type) const;
bool GetPointerParameter(const String& name, void** value) const;
bool GetStringParameter(const String& name, String* value) const;
bool GetUserdataParameter(const String& name, void** value) const;
bool HasParameter(const NzString& name) const;
bool HasParameter(const String& name) const;
void RemoveParameter(const NzString& name);
void RemoveParameter(const String& name);
void SetParameter(const NzString& name);
void SetParameter(const NzString& name, const NzString& value);
void SetParameter(const NzString& name, const char* value);
void SetParameter(const NzString& name, void* value);
void SetParameter(const NzString& name, void* value, Destructor destructor);
void SetParameter(const NzString& name, bool value);
void SetParameter(const NzString& name, float value);
void SetParameter(const NzString& name, int value);
void SetParameter(const String& name);
void SetParameter(const String& name, const String& value);
void SetParameter(const String& name, const char* value);
void SetParameter(const String& name, void* value);
void SetParameter(const String& name, void* value, Destructor destructor);
void SetParameter(const String& name, bool value);
void SetParameter(const String& name, float value);
void SetParameter(const String& name, int value);
NzParameterList& operator=(const NzParameterList& list);
NzParameterList& operator=(NzParameterList&& list);
ParameterList& operator=(const ParameterList& list);
ParameterList& operator=(ParameterList&&) = default;
private:
struct Parameter
{
struct UserdataValue
private:
struct Parameter
{
UserdataValue(Destructor Destructor, void* value) :
counter(1),
destructor(Destructor),
ptr(value)
struct UserdataValue
{
}
UserdataValue(Destructor Destructor, void* value) :
counter(1),
destructor(Destructor),
ptr(value)
{
}
std::atomic_uint counter;
Destructor destructor;
void* ptr;
std::atomic_uint counter;
Destructor destructor;
void* ptr;
};
ParameterType type;
union Value
{
// On définit un constructeur/destructeur vide, permettant de mettre des classes dans l'union
Value() {}
Value(const Value&) {} // Placeholder
~Value() {}
bool boolVal;
float floatVal;
int intVal;
void* ptrVal;
String stringVal;
UserdataValue* userdataVal;
};
Value value;
};
nzParameterType type;
union Value
{
// On définit un constructeur/destructeur vide, permettant de mettre des classes dans l'union
Value() {}
Value(const Value&) {} // Placeholder
~Value() {}
using ParameterMap = std::unordered_map<String, Parameter>;
bool boolVal;
float floatVal;
int intVal;
void* ptrVal;
NzString stringVal;
UserdataValue* userdataVal;
};
void DestroyValue(Parameter& parameter);
Value value;
};
using ParameterMap = std::unordered_map<NzString, Parameter>;
void DestroyValue(Parameter& parameter);
ParameterMap m_parameters;
};
ParameterMap m_parameters;
};
}
#endif // NAZARA_PARAMETERLIST_HPP

View File

@@ -14,34 +14,35 @@
#include <unordered_map>
///TODO: Révision
class NzDynLib;
class NAZARA_CORE_API NzPluginManager
namespace Nz
{
public:
NzPluginManager() = delete;
~NzPluginManager() = delete;
class DynLib;
static void AddDirectory(const NzString& directoryPath);
class NAZARA_CORE_API PluginManager
{
public:
PluginManager() = delete;
~PluginManager() = delete;
static bool Initialize();
static void AddDirectory(const String& directoryPath);
static bool Mount(nzPlugin plugin);
static bool Mount(const NzString& pluginPath, bool appendExtension = true);
static bool Initialize();
static void RemoveDirectory(const NzString& directoryPath);
static bool Mount(Plugin plugin);
static bool Mount(const String& pluginPath, bool appendExtension = true);
static void Unmount(nzPlugin plugin);
static void Unmount(const NzString& pluginPath);
static void RemoveDirectory(const String& directoryPath);
static void Uninitialize();
static void Unmount(Plugin plugin);
static void Unmount(const String& pluginPath);
private:
static std::set<NzString> s_directories;
static std::unordered_map<NzString, NzDynLib*> s_plugins;
static bool s_initialized;
static void Uninitialize();
};
private:
static std::set<String> s_directories;
static std::unordered_map<String, DynLib*> s_plugins;
static bool s_initialized;
};
}
#endif // NAZARA_PLUGINMANAGER_HPP

View File

@@ -14,94 +14,97 @@
#include <Nazara/Math/Rect.hpp>
#include <Nazara/Math/Vector3.hpp>
struct NzPrimitive
namespace Nz
{
void MakeBox(const NzVector3f& lengths, const NzVector3ui& subdivision = NzVector3ui(0U), const NzMatrix4f& transformMatrix = NzMatrix4f::Identity(), const NzRectf& uvCoords = NzRectf(0.f, 0.f, 1.f, 1.f));
void MakeBox(const NzVector3f& lengths, const NzVector3ui& subdivision, const NzVector3f& position, const NzQuaternionf& rotation = NzQuaternionf::Identity(), const NzRectf& uvCoords = NzRectf(0.f, 0.f, 1.f, 1.f));
void MakeCone(float length, float radius, unsigned int subdivision = 4, const NzMatrix4f& transformMatrix = NzMatrix4f::Identity(), const NzRectf& uvCoords = NzRectf(0.f, 0.f, 1.f, 1.f));
void MakeCone(float length, float radius, unsigned int subdivision, const NzVector3f& position, const NzQuaternionf& rotation = NzQuaternionf::Identity(), const NzRectf& uvCoords = NzRectf(0.f, 0.f, 1.f, 1.f));
void MakeCubicSphere(float size, unsigned int subdivision = 4, const NzMatrix4f& transformMatrix = NzMatrix4f::Identity(), const NzRectf& uvCoords = NzRectf(0.f, 0.f, 1.f, 1.f));
void MakeCubicSphere(float size, unsigned int subdivision, const NzVector3f& position, const NzQuaternionf& rotation = NzQuaternionf::Identity(), const NzRectf& uvCoords = NzRectf(0.f, 0.f, 1.f, 1.f));
void MakeIcoSphere(float size, unsigned int recursionLevel = 3, const NzMatrix4f& transformMatrix = NzMatrix4f::Identity(), const NzRectf& uvCoords = NzRectf(0.f, 0.f, 1.f, 1.f));
void MakeIcoSphere(float size, unsigned int recursionLevel, const NzVector3f& position, const NzQuaternionf& rotation = NzQuaternionf::Identity(), const NzRectf& uvCoords = NzRectf(0.f, 0.f, 1.f, 1.f));
void MakePlane(const NzVector2f& size, const NzVector2ui& subdivision, const NzMatrix4f& transformMatrix = NzMatrix4f::Identity(), const NzRectf& uvCoords = NzRectf(0.f, 0.f, 1.f, 1.f));
void MakePlane(const NzVector2f& size, const NzVector2ui& subdivision, const NzPlanef& plane, const NzRectf& uvCoords = NzRectf(0.f, 0.f, 1.f, 1.f));
void MakePlane(const NzVector2f& size, const NzVector2ui& subdivision, const NzVector3f& position, const NzQuaternionf& rotation = NzQuaternionf::Identity(), const NzRectf& uvCoords = NzRectf(0.f, 0.f, 1.f, 1.f));
void MakeUVSphere(float size, unsigned int sliceCount = 4, unsigned int stackCount = 4, const NzMatrix4f& transformMatrix = NzMatrix4f::Identity(), const NzRectf& uvCoords = NzRectf(0.f, 0.f, 1.f, 1.f));
void MakeUVSphere(float size, unsigned int sliceCount, unsigned int stackCount, const NzVector3f& position, const NzQuaternionf& rotation = NzQuaternionf::Identity(), const NzRectf& uvCoords = NzRectf(0.f, 0.f, 1.f, 1.f));
static NzPrimitive Box(const NzVector3f& lengths, const NzVector3ui& subdivision = NzVector3ui(0U), const NzMatrix4f& transformMatrix = NzMatrix4f::Identity(), const NzRectf& uvCoords = NzRectf(0.f, 0.f, 1.f, 1.f));
static NzPrimitive Box(const NzVector3f& lengths, const NzVector3ui& subdivision, const NzVector3f& position, const NzQuaternionf& rotation = NzQuaternionf::Identity(), const NzRectf& uvCoords = NzRectf(0.f, 0.f, 1.f, 1.f));
static NzPrimitive Cone(float length, float radius, unsigned int subdivision = 4, const NzMatrix4f& transformMatrix = NzMatrix4f::Identity(), const NzRectf& uvCoords = NzRectf(0.f, 0.f, 1.f, 1.f));
static NzPrimitive Cone(float length, float radius, unsigned int subdivision, const NzVector3f& position, const NzQuaternionf& rotation = NzQuaternionf::Identity(), const NzRectf& uvCoords = NzRectf(0.f, 0.f, 1.f, 1.f));
static NzPrimitive CubicSphere(float size, unsigned int subdivision = 4, const NzMatrix4f& transformMatrix = NzMatrix4f::Identity(), const NzRectf& uvCoords = NzRectf(0.f, 0.f, 1.f, 1.f));
static NzPrimitive CubicSphere(float size, unsigned int subdivision, const NzVector3f& position, const NzQuaternionf& rotation = NzQuaternionf::Identity(), const NzRectf& uvCoords = NzRectf(0.f, 0.f, 1.f, 1.f));
static NzPrimitive IcoSphere(float size, unsigned int recursionLevel = 3, const NzMatrix4f& transformMatrix = NzMatrix4f::Identity(), const NzRectf& uvCoords = NzRectf(0.f, 0.f, 1.f, 1.f));
static NzPrimitive IcoSphere(float size, unsigned int recursionLevel, const NzVector3f& position, const NzQuaternionf& rotation = NzQuaternionf::Identity(), const NzRectf& uvCoords = NzRectf(0.f, 0.f, 1.f, 1.f));
static NzPrimitive Plane(const NzVector2f& size, const NzVector2ui& subdivision = NzVector2ui(0U), const NzMatrix4f& transformMatrix = NzMatrix4f::Identity(), const NzRectf& uvCoords = NzRectf(0.f, 0.f, 1.f, 1.f));
static NzPrimitive Plane(const NzVector2f& size, const NzVector2ui& subdivision, const NzPlanef& plane, const NzRectf& uvCoords = NzRectf(0.f, 0.f, 1.f, 1.f));
static NzPrimitive Plane(const NzVector2f& size, const NzVector2ui& subdivision, const NzVector3f& position, const NzQuaternionf& rotation = NzQuaternionf::Identity(), const NzRectf& uvCoords = NzRectf(0.f, 0.f, 1.f, 1.f));
static NzPrimitive UVSphere(float size, unsigned int sliceCount = 4, unsigned int stackCount = 4, const NzMatrix4f& transformMatrix = NzMatrix4f::Identity(), const NzRectf& uvCoords = NzRectf(0.f, 0.f, 1.f, 1.f));
static NzPrimitive UVSphere(float size, unsigned int sliceCount, unsigned int stackCount, const NzVector3f& position, const NzQuaternionf& rotation = NzQuaternionf::Identity(), const NzRectf& uvCoords = NzRectf(0.f, 0.f, 1.f, 1.f));
NzMatrix4f matrix;
nzPrimitiveType type;
NzRectf textureCoords;
union
struct Primitive
{
struct
{
NzVector3f lengths;
NzVector3ui subdivision;
}
box;
void MakeBox(const Vector3f& lengths, const Vector3ui& subdivision = Vector3ui(0U), const Matrix4f& transformMatrix = Matrix4f::Identity(), const Rectf& uvCoords = Rectf(0.f, 0.f, 1.f, 1.f));
void MakeBox(const Vector3f& lengths, const Vector3ui& subdivision, const Vector3f& position, const Quaternionf& rotation = Quaternionf::Identity(), const Rectf& uvCoords = Rectf(0.f, 0.f, 1.f, 1.f));
void MakeCone(float length, float radius, unsigned int subdivision = 4, const Matrix4f& transformMatrix = Matrix4f::Identity(), const Rectf& uvCoords = Rectf(0.f, 0.f, 1.f, 1.f));
void MakeCone(float length, float radius, unsigned int subdivision, const Vector3f& position, const Quaternionf& rotation = Quaternionf::Identity(), const Rectf& uvCoords = Rectf(0.f, 0.f, 1.f, 1.f));
void MakeCubicSphere(float size, unsigned int subdivision = 4, const Matrix4f& transformMatrix = Matrix4f::Identity(), const Rectf& uvCoords = Rectf(0.f, 0.f, 1.f, 1.f));
void MakeCubicSphere(float size, unsigned int subdivision, const Vector3f& position, const Quaternionf& rotation = Quaternionf::Identity(), const Rectf& uvCoords = Rectf(0.f, 0.f, 1.f, 1.f));
void MakeIcoSphere(float size, unsigned int recursionLevel = 3, const Matrix4f& transformMatrix = Matrix4f::Identity(), const Rectf& uvCoords = Rectf(0.f, 0.f, 1.f, 1.f));
void MakeIcoSphere(float size, unsigned int recursionLevel, const Vector3f& position, const Quaternionf& rotation = Quaternionf::Identity(), const Rectf& uvCoords = Rectf(0.f, 0.f, 1.f, 1.f));
void MakePlane(const Vector2f& size, const Vector2ui& subdivision, const Matrix4f& transformMatrix = Matrix4f::Identity(), const Rectf& uvCoords = Rectf(0.f, 0.f, 1.f, 1.f));
void MakePlane(const Vector2f& size, const Vector2ui& subdivision, const Planef& plane, const Rectf& uvCoords = Rectf(0.f, 0.f, 1.f, 1.f));
void MakePlane(const Vector2f& size, const Vector2ui& subdivision, const Vector3f& position, const Quaternionf& rotation = Quaternionf::Identity(), const Rectf& uvCoords = Rectf(0.f, 0.f, 1.f, 1.f));
void MakeUVSphere(float size, unsigned int sliceCount = 4, unsigned int stackCount = 4, const Matrix4f& transformMatrix = Matrix4f::Identity(), const Rectf& uvCoords = Rectf(0.f, 0.f, 1.f, 1.f));
void MakeUVSphere(float size, unsigned int sliceCount, unsigned int stackCount, const Vector3f& position, const Quaternionf& rotation = Quaternionf::Identity(), const Rectf& uvCoords = Rectf(0.f, 0.f, 1.f, 1.f));
struct
{
float length;
float radius;
unsigned int subdivision;
}
cone;
static Primitive Box(const Vector3f& lengths, const Vector3ui& subdivision = Vector3ui(0U), const Matrix4f& transformMatrix = Matrix4f::Identity(), const Rectf& uvCoords = Rectf(0.f, 0.f, 1.f, 1.f));
static Primitive Box(const Vector3f& lengths, const Vector3ui& subdivision, const Vector3f& position, const Quaternionf& rotation = Quaternionf::Identity(), const Rectf& uvCoords = Rectf(0.f, 0.f, 1.f, 1.f));
static Primitive Cone(float length, float radius, unsigned int subdivision = 4, const Matrix4f& transformMatrix = Matrix4f::Identity(), const Rectf& uvCoords = Rectf(0.f, 0.f, 1.f, 1.f));
static Primitive Cone(float length, float radius, unsigned int subdivision, const Vector3f& position, const Quaternionf& rotation = Quaternionf::Identity(), const Rectf& uvCoords = Rectf(0.f, 0.f, 1.f, 1.f));
static Primitive CubicSphere(float size, unsigned int subdivision = 4, const Matrix4f& transformMatrix = Matrix4f::Identity(), const Rectf& uvCoords = Rectf(0.f, 0.f, 1.f, 1.f));
static Primitive CubicSphere(float size, unsigned int subdivision, const Vector3f& position, const Quaternionf& rotation = Quaternionf::Identity(), const Rectf& uvCoords = Rectf(0.f, 0.f, 1.f, 1.f));
static Primitive IcoSphere(float size, unsigned int recursionLevel = 3, const Matrix4f& transformMatrix = Matrix4f::Identity(), const Rectf& uvCoords = Rectf(0.f, 0.f, 1.f, 1.f));
static Primitive IcoSphere(float size, unsigned int recursionLevel, const Vector3f& position, const Quaternionf& rotation = Quaternionf::Identity(), const Rectf& uvCoords = Rectf(0.f, 0.f, 1.f, 1.f));
static Primitive Plane(const Vector2f& size, const Vector2ui& subdivision = Vector2ui(0U), const Matrix4f& transformMatrix = Matrix4f::Identity(), const Rectf& uvCoords = Rectf(0.f, 0.f, 1.f, 1.f));
static Primitive Plane(const Vector2f& size, const Vector2ui& subdivision, const Planef& plane, const Rectf& uvCoords = Rectf(0.f, 0.f, 1.f, 1.f));
static Primitive Plane(const Vector2f& size, const Vector2ui& subdivision, const Vector3f& position, const Quaternionf& rotation = Quaternionf::Identity(), const Rectf& uvCoords = Rectf(0.f, 0.f, 1.f, 1.f));
static Primitive UVSphere(float size, unsigned int sliceCount = 4, unsigned int stackCount = 4, const Matrix4f& transformMatrix = Matrix4f::Identity(), const Rectf& uvCoords = Rectf(0.f, 0.f, 1.f, 1.f));
static Primitive UVSphere(float size, unsigned int sliceCount, unsigned int stackCount, const Vector3f& position, const Quaternionf& rotation = Quaternionf::Identity(), const Rectf& uvCoords = Rectf(0.f, 0.f, 1.f, 1.f));
struct
{
NzVector2f size;
NzVector2ui subdivision;
}
plane;
Matrix4f matrix;
PrimitiveType type;
Rectf textureCoords;
struct
union
{
nzSphereType type;
float size;
union
struct
{
struct
{
unsigned int subdivision;
}
cubic;
Vector3f lengths;
Vector3ui subdivision;
}
box;
struct
{
unsigned int recursionLevel;
}
ico;
struct
{
float length;
float radius;
unsigned int subdivision;
}
cone;
struct
struct
{
Vector2f size;
Vector2ui subdivision;
}
plane;
struct
{
SphereType type;
float size;
union
{
unsigned int sliceCount;
unsigned int stackCount;
}
uv;
};
}
sphere;
struct
{
unsigned int subdivision;
}
cubic;
struct
{
unsigned int recursionLevel;
}
ico;
struct
{
unsigned int sliceCount;
unsigned int stackCount;
}
uv;
};
}
sphere;
};
};
};
}
#include <Nazara/Core/Primitive.inl>

View File

@@ -4,202 +4,205 @@
#include <Nazara/Core/Debug.hpp>
inline void NzPrimitive::MakeBox(const NzVector3f& lengths, const NzVector3ui& subdivision, const NzMatrix4f& transformMatrix, const NzRectf& uvCoords)
namespace Nz
{
matrix = transformMatrix;
textureCoords = uvCoords;
type = nzPrimitiveType_Box;
box.lengths = lengths;
box.subdivision = subdivision;
}
inline void Primitive::MakeBox(const Vector3f& lengths, const Vector3ui& subdivision, const Matrix4f& transformMatrix, const Rectf& uvCoords)
{
matrix = transformMatrix;
textureCoords = uvCoords;
type = PrimitiveType_Box;
box.lengths = lengths;
box.subdivision = subdivision;
}
inline void NzPrimitive::MakeBox(const NzVector3f& lengths, const NzVector3ui& subdivision, const NzVector3f& position, const NzQuaternionf& rotation, const NzRectf& uvCoords)
{
MakeBox(lengths, subdivision, NzMatrix4f::Transform(position, rotation), uvCoords);
}
inline void Primitive::MakeBox(const Vector3f& lengths, const Vector3ui& subdivision, const Vector3f& position, const Quaternionf& rotation, const Rectf& uvCoords)
{
MakeBox(lengths, subdivision, Matrix4f::Transform(position, rotation), uvCoords);
}
inline void NzPrimitive::MakeCone(float length, float radius, unsigned int subdivision, const NzMatrix4f& transformMatrix, const NzRectf& uvCoords)
{
matrix = transformMatrix;
textureCoords = uvCoords;
type = nzPrimitiveType_Cone;
cone.length = length;
cone.radius = radius;
cone.subdivision = subdivision;
}
inline void Primitive::MakeCone(float length, float radius, unsigned int subdivision, const Matrix4f& transformMatrix, const Rectf& uvCoords)
{
matrix = transformMatrix;
textureCoords = uvCoords;
type = PrimitiveType_Cone;
cone.length = length;
cone.radius = radius;
cone.subdivision = subdivision;
}
inline void NzPrimitive::MakeCone(float length, float radius, unsigned int subdivision, const NzVector3f& position, const NzQuaternionf& rotation, const NzRectf& uvCoords)
{
MakeCone(length, radius, subdivision, NzMatrix4f::Transform(position, rotation), uvCoords);
}
inline void Primitive::MakeCone(float length, float radius, unsigned int subdivision, const Vector3f& position, const Quaternionf& rotation, const Rectf& uvCoords)
{
MakeCone(length, radius, subdivision, Matrix4f::Transform(position, rotation), uvCoords);
}
inline void NzPrimitive::MakeCubicSphere(float size, unsigned int subdivision, const NzMatrix4f& transformMatrix, const NzRectf& uvCoords)
{
matrix = transformMatrix;
textureCoords = uvCoords;
type = nzPrimitiveType_Sphere;
sphere.size = size;
sphere.type = nzSphereType_Cubic;
sphere.cubic.subdivision = subdivision;
}
inline void Primitive::MakeCubicSphere(float size, unsigned int subdivision, const Matrix4f& transformMatrix, const Rectf& uvCoords)
{
matrix = transformMatrix;
textureCoords = uvCoords;
type = PrimitiveType_Sphere;
sphere.size = size;
sphere.type = SphereType_Cubic;
sphere.cubic.subdivision = subdivision;
}
inline void NzPrimitive::MakeCubicSphere(float size, unsigned int subdivision, const NzVector3f& position, const NzQuaternionf& rotation, const NzRectf& uvCoords)
{
MakeCubicSphere(size, subdivision, NzMatrix4f::Transform(position, rotation), uvCoords);
}
inline void Primitive::MakeCubicSphere(float size, unsigned int subdivision, const Vector3f& position, const Quaternionf& rotation, const Rectf& uvCoords)
{
MakeCubicSphere(size, subdivision, Matrix4f::Transform(position, rotation), uvCoords);
}
inline void NzPrimitive::MakeIcoSphere(float size, unsigned int recursionLevel, const NzMatrix4f& transformMatrix, const NzRectf& uvCoords)
{
matrix = transformMatrix;
textureCoords = uvCoords;
type = nzPrimitiveType_Sphere;
sphere.size = size;
sphere.type = nzSphereType_Ico;
sphere.ico.recursionLevel = recursionLevel;
}
inline void Primitive::MakeIcoSphere(float size, unsigned int recursionLevel, const Matrix4f& transformMatrix, const Rectf& uvCoords)
{
matrix = transformMatrix;
textureCoords = uvCoords;
type = PrimitiveType_Sphere;
sphere.size = size;
sphere.type = SphereType_Ico;
sphere.ico.recursionLevel = recursionLevel;
}
inline void NzPrimitive::MakeIcoSphere(float size, unsigned int recursionLevel, const NzVector3f& position, const NzQuaternionf& rotation, const NzRectf& uvCoords)
{
MakeIcoSphere(size, recursionLevel, NzMatrix4f::Transform(position, rotation), uvCoords);
}
inline void Primitive::MakeIcoSphere(float size, unsigned int recursionLevel, const Vector3f& position, const Quaternionf& rotation, const Rectf& uvCoords)
{
MakeIcoSphere(size, recursionLevel, Matrix4f::Transform(position, rotation), uvCoords);
}
inline void NzPrimitive::MakePlane(const NzVector2f& size, const NzVector2ui& subdivision, const NzMatrix4f& transformMatrix, const NzRectf& uvCoords)
{
matrix = transformMatrix;
textureCoords = uvCoords;
type = nzPrimitiveType_Plane;
plane.size = size;
plane.subdivision = subdivision;
}
inline void Primitive::MakePlane(const Vector2f& size, const Vector2ui& subdivision, const Matrix4f& transformMatrix, const Rectf& uvCoords)
{
matrix = transformMatrix;
textureCoords = uvCoords;
type = PrimitiveType_Plane;
plane.size = size;
plane.subdivision = subdivision;
}
inline void NzPrimitive::MakePlane(const NzVector2f& size, const NzVector2ui& subdivision, const NzPlanef& planeInfo, const NzRectf& uvCoords)
{
MakePlane(size, subdivision, NzMatrix4f::Transform(planeInfo.distance * planeInfo.normal, NzQuaternionf::RotationBetween(NzVector3f::Up(), planeInfo.normal)), uvCoords);
}
inline void Primitive::MakePlane(const Vector2f& size, const Vector2ui& subdivision, const Planef& planeInfo, const Rectf& uvCoords)
{
MakePlane(size, subdivision, Matrix4f::Transform(planeInfo.distance * planeInfo.normal, Quaternionf::RotationBetween(Vector3f::Up(), planeInfo.normal)), uvCoords);
}
inline void NzPrimitive::MakePlane(const NzVector2f& size, const NzVector2ui& subdivision, const NzVector3f& position, const NzQuaternionf& rotation, const NzRectf& uvCoords)
{
MakePlane(size, subdivision, NzMatrix4f::Transform(position, rotation), uvCoords);
}
inline void Primitive::MakePlane(const Vector2f& size, const Vector2ui& subdivision, const Vector3f& position, const Quaternionf& rotation, const Rectf& uvCoords)
{
MakePlane(size, subdivision, Matrix4f::Transform(position, rotation), uvCoords);
}
inline void NzPrimitive::MakeUVSphere(float size, unsigned int sliceCount, unsigned int stackCount, const NzMatrix4f& transformMatrix, const NzRectf& uvCoords)
{
matrix = transformMatrix;
textureCoords = uvCoords;
type = nzPrimitiveType_Sphere;
sphere.size = size;
sphere.type = nzSphereType_UV;
sphere.uv.sliceCount = sliceCount;
sphere.uv.stackCount = stackCount;
}
inline void Primitive::MakeUVSphere(float size, unsigned int sliceCount, unsigned int stackCount, const Matrix4f& transformMatrix, const Rectf& uvCoords)
{
matrix = transformMatrix;
textureCoords = uvCoords;
type = PrimitiveType_Sphere;
sphere.size = size;
sphere.type = SphereType_UV;
sphere.uv.sliceCount = sliceCount;
sphere.uv.stackCount = stackCount;
}
inline void NzPrimitive::MakeUVSphere(float size, unsigned int sliceCount, unsigned int stackCount, const NzVector3f& position, const NzQuaternionf& rotation, const NzRectf& uvCoords)
{
MakeUVSphere(size, sliceCount, stackCount, NzMatrix4f::Transform(position, rotation), uvCoords);
}
inline void Primitive::MakeUVSphere(float size, unsigned int sliceCount, unsigned int stackCount, const Vector3f& position, const Quaternionf& rotation, const Rectf& uvCoords)
{
MakeUVSphere(size, sliceCount, stackCount, Matrix4f::Transform(position, rotation), uvCoords);
}
inline NzPrimitive NzPrimitive::Box(const NzVector3f& lengths, const NzVector3ui& subdivision, const NzMatrix4f& transformMatrix, const NzRectf& uvCoords)
{
NzPrimitive primitive;
primitive.MakeBox(lengths, subdivision, transformMatrix, uvCoords);
inline Primitive Primitive::Box(const Vector3f& lengths, const Vector3ui& subdivision, const Matrix4f& transformMatrix, const Rectf& uvCoords)
{
Primitive primitive;
primitive.MakeBox(lengths, subdivision, transformMatrix, uvCoords);
return primitive;
}
return primitive;
}
inline NzPrimitive NzPrimitive::Box(const NzVector3f& lengths, const NzVector3ui& subdivision, const NzVector3f& position, const NzQuaternionf& rotation, const NzRectf& uvCoords)
{
NzPrimitive primitive;
primitive.MakeBox(lengths, subdivision, position, rotation, uvCoords);
inline Primitive Primitive::Box(const Vector3f& lengths, const Vector3ui& subdivision, const Vector3f& position, const Quaternionf& rotation, const Rectf& uvCoords)
{
Primitive primitive;
primitive.MakeBox(lengths, subdivision, position, rotation, uvCoords);
return primitive;
}
return primitive;
}
inline NzPrimitive NzPrimitive::Cone(float length, float radius, unsigned int subdivision, const NzMatrix4f& transformMatrix, const NzRectf& uvCoords)
{
NzPrimitive primitive;
primitive.MakeCone(length, radius, subdivision, transformMatrix, uvCoords);
inline Primitive Primitive::Cone(float length, float radius, unsigned int subdivision, const Matrix4f& transformMatrix, const Rectf& uvCoords)
{
Primitive primitive;
primitive.MakeCone(length, radius, subdivision, transformMatrix, uvCoords);
return primitive;
}
return primitive;
}
inline NzPrimitive NzPrimitive::Cone(float length, float radius, unsigned int subdivision, const NzVector3f& position, const NzQuaternionf& rotation, const NzRectf& uvCoords)
{
NzPrimitive primitive;
primitive.MakeCone(length, radius, subdivision, position, rotation, uvCoords);
inline Primitive Primitive::Cone(float length, float radius, unsigned int subdivision, const Vector3f& position, const Quaternionf& rotation, const Rectf& uvCoords)
{
Primitive primitive;
primitive.MakeCone(length, radius, subdivision, position, rotation, uvCoords);
return primitive;
}
return primitive;
}
inline NzPrimitive NzPrimitive::CubicSphere(float size, unsigned int subdivision, const NzMatrix4f& transformMatrix, const NzRectf& uvCoords)
{
NzPrimitive primitive;
primitive.MakeCubicSphere(size, subdivision, transformMatrix, uvCoords);
inline Primitive Primitive::CubicSphere(float size, unsigned int subdivision, const Matrix4f& transformMatrix, const Rectf& uvCoords)
{
Primitive primitive;
primitive.MakeCubicSphere(size, subdivision, transformMatrix, uvCoords);
return primitive;
}
return primitive;
}
inline NzPrimitive NzPrimitive::CubicSphere(float size, unsigned int subdivision, const NzVector3f& position, const NzQuaternionf& rotation, const NzRectf& uvCoords)
{
NzPrimitive primitive;
primitive.MakeCubicSphere(size, subdivision, position, rotation, uvCoords);
inline Primitive Primitive::CubicSphere(float size, unsigned int subdivision, const Vector3f& position, const Quaternionf& rotation, const Rectf& uvCoords)
{
Primitive primitive;
primitive.MakeCubicSphere(size, subdivision, position, rotation, uvCoords);
return primitive;
}
return primitive;
}
inline NzPrimitive NzPrimitive::IcoSphere(float size, unsigned int recursionLevel, const NzMatrix4f& transformMatrix, const NzRectf& uvCoords)
{
NzPrimitive primitive;
primitive.MakeIcoSphere(size, recursionLevel, transformMatrix, uvCoords);
inline Primitive Primitive::IcoSphere(float size, unsigned int recursionLevel, const Matrix4f& transformMatrix, const Rectf& uvCoords)
{
Primitive primitive;
primitive.MakeIcoSphere(size, recursionLevel, transformMatrix, uvCoords);
return primitive;
}
return primitive;
}
inline NzPrimitive NzPrimitive::IcoSphere(float size, unsigned int recursionLevel, const NzVector3f& position, const NzQuaternionf& rotation, const NzRectf& uvCoords)
{
NzPrimitive primitive;
primitive.MakeIcoSphere(size, recursionLevel, position, rotation, uvCoords);
inline Primitive Primitive::IcoSphere(float size, unsigned int recursionLevel, const Vector3f& position, const Quaternionf& rotation, const Rectf& uvCoords)
{
Primitive primitive;
primitive.MakeIcoSphere(size, recursionLevel, position, rotation, uvCoords);
return primitive;
}
return primitive;
}
inline NzPrimitive NzPrimitive::Plane(const NzVector2f& size, const NzVector2ui& subdivision, const NzMatrix4f& transformMatrix, const NzRectf& uvCoords)
{
NzPrimitive primitive;
primitive.MakePlane(size, subdivision, transformMatrix, uvCoords);
inline Primitive Primitive::Plane(const Vector2f& size, const Vector2ui& subdivision, const Matrix4f& transformMatrix, const Rectf& uvCoords)
{
Primitive primitive;
primitive.MakePlane(size, subdivision, transformMatrix, uvCoords);
return primitive;
}
return primitive;
}
inline NzPrimitive NzPrimitive::Plane(const NzVector2f& size, const NzVector2ui& subdivision, const NzPlanef& plane, const NzRectf& uvCoords)
{
NzPrimitive primitive;
primitive.MakePlane(size, subdivision, plane, uvCoords);
inline Primitive Primitive::Plane(const Vector2f& size, const Vector2ui& subdivision, const Planef& plane, const Rectf& uvCoords)
{
Primitive primitive;
primitive.MakePlane(size, subdivision, plane, uvCoords);
return primitive;
}
return primitive;
}
inline NzPrimitive NzPrimitive::Plane(const NzVector2f& size, const NzVector2ui& subdivision, const NzVector3f& position, const NzQuaternionf& rotation, const NzRectf& uvCoords)
{
NzPrimitive primitive;
primitive.MakePlane(size, subdivision, position, rotation, uvCoords);
inline Primitive Primitive::Plane(const Vector2f& size, const Vector2ui& subdivision, const Vector3f& position, const Quaternionf& rotation, const Rectf& uvCoords)
{
Primitive primitive;
primitive.MakePlane(size, subdivision, position, rotation, uvCoords);
return primitive;
}
return primitive;
}
inline NzPrimitive NzPrimitive::UVSphere(float size, unsigned int sliceCount, unsigned int stackCount, const NzMatrix4f& transformMatrix, const NzRectf& uvCoords)
{
NzPrimitive primitive;
primitive.MakeUVSphere(size, sliceCount, stackCount, transformMatrix, uvCoords);
inline Primitive Primitive::UVSphere(float size, unsigned int sliceCount, unsigned int stackCount, const Matrix4f& transformMatrix, const Rectf& uvCoords)
{
Primitive primitive;
primitive.MakeUVSphere(size, sliceCount, stackCount, transformMatrix, uvCoords);
return primitive;
}
return primitive;
}
inline NzPrimitive NzPrimitive::UVSphere(float size, unsigned int sliceCount, unsigned int stackCount, const NzVector3f& position, const NzQuaternionf& rotation, const NzRectf& uvCoords)
{
NzPrimitive primitive;
primitive.MakeUVSphere(size, sliceCount, stackCount, position, rotation, uvCoords);
inline Primitive Primitive::UVSphere(float size, unsigned int sliceCount, unsigned int stackCount, const Vector3f& position, const Quaternionf& rotation, const Rectf& uvCoords)
{
Primitive primitive;
primitive.MakeUVSphere(size, sliceCount, stackCount, position, rotation, uvCoords);
return primitive;
return primitive;
}
}
#include <Nazara/Core/DebugOff.hpp>

View File

@@ -11,35 +11,44 @@
#include <Nazara/Core/Primitive.hpp>
#include <Nazara/Math/Quaternion.hpp>
class NAZARA_CORE_API NzPrimitiveList
namespace Nz
{
public:
NzPrimitiveList() = default;
~NzPrimitiveList() = default;
///TODO: Inline this
class NAZARA_CORE_API PrimitiveList
{
public:
PrimitiveList() = default;
PrimitiveList(const PrimitiveList&) = default;
PrimitiveList(PrimitiveList&&) = default;
~PrimitiveList() = default;
void AddBox(const NzVector3f& lengths, const NzVector3ui& subdivision = NzVector3ui(0U), const NzMatrix4f& transformMatrix = NzMatrix4f::Identity());
void AddBox(const NzVector3f& lengths, const NzVector3ui& subdivision, const NzVector3f& position, const NzQuaternionf& rotation = NzQuaternionf::Identity());
void AddCone(float length, float radius, unsigned int subdivision = 4, const NzMatrix4f& transformMatrix = NzMatrix4f::Identity());
void AddCone(float length, float radius, unsigned int subdivision, const NzVector3f& position, const NzQuaternionf& rotation = NzQuaternionf::Identity());
void AddCubicSphere(float size, unsigned int subdivision = 4, const NzMatrix4f& transformMatrix = NzMatrix4f::Identity());
void AddCubicSphere(float size, unsigned int subdivision, const NzVector3f& position, const NzQuaternionf& rotation = NzQuaternionf::Identity());
void AddIcoSphere(float size, unsigned int recursionLevel = 3, const NzMatrix4f& transformMatrix = NzMatrix4f::Identity());
void AddIcoSphere(float size, unsigned int recursionLevel, const NzVector3f& position, const NzQuaternionf& rotation = NzQuaternionf::Identity());
void AddPlane(const NzVector2f& size, const NzVector2ui& subdivision, const NzMatrix4f& transformMatrix = NzMatrix4f::Identity());
void AddPlane(const NzVector2f& size, const NzVector2ui& subdivision, const NzPlanef& planeInfo);
void AddPlane(const NzVector2f& size, const NzVector2ui& subdivision, const NzVector3f& position, const NzQuaternionf& rotation = NzQuaternionf::Identity());
void AddUVSphere(float size, unsigned int sliceCount = 4, unsigned int stackCount = 4, const NzMatrix4f& transformMatrix = NzMatrix4f::Identity());
void AddUVSphere(float size, unsigned int sliceCount, unsigned int stackCount, const NzVector3f& position, const NzQuaternionf& rotation = NzQuaternionf::Identity());
void AddBox(const Vector3f& lengths, const Vector3ui& subdivision = Vector3ui(0U), const Matrix4f& transformMatrix = Matrix4f::Identity());
void AddBox(const Vector3f& lengths, const Vector3ui& subdivision, const Vector3f& position, const Quaternionf& rotation = Quaternionf::Identity());
void AddCone(float length, float radius, unsigned int subdivision = 4, const Matrix4f& transformMatrix = Matrix4f::Identity());
void AddCone(float length, float radius, unsigned int subdivision, const Vector3f& position, const Quaternionf& rotation = Quaternionf::Identity());
void AddCubicSphere(float size, unsigned int subdivision = 4, const Matrix4f& transformMatrix = Matrix4f::Identity());
void AddCubicSphere(float size, unsigned int subdivision, const Vector3f& position, const Quaternionf& rotation = Quaternionf::Identity());
void AddIcoSphere(float size, unsigned int recursionLevel = 3, const Matrix4f& transformMatrix = Matrix4f::Identity());
void AddIcoSphere(float size, unsigned int recursionLevel, const Vector3f& position, const Quaternionf& rotation = Quaternionf::Identity());
void AddPlane(const Vector2f& size, const Vector2ui& subdivision, const Matrix4f& transformMatrix = Matrix4f::Identity());
void AddPlane(const Vector2f& size, const Vector2ui& subdivision, const Planef& planeInfo);
void AddPlane(const Vector2f& size, const Vector2ui& subdivision, const Vector3f& position, const Quaternionf& rotation = Quaternionf::Identity());
void AddUVSphere(float size, unsigned int sliceCount = 4, unsigned int stackCount = 4, const Matrix4f& transformMatrix = Matrix4f::Identity());
void AddUVSphere(float size, unsigned int sliceCount, unsigned int stackCount, const Vector3f& position, const Quaternionf& rotation = Quaternionf::Identity());
NzPrimitive& GetPrimitive(unsigned int i);
const NzPrimitive& GetPrimitive(unsigned int i) const;
unsigned int GetSize() const;
Primitive& GetPrimitive(std::size_t i);
const Primitive& GetPrimitive(std::size_t i) const;
std::size_t GetSize() const;
NzPrimitive& operator()(unsigned int i);
const NzPrimitive& operator()(unsigned int i) const;
PrimitiveList& operator=(const PrimitiveList&) = default;
PrimitiveList& operator=(PrimitiveList&&) = default;
private:
std::vector<NzPrimitive> m_primitives;
};
Primitive& operator()(unsigned int i);
const Primitive& operator()(unsigned int i) const;
private:
std::vector<Primitive> m_primitives;
};
}
#endif // NAZARA_PRIMITIVELIST_HPP

View File

@@ -17,30 +17,33 @@
#include <Nazara/Core/ThreadSafetyOff.hpp>
#endif
class NAZARA_CORE_API NzRefCounted
namespace Nz
{
public:
NzRefCounted(bool persistent = true);
NzRefCounted(const NzRefCounted&) = delete;
NzRefCounted(NzRefCounted&&) = default;
virtual ~NzRefCounted();
class NAZARA_CORE_API RefCounted
{
public:
RefCounted(bool persistent = true);
RefCounted(const RefCounted&) = delete;
RefCounted(RefCounted&&) = default;
virtual ~RefCounted();
void AddReference() const;
void AddReference() const;
unsigned int GetReferenceCount() const;
unsigned int GetReferenceCount() const;
bool IsPersistent() const;
bool IsPersistent() const;
bool RemoveReference() const;
bool RemoveReference() const;
bool SetPersistent(bool persistent = true, bool checkReferenceCount = false);
bool SetPersistent(bool persistent = true, bool checkReferenceCount = false);
NzRefCounted& operator=(const NzRefCounted&) = delete;
NzRefCounted& operator=(NzRefCounted&&) = default;
RefCounted& operator=(const RefCounted&) = delete;
RefCounted& operator=(RefCounted&&) = default;
private:
std::atomic_bool m_persistent;
mutable std::atomic_uint m_referenceCount;
};
private:
std::atomic_bool m_persistent;
mutable std::atomic_uint m_referenceCount;
};
}
#endif // NAZARA_RESOURCE_HPP

View File

@@ -10,23 +10,26 @@
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/String.hpp>
class NAZARA_CORE_API NzResource
namespace Nz
{
public:
NzResource() = default;
NzResource(const NzResource&) = default;
NzResource(NzResource&&) = default;
virtual ~NzResource();
class NAZARA_CORE_API Resource
{
public:
Resource() = default;
Resource(const Resource&) = default;
Resource(Resource&&) = default;
virtual ~Resource();
const NzString& GetFilePath() const;
const String& GetFilePath() const;
void SetFilePath(const NzString& filePath);
void SetFilePath(const String& filePath);
NzResource& operator=(const NzResource&) = default;
NzResource& operator=(NzResource&&) = default;
Resource& operator=(const Resource&) = default;
Resource& operator=(Resource&&) = default;
private:
NzString m_filePath;
};
private:
String m_filePath;
};
}
#endif // NAZARA_RESOURCE_HPP

View File

@@ -14,36 +14,39 @@
#include <tuple>
#include <type_traits>
class NzInputStream;
template<typename Type, typename Parameters>
class NzResourceLoader
namespace Nz
{
friend Type;
class Stream;
public:
using ExtensionGetter = bool (*)(const NzString& extension);
using FileLoader = bool (*)(Type* resource, const NzString& filePath, const Parameters& parameters);
using MemoryLoader = bool (*)(Type* resource, const void* data, std::size_t size, const Parameters& parameters);
using StreamChecker = nzTernary (*)(NzInputStream& stream, const Parameters& parameters);
using StreamLoader = bool (*)(Type* resource, NzInputStream& stream, const Parameters& parameters);
template<typename Type, typename Parameters>
class ResourceLoader
{
friend Type;
NzResourceLoader() = delete;
~NzResourceLoader() = delete;
public:
using ExtensionGetter = bool (*)(const String& extension);
using FileLoader = bool (*)(Type* resource, const String& filePath, const Parameters& parameters);
using MemoryLoader = bool (*)(Type* resource, const void* data, std::size_t size, const Parameters& parameters);
using StreamChecker = Ternary (*)(Stream& stream, const Parameters& parameters);
using StreamLoader = bool (*)(Type* resource, Stream& stream, const Parameters& parameters);
static bool IsExtensionSupported(const NzString& extension);
ResourceLoader() = delete;
~ResourceLoader() = delete;
static bool LoadFromFile(Type* resource, const NzString& filePath, const Parameters& parameters = Parameters());
static bool LoadFromMemory(Type* resource, const void* data, unsigned int size, const Parameters& parameters = Parameters());
static bool LoadFromStream(Type* resource, NzInputStream& stream, const Parameters& parameters = Parameters());
static bool IsExtensionSupported(const String& extension);
static void RegisterLoader(ExtensionGetter extensionGetter, StreamChecker checkFunc, StreamLoader streamLoader, FileLoader fileLoader = nullptr, MemoryLoader memoryLoader = nullptr);
static void UnregisterLoader(ExtensionGetter extensionGetter, StreamChecker checkFunc, StreamLoader streamLoader, FileLoader fileLoader = nullptr, MemoryLoader memoryLoader = nullptr);
static bool LoadFromFile(Type* resource, const String& filePath, const Parameters& parameters = Parameters());
static bool LoadFromMemory(Type* resource, const void* data, unsigned int size, const Parameters& parameters = Parameters());
static bool LoadFromStream(Type* resource, Stream& stream, const Parameters& parameters = Parameters());
private:
using Loader = std::tuple<ExtensionGetter, StreamChecker, StreamLoader, FileLoader, MemoryLoader>;
using LoaderList = std::list<Loader>;
};
static void RegisterLoader(ExtensionGetter extensionGetter, StreamChecker checkFunc, StreamLoader streamLoader, FileLoader fileLoader = nullptr, MemoryLoader memoryLoader = nullptr);
static void UnregisterLoader(ExtensionGetter extensionGetter, StreamChecker checkFunc, StreamLoader streamLoader, FileLoader fileLoader = nullptr, MemoryLoader memoryLoader = nullptr);
private:
using Loader = std::tuple<ExtensionGetter, StreamChecker, StreamLoader, FileLoader, MemoryLoader>;
using LoaderList = std::list<Loader>;
};
}
#include <Nazara/Core/ResourceLoader.inl>

View File

@@ -5,275 +5,278 @@
#include <Nazara/Core/Config.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Core/File.hpp>
#include <Nazara/Core/InputStream.hpp>
#include <Nazara/Core/MemoryStream.hpp>
#include <Nazara/Core/MemoryView.hpp>
#include <Nazara/Core/Stream.hpp>
#include <Nazara/Core/Debug.hpp>
template<typename Type, typename Parameters>
bool NzResourceLoader<Type, Parameters>::IsExtensionSupported(const NzString& extension)
namespace Nz
{
for (Loader& loader : Type::s_loaders)
template<typename Type, typename Parameters>
bool ResourceLoader<Type, Parameters>::IsExtensionSupported(const String& extension)
{
ExtensionGetter isExtensionSupported = std::get<0>(loader);
if (isExtensionSupported && isExtensionSupported(extension))
return true;
}
return false;
}
template<typename Type, typename Parameters>
bool NzResourceLoader<Type, Parameters>::LoadFromFile(Type* resource, const NzString& filePath, const Parameters& parameters)
{
#if NAZARA_CORE_SAFE
if (!parameters.IsValid())
{
NazaraError("Invalid parameters");
return false;
}
#endif
NzString path = NzFile::NormalizePath(filePath);
NzString ext = path.SubStringFrom('.', -1, true).ToLower();
if (ext.IsEmpty())
{
NazaraError("Failed to get file extension from \"" + filePath + '"');
return false;
}
NzFile file(path); // Ouvert seulement en cas de besoin
bool found = false;
for (Loader& loader : Type::s_loaders)
{
ExtensionGetter isExtensionSupported = std::get<0>(loader);
if (!isExtensionSupported || !isExtensionSupported(ext))
continue;
StreamChecker checkFunc = std::get<1>(loader);
StreamLoader streamLoader = std::get<2>(loader);
FileLoader fileLoader = std::get<3>(loader);
if (checkFunc && !file.IsOpen())
for (Loader& loader : Type::s_loaders)
{
if (!file.Open(nzOpenMode_ReadOnly))
{
NazaraError("Failed to load file: unable to open \"" + filePath + '"');
return false;
}
ExtensionGetter isExtensionSupported = std::get<0>(loader);
if (isExtensionSupported && isExtensionSupported(extension))
return true;
}
nzTernary recognized = nzTernary_Unknown;
if (fileLoader)
return false;
}
template<typename Type, typename Parameters>
bool ResourceLoader<Type, Parameters>::LoadFromFile(Type* resource, const String& filePath, const Parameters& parameters)
{
#if NAZARA_CORE_SAFE
if (!parameters.IsValid())
{
if (checkFunc)
NazaraError("Invalid parameters");
return false;
}
#endif
String path = File::NormalizePath(filePath);
String ext = path.SubStringFrom('.', -1, true).ToLower();
if (ext.IsEmpty())
{
NazaraError("Failed to get file extension from \"" + filePath + '"');
return false;
}
File file(path); // Ouvert seulement en cas de besoin
bool found = false;
for (Loader& loader : Type::s_loaders)
{
ExtensionGetter isExtensionSupported = std::get<0>(loader);
if (!isExtensionSupported || !isExtensionSupported(ext))
continue;
StreamChecker checkFunc = std::get<1>(loader);
StreamLoader streamLoader = std::get<2>(loader);
FileLoader fileLoader = std::get<3>(loader);
if (checkFunc && !file.IsOpen())
{
if (!file.Open(OpenMode_ReadOnly))
{
NazaraError("Failed to load file: unable to open \"" + filePath + '"');
return false;
}
}
Ternary recognized = Ternary_Unknown;
if (fileLoader)
{
if (checkFunc)
{
file.SetCursorPos(0);
recognized = checkFunc(file, parameters);
if (recognized == Ternary_False)
continue;
else
found = true;
}
else
{
recognized = Ternary_Unknown;
found = true;
}
if (fileLoader(resource, filePath, parameters))
{
resource->SetFilePath(filePath);
return true;
}
}
else
{
file.SetCursorPos(0);
recognized = checkFunc(file, parameters);
if (recognized == nzTernary_False)
if (recognized == Ternary_False)
continue;
else
else if (recognized == Ternary_True)
found = true;
file.SetCursorPos(0);
if (streamLoader(resource, file, parameters))
{
resource->SetFilePath(filePath);
return true;
}
}
if (recognized == Ternary_True)
NazaraWarning("Loader failed");
}
if (found)
NazaraError("Failed to load file: all loaders failed");
else
NazaraError("Failed to load file: no loader found for extension \"" + ext + '"');
return false;
}
template<typename Type, typename Parameters>
bool ResourceLoader<Type, Parameters>::LoadFromMemory(Type* resource, const void* data, unsigned int size, const Parameters& parameters)
{
#if NAZARA_CORE_SAFE
if (!parameters.IsValid())
{
NazaraError("Invalid parameters");
return false;
}
if (size == 0)
{
NazaraError("No data to load");
return false;
}
#endif
MemoryView stream(data, size);
bool found = false;
for (Loader& loader : Type::s_loaders)
{
StreamChecker checkFunc = std::get<1>(loader);
StreamLoader streamLoader = std::get<2>(loader);
MemoryLoader memoryLoader = std::get<4>(loader);
Ternary recognized = Ternary_Unknown;
if (memoryLoader)
{
if (checkFunc)
{
stream.SetCursorPos(0);
recognized = checkFunc(stream, parameters);
if (recognized == Ternary_False)
continue;
else
found = true;
}
else
{
recognized = Ternary_Unknown;
found = true;
}
if (memoryLoader(resource, data, size, parameters))
return true;
}
else
{
recognized = nzTernary_Unknown;
found = true;
}
if (fileLoader(resource, filePath, parameters))
{
resource->SetFilePath(filePath);
return true;
}
}
else
{
file.SetCursorPos(0);
recognized = checkFunc(file, parameters);
if (recognized == nzTernary_False)
continue;
else if (recognized == nzTernary_True)
found = true;
file.SetCursorPos(0);
if (streamLoader(resource, file, parameters))
{
resource->SetFilePath(filePath);
return true;
}
}
if (recognized == nzTernary_True)
NazaraWarning("Loader failed");
}
if (found)
NazaraError("Failed to load file: all loaders failed");
else
NazaraError("Failed to load file: no loader found for extension \"" + ext + '"');
return false;
}
template<typename Type, typename Parameters>
bool NzResourceLoader<Type, Parameters>::LoadFromMemory(Type* resource, const void* data, unsigned int size, const Parameters& parameters)
{
#if NAZARA_CORE_SAFE
if (!parameters.IsValid())
{
NazaraError("Invalid parameters");
return false;
}
if (size == 0)
{
NazaraError("No data to load");
return false;
}
#endif
NzMemoryStream stream(data, size);
bool found = false;
for (Loader& loader : Type::s_loaders)
{
StreamChecker checkFunc = std::get<1>(loader);
StreamLoader streamLoader = std::get<2>(loader);
MemoryLoader memoryLoader = std::get<4>(loader);
nzTernary recognized = nzTernary_Unknown;
if (memoryLoader)
{
if (checkFunc)
{
stream.SetCursorPos(0);
recognized = checkFunc(stream, parameters);
if (recognized == nzTernary_False)
if (recognized == Ternary_False)
continue;
else
else if (recognized == Ternary_True)
found = true;
}
else
{
recognized = nzTernary_Unknown;
found = true;
stream.SetCursorPos(0);
if (streamLoader(resource, stream, parameters))
return true;
}
if (memoryLoader(resource, data, size, parameters))
return true;
if (recognized == Ternary_True)
NazaraWarning("Loader failed");
}
else
{
stream.SetCursorPos(0);
recognized = checkFunc(stream, parameters);
if (recognized == nzTernary_False)
if (found)
NazaraError("Failed to load file: all loaders failed");
else
NazaraError("Failed to load file: no loader found");
return false;
}
template<typename Type, typename Parameters>
bool ResourceLoader<Type, Parameters>::LoadFromStream(Type* resource, Stream& stream, const Parameters& parameters)
{
#if NAZARA_CORE_SAFE
if (!parameters.IsValid())
{
NazaraError("Invalid parameters");
return false;
}
if (stream.GetSize() == 0 || stream.GetCursorPos() >= stream.GetSize())
{
NazaraError("No data to load");
return false;
}
#endif
UInt64 streamPos = stream.GetCursorPos();
bool found = false;
for (Loader& loader : Type::s_loaders)
{
StreamChecker checkFunc = std::get<1>(loader);
StreamLoader streamLoader = std::get<2>(loader);
stream.SetCursorPos(streamPos);
// Le loader supporte-t-il les données ?
Ternary recognized = checkFunc(stream, parameters);
if (recognized == Ternary_False)
continue;
else if (recognized == nzTernary_True)
else if (recognized == Ternary_True)
found = true;
stream.SetCursorPos(0);
// On repositionne le stream à son ancienne position
stream.SetCursorPos(streamPos);
// Chargement de la ressource
if (streamLoader(resource, stream, parameters))
return true;
if (recognized == Ternary_True)
NazaraWarning("Loader failed");
}
if (recognized == nzTernary_True)
NazaraWarning("Loader failed");
}
if (found)
NazaraError("Failed to load file: all loaders failed");
else
NazaraError("Failed to load file: no loader found");
if (found)
NazaraError("Failed to load file: all loaders failed");
else
NazaraError("Failed to load file: no loader found");
return false;
}
template<typename Type, typename Parameters>
bool NzResourceLoader<Type, Parameters>::LoadFromStream(Type* resource, NzInputStream& stream, const Parameters& parameters)
{
#if NAZARA_CORE_SAFE
if (!parameters.IsValid())
{
NazaraError("Invalid parameters");
return false;
}
if (stream.GetSize() == 0 || stream.GetCursorPos() >= stream.GetSize())
template<typename Type, typename Parameters>
void ResourceLoader<Type, Parameters>::RegisterLoader(ExtensionGetter extensionGetter, StreamChecker checkFunc, StreamLoader streamLoader, FileLoader fileLoader, MemoryLoader memoryLoader)
{
NazaraError("No data to load");
return false;
}
#endif
nzUInt64 streamPos = stream.GetCursorPos();
bool found = false;
for (Loader& loader : Type::s_loaders)
{
StreamChecker checkFunc = std::get<1>(loader);
StreamLoader streamLoader = std::get<2>(loader);
stream.SetCursorPos(streamPos);
// Le loader supporte-t-il les données ?
nzTernary recognized = checkFunc(stream, parameters);
if (recognized == nzTernary_False)
continue;
else if (recognized == nzTernary_True)
found = true;
// On repositionne le stream à son ancienne position
stream.SetCursorPos(streamPos);
// Chargement de la ressource
if (streamLoader(resource, stream, parameters))
return true;
if (recognized == nzTernary_True)
NazaraWarning("Loader failed");
}
if (found)
NazaraError("Failed to load file: all loaders failed");
else
NazaraError("Failed to load file: no loader found");
return false;
}
template<typename Type, typename Parameters>
void NzResourceLoader<Type, Parameters>::RegisterLoader(ExtensionGetter extensionGetter, StreamChecker checkFunc, StreamLoader streamLoader, FileLoader fileLoader, MemoryLoader memoryLoader)
{
#if NAZARA_CORE_SAFE
if (streamLoader)
{
if (!checkFunc)
#if NAZARA_CORE_SAFE
if (streamLoader)
{
NazaraError("StreamLoader present without StreamChecker");
if (!checkFunc)
{
NazaraError("StreamLoader present without StreamChecker");
return;
}
}
else if (!fileLoader && !memoryLoader)
{
NazaraError("Neither FileLoader nor MemoryLoader nor StreamLoader were present");
return;
}
#endif
Type::s_loaders.push_front(std::make_tuple(extensionGetter, checkFunc, streamLoader, fileLoader, memoryLoader));
}
else if (!fileLoader && !memoryLoader)
template<typename Type, typename Parameters>
void ResourceLoader<Type, Parameters>::UnregisterLoader(ExtensionGetter extensionGetter, StreamChecker checkFunc, StreamLoader streamLoader, FileLoader fileLoader, MemoryLoader memoryLoader)
{
NazaraError("Neither FileLoader nor MemoryLoader nor StreamLoader were present");
return;
Type::s_loaders.remove(std::make_tuple(extensionGetter, checkFunc, streamLoader, fileLoader, memoryLoader));
}
#endif
Type::s_loaders.push_front(std::make_tuple(extensionGetter, checkFunc, streamLoader, fileLoader, memoryLoader));
}
template<typename Type, typename Parameters>
void NzResourceLoader<Type, Parameters>::UnregisterLoader(ExtensionGetter extensionGetter, StreamChecker checkFunc, StreamLoader streamLoader, FileLoader fileLoader, MemoryLoader memoryLoader)
{
Type::s_loaders.remove(std::make_tuple(extensionGetter, checkFunc, streamLoader, fileLoader, memoryLoader));
}
#include <Nazara/Core/DebugOff.hpp>

View File

@@ -11,32 +11,35 @@
#include <Nazara/Core/String.hpp>
#include <unordered_map>
template<typename Type, typename Parameters>
class NzResourceManager
namespace Nz
{
friend Type;
template<typename Type, typename Parameters>
class ResourceManager
{
friend Type;
public:
NzResourceManager() = delete;
~NzResourceManager() = delete;
public:
ResourceManager() = delete;
~ResourceManager() = delete;
static void Clear();
static void Clear();
static NzObjectRef<Type> Get(const NzString& filePath);
static const Parameters& GetDefaultParameters();
static ObjectRef<Type> Get(const String& filePath);
static const Parameters& GetDefaultParameters();
static void Purge();
static void Register(const NzString& filePath, NzObjectRef<Type> resource);
static void SetDefaultParameters(const Parameters& params);
static void Unregister(const NzString& filePath);
static void Purge();
static void Register(const String& filePath, ObjectRef<Type> resource);
static void SetDefaultParameters(const Parameters& params);
static void Unregister(const String& filePath);
private:
static bool Initialize();
static void Uninitialize();
private:
static bool Initialize();
static void Uninitialize();
using ManagerMap = std::unordered_map<NzString, NzObjectRef<Type>>;
using ManagerParams = Parameters;
};
using ManagerMap = std::unordered_map<String, ObjectRef<Type>>;
using ManagerParams = Parameters;
};
}
#include <Nazara/Core/ResourceManager.inl>

View File

@@ -7,95 +7,98 @@
#include <Nazara/Core/Log.hpp>
#include <Nazara/Core/Debug.hpp>
template<typename Type, typename Parameters>
void NzResourceManager<Type, Parameters>::Clear()
namespace Nz
{
Type::s_managerMap.clear();
}
template<typename Type, typename Parameters>
NzObjectRef<Type> NzResourceManager<Type, Parameters>::Get(const NzString& filePath)
{
NzString absolutePath = NzFile::AbsolutePath(filePath);
auto it = Type::s_managerMap.find(absolutePath);
if (it == Type::s_managerMap.end())
template<typename Type, typename Parameters>
void ResourceManager<Type, Parameters>::Clear()
{
NzObjectRef<Type> resource = Type::New();
if (!resource)
{
NazaraError("Failed to create resource");
return NzObjectRef<Type>();
}
if (!resource->LoadFromFile(absolutePath, GetDefaultParameters()))
{
NazaraError("Failed to load resource from file: " + absolutePath);
return NzObjectRef<Type>();
}
NazaraDebug("Loaded resource from file " + absolutePath);
it = Type::s_managerMap.insert(std::make_pair(absolutePath, resource)).first;
Type::s_managerMap.clear();
}
return it->second;
}
template<typename Type, typename Parameters>
const Parameters& NzResourceManager<Type, Parameters>::GetDefaultParameters()
{
return Type::s_managerParameters;
}
template<typename Type, typename Parameters>
void NzResourceManager<Type, Parameters>::Purge()
{
auto it = Type::s_managerMap.begin();
while (it != Type::s_managerMap.end())
template<typename Type, typename Parameters>
ObjectRef<Type> ResourceManager<Type, Parameters>::Get(const String& filePath)
{
const NzObjectRef<Type>& ref = it->second;
if (ref.GetReferenceCount() == 1) // Sommes-nous les seuls à détenir la ressource ?
String absolutePath = File::AbsolutePath(filePath);
auto it = Type::s_managerMap.find(absolutePath);
if (it == Type::s_managerMap.end())
{
NazaraDebug("Purging resource from file " + ref->GetFilePath());
Type::s_managerMap.erase(it++); // Alors on la supprime
ObjectRef<Type> resource = Type::New();
if (!resource)
{
NazaraError("Failed to create resource");
return ObjectRef<Type>();
}
if (!resource->LoadFromFile(absolutePath, GetDefaultParameters()))
{
NazaraError("Failed to load resource from file: " + absolutePath);
return ObjectRef<Type>();
}
NazaraDebug("Loaded resource from file " + absolutePath);
it = Type::s_managerMap.insert(std::make_pair(absolutePath, resource)).first;
}
else
++it;
return it->second;
}
}
template<typename Type, typename Parameters>
void NzResourceManager<Type, Parameters>::Register(const NzString& filePath, NzObjectRef<Type> resource)
{
NzString absolutePath = NzFile::AbsolutePath(filePath);
template<typename Type, typename Parameters>
const Parameters& ResourceManager<Type, Parameters>::GetDefaultParameters()
{
return Type::s_managerParameters;
}
Type::s_managerMap[absolutePath] = resource;
}
template<typename Type, typename Parameters>
void ResourceManager<Type, Parameters>::Purge()
{
auto it = Type::s_managerMap.begin();
while (it != Type::s_managerMap.end())
{
const ObjectRef<Type>& ref = it->second;
if (ref.GetReferenceCount() == 1) // Sommes-nous les seuls à détenir la ressource ?
{
NazaraDebug("Purging resource from file " + ref->GetFilePath());
Type::s_managerMap.erase(it++); // Alors on la supprime
}
else
++it;
}
}
template<typename Type, typename Parameters>
void NzResourceManager<Type, Parameters>::SetDefaultParameters(const Parameters& params)
{
Type::s_managerParameters = params;
}
template<typename Type, typename Parameters>
void ResourceManager<Type, Parameters>::Register(const String& filePath, ObjectRef<Type> resource)
{
String absolutePath = File::AbsolutePath(filePath);
template<typename Type, typename Parameters>
void NzResourceManager<Type, Parameters>::Unregister(const NzString& filePath)
{
NzString absolutePath = NzFile::AbsolutePath(filePath);
Type::s_managerMap[absolutePath] = resource;
}
Type::s_managerMap.erase(absolutePath);
}
template<typename Type, typename Parameters>
void ResourceManager<Type, Parameters>::SetDefaultParameters(const Parameters& params)
{
Type::s_managerParameters = params;
}
template<typename Type, typename Parameters>
bool NzResourceManager<Type, Parameters>::Initialize()
{
return true;
}
template<typename Type, typename Parameters>
void ResourceManager<Type, Parameters>::Unregister(const String& filePath)
{
String absolutePath = File::AbsolutePath(filePath);
template<typename Type, typename Parameters>
void NzResourceManager<Type, Parameters>::Uninitialize()
{
Clear();
Type::s_managerMap.erase(absolutePath);
}
template<typename Type, typename Parameters>
bool ResourceManager<Type, Parameters>::Initialize()
{
return true;
}
template<typename Type, typename Parameters>
void ResourceManager<Type, Parameters>::Uninitialize()
{
Clear();
}
}
#include <Nazara/Core/DebugOff.hpp>

View File

@@ -8,25 +8,32 @@
#define NAZARA_SEMAPHORE_HPP
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/NonCopyable.hpp>
class NzSemaphoreImpl;
class NAZARA_CORE_API NzSemaphore : NzNonCopyable
namespace Nz
{
public:
NzSemaphore(unsigned int count);
~NzSemaphore();
class SemaphoreImpl;
unsigned int GetCount() const;
class NAZARA_CORE_API Semaphore
{
public:
Semaphore(unsigned int count);
Semaphore(const Semaphore&) = delete;
Semaphore(Semaphore&&) = delete; ///TODO
~Semaphore();
void Post();
unsigned int GetCount() const;
void Wait();
bool Wait(nzUInt32 timeout);
void Post();
private:
NzSemaphoreImpl* m_impl;
};
void Wait();
bool Wait(UInt32 timeout);
Semaphore& operator=(const Semaphore&) = delete;
Semaphore& operator=(Semaphore&&) = delete; ///TODO
private:
SemaphoreImpl* m_impl;
};
}
#endif // NAZARA_SEMAPHORE_HPP

View File

@@ -0,0 +1,37 @@
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#pragma once
#ifndef NAZARA_SERIALIZATION_HPP
#define NAZARA_SERIALIZATION_HPP
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/Endianness.hpp>
#include <functional>
#include <tuple>
#include <type_traits>
namespace Nz
{
class Stream;
struct SerializationContext
{
Stream* stream;
Endianness endianness;
UInt8 currentBitPos;
UInt8 currentByte;
};
struct UnserializationContext
{
Stream* stream;
Endianness endianness;
UInt8 currentBitPos;
UInt8 currentByte;
};
}
#endif // NAZARA_SERIALIZATION_HPP

View File

@@ -0,0 +1,46 @@
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#pragma once
#ifndef NAZARA_SERIALIZER_HPP
#define NAZARA_SERIALIZER_HPP
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/Serialization.hpp>
namespace Nz
{
class Stream;
class Serializer
{
public:
inline Serializer(Stream& stream);
Serializer(const Serializer&) = default;
Serializer(Serializer&&) = default;
~Serializer();
inline Endianness GetDataEndianness() const;
inline Stream& GetStream() const;
inline bool FlushBits();
inline void SetDataEndianness(Endianness endiannes);
inline void SetStream(Stream& stream);
template<typename T>
Serializer& operator<<(const T& value);
Serializer& operator=(const Serializer&) = default;
Serializer& operator=(Serializer&&) = default;
private:
SerializationContext m_serializationContext;
};
}
#include <Nazara/Core/Serializer.inl>
#endif // NAZARA_SERIALIZER_HPP

View File

@@ -0,0 +1,67 @@
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Core/Algorithm.hpp>
#include <Nazara/Core/Debug.hpp>
namespace Nz
{
inline Serializer::Serializer(Stream& stream)
{
m_serializationContext.currentBitPos = 8;
m_serializationContext.endianness = Endianness_BigEndian;
m_serializationContext.stream = &stream;
}
inline Serializer::~Serializer()
{
if (!FlushBits())
NazaraWarning("Failed to flush bits at serializer destruction");
}
inline Endianness Serializer::GetDataEndianness() const
{
return m_serializationContext.endianness;
}
inline Stream& Serializer::GetStream() const
{
return *m_serializationContext.stream;
}
inline bool Serializer::FlushBits()
{
if (m_serializationContext.currentBitPos != 8)
{
m_serializationContext.currentBitPos = 8; //< To prevent Serialize to flush bits itself
if (!Serialize<UInt8>(m_serializationContext, m_serializationContext.currentByte))
return false;
}
return true;
}
inline void Serializer::SetDataEndianness(Endianness endiannes)
{
m_serializationContext.endianness = endiannes;
}
inline void Serializer::SetStream(Stream& stream)
{
m_serializationContext.stream = &stream;
}
template<typename T>
Serializer& Serializer::operator<<(const T& value)
{
if (!Serialize(m_serializationContext, value))
NazaraError("Failed to serialize value");
return *this;
}
}
#include <Nazara/Core/DebugOff.hpp>
#include "Serializer.hpp"

View File

@@ -11,122 +11,128 @@
#include <memory>
#include <vector>
#define NazaraSignal(SignalName, ...) using SignalName ## Type = NzSignal<__VA_ARGS__>; \
mutable SignalName ## Type SignalName
#define NazaraDetailSignal(Keyword, SignalName, ...) using SignalName ## Type = Nz::Signal<__VA_ARGS__>; \
Keyword SignalName ## Type SignalName
#define NazaraSignal(SignalName, ...) NazaraDetailSignal(mutable, SignalName, __VA_ARGS__)
#define NazaraStaticSignal(SignalName, ...) NazaraDetailSignal(static, SignalName, __VA_ARGS__)
#define NazaraStaticSignalImpl(Class, SignalName) Class :: SignalName ## Type Class :: SignalName
#define NazaraSlotType(Class, SignalName) Class::SignalName ## Type::ConnectionGuard
#define NazaraSlot(Class, SignalName, SlotName) NazaraSlotType(Class, SignalName) SlotName
template<typename... Args>
class NzSignal
namespace Nz
{
public:
using Callback = std::function<void(Args...)>;
class Connection;
class ConnectionGuard;
template<typename... Args>
class Signal
{
public:
using Callback = std::function<void(Args...)>;
class Connection;
class ConnectionGuard;
NzSignal();
NzSignal(const NzSignal&) = delete;
NzSignal(NzSignal&& signal);
~NzSignal() = default;
Signal();
Signal(const Signal&) = delete;
Signal(Signal&& signal);
~Signal() = default;
void Clear();
void Clear();
Connection Connect(const Callback& func);
Connection Connect(Callback&& func);
template<typename O> Connection Connect(O& object, void (O::*method)(Args...));
template<typename O> Connection Connect(O* object, void (O::*method)(Args...));
template<typename O> Connection Connect(const O& object, void (O::*method)(Args...) const);
template<typename O> Connection Connect(const O* object, void (O::*method)(Args...) const);
Connection Connect(const Callback& func);
Connection Connect(Callback&& func);
template<typename O> Connection Connect(O& object, void (O::*method)(Args...));
template<typename O> Connection Connect(O* object, void (O::*method)(Args...));
template<typename O> Connection Connect(const O& object, void (O::*method)(Args...) const);
template<typename O> Connection Connect(const O* object, void (O::*method)(Args...) const);
void operator()(Args... args) const;
void operator()(Args... args) const;
NzSignal& operator=(const NzSignal&) = delete;
NzSignal& operator=(NzSignal&& signal);
Signal& operator=(const Signal&) = delete;
Signal& operator=(Signal&& signal);
private:
struct Slot;
private:
struct Slot;
using SlotPtr = std::shared_ptr<Slot>;
using SlotList = std::vector<SlotPtr>;
using SlotListIndex = typename SlotList::size_type;
using SlotPtr = std::shared_ptr<Slot>;
using SlotList = std::vector<SlotPtr>;
using SlotListIndex = typename SlotList::size_type;
struct Slot
{
Slot(NzSignal* me) :
signal(me)
struct Slot
{
}
Slot(Signal* me) :
signal(me)
{
}
Callback callback;
NzSignal* signal;
SlotListIndex index;
};
Callback callback;
Signal* signal;
SlotListIndex index;
};
void Disconnect(const SlotPtr& slot);
void Disconnect(const SlotPtr& slot);
SlotList m_slots;
mutable SlotListIndex m_slotIterator;
};
SlotList m_slots;
mutable SlotListIndex m_slotIterator;
};
template<typename... Args>
class NzSignal<Args...>::Connection
{
using BaseClass = NzSignal<Args...>;
friend BaseClass;
template<typename... Args>
class Signal<Args...>::Connection
{
using BaseClass = Signal<Args...>;
friend BaseClass;
public:
Connection() = default;
Connection(const Connection& connection) = default;
Connection(Connection&& connection) = default;
~Connection() = default;
public:
Connection() = default;
Connection(const Connection& connection) = default;
Connection(Connection&& connection) = default;
~Connection() = default;
template<typename... ConnectArgs>
void Connect(BaseClass& signal, ConnectArgs&&... args);
void Disconnect();
template<typename... ConnectArgs>
void Connect(BaseClass& signal, ConnectArgs&&... args);
void Disconnect();
bool IsConnected() const;
bool IsConnected() const;
Connection& operator=(const Connection& connection) = default;
Connection& operator=(Connection&& connection) = default;
Connection& operator=(const Connection& connection) = default;
Connection& operator=(Connection&& connection) = default;
private:
Connection(const SlotPtr& slot);
private:
Connection(const SlotPtr& slot);
std::weak_ptr<Slot> m_ptr;
};
std::weak_ptr<Slot> m_ptr;
};
template<typename... Args>
class NzSignal<Args...>::ConnectionGuard
{
using BaseClass = NzSignal<Args...>;
using Connection = typename BaseClass::Connection;
template<typename... Args>
class Signal<Args...>::ConnectionGuard
{
using BaseClass = Signal<Args...>;
using Connection = typename BaseClass::Connection;
public:
ConnectionGuard() = default;
ConnectionGuard(const Connection& connection);
ConnectionGuard(const ConnectionGuard& connection) = delete;
ConnectionGuard(Connection&& connection);
ConnectionGuard(ConnectionGuard&& connection) = default;
~ConnectionGuard();
public:
ConnectionGuard() = default;
ConnectionGuard(const Connection& connection);
ConnectionGuard(const ConnectionGuard& connection) = delete;
ConnectionGuard(Connection&& connection);
ConnectionGuard(ConnectionGuard&& connection) = default;
~ConnectionGuard();
template<typename... ConnectArgs>
void Connect(BaseClass& signal, ConnectArgs&&... args);
void Disconnect();
template<typename... ConnectArgs>
void Connect(BaseClass& signal, ConnectArgs&&... args);
void Disconnect();
Connection& GetConnection();
Connection& GetConnection();
bool IsConnected() const;
bool IsConnected() const;
ConnectionGuard& operator=(const Connection& connection);
ConnectionGuard& operator=(const ConnectionGuard& connection) = delete;
ConnectionGuard& operator=(Connection&& connection);
ConnectionGuard& operator=(ConnectionGuard&& connection);
ConnectionGuard& operator=(const Connection& connection);
ConnectionGuard& operator=(const ConnectionGuard& connection) = delete;
ConnectionGuard& operator=(Connection&& connection);
ConnectionGuard& operator=(ConnectionGuard&& connection);
private:
Connection m_connection;
};
private:
Connection m_connection;
};
}
#include <Nazara/Core/Signal.inl>

View File

@@ -6,245 +6,248 @@
#include <utility>
#include <Nazara/Core/Debug.hpp>
template<typename... Args>
NzSignal<Args...>::NzSignal() :
m_slotIterator(0)
namespace Nz
{
}
template<typename... Args>
NzSignal<Args...>::NzSignal(NzSignal&& signal)
{
operator=(std::move(signal));
}
template<typename... Args>
void NzSignal<Args...>::Clear()
{
m_slots.clear();
m_slotIterator = 0;
}
template<typename... Args>
typename NzSignal<Args...>::Connection NzSignal<Args...>::Connect(const Callback& func)
{
return Connect(Callback(func));
}
template<typename... Args>
typename NzSignal<Args...>::Connection NzSignal<Args...>::Connect(Callback&& func)
{
NazaraAssert(func, "Invalid function");
// Since we're incrementing the slot vector size, we need to replace our iterator at the end
// (Except when we are iterating on the signal)
bool resetIt = (m_slotIterator >= m_slots.size());
auto tempPtr = std::make_shared<Slot>(this);
tempPtr->callback = std::move(func);
tempPtr->index = m_slots.size();
m_slots.emplace_back(std::move(tempPtr));
if (resetIt)
m_slotIterator = m_slots.size(); //< Replace the iterator to the end
return Connection(m_slots.back());
}
template<typename... Args>
template<typename O>
typename NzSignal<Args...>::Connection NzSignal<Args...>::Connect(O& object, void (O::*method) (Args...))
{
return Connect([&object, method] (Args&&... args)
{
return (object .* method) (std::forward<Args>(args)...);
});
}
template<typename... Args>
template<typename O>
typename NzSignal<Args...>::Connection NzSignal<Args...>::Connect(O* object, void (O::*method)(Args...))
{
return Connect([object, method] (Args&&... args)
{
return (object ->* method) (std::forward<Args>(args)...);
});
}
template<typename... Args>
template<typename O>
typename NzSignal<Args...>::Connection NzSignal<Args...>::Connect(const O& object, void (O::*method) (Args...) const)
{
return Connect([&object, method] (Args&&... args)
{
return (object .* method) (std::forward<Args>(args)...);
});
}
template<typename... Args>
template<typename O>
typename NzSignal<Args...>::Connection NzSignal<Args...>::Connect(const O* object, void (O::*method)(Args...) const)
{
return Connect([object, method] (Args&&... args)
{
return (object ->* method) (std::forward<Args>(args)...);
});
}
template<typename... Args>
void NzSignal<Args...>::operator()(Args... args) const
{
for (m_slotIterator = 0; m_slotIterator < m_slots.size(); ++m_slotIterator)
m_slots[m_slotIterator]->callback(args...);
}
template<typename... Args>
NzSignal<Args...>& NzSignal<Args...>::operator=(NzSignal&& signal)
{
m_slots = std::move(signal.m_slots);
m_slotIterator = signal.m_slotIterator;
// We need to update the signal pointer inside of each slot
for (SlotPtr& slot : m_slots)
slot->signal = this;
return *this;
}
template<typename... Args>
void NzSignal<Args...>::Disconnect(const SlotPtr& slot)
{
NazaraAssert(slot, "Invalid slot pointer");
NazaraAssert(slot->index < m_slots.size(), "Invalid slot index");
// "Swap this slot with the last one and pop" idiom
// This will preserve slot indexes
// Can we safely "remove" this slot?
if (m_slotIterator >= m_slots.size()-1 || slot->index > m_slotIterator)
template<typename... Args>
Signal<Args...>::Signal() :
m_slotIterator(0)
{
// Yes we can
SlotPtr& newSlot = m_slots[slot->index];
newSlot = std::move(m_slots.back());
newSlot->index = slot->index; //< Update the moved slot index before resizing (in case it's the last one)
}
else
{
// Nope, let's be tricky
SlotPtr& current = m_slots[m_slotIterator];
SlotPtr& newSlot = m_slots[slot->index];
newSlot = std::move(current);
newSlot->index = slot->index; //< Update the moved slot index
current = std::move(m_slots.back());
current->index = m_slotIterator; //< Update the moved slot index
--m_slotIterator;
}
// Pop the last entry (from where we moved our slot)
m_slots.pop_back();
}
template<typename... Args>
Signal<Args...>::Signal(Signal&& signal)
{
operator=(std::move(signal));
}
template<typename... Args>
void Signal<Args...>::Clear()
{
m_slots.clear();
m_slotIterator = 0;
}
template<typename... Args>
typename Signal<Args...>::Connection Signal<Args...>::Connect(const Callback& func)
{
return Connect(Callback(func));
}
template<typename... Args>
typename Signal<Args...>::Connection Signal<Args...>::Connect(Callback&& func)
{
NazaraAssert(func, "Invalid function");
// Since we're incrementing the slot vector size, we need to replace our iterator at the end
// (Except when we are iterating on the signal)
bool resetIt = (m_slotIterator >= m_slots.size());
auto tempPtr = std::make_shared<Slot>(this);
tempPtr->callback = std::move(func);
tempPtr->index = m_slots.size();
m_slots.emplace_back(std::move(tempPtr));
if (resetIt)
m_slotIterator = m_slots.size(); //< Replace the iterator to the end
return Connection(m_slots.back());
}
template<typename... Args>
template<typename O>
typename Signal<Args...>::Connection Signal<Args...>::Connect(O& object, void (O::*method) (Args...))
{
return Connect([&object, method] (Args&&... args)
{
return (object .* method) (std::forward<Args>(args)...);
});
}
template<typename... Args>
template<typename O>
typename Signal<Args...>::Connection Signal<Args...>::Connect(O* object, void (O::*method)(Args...))
{
return Connect([object, method] (Args&&... args)
{
return (object ->* method) (std::forward<Args>(args)...);
});
}
template<typename... Args>
template<typename O>
typename Signal<Args...>::Connection Signal<Args...>::Connect(const O& object, void (O::*method) (Args...) const)
{
return Connect([&object, method] (Args&&... args)
{
return (object .* method) (std::forward<Args>(args)...);
});
}
template<typename... Args>
template<typename O>
typename Signal<Args...>::Connection Signal<Args...>::Connect(const O* object, void (O::*method)(Args...) const)
{
return Connect([object, method] (Args&&... args)
{
return (object ->* method) (std::forward<Args>(args)...);
});
}
template<typename... Args>
void Signal<Args...>::operator()(Args... args) const
{
for (m_slotIterator = 0; m_slotIterator < m_slots.size(); ++m_slotIterator)
m_slots[m_slotIterator]->callback(args...);
}
template<typename... Args>
Signal<Args...>& Signal<Args...>::operator=(Signal&& signal)
{
m_slots = std::move(signal.m_slots);
m_slotIterator = signal.m_slotIterator;
// We need to update the signal pointer inside of each slot
for (SlotPtr& slot : m_slots)
slot->signal = this;
return *this;
}
template<typename... Args>
void Signal<Args...>::Disconnect(const SlotPtr& slot)
{
NazaraAssert(slot, "Invalid slot pointer");
NazaraAssert(slot->index < m_slots.size(), "Invalid slot index");
// "Swap this slot with the last one and pop" idiom
// This will preserve slot indexes
// Can we safely "remove" this slot?
if (m_slotIterator >= m_slots.size()-1 || slot->index > m_slotIterator)
{
// Yes we can
SlotPtr& newSlot = m_slots[slot->index];
newSlot = std::move(m_slots.back());
newSlot->index = slot->index; //< Update the moved slot index before resizing (in case it's the last one)
}
else
{
// Nope, let's be tricky
SlotPtr& current = m_slots[m_slotIterator];
SlotPtr& newSlot = m_slots[slot->index];
newSlot = std::move(current);
newSlot->index = slot->index; //< Update the moved slot index
current = std::move(m_slots.back());
current->index = m_slotIterator; //< Update the moved slot index
--m_slotIterator;
}
// Pop the last entry (from where we moved our slot)
m_slots.pop_back();
}
template<typename... Args>
NzSignal<Args...>::Connection::Connection(const SlotPtr& slot) :
m_ptr(slot)
{
}
template<typename... Args>
Signal<Args...>::Connection::Connection(const SlotPtr& slot) :
m_ptr(slot)
{
}
template<typename... Args>
template<typename... ConnectArgs>
void NzSignal<Args...>::Connection::Connect(BaseClass& signal, ConnectArgs&&... args)
{
operator=(signal.Connect(std::forward<ConnectArgs>(args)...));
}
template<typename... Args>
template<typename... ConnectArgs>
void Signal<Args...>::Connection::Connect(BaseClass& signal, ConnectArgs&&... args)
{
operator=(signal.Connect(std::forward<ConnectArgs>(args)...));
}
template<typename... Args>
void NzSignal<Args...>::Connection::Disconnect()
{
if (SlotPtr ptr = m_ptr.lock())
ptr->signal->Disconnect(ptr);
}
template<typename... Args>
void Signal<Args...>::Connection::Disconnect()
{
if (SlotPtr ptr = m_ptr.lock())
ptr->signal->Disconnect(ptr);
}
template<typename... Args>
bool NzSignal<Args...>::Connection::IsConnected() const
{
return !m_ptr.expired();
}
template<typename... Args>
bool Signal<Args...>::Connection::IsConnected() const
{
return !m_ptr.expired();
}
template<typename... Args>
NzSignal<Args...>::ConnectionGuard::ConnectionGuard(const Connection& connection) :
m_connection(connection)
{
}
template<typename... Args>
Signal<Args...>::ConnectionGuard::ConnectionGuard(const Connection& connection) :
m_connection(connection)
{
}
template<typename... Args>
NzSignal<Args...>::ConnectionGuard::ConnectionGuard(Connection&& connection) :
m_connection(std::move(connection))
{
}
template<typename... Args>
Signal<Args...>::ConnectionGuard::ConnectionGuard(Connection&& connection) :
m_connection(std::move(connection))
{
}
template<typename... Args>
NzSignal<Args...>::ConnectionGuard::~ConnectionGuard()
{
m_connection.Disconnect();
}
template<typename... Args>
Signal<Args...>::ConnectionGuard::~ConnectionGuard()
{
m_connection.Disconnect();
}
template<typename... Args>
template<typename... ConnectArgs>
void NzSignal<Args...>::ConnectionGuard::Connect(BaseClass& signal, ConnectArgs&&... args)
{
m_connection.Disconnect();
m_connection.Connect(signal, std::forward<ConnectArgs>(args)...);
}
template<typename... Args>
template<typename... ConnectArgs>
void Signal<Args...>::ConnectionGuard::Connect(BaseClass& signal, ConnectArgs&&... args)
{
m_connection.Disconnect();
m_connection.Connect(signal, std::forward<ConnectArgs>(args)...);
}
template<typename... Args>
void NzSignal<Args...>::ConnectionGuard::Disconnect()
{
m_connection.Disconnect();
}
template<typename... Args>
void Signal<Args...>::ConnectionGuard::Disconnect()
{
m_connection.Disconnect();
}
template<typename... Args>
typename NzSignal<Args...>::Connection& NzSignal<Args...>::ConnectionGuard::GetConnection()
{
return m_connection;
}
template<typename... Args>
typename Signal<Args...>::Connection& Signal<Args...>::ConnectionGuard::GetConnection()
{
return m_connection;
}
template<typename... Args>
bool NzSignal<Args...>::ConnectionGuard::IsConnected() const
{
return m_connection.IsConnected();
}
template<typename... Args>
bool Signal<Args...>::ConnectionGuard::IsConnected() const
{
return m_connection.IsConnected();
}
template<typename... Args>
typename NzSignal<Args...>::ConnectionGuard& NzSignal<Args...>::ConnectionGuard::operator=(const Connection& connection)
{
m_connection.Disconnect();
m_connection = connection;
template<typename... Args>
typename Signal<Args...>::ConnectionGuard& Signal<Args...>::ConnectionGuard::operator=(const Connection& connection)
{
m_connection.Disconnect();
m_connection = connection;
return *this;
}
return *this;
}
template<typename... Args>
typename NzSignal<Args...>::ConnectionGuard& NzSignal<Args...>::ConnectionGuard::operator=(Connection&& connection)
{
m_connection.Disconnect();
m_connection = std::move(connection);
template<typename... Args>
typename Signal<Args...>::ConnectionGuard& Signal<Args...>::ConnectionGuard::operator=(Connection&& connection)
{
m_connection.Disconnect();
m_connection = std::move(connection);
return *this;
}
return *this;
}
template<typename... Args>
typename NzSignal<Args...>::ConnectionGuard& NzSignal<Args...>::ConnectionGuard::operator=(ConnectionGuard&& connection)
{
m_connection.Disconnect();
m_connection = std::move(connection.m_connection);
template<typename... Args>
typename Signal<Args...>::ConnectionGuard& Signal<Args...>::ConnectionGuard::operator=(ConnectionGuard&& connection)
{
m_connection.Disconnect();
m_connection = std::move(connection.m_connection);
return *this;
return *this;
}
}
#include <Nazara/Core/DebugOff.hpp>

View File

@@ -13,66 +13,69 @@
#include <cstddef>
#include <type_traits>
template<typename T>
class NzSparsePtr
namespace Nz
{
public:
using BytePtr = typename std::conditional<std::is_const<T>::value, const nzUInt8*, nzUInt8*>::type;
using VoidPtr = typename std::conditional<std::is_const<T>::value, const void*, void*>::type;
template<typename T>
class SparsePtr
{
public:
using BytePtr = typename std::conditional<std::is_const<T>::value, const UInt8*, UInt8*>::type;
using VoidPtr = typename std::conditional<std::is_const<T>::value, const void*, void*>::type;
NzSparsePtr();
NzSparsePtr(T* ptr);
NzSparsePtr(VoidPtr ptr, int stride);
template<typename U> NzSparsePtr(const NzSparsePtr<U>& ptr);
NzSparsePtr(const NzSparsePtr& ptr) = default;
~NzSparsePtr() = default;
SparsePtr();
SparsePtr(T* ptr);
SparsePtr(VoidPtr ptr, int stride);
template<typename U> SparsePtr(const SparsePtr<U>& ptr);
SparsePtr(const SparsePtr& ptr) = default;
~SparsePtr() = default;
VoidPtr GetPtr() const;
int GetStride() const;
VoidPtr GetPtr() const;
int GetStride() const;
void Reset();
void Reset(T* ptr);
void Reset(VoidPtr ptr, int stride);
void Reset(const NzSparsePtr& ptr);
template<typename U> void Reset(const NzSparsePtr<U>& ptr);
void Reset();
void Reset(T* ptr);
void Reset(VoidPtr ptr, int stride);
void Reset(const SparsePtr& ptr);
template<typename U> void Reset(const SparsePtr<U>& ptr);
void SetPtr(VoidPtr ptr);
void SetStride(int stride);
void SetPtr(VoidPtr ptr);
void SetStride(int stride);
operator bool() const;
operator T*() const;
T& operator*() const;
T* operator->() const;
T& operator[](int index) const;
operator bool() const;
operator T*() const;
T& operator*() const;
T* operator->() const;
T& operator[](int index) const;
NzSparsePtr operator+(int count) const;
NzSparsePtr operator+(unsigned int count) const;
NzSparsePtr operator-(int count) const;
NzSparsePtr operator-(unsigned int count) const;
std::ptrdiff_t operator-(const NzSparsePtr& ptr) const;
SparsePtr& operator=(const SparsePtr& ptr) = default;
NzSparsePtr& operator+=(int count);
NzSparsePtr& operator-=(int count);
SparsePtr operator+(int count) const;
SparsePtr operator+(unsigned int count) const;
SparsePtr operator-(int count) const;
SparsePtr operator-(unsigned int count) const;
std::ptrdiff_t operator-(const SparsePtr& ptr) const;
NzSparsePtr& operator++();
NzSparsePtr operator++(int);
SparsePtr& operator+=(int count);
SparsePtr& operator-=(int count);
NzSparsePtr& operator--();
NzSparsePtr operator--(int);
SparsePtr& operator++();
SparsePtr operator++(int);
bool operator==(const NzSparsePtr& ptr) const;
bool operator!=(const NzSparsePtr& ptr) const;
bool operator<(const NzSparsePtr& ptr) const;
bool operator>(const NzSparsePtr& ptr) const;
bool operator<=(const NzSparsePtr& ptr) const;
bool operator>=(const NzSparsePtr& ptr) const;
SparsePtr& operator--();
SparsePtr operator--(int);
NzSparsePtr& operator=(const NzSparsePtr& ptr) = default;
bool operator==(const SparsePtr& ptr) const;
bool operator!=(const SparsePtr& ptr) const;
bool operator<(const SparsePtr& ptr) const;
bool operator>(const SparsePtr& ptr) const;
bool operator<=(const SparsePtr& ptr) const;
bool operator>=(const SparsePtr& ptr) const;
private:
BytePtr m_ptr;
int m_stride;
};
private:
BytePtr m_ptr;
int m_stride;
};
}
#include <Nazara/Core/SparsePtr.inl>

View File

@@ -5,250 +5,253 @@
#include <iterator>
#include <Nazara/Core/Debug.hpp>
template<typename T>
NzSparsePtr<T>::NzSparsePtr()
namespace Nz
{
Reset();
}
template<typename T>
SparsePtr<T>::SparsePtr()
{
Reset();
}
template<typename T>
NzSparsePtr<T>::NzSparsePtr(T* ptr)
{
Reset(ptr);
}
template<typename T>
SparsePtr<T>::SparsePtr(T* ptr)
{
Reset(ptr);
}
template<typename T>
NzSparsePtr<T>::NzSparsePtr(VoidPtr ptr, int stride)
{
Reset(ptr, stride);
}
template<typename T>
SparsePtr<T>::SparsePtr(VoidPtr ptr, int stride)
{
Reset(ptr, stride);
}
template<typename T>
template<typename U>
NzSparsePtr<T>::NzSparsePtr(const NzSparsePtr<U>& ptr)
{
Reset(ptr);
}
template<typename T>
template<typename U>
SparsePtr<T>::SparsePtr(const SparsePtr<U>& ptr)
{
Reset(ptr);
}
template<typename T>
typename NzSparsePtr<T>::VoidPtr NzSparsePtr<T>::GetPtr() const
{
return m_ptr;
}
template<typename T>
typename SparsePtr<T>::VoidPtr SparsePtr<T>::GetPtr() const
{
return m_ptr;
}
template<typename T>
int NzSparsePtr<T>::GetStride() const
{
return m_stride;
}
template<typename T>
int SparsePtr<T>::GetStride() const
{
return m_stride;
}
template<typename T>
void NzSparsePtr<T>::Reset()
{
SetPtr(nullptr);
SetStride(0);
}
template<typename T>
void SparsePtr<T>::Reset()
{
SetPtr(nullptr);
SetStride(0);
}
template<typename T>
void NzSparsePtr<T>::Reset(T* ptr)
{
SetPtr(ptr);
SetStride(sizeof(T));
}
template<typename T>
void SparsePtr<T>::Reset(T* ptr)
{
SetPtr(ptr);
SetStride(sizeof(T));
}
template<typename T>
void NzSparsePtr<T>::Reset(VoidPtr ptr, int stride)
{
SetPtr(ptr);
SetStride(stride);
}
template<typename T>
void SparsePtr<T>::Reset(VoidPtr ptr, int stride)
{
SetPtr(ptr);
SetStride(stride);
}
template<typename T>
void NzSparsePtr<T>::Reset(const NzSparsePtr& ptr)
{
SetPtr(ptr.GetPtr());
SetStride(ptr.GetStride());
}
template<typename T>
void SparsePtr<T>::Reset(const SparsePtr& ptr)
{
SetPtr(ptr.GetPtr());
SetStride(ptr.GetStride());
}
template<typename T>
template<typename U>
void NzSparsePtr<T>::Reset(const NzSparsePtr<U>& ptr)
{
static_assert(std::is_convertible<U*, T*>::value, "Source type pointer cannot be implicitely converted to target type pointer");
template<typename T>
template<typename U>
void SparsePtr<T>::Reset(const SparsePtr<U>& ptr)
{
static_assert(std::is_convertible<U*, T*>::value, "Source type pointer cannot be implicitely converted to target type pointer");
SetPtr(static_cast<T*>(ptr.GetPtr()));
SetStride(ptr.GetStride());
}
SetPtr(static_cast<T*>(ptr.GetPtr()));
SetStride(ptr.GetStride());
}
template<typename T>
void NzSparsePtr<T>::SetPtr(VoidPtr ptr)
{
m_ptr = reinterpret_cast<BytePtr>(ptr);
}
template<typename T>
void SparsePtr<T>::SetPtr(VoidPtr ptr)
{
m_ptr = reinterpret_cast<BytePtr>(ptr);
}
template<typename T>
void NzSparsePtr<T>::SetStride(int stride)
{
m_stride = stride;
}
template<typename T>
void SparsePtr<T>::SetStride(int stride)
{
m_stride = stride;
}
template<typename T>
NzSparsePtr<T>::operator bool() const
{
return m_ptr != nullptr;
}
template<typename T>
SparsePtr<T>::operator bool() const
{
return m_ptr != nullptr;
}
template<typename T>
NzSparsePtr<T>::operator T*() const
{
return reinterpret_cast<T*>(m_ptr);
}
template<typename T>
SparsePtr<T>::operator T*() const
{
return reinterpret_cast<T*>(m_ptr);
}
template<typename T>
T& NzSparsePtr<T>::operator*() const
{
return *reinterpret_cast<T*>(m_ptr);
}
template<typename T>
T& SparsePtr<T>::operator*() const
{
return *reinterpret_cast<T*>(m_ptr);
}
template<typename T>
T* NzSparsePtr<T>::operator->() const
{
return reinterpret_cast<T*>(m_ptr);
}
template<typename T>
T* SparsePtr<T>::operator->() const
{
return reinterpret_cast<T*>(m_ptr);
}
template<typename T>
T& NzSparsePtr<T>::operator[](int index) const
{
return *reinterpret_cast<T*>(m_ptr + index*m_stride);
}
template<typename T>
T& SparsePtr<T>::operator[](int index) const
{
return *reinterpret_cast<T*>(m_ptr + index*m_stride);
}
template<typename T>
NzSparsePtr<T> NzSparsePtr<T>::operator+(int count) const
{
return NzSparsePtr(m_ptr + count*m_stride, m_stride);
}
template<typename T>
SparsePtr<T> SparsePtr<T>::operator+(int count) const
{
return SparsePtr(m_ptr + count*m_stride, m_stride);
}
template<typename T>
NzSparsePtr<T> NzSparsePtr<T>::operator+(unsigned int count) const
{
return NzSparsePtr(m_ptr + count*m_stride, m_stride);
}
template<typename T>
SparsePtr<T> SparsePtr<T>::operator+(unsigned int count) const
{
return SparsePtr(m_ptr + count*m_stride, m_stride);
}
template<typename T>
NzSparsePtr<T> NzSparsePtr<T>::operator-(int count) const
{
return NzSparsePtr(m_ptr - count*m_stride, m_stride);
}
template<typename T>
SparsePtr<T> SparsePtr<T>::operator-(int count) const
{
return SparsePtr(m_ptr - count*m_stride, m_stride);
}
template<typename T>
NzSparsePtr<T> NzSparsePtr<T>::operator-(unsigned int count) const
{
return NzSparsePtr(m_ptr - count*m_stride, m_stride);
}
template<typename T>
SparsePtr<T> SparsePtr<T>::operator-(unsigned int count) const
{
return SparsePtr(m_ptr - count*m_stride, m_stride);
}
template<typename T>
std::ptrdiff_t NzSparsePtr<T>::operator-(const NzSparsePtr& ptr) const
{
return (m_ptr - ptr.m_ptr)/m_stride;
}
template<typename T>
std::ptrdiff_t SparsePtr<T>::operator-(const SparsePtr& ptr) const
{
return (m_ptr - ptr.m_ptr)/m_stride;
}
template<typename T>
NzSparsePtr<T>& NzSparsePtr<T>::operator+=(int count)
{
m_ptr += count*m_stride;
template<typename T>
SparsePtr<T>& SparsePtr<T>::operator+=(int count)
{
m_ptr += count*m_stride;
return *this;
}
return *this;
}
template<typename T>
NzSparsePtr<T>& NzSparsePtr<T>::operator-=(int count)
{
m_ptr -= count*m_stride;
template<typename T>
SparsePtr<T>& SparsePtr<T>::operator-=(int count)
{
m_ptr -= count*m_stride;
return *this;
}
return *this;
}
template<typename T>
NzSparsePtr<T>& NzSparsePtr<T>::operator++()
{
m_ptr += m_stride;
template<typename T>
SparsePtr<T>& SparsePtr<T>::operator++()
{
m_ptr += m_stride;
return *this;
}
return *this;
}
template<typename T>
NzSparsePtr<T> NzSparsePtr<T>::operator++(int)
{
// On fait une copie de l'objet
NzSparsePtr tmp(*this);
template<typename T>
SparsePtr<T> SparsePtr<T>::operator++(int)
{
// On fait une copie de l'objet
SparsePtr tmp(*this);
// On modifie l'objet
operator++();
// On modifie l'objet
operator++();
// On retourne la copie
return tmp;
}
// On retourne la copie
return tmp;
}
template<typename T>
NzSparsePtr<T>& NzSparsePtr<T>::operator--()
{
m_ptr -= m_stride;
return *this;
}
template<typename T>
SparsePtr<T>& SparsePtr<T>::operator--()
{
m_ptr -= m_stride;
return *this;
}
template<typename T>
NzSparsePtr<T> NzSparsePtr<T>::operator--(int)
{
// On fait une copie de l'objet
NzSparsePtr tmp(*this);
template<typename T>
SparsePtr<T> SparsePtr<T>::operator--(int)
{
// On fait une copie de l'objet
SparsePtr tmp(*this);
// On modifie l'objet
operator--();
// On modifie l'objet
operator--();
// On retourne la copie
return tmp;
}
// On retourne la copie
return tmp;
}
template<typename T>
bool NzSparsePtr<T>::operator==(const NzSparsePtr& ptr) const
{
return m_ptr == ptr.m_ptr;
}
template<typename T>
bool SparsePtr<T>::operator==(const SparsePtr& ptr) const
{
return m_ptr == ptr.m_ptr;
}
template<typename T>
bool NzSparsePtr<T>::operator!=(const NzSparsePtr& ptr) const
{
return m_ptr != ptr.m_ptr;
}
template<typename T>
bool SparsePtr<T>::operator!=(const SparsePtr& ptr) const
{
return m_ptr != ptr.m_ptr;
}
template<typename T>
bool NzSparsePtr<T>::operator<(const NzSparsePtr& ptr) const
{
return m_ptr < ptr.m_ptr;
}
template<typename T>
bool SparsePtr<T>::operator<(const SparsePtr& ptr) const
{
return m_ptr < ptr.m_ptr;
}
template<typename T>
bool NzSparsePtr<T>::operator>(const NzSparsePtr& ptr) const
{
return m_ptr > ptr.m_ptr;
}
template<typename T>
bool SparsePtr<T>::operator>(const SparsePtr& ptr) const
{
return m_ptr > ptr.m_ptr;
}
template<typename T>
bool NzSparsePtr<T>::operator<=(const NzSparsePtr& ptr) const
{
return m_ptr <= ptr.m_ptr;
}
template<typename T>
bool SparsePtr<T>::operator<=(const SparsePtr& ptr) const
{
return m_ptr <= ptr.m_ptr;
}
template<typename T>
bool NzSparsePtr<T>::operator>=(const NzSparsePtr& ptr) const
{
return m_ptr >= ptr.m_ptr;
template<typename T>
bool SparsePtr<T>::operator>=(const SparsePtr& ptr) const
{
return m_ptr >= ptr.m_ptr;
}
}
namespace std
{
template<typename T>
struct iterator_traits<NzSparsePtr<T>>
struct iterator_traits<Nz::SparsePtr<T>>
{
using difference_type = ptrdiff_t;
using iterator_category = random_access_iterator_tag;

View File

@@ -0,0 +1,35 @@
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#pragma once
#ifndef NAZARA_STDLOGGER_HPP
#define NAZARA_STDLOGGER_HPP
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/AbstractLogger.hpp>
namespace Nz
{
class NAZARA_CORE_API StdLogger : public AbstractLogger
{
public:
StdLogger() = default;
StdLogger(const StdLogger&) = default;
StdLogger(StdLogger&&) = default;
~StdLogger();
void EnableStdReplication(bool enable) override;
bool IsStdReplicationEnabled() override;
void Write(const String& string) override;
void WriteError(ErrorType type, const String& error, unsigned int line = 0, const char* file = nullptr, const char* function = nullptr) override;
StdLogger& operator=(const StdLogger&) = default;
StdLogger& operator=(StdLogger&&) = default;
};
}
#endif // NAZARA_STDLOGGER_HPP

View File

@@ -8,25 +8,64 @@
#define NAZARA_STREAM_HPP
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/Endianness.hpp>
#include <Nazara/Core/Enums.hpp>
#include <Nazara/Core/String.hpp>
class NAZARA_CORE_API NzStream
namespace Nz
{
public:
NzStream() = default;
virtual ~NzStream();
class ByteArray;
class String; //< Do not include String.hpp in this file
virtual nzUInt64 GetCursorPos() const = 0;
virtual NzString GetDirectory() const;
virtual NzString GetPath() const;
unsigned int GetStreamOptions() const;
class NAZARA_CORE_API Stream
{
public:
Stream(const Stream&) = default;
Stream(Stream&&) = default;
virtual ~Stream();
virtual bool SetCursorPos(nzUInt64 offset) = 0;
void SetStreamOptions(unsigned int options);
virtual bool EndOfStream() const = 0;
protected:
unsigned int m_streamOptions = 0;
};
inline void EnableTextMode(bool textMode);
inline void Flush();
virtual UInt64 GetCursorPos() const = 0;
virtual String GetDirectory() const;
virtual String GetPath() const;
inline UInt32 GetOpenMode() const;
inline UInt32 GetStreamOptions() const;
virtual UInt64 GetSize() const = 0;
inline std::size_t Read(void* buffer, std::size_t size);
virtual String ReadLine(unsigned int lineSize = 0);
inline bool IsReadable() const;
inline bool IsSequential() const;
inline bool IsTextModeEnabled() const;
inline bool IsWritable() const;
virtual bool SetCursorPos(UInt64 offset) = 0;
bool Write(const ByteArray& byteArray);
bool Write(const String& string);
inline std::size_t Write(const void* buffer, std::size_t size);
Stream& operator=(const Stream&) = default;
Stream& operator=(Stream&&) = default;
protected:
inline Stream(UInt32 streamOptions = StreamOption_None, UInt32 openMode = OpenMode_NotOpen);
virtual void FlushStream() = 0;
virtual std::size_t ReadBlock(void* buffer, std::size_t size) = 0;
virtual std::size_t WriteBlock(const void* buffer, std::size_t size) = 0;
UInt32 m_openMode;
UInt32 m_streamOptions;
};
}
#include <Nazara/Core/Stream.inl>
#endif // NAZARA_STREAM_HPP

View File

@@ -0,0 +1,74 @@
// Copyright (C) 2015 Jérôme Leclercq
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Core/Error.hpp>
#include "Stream.hpp"
namespace Nz
{
inline Stream::Stream(UInt32 streamOptions, UInt32 openMode) :
m_openMode(openMode),
m_streamOptions(streamOptions)
{
}
inline void Stream::EnableTextMode(bool textMode)
{
if (textMode)
m_streamOptions |= StreamOption_Text;
else
m_streamOptions &= ~StreamOption_Text;
}
inline void Stream::Flush()
{
NazaraAssert(IsWritable(), "Stream is not writable");
FlushStream();
}
inline UInt32 Stream::GetOpenMode() const
{
return m_openMode;
}
inline UInt32 Stream::GetStreamOptions() const
{
return m_streamOptions;
}
inline bool Stream::IsReadable() const
{
return (m_openMode & OpenMode_ReadOnly) != 0;
}
inline bool Stream::IsSequential() const
{
return (m_streamOptions & StreamOption_Sequential) != 0;
}
inline bool Stream::IsTextModeEnabled() const
{
return (m_streamOptions & StreamOption_Text) != 0;
}
inline bool Stream::IsWritable() const
{
return (m_openMode & OpenMode_WriteOnly) != 0;
}
inline std::size_t Stream::Read(void* buffer, std::size_t size)
{
NazaraAssert(IsReadable(), "Stream is not readable");
return ReadBlock(buffer, size);
}
inline std::size_t Stream::Write(const void* buffer, std::size_t size)
{
NazaraAssert(IsWritable(), "Stream is not writable");
return WriteBlock(buffer, size);
}
}

View File

@@ -8,325 +8,335 @@
#define NAZARA_STRING_HPP
#include <Nazara/Prerequesites.hpp>
#include <Nazara/Core/Hashable.hpp>
#include <Nazara/Core/Endianness.hpp>
#include <Nazara/Core/Serialization.hpp>
#include <atomic>
#include <iosfwd>
#include <memory>
#include <string>
#include <vector>
class NzAbstractHash;
class NzHashDigest;
class NAZARA_CORE_API NzString : public NzHashable
namespace Nz
{
public:
enum Flags
{
None = 0x00, // Mode par défaut
CaseInsensitive = 0x01, // Insensible à la casse
HandleUtf8 = 0x02, // Traite les octets comme une suite de caractères UTF-8
TrimOnlyLeft = 0x04, // Trim(med), ne coupe que la partie gauche de la chaîne
TrimOnlyRight = 0x08 // Trim(med), ne coupe que la partie droite de la chaîne
};
class NAZARA_CORE_API String
{
public:
enum Flags
{
None = 0x00, // Mode par défaut
CaseInsensitive = 0x01, // Insensible à la casse
HandleUtf8 = 0x02, // Traite les octets comme une suite de caractères UTF-8
TrimOnlyLeft = 0x04, // Trim(med), ne coupe que la partie gauche de la chaîne
TrimOnlyRight = 0x08 // Trim(med), ne coupe que la partie droite de la chaîne
};
NzString();
explicit NzString(char character);
NzString(unsigned int rep, char character);
NzString(unsigned int rep, const char* string);
NzString(unsigned int rep, const char* string, unsigned int length);
NzString(unsigned int rep, const NzString& string);
NzString(const char* string);
NzString(const char* string, unsigned int length);
NzString(const std::string& string);
NzString(const NzString& string) = default;
NzString(NzString&& string) noexcept = default;
~NzString() = default;
String();
explicit String(char character);
String(std::size_t rep, char character);
String(std::size_t rep, const char* string);
String(std::size_t rep, const char* string, std::size_t length);
String(std::size_t rep, const String& string);
String(const char* string);
String(const char* string, std::size_t length);
String(const std::string& string);
String(const String& string) = default;
String(String&& string) noexcept = default;
~String() = default;
NzString& Append(char character);
NzString& Append(const char* string);
NzString& Append(const char* string, unsigned int length);
NzString& Append(const NzString& string);
String& Append(char character);
String& Append(const char* string);
String& Append(const char* string, std::size_t length);
String& Append(const String& string);
void Clear(bool keepBuffer = false);
void Clear(bool keepBuffer = false);
bool Contains(char character, int start = 0, nzUInt32 flags = None) const;
bool Contains(const char* string, int start = 0, nzUInt32 flags = None) const;
bool Contains(const NzString& string, int start = 0, nzUInt32 flags = None) const;
bool Contains(char character, std::intmax_t start = 0, UInt32 flags = None) const;
bool Contains(const char* string, std::intmax_t start = 0, UInt32 flags = None) const;
bool Contains(const String& string, std::intmax_t start = 0, UInt32 flags = None) const;
unsigned int Count(char character, int start = 0, nzUInt32 flags = None) const;
unsigned int Count(const char* string, int start = 0, nzUInt32 flags = None) const;
unsigned int Count(const NzString& string, int start = 0, nzUInt32 flags = None) const;
unsigned int CountAny(const char* string, int start = 0, nzUInt32 flags = None) const;
unsigned int CountAny(const NzString& string, int start = 0, nzUInt32 flags = None) const;
unsigned int Count(char character, std::intmax_t start = 0, UInt32 flags = None) const;
unsigned int Count(const char* string, std::intmax_t start = 0, UInt32 flags = None) const;
unsigned int Count(const String& string, std::intmax_t start = 0, UInt32 flags = None) const;
unsigned int CountAny(const char* string, std::intmax_t start = 0, UInt32 flags = None) const;
unsigned int CountAny(const String& string, std::intmax_t start = 0, UInt32 flags = None) const;
bool EndsWith(char character, nzUInt32 flags = None) const;
bool EndsWith(const char* string, nzUInt32 flags = None) const;
bool EndsWith(const char* string, unsigned int length, nzUInt32 flags = None) const;
bool EndsWith(const NzString& string, nzUInt32 flags = None) const;
bool EndsWith(char character, UInt32 flags = None) const;
bool EndsWith(const char* string, UInt32 flags = None) const;
bool EndsWith(const char* string, std::size_t length, UInt32 flags = None) const;
bool EndsWith(const String& string, UInt32 flags = None) const;
unsigned int Find(char character, int start = 0, nzUInt32 flags = None) const;
unsigned int Find(const char* string, int start = 0, nzUInt32 flags = None) const;
unsigned int Find(const NzString& string, int start = 0, nzUInt32 flags = None) const;
unsigned int FindAny(const char* string, int start = 0, nzUInt32 flags = None) const;
unsigned int FindAny(const NzString& string, int start = 0, nzUInt32 flags = None) const;
unsigned int FindLast(char character, int start = -1, nzUInt32 flags = None) const;
unsigned int FindLast(const char *string, int start = -1, nzUInt32 flags = None) const;
unsigned int FindLast(const NzString& string, int start = -1, nzUInt32 flags = None) const;
unsigned int FindLastAny(const char* string, int start = -1, nzUInt32 flags = None) const;
unsigned int FindLastAny(const NzString& string, int start = -1, nzUInt32 flags = None) const;
unsigned int FindLastWord(const char* string, int start = -1, nzUInt32 flags = None) const;
unsigned int FindLastWord(const NzString& string, int start = -1, nzUInt32 flags = None) const;
unsigned int FindWord(const char* string, int start = 0, nzUInt32 flags = None) const;
unsigned int FindWord(const NzString& string, int start = 0, nzUInt32 flags = None) const;
std::size_t Find(char character, std::intmax_t start = 0, UInt32 flags = None) const;
std::size_t Find(const char* string, std::intmax_t start = 0, UInt32 flags = None) const;
std::size_t Find(const String& string, std::intmax_t start = 0, UInt32 flags = None) const;
std::size_t FindAny(const char* string, std::intmax_t start = 0, UInt32 flags = None) const;
std::size_t FindAny(const String& string, std::intmax_t start = 0, UInt32 flags = None) const;
std::size_t FindLast(char character, std::intmax_t start = -1, UInt32 flags = None) const;
std::size_t FindLast(const char *string, std::intmax_t start = -1, UInt32 flags = None) const;
std::size_t FindLast(const String& string, std::intmax_t start = -1, UInt32 flags = None) const;
std::size_t FindLastAny(const char* string, std::intmax_t start = -1, UInt32 flags = None) const;
std::size_t FindLastAny(const String& string, std::intmax_t start = -1, UInt32 flags = None) const;
std::size_t FindLastWord(const char* string, std::intmax_t start = -1, UInt32 flags = None) const;
std::size_t FindLastWord(const String& string, std::intmax_t start = -1, UInt32 flags = None) const;
std::size_t FindWord(const char* string, std::intmax_t start = 0, UInt32 flags = None) const;
std::size_t FindWord(const String& string, std::intmax_t start = 0, UInt32 flags = None) const;
char* GetBuffer();
unsigned int GetCapacity() const;
const char* GetConstBuffer() const;
unsigned int GetLength() const;
unsigned int GetSize() const;
std::string GetUtf8String() const;
std::u16string GetUtf16String() const;
std::u32string GetUtf32String() const;
std::wstring GetWideString() const;
NzString GetWord(unsigned int index, nzUInt32 flags = None) const;
unsigned int GetWordPosition(unsigned int index, nzUInt32 flags = None) const;
char* GetBuffer();
std::size_t GetCapacity() const;
const char* GetConstBuffer() const;
std::size_t GetLength() const;
std::size_t GetSize() const;
std::string GetUtf8String() const;
std::u16string GetUtf16String() const;
std::u32string GetUtf32String() const;
std::wstring GetWideString() const;
String GetWord(unsigned int index, UInt32 flags = None) const;
std::size_t GetWordPosition(unsigned int index, UInt32 flags = None) const;
NzString& Insert(int pos, char character);
NzString& Insert(int pos, const char* string);
NzString& Insert(int pos, const char* string, unsigned int length);
NzString& Insert(int pos, const NzString& string);
String& Insert(std::intmax_t pos, char character);
String& Insert(std::intmax_t pos, const char* string);
String& Insert(std::intmax_t pos, const char* string, std::size_t length);
String& Insert(std::intmax_t pos, const String& string);
bool IsEmpty() const;
bool IsNull() const;
bool IsNumber(nzUInt8 radix = 10, nzUInt32 flags = CaseInsensitive) const;
bool IsEmpty() const;
bool IsNull() const;
bool IsNumber(UInt8 radix = 10, UInt32 flags = CaseInsensitive) const;
bool Match(const char* pattern) const;
bool Match(const NzString& pattern) const;
bool Match(const char* pattern) const;
bool Match(const String& pattern) const;
NzString& Prepend(char character);
NzString& Prepend(const char* string);
NzString& Prepend(const char* string, unsigned int length);
NzString& Prepend(const NzString& string);
String& Prepend(char character);
String& Prepend(const char* string);
String& Prepend(const char* string, std::size_t length);
String& Prepend(const String& string);
unsigned int Replace(char oldCharacter, char newCharacter, int start = 0, nzUInt32 flags = None);
unsigned int Replace(const char* oldString, const char* replaceString, int start = 0, nzUInt32 flags = None);
unsigned int Replace(const char* oldString, unsigned int oldLength, const char* replaceString, unsigned int replaceLength, int start = 0, nzUInt32 flags = None);
unsigned int Replace(const NzString& oldString, const NzString& replaceString, int start = 0, nzUInt32 flags = None);
unsigned int ReplaceAny(const char* oldCharacters, char replaceCharacter, int start = 0, nzUInt32 flags = None);
//unsigned int ReplaceAny(const char* oldCharacters, const char* replaceString, int start = 0, nzUInt32 flags = None);
//unsigned int ReplaceAny(const NzString& oldCharacters, const NzString& replaceString, int start = 0, nzUInt32 flags = None);
unsigned int Replace(char oldCharacter, char newCharacter, std::intmax_t start = 0, UInt32 flags = None);
unsigned int Replace(const char* oldString, const char* replaceString, std::intmax_t start = 0, UInt32 flags = None);
unsigned int Replace(const char* oldString, std::size_t oldLength, const char* replaceString, std::size_t replaceLength, std::intmax_t start = 0, UInt32 flags = None);
unsigned int Replace(const String& oldString, const String& replaceString, std::intmax_t start = 0, UInt32 flags = None);
unsigned int ReplaceAny(const char* oldCharacters, char replaceCharacter, std::intmax_t start = 0, UInt32 flags = None);
//unsigned int ReplaceAny(const char* oldCharacters, const char* replaceString, std::intmax_t start = 0, UInt32 flags = None);
//unsigned int ReplaceAny(const String& oldCharacters, const String& replaceString, std::intmax_t start = 0, UInt32 flags = None);
void Reserve(unsigned int bufferSize);
void Reserve(std::size_t bufferSize);
NzString& Resize(int size, char character = ' ');
NzString Resized(int size, char character = ' ') const;
String& Resize(std::intmax_t size, char character = ' ');
String Resized(std::intmax_t size, char character = ' ') const;
NzString& Reverse();
NzString Reversed() const;
String& Reverse();
String Reversed() const;
NzString& Set(char character);
NzString& Set(unsigned int rep, char character);
NzString& Set(unsigned int rep, const char* string);
NzString& Set(unsigned int rep, const char* string, unsigned int length);
NzString& Set(unsigned int rep, const NzString& string);
NzString& Set(const char* string);
NzString& Set(const char* string, unsigned int length);
NzString& Set(const std::string& string);
NzString& Set(const NzString& string);
NzString& Set(NzString&& string) noexcept;
String& Set(char character);
String& Set(std::size_t rep, char character);
String& Set(std::size_t rep, const char* string);
String& Set(std::size_t rep, const char* string, std::size_t length);
String& Set(std::size_t rep, const String& string);
String& Set(const char* string);
String& Set(const char* string, std::size_t length);
String& Set(const std::string& string);
String& Set(const String& string);
String& Set(String&& string) noexcept;
NzString Simplified(nzUInt32 flags = None) const;
NzString& Simplify(nzUInt32 flags = None);
String Simplified(UInt32 flags = None) const;
String& Simplify(UInt32 flags = None);
unsigned int Split(std::vector<NzString>& result, char separation = ' ', int start = 0, nzUInt32 flags = None) const;
unsigned int Split(std::vector<NzString>& result, const char* separation, int start = 0, nzUInt32 flags = None) const;
unsigned int Split(std::vector<NzString>& result, const char* separation, unsigned int length, int start = 0, nzUInt32 flags = None) const;
unsigned int Split(std::vector<NzString>& result, const NzString& separation, int start = 0, nzUInt32 flags = None) const;
unsigned int SplitAny(std::vector<NzString>& result, const char* separations, int start = 0, nzUInt32 flags = None) const;
unsigned int SplitAny(std::vector<NzString>& result, const NzString& separations, int start = 0, nzUInt32 flags = None) const;
unsigned int Split(std::vector<String>& result, char separation = ' ', std::intmax_t start = 0, UInt32 flags = None) const;
unsigned int Split(std::vector<String>& result, const char* separation, std::intmax_t start = 0, UInt32 flags = None) const;
unsigned int Split(std::vector<String>& result, const char* separation, std::size_t length, std::intmax_t start = 0, UInt32 flags = None) const;
unsigned int Split(std::vector<String>& result, const String& separation, std::intmax_t start = 0, UInt32 flags = None) const;
unsigned int SplitAny(std::vector<String>& result, const char* separations, std::intmax_t start = 0, UInt32 flags = None) const;
unsigned int SplitAny(std::vector<String>& result, const String& separations, std::intmax_t start = 0, UInt32 flags = None) const;
bool StartsWith(char character, nzUInt32 flags = None) const;
bool StartsWith(const char* string, nzUInt32 flags = None) const;
bool StartsWith(const NzString& string, nzUInt32 flags = None) const;
bool StartsWith(char character, UInt32 flags = None) const;
bool StartsWith(const char* string, UInt32 flags = None) const;
bool StartsWith(const String& string, UInt32 flags = None) const;
NzString SubString(int startPos, int endPos = -1) const;
NzString SubStringFrom(char character, int startPos = 0, bool fromLast = false, bool include = false, nzUInt32 flags = None) const;
NzString SubStringFrom(const char *string, int startPos = 0, bool fromLast = false, bool include = false, nzUInt32 flags = None) const;
NzString SubStringFrom(const char *string, unsigned int length, int startPos = 0, bool fromLast = false, bool include = false, nzUInt32 flags = None) const;
NzString SubStringFrom(const NzString& string, int startPos = 0, bool fromLast = false, bool include = false, nzUInt32 flags = None) const;
NzString SubStringTo(char character, int startPos = 0, bool toLast = false, bool include = false, nzUInt32 flags = None) const;
NzString SubStringTo(const char *string, int startPos = 0, bool toLast = false, bool include = false, nzUInt32 flags = None) const;
NzString SubStringTo(const char *string, unsigned int length, int startPos = 0, bool toLast = false, bool include = false, nzUInt32 flags = None) const;
NzString SubStringTo(const NzString& string, int startPos = 0, bool toLast = false, bool include = false, nzUInt32 flags = None) const;
String SubString(std::intmax_t startPos, std::intmax_t endPos = -1) const;
String SubStringFrom(char character, std::intmax_t startPos = 0, bool fromLast = false, bool include = false, UInt32 flags = None) const;
String SubStringFrom(const char* string, std::intmax_t startPos = 0, bool fromLast = false, bool include = false, UInt32 flags = None) const;
String SubStringFrom(const char* string, std::size_t length, std::intmax_t startPos = 0, bool fromLast = false, bool include = false, UInt32 flags = None) const;
String SubStringFrom(const String& string, std::intmax_t startPos = 0, bool fromLast = false, bool include = false, UInt32 flags = None) const;
String SubStringTo(char character, std::intmax_t startPos = 0, bool toLast = false, bool include = false, UInt32 flags = None) const;
String SubStringTo(const char* string, std::intmax_t startPos = 0, bool toLast = false, bool include = false, UInt32 flags = None) const;
String SubStringTo(const char* string, std::size_t length, std::intmax_t startPos = 0, bool toLast = false, bool include = false, UInt32 flags = None) const;
String SubStringTo(const String& string, std::intmax_t startPos = 0, bool toLast = false, bool include = false, UInt32 flags = None) const;
void Swap(NzString& str);
void Swap(String& str);
bool ToBool(bool* value, nzUInt32 flags = None) const;
bool ToDouble(double* value) const;
bool ToInteger(long long* value, nzUInt8 radix = 10) const;
NzString ToLower(nzUInt32 flags = None) const;
NzString ToUpper(nzUInt32 flags = None) const;
bool ToBool(bool* value, UInt32 flags = None) const;
bool ToDouble(double* value) const;
bool ToInteger(long long* value, UInt8 radix = 10) const;
String ToLower(UInt32 flags = None) const;
String ToUpper(UInt32 flags = None) const;
NzString& Trim(nzUInt32 flags = None);
NzString& Trim(char character, nzUInt32 flags = None);
NzString Trimmed(nzUInt32 flags = None) const;
NzString Trimmed(char character, nzUInt32 flags = None) const;
String& Trim(UInt32 flags = None);
String& Trim(char character, UInt32 flags = None);
String Trimmed(UInt32 flags = None) const;
String Trimmed(char character, UInt32 flags = None) const;
// Méthodes STD
char* begin();
const char* begin() const;
char* end();
const char* end() const;
void push_front(char c);
void push_back(char c);
//char* rbegin();
//const char* rbegin() const;
//char* rend();
//const char* rend() const;
// Méthodes STD
char* begin();
const char* begin() const;
char* end();
const char* end() const;
void push_front(char c);
void push_back(char c);
//char* rbegin();
//const char* rbegin() const;
//char* rend();
//const char* rend() const;
typedef const char& const_reference;
typedef char* iterator;
//typedef char* reverse_iterator;
typedef char value_type;
// Méthodes STD
typedef const char& const_reference;
typedef char* iterator;
//typedef char* reverse_iterator;
typedef char value_type;
// Méthodes STD
operator std::string() const;
operator std::string() const;
char& operator[](unsigned int pos);
char operator[](unsigned int pos) const;
char& operator[](std::size_t pos);
char operator[](std::size_t pos) const;
NzString& operator=(char character);
NzString& operator=(const char* string);
NzString& operator=(const std::string& string);
NzString& operator=(const NzString& string);
NzString& operator=(NzString&& string) noexcept;
String& operator=(char character);
String& operator=(const char* string);
String& operator=(const std::string& string);
String& operator=(const String& string);
String& operator=(String&& string) noexcept;
NzString operator+(char character) const;
NzString operator+(const char* string) const;
NzString operator+(const std::string& string) const;
NzString operator+(const NzString& string) const;
String operator+(char character) const;
String operator+(const char* string) const;
String operator+(const std::string& string) const;
String operator+(const String& string) const;
NzString& operator+=(char character);
NzString& operator+=(const char* string);
NzString& operator+=(const std::string& string);
NzString& operator+=(const NzString& string);
String& operator+=(char character);
String& operator+=(const char* string);
String& operator+=(const std::string& string);
String& operator+=(const String& string);
bool operator==(char character) const;
bool operator==(const char* string) const;
bool operator==(const std::string& string) const;
bool operator==(char character) const;
bool operator==(const char* string) const;
bool operator==(const std::string& string) const;
bool operator!=(char character) const;
bool operator!=(const char* string) const;
bool operator!=(const std::string& string) const;
bool operator!=(char character) const;
bool operator!=(const char* string) const;
bool operator!=(const std::string& string) const;
bool operator<(char character) const;
bool operator<(const char* string) const;
bool operator<(const std::string& string) const;
bool operator<(char character) const;
bool operator<(const char* string) const;
bool operator<(const std::string& string) const;
bool operator<=(char character) const;
bool operator<=(const char* string) const;
bool operator<=(const std::string& string) const;
bool operator<=(char character) const;
bool operator<=(const char* string) const;
bool operator<=(const std::string& string) const;
bool operator>(char character) const;
bool operator>(const char* string) const;
bool operator>(const std::string& string) const;
bool operator>(char character) const;
bool operator>(const char* string) const;
bool operator>(const std::string& string) const;
bool operator>=(char character) const;
bool operator>=(const char* string) const;
bool operator>=(const std::string& string) const;
bool operator>=(char character) const;
bool operator>=(const char* string) const;
bool operator>=(const std::string& string) const;
static NzString Boolean(bool boolean);
static int Compare(const NzString& first, const NzString& second);
static NzString Number(float number);
static NzString Number(double number);
static NzString Number(long double number);
static NzString Number(signed char number, nzUInt8 radix = 10);
static NzString Number(unsigned char number, nzUInt8 radix = 10);
static NzString Number(short number, nzUInt8 radix = 10);
static NzString Number(unsigned short number, nzUInt8 radix = 10);
static NzString Number(int number, nzUInt8 radix = 10);
static NzString Number(unsigned int number, nzUInt8 radix = 10);
static NzString Number(long number, nzUInt8 radix = 10);
static NzString Number(unsigned long number, nzUInt8 radix = 10);
static NzString Number(long long number, nzUInt8 radix = 10);
static NzString Number(unsigned long long number, nzUInt8 radix = 10);
static NzString Pointer(const void* ptr);
static NzString Unicode(char32_t character);
static NzString Unicode(const char* u8String);
static NzString Unicode(const char16_t* u16String);
static NzString Unicode(const char32_t* u32String);
static NzString Unicode(const wchar_t* wString);
static String Boolean(bool boolean);
static int Compare(const String& first, const String& second);
static String Number(float number);
static String Number(double number);
static String Number(long double number);
static String Number(signed char number, UInt8 radix = 10);
static String Number(unsigned char number, UInt8 radix = 10);
static String Number(short number, UInt8 radix = 10);
static String Number(unsigned short number, UInt8 radix = 10);
static String Number(int number, UInt8 radix = 10);
static String Number(unsigned int number, UInt8 radix = 10);
static String Number(long number, UInt8 radix = 10);
static String Number(unsigned long number, UInt8 radix = 10);
static String Number(long long number, UInt8 radix = 10);
static String Number(unsigned long long number, UInt8 radix = 10);
static String Pointer(const void* ptr);
static String Unicode(char32_t character);
static String Unicode(const char* u8String);
static String Unicode(const char16_t* u16String);
static String Unicode(const char32_t* u32String);
static String Unicode(const wchar_t* wString);
NAZARA_CORE_API friend std::istream& operator>>(std::istream& in, NzString& string);
NAZARA_CORE_API friend std::ostream& operator<<(std::ostream& out, const NzString& string);
NAZARA_CORE_API friend std::istream& operator>>(std::istream& in, String& string);
NAZARA_CORE_API friend std::ostream& operator<<(std::ostream& out, const String& string);
NAZARA_CORE_API friend NzString operator+(char character, const NzString& string);
NAZARA_CORE_API friend NzString operator+(const char* string, const NzString& nstring);
NAZARA_CORE_API friend NzString operator+(const std::string& string, const NzString& nstring);
NAZARA_CORE_API friend String operator+(char character, const String& string);
NAZARA_CORE_API friend String operator+(const char* string, const String& nstring);
NAZARA_CORE_API friend String operator+(const std::string& string, const String& nstring);
NAZARA_CORE_API friend bool operator==(const NzString& first, const NzString& second);
NAZARA_CORE_API friend bool operator!=(const NzString& first, const NzString& second);
NAZARA_CORE_API friend bool operator<(const NzString& first, const NzString& second);
NAZARA_CORE_API friend bool operator<=(const NzString& first, const NzString& second);
NAZARA_CORE_API friend bool operator>(const NzString& first, const NzString& second);
NAZARA_CORE_API friend bool operator>=(const NzString& first, const NzString& second);
NAZARA_CORE_API friend bool operator==(const String& first, const String& second);
NAZARA_CORE_API friend bool operator!=(const String& first, const String& second);
NAZARA_CORE_API friend bool operator<(const String& first, const String& second);
NAZARA_CORE_API friend bool operator<=(const String& first, const String& second);
NAZARA_CORE_API friend bool operator>(const String& first, const String& second);
NAZARA_CORE_API friend bool operator>=(const String& first, const String& second);
NAZARA_CORE_API friend bool operator==(char character, const NzString& nstring);
NAZARA_CORE_API friend bool operator==(const char* string, const NzString& nstring);
NAZARA_CORE_API friend bool operator==(const std::string& string, const NzString& nstring);
NAZARA_CORE_API friend bool operator==(char character, const String& nstring);
NAZARA_CORE_API friend bool operator==(const char* string, const String& nstring);
NAZARA_CORE_API friend bool operator==(const std::string& string, const String& nstring);
NAZARA_CORE_API friend bool operator!=(char character, const NzString& nstring);
NAZARA_CORE_API friend bool operator!=(const char* string, const NzString& nstring);
NAZARA_CORE_API friend bool operator!=(const std::string& string, const NzString& nstring);
NAZARA_CORE_API friend bool operator!=(char character, const String& nstring);
NAZARA_CORE_API friend bool operator!=(const char* string, const String& nstring);
NAZARA_CORE_API friend bool operator!=(const std::string& string, const String& nstring);
NAZARA_CORE_API friend bool operator<(char character, const NzString& nstring);
NAZARA_CORE_API friend bool operator<(const char* string, const NzString& nstring);
NAZARA_CORE_API friend bool operator<(const std::string& string, const NzString& nstring);
NAZARA_CORE_API friend bool operator<(char character, const String& nstring);
NAZARA_CORE_API friend bool operator<(const char* string, const String& nstring);
NAZARA_CORE_API friend bool operator<(const std::string& string, const String& nstring);
NAZARA_CORE_API friend bool operator<=(char character, const NzString& nstring);
NAZARA_CORE_API friend bool operator<=(const char* string, const NzString& nstring);
NAZARA_CORE_API friend bool operator<=(const std::string& string, const NzString& nstring);
NAZARA_CORE_API friend bool operator<=(char character, const String& nstring);
NAZARA_CORE_API friend bool operator<=(const char* string, const String& nstring);
NAZARA_CORE_API friend bool operator<=(const std::string& string, const String& nstring);
NAZARA_CORE_API friend bool operator>(char character, const NzString& nstring);
NAZARA_CORE_API friend bool operator>(const char* string, const NzString& nstring);
NAZARA_CORE_API friend bool operator>(const std::string& string, const NzString& nstring);
NAZARA_CORE_API friend bool operator>(char character, const String& nstring);
NAZARA_CORE_API friend bool operator>(const char* string, const String& nstring);
NAZARA_CORE_API friend bool operator>(const std::string& string, const String& nstring);
NAZARA_CORE_API friend bool operator>=(char character, const NzString& nstring);
NAZARA_CORE_API friend bool operator>=(const char* string, const NzString& nstring);
NAZARA_CORE_API friend bool operator>=(const std::string& string, const NzString& nstring);
NAZARA_CORE_API friend bool operator>=(char character, const String& nstring);
NAZARA_CORE_API friend bool operator>=(const char* string, const String& nstring);
NAZARA_CORE_API friend bool operator>=(const std::string& string, const String& nstring);
static const unsigned int npos;
static const std::size_t npos;
private:
struct SharedString;
private:
struct SharedString;
NzString(std::shared_ptr<SharedString>&& sharedString);
String(std::shared_ptr<SharedString>&& sharedString);
void EnsureOwnership(bool discardContent = false);
bool FillHash(NzAbstractHash* hash) const;
inline void ReleaseString();
void EnsureOwnership(bool discardContent = false);
inline void ReleaseString();
static const std::shared_ptr<SharedString>& GetEmptyString();
static const std::shared_ptr<SharedString>& GetEmptyString();
std::shared_ptr<SharedString> m_sharedString;
std::shared_ptr<SharedString> m_sharedString;
struct SharedString
{
inline SharedString();
inline SharedString(unsigned int strSize);
struct SharedString
{
inline SharedString();
inline SharedString(std::size_t strSize);
inline SharedString(std::size_t strSize, std::size_t strCapacity);
unsigned int capacity;
unsigned int size;
std::unique_ptr<char[]> string;
};
};
std::size_t capacity;
std::size_t size;
std::unique_ptr<char[]> string;
};
};
class AbstractHash;
inline bool HashAppend(AbstractHash* hash, const String& string);
NAZARA_CORE_API bool Serialize(SerializationContext& context, const String& string);
NAZARA_CORE_API bool Unserialize(UnserializationContext& context, String* string);
}
namespace std
{
NAZARA_CORE_API istream& getline(istream& is, NzString& str);
NAZARA_CORE_API istream& getline(istream& is, NzString& str, char delim);
NAZARA_CORE_API void swap(NzString& lhs, NzString& rhs);
NAZARA_CORE_API istream& getline(istream& is, Nz::String& str);
NAZARA_CORE_API istream& getline(istream& is, Nz::String& str, char delim);
NAZARA_CORE_API void swap(Nz::String& lhs, Nz::String& rhs);
template<>
struct hash<Nz::String>;
}
#include <Nazara/Core/String.inl>

View File

@@ -2,39 +2,56 @@
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Core/AbstractHash.hpp>
#include <Nazara/Core/Debug.hpp>
inline NzString::NzString(std::shared_ptr<SharedString>&& sharedString) :
m_sharedString(std::move(sharedString))
namespace Nz
{
}
inline String::String(std::shared_ptr<SharedString>&& sharedString) :
m_sharedString(std::move(sharedString))
{
}
inline void NzString::ReleaseString()
{
m_sharedString = std::move(GetEmptyString());
}
inline void String::ReleaseString()
{
m_sharedString = std::move(GetEmptyString());
}
inline NzString::SharedString::SharedString() : // Special case: empty string
capacity(0),
size(0)
{
}
inline String::SharedString::SharedString() : // Special case: empty string
capacity(0),
size(0)
{
}
inline NzString::SharedString::SharedString(unsigned int strSize) :
capacity(strSize),
size(strSize),
string(new char[strSize + 1])
{
string[strSize] = '\0';
}
inline String::SharedString::SharedString(std::size_t strSize) :
capacity(strSize),
size(strSize),
string(new char[strSize + 1])
{
string[strSize] = '\0';
}
inline String::SharedString::SharedString(std::size_t strSize, std::size_t strCapacity) :
capacity(strCapacity),
size(strSize),
string(new char[strCapacity + 1])
{
string[strSize] = '\0';
}
inline bool HashAppend(AbstractHash* hash, const String& string)
{
hash->Append(reinterpret_cast<const UInt8*>(string.GetConstBuffer()), string.GetSize());
return true;
}
}
namespace std
{
template<>
struct hash<NzString>
struct hash<Nz::String>
{
size_t operator()(const NzString& str) const
size_t operator()(const Nz::String& str) const
{
// Algorithme DJB2
// http://www.cse.yorku.ca/~oz/hash.html

Some files were not shown because too many files have changed in this diff Show More