Big f***ing cleanup part 1

This commit is contained in:
Lynix 2020-02-23 00:42:22 +01:00
parent 67d0e0a689
commit 3d22321109
178 changed files with 2190 additions and 5113 deletions

View File

@ -8,7 +8,6 @@
#define NDK_LUABINDING_CORE_HPP
#include <Nazara/Core/Clock.hpp>
#include <Nazara/Core/Directory.hpp>
#include <Nazara/Core/File.hpp>
#include <Nazara/Core/Stream.hpp>
#include <NDK/Lua/LuaBinding_Base.hpp>
@ -24,7 +23,6 @@ namespace Ndk
void Register(Nz::LuaState& state) override;
Nz::LuaClass<Nz::Clock> clock;
Nz::LuaClass<Nz::Directory> directory;
Nz::LuaClass<Nz::File> file;
Nz::LuaClass<Nz::Stream> stream;
};

View File

@ -385,7 +385,7 @@ namespace Nz
params->loadHeightMap = state.CheckField<bool>("LoadHeightMap", params->loadHeightMap);
params->loadNormalMap = state.CheckField<bool>("LoadNormalMap", params->loadNormalMap);
params->loadSpecularMap = state.CheckField<bool>("LoadSpecularMap", params->loadSpecularMap);
params->shaderName = state.CheckField<String>("ShaderName", params->shaderName);
params->shaderName = state.CheckField<std::string>("ShaderName", params->shaderName);
return 1;
}

View File

@ -80,7 +80,7 @@ namespace Ndk
music.BindMethod("__tostring", [] (Nz::LuaState& lua, Nz::Music& instance, std::size_t /*argumentCount*/) -> int
{
Nz::StringStream ss("Music(");
ss << instance.GetFilePath() << ')';
ss << instance.GetFilePath().generic_u8string() << ')';
lua.PushString(ss);
return 1;
@ -169,9 +169,9 @@ namespace Ndk
Nz::StringStream ss("SoundBuffer(");
if (instance->IsValid())
{
Nz::String filePath = instance->GetFilePath();
if (!filePath.IsEmpty())
ss << "File: " << filePath << ", ";
std::filesystem::path filePath = instance->GetFilePath();
if (!filePath.empty())
ss << "File: " << filePath.generic_u8string() << ", ";
ss << "Duration: " << instance->GetDuration() / 1000.f << "s";
}

View File

@ -115,60 +115,6 @@ namespace Ndk
});
}
/********************************* Nz::Directory ********************************/
directory.Reset("Directory");
{
directory.SetConstructor([] (Nz::LuaState& lua, Nz::Directory* instance, std::size_t argumentCount)
{
std::size_t argCount = std::min<std::size_t>(argumentCount, 1U);
int argIndex = 2;
switch (argCount)
{
case 0:
Nz::PlacementNew(instance);
return true;
case 1:
Nz::PlacementNew(instance, lua.Check<Nz::String>(&argIndex));
return true;
}
return false;
});
directory.BindMethod("Close", &Nz::Directory::Close);
directory.BindMethod("Exists", &Nz::Directory::Exists);
directory.BindMethod("GetPath", &Nz::Directory::GetPath);
directory.BindMethod("GetPattern", &Nz::Directory::GetPattern);
directory.BindMethod("GetResultName", &Nz::Directory::GetResultName);
directory.BindMethod("GetResultPath", &Nz::Directory::GetResultPath);
directory.BindMethod("GetResultSize", &Nz::Directory::GetResultSize);
directory.BindMethod("IsOpen", &Nz::Directory::IsOpen);
directory.BindMethod("IsResultDirectory", &Nz::Directory::IsResultDirectory);
directory.BindMethod("NextResult", &Nz::Directory::NextResult, true);
directory.BindMethod("Open", &Nz::Directory::Open);
directory.BindMethod("SetPath", &Nz::Directory::SetPath);
directory.BindMethod("SetPattern", &Nz::Directory::SetPattern);
directory.BindStaticMethod("Copy", Nz::Directory::Copy);
directory.BindStaticMethod("Create", Nz::Directory::Create);
directory.BindStaticMethod("Exists", Nz::Directory::Exists);
directory.BindStaticMethod("GetCurrent", Nz::Directory::GetCurrent);
directory.BindStaticMethod("Remove", Nz::Directory::Remove);
directory.BindStaticMethod("SetCurrent", Nz::Directory::SetCurrent);
// Manual
directory.BindMethod("__tostring", [] (Nz::LuaState& lua, Nz::Directory& instance, std::size_t /*argumentCount*/) -> int {
Nz::StringStream ss("Directory(");
ss << instance.GetPath();
ss << ')';
lua.PushString(ss);
return 1;
});
}
/*********************************** Nz::File ***********************************/
file.Reset("File");
{
@ -187,7 +133,7 @@ namespace Ndk
case 1:
{
Nz::String filePath = lua.Check<Nz::String>(&argIndex);
std::string filePath = lua.Check<std::string>(&argIndex);
Nz::PlacementNew(instance, filePath);
return true;
@ -195,7 +141,7 @@ namespace Ndk
case 2:
{
Nz::String filePath = lua.Check<Nz::String>(&argIndex);
std::string filePath = lua.Check<std::string>(&argIndex);
Nz::UInt32 openMode = lua.Check<Nz::UInt32>(&argIndex);
Nz::PlacementNew(instance, filePath, openMode);
@ -212,29 +158,8 @@ namespace Ndk
file.BindMethod("Delete", &Nz::File::Delete);
file.BindMethod("EndOfFile", &Nz::File::EndOfFile);
file.BindMethod("Exists", &Nz::File::Exists);
file.BindMethod("GetCreationTime", &Nz::File::GetCreationTime);
file.BindMethod("GetFileName", &Nz::File::GetFileName);
file.BindMethod("GetLastAccessTime", &Nz::File::GetLastAccessTime);
file.BindMethod("GetLastWriteTime", &Nz::File::GetLastWriteTime);
file.BindMethod("IsOpen", &Nz::File::IsOpen);
file.BindMethod("Rename", &Nz::File::GetLastWriteTime);
file.BindMethod("GetLastWriteTime", &Nz::File::GetLastWriteTime);
file.BindMethod("SetFile", &Nz::File::GetLastWriteTime);
file.BindStaticMethod("AbsolutePath", &Nz::File::AbsolutePath);
file.BindStaticMethod("ComputeHash", (Nz::ByteArray(*)(Nz::HashType, const Nz::String&)) &Nz::File::ComputeHash);
file.BindStaticMethod("Copy", &Nz::File::Copy);
file.BindStaticMethod("Delete", &Nz::File::Delete);
file.BindStaticMethod("Exists", &Nz::File::Exists);
//fileClass.SetStaticMethod("GetCreationTime", &Nz::File::GetCreationTime);
file.BindStaticMethod("GetDirectory", &Nz::File::GetDirectory);
//fileClass.SetStaticMethod("GetLastAccessTime", &Nz::File::GetLastAccessTime);
//fileClass.SetStaticMethod("GetLastWriteTime", &Nz::File::GetLastWriteTime);
file.BindStaticMethod("GetSize", &Nz::File::GetSize);
file.BindStaticMethod("IsAbsolute", &Nz::File::IsAbsolute);
file.BindStaticMethod("NormalizePath", &Nz::File::NormalizePath);
file.BindStaticMethod("NormalizeSeparators", &Nz::File::NormalizeSeparators);
file.BindStaticMethod("Rename", &Nz::File::Rename);
// Manual
file.BindMethod("Open", [] (Nz::LuaState& lua, Nz::File& instance, std::size_t argumentCount) -> int
@ -250,7 +175,7 @@ namespace Ndk
case 2:
{
Nz::String filePath = lua.Check<Nz::String>(&argIndex);
std::string filePath = lua.Check<std::string>(&argIndex);
Nz::UInt32 openMode = lua.Check<Nz::UInt32>(&argIndex, Nz::OpenMode_NotOpen);
return lua.Push(instance.Open(filePath, openMode));
}
@ -285,7 +210,7 @@ namespace Ndk
file.BindMethod("__tostring", [] (Nz::LuaState& lua, Nz::File& instance, std::size_t /*argumentCount*/) -> int {
Nz::StringStream ss("File(");
if (instance.IsOpen())
ss << "Path: " << instance.GetPath();
ss << "Path: " << instance.GetPath().generic_u8string();
ss << ')';
@ -304,7 +229,6 @@ namespace Ndk
{
// Classes
clock.Register(state);
directory.Register(state);
file.Register(state);
stream.Register(state);

View File

@ -94,7 +94,7 @@ namespace Ndk
}
else
{
Nz::PlacementNew(instance, Nz::Material::New(lua.Check<Nz::String>(&argIndex)));
Nz::PlacementNew(instance, Nz::Material::New(lua.Check<std::string>(&argIndex)));
return true;
}
}
@ -114,7 +114,7 @@ namespace Ndk
}
else
{
lua.Push(instance->Configure(lua.Check<Nz::String>(&argIndex)));
lua.Push(instance->Configure(lua.Check<std::string>(&argIndex)));
return 1;
}
});
@ -214,7 +214,7 @@ namespace Ndk
return 0;
}
else
return lua.Push(instance->SetAlphaMap(lua.Check<Nz::String>(&argIndex)));
return lua.Push(instance->SetAlphaMap(lua.Check<std::string>(&argIndex)));
});
material.BindMethod("SetDiffuseMap", [] (Nz::LuaState& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
@ -226,7 +226,7 @@ namespace Ndk
return 0;
}
else
return lua.Push(instance->SetDiffuseMap(lua.Check<Nz::String>(&argIndex)));
return lua.Push(instance->SetDiffuseMap(lua.Check<std::string>(&argIndex)));
});
material.BindMethod("SetEmissiveMap", [] (Nz::LuaState& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
@ -238,7 +238,7 @@ namespace Ndk
return 0;
}
else
return lua.Push(instance->SetEmissiveMap(lua.Check<Nz::String>(&argIndex)));
return lua.Push(instance->SetEmissiveMap(lua.Check<std::string>(&argIndex)));
});
material.BindMethod("SetHeightMap", [] (Nz::LuaState& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
@ -250,7 +250,7 @@ namespace Ndk
return 0;
}
else
return lua.Push(instance->SetHeightMap(lua.Check<Nz::String>(&argIndex)));
return lua.Push(instance->SetHeightMap(lua.Check<std::string>(&argIndex)));
});
material.BindMethod("SetNormalMap", [] (Nz::LuaState& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
@ -262,7 +262,7 @@ namespace Ndk
return 0;
}
else
return lua.Push(instance->SetNormalMap(lua.Check<Nz::String>(&argIndex)));
return lua.Push(instance->SetNormalMap(lua.Check<std::string>(&argIndex)));
});
material.BindMethod("SetShader", [] (Nz::LuaState& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
@ -274,7 +274,7 @@ namespace Ndk
return 0;
}
else
return lua.Push(instance->SetShader(lua.Check<Nz::String>(&argIndex)));
return lua.Push(instance->SetShader(lua.Check<std::string>(&argIndex)));
});
material.BindMethod("SetSpecularMap", [] (Nz::LuaState& lua, Nz::MaterialRef& instance, std::size_t /*argumentCount*/) -> int
@ -286,7 +286,7 @@ namespace Ndk
return 0;
}
else
return lua.Push(instance->SetSpecularMap(lua.Check<Nz::String>(&argIndex)));
return lua.Push(instance->SetSpecularMap(lua.Check<std::string>(&argIndex)));
});
}
@ -326,7 +326,7 @@ namespace Ndk
}
else if (lua.IsOfType(argIndex, Nz::LuaType_String))
{
Nz::String subMesh(lua.Check<Nz::String>(&argIndex));
std::string subMesh(lua.Check<std::string>(&argIndex));
Nz::MaterialRef mat(lua.Check<Nz::MaterialRef>(&argIndex));
instance->SetMaterial(subMesh, std::move(mat));
@ -351,7 +351,7 @@ namespace Ndk
else if (lua.IsOfType(argIndex, Nz::LuaType_String))
{
std::size_t skinIndex(lua.Check<std::size_t>(&argIndex));
Nz::String subMesh(lua.Check<Nz::String>(&argIndex));
std::string subMesh(lua.Check<std::string>(&argIndex));
Nz::MaterialRef materialRef(lua.Check<Nz::MaterialRef>(&argIndex));
instance->SetMaterial(skinIndex, subMesh, std::move(materialRef));
@ -423,7 +423,7 @@ namespace Ndk
if (lua.IsOfType(argIndex, "Material"))
instance->SetMaterial(skinIndex, *static_cast<Nz::MaterialRef*>(lua.ToUserdata(argIndex)), resizeSprite);
else
instance->SetMaterial(skinIndex, lua.Check<Nz::String>(&argIndex), resizeSprite);
instance->SetMaterial(skinIndex, lua.Check<std::string>(&argIndex), resizeSprite);
}
return 0;
@ -452,7 +452,7 @@ namespace Ndk
if (lua.IsOfType(argIndex, "Texture"))
instance->SetTexture(skinIndex, *static_cast<Nz::TextureRef*>(lua.ToUserdata(argIndex)), resizeSprite);
else
instance->SetTexture(skinIndex, lua.Check<Nz::String>(&argIndex), resizeSprite);
instance->SetTexture(skinIndex, lua.Check<std::string>(&argIndex), resizeSprite);
}
return 0;

View File

@ -10,10 +10,10 @@
#include <Nazara/Audio.hpp>
#include <Nazara/Core/Clock.hpp>
#include <Nazara/Core/Thread.hpp> // Thread::Sleep
#include <Nazara/Math/Vector3.hpp>
#include <Nazara/Platform/Keyboard.hpp>
#include <Nazara/Platform/Platform.hpp>
#include <chrono>
#include <iostream>
int main()
@ -61,7 +61,7 @@ int main()
int sleepTime = int(1000/60 - clock.GetMilliseconds()); // 60 FPS
if (sleepTime > 0)
Nz::Thread::Sleep(sleepTime);
std::this_thread::sleep_for(std::chrono::milliseconds(sleepTime));
// On bouge la source du son en fonction du temps depuis chaque mise à jour
Nz::Vector3f pos = sound.GetPosition() + sound.GetVelocity()*clock.GetSeconds();

View File

@ -1,4 +1,3 @@
#include <Nazara/Core/Directory.hpp>
#include <Nazara/Core/File.hpp>
#include <Nazara/Math/Box.hpp>
#include <Nazara/Utility/Animation.hpp>
@ -26,25 +25,17 @@ int main()
for (;;)
{
Nz::Directory resourceDirectory("resources");
if (!resourceDirectory.Open())
std::vector<std::filesystem::path> models;
for (auto& p : std::filesystem::directory_iterator("resources"))
{
std::cerr << "Failed to open resource directory" << std::endl;
std::getchar();
return EXIT_FAILURE;
}
if (!p.is_regular_file())
continue;
std::vector<Nz::String> models;
while (resourceDirectory.NextResult())
{
Nz::String path = resourceDirectory.GetResultName();
Nz::String ext = path.SubStringFrom('.', -1, true); // Tout ce qui vient après le dernier '.' de la chaîne
if (Nz::MeshLoader::IsExtensionSupported(ext)) // L'extension est-elle supportée par le MeshLoader ?
models.push_back(path);
const std::filesystem::path& filePath = p.path();
if (Nz::MeshLoader::IsExtensionSupported(filePath.extension().generic_u8string())) // L'extension est-elle supportée par le MeshLoader ?
models.push_back(filePath);
}
resourceDirectory.Close();
if (models.empty())
{
std::cout << "No loadable mesh found in resource directory" << std::endl;
@ -71,7 +62,7 @@ int main()
if (iChoice == 0)
break;
Nz::MeshRef mesh = Nz::Mesh::LoadFromFile(resourceDirectory.GetPath() + '/' + models[iChoice-1]);
Nz::MeshRef mesh = Nz::Mesh::LoadFromFile(models[iChoice-1]);
if (!mesh)
{
std::cout << "Failed to load mesh" << std::endl;
@ -123,8 +114,8 @@ int main()
}
}
Nz::String animationPath = mesh->GetAnimation();
if (!animationPath.IsEmpty())
std::filesystem::path animationPath = mesh->GetAnimation();
if (!animationPath.empty())
{
Nz::AnimationRef animation = Nz::Animation::LoadFromFile(animationPath);
if (animation)

View File

@ -173,7 +173,7 @@ int main()
window.CopyToImage(&screenshot);
static unsigned int counter = 1;
screenshot.SaveToFile("screenshot_" + Nz::String::Number(counter++) + ".png");
screenshot.SaveToFile("screenshot_" + std::to_string(counter++) + ".png");
break;
}

View File

@ -39,7 +39,7 @@ namespace Nz
bool IsLooping() const override;
bool OpenFromFile(const String& filePath, const SoundStreamParams& params = SoundStreamParams());
bool OpenFromFile(const std::filesystem::path& filePath, const SoundStreamParams& params = SoundStreamParams());
bool OpenFromMemory(const void* data, std::size_t size, const SoundStreamParams& params = SoundStreamParams());
bool OpenFromStream(Stream& stream, const SoundStreamParams& params = SoundStreamParams());

View File

@ -34,7 +34,7 @@ namespace Nz
bool IsPlayable() const;
bool IsPlaying() const;
bool LoadFromFile(const String& filePath, const SoundBufferParams& params = SoundBufferParams());
bool LoadFromFile(const std::filesystem::path& 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());

View File

@ -71,7 +71,7 @@ namespace Nz
static bool IsFormatSupported(AudioFormat format);
static SoundBufferRef LoadFromFile(const String& filePath, const SoundBufferParams& params = SoundBufferParams());
static SoundBufferRef LoadFromFile(const std::filesystem::path& filePath, const SoundBufferParams& params = SoundBufferParams());
static SoundBufferRef LoadFromMemory(const void* data, std::size_t size, const SoundBufferParams& params = SoundBufferParams());
static SoundBufferRef LoadFromStream(Stream& stream, const SoundBufferParams& params = SoundBufferParams());

View File

@ -14,6 +14,7 @@
#include <Nazara/Core/Resource.hpp>
#include <Nazara/Core/ResourceLoader.hpp>
#include <Nazara/Core/ResourceParameters.hpp>
#include <mutex>
namespace Nz
{
@ -40,7 +41,7 @@ namespace Nz
virtual UInt32 GetDuration() const = 0;
virtual AudioFormat GetFormat() const = 0;
virtual Mutex& GetMutex() = 0;
virtual std::mutex& GetMutex() = 0;
virtual UInt64 GetSampleCount() const = 0;
virtual UInt32 GetSampleRate() const = 0;
@ -48,7 +49,7 @@ namespace Nz
virtual void Seek(UInt64 offset) = 0;
virtual UInt64 Tell() = 0;
static SoundStreamRef OpenFromFile(const String& filePath, const SoundStreamParams& params = SoundStreamParams());
static SoundStreamRef OpenFromFile(const std::filesystem::path& filePath, const SoundStreamParams& params = SoundStreamParams());
static SoundStreamRef OpenFromMemory(const void* data, std::size_t size, const SoundStreamParams& params = SoundStreamParams());
static SoundStreamRef OpenFromStream(Stream& stream, const SoundStreamParams& params = SoundStreamParams());

View File

@ -34,14 +34,13 @@
#include <Nazara/Core/Algorithm.hpp>
#include <Nazara/Core/Bitset.hpp>
#include <Nazara/Core/ByteArray.hpp>
#include <Nazara/Core/ByteArrayPool.hpp>
#include <Nazara/Core/ByteStream.hpp>
#include <Nazara/Core/CallOnExit.hpp>
#include <Nazara/Core/Clock.hpp>
#include <Nazara/Core/Color.hpp>
#include <Nazara/Core/ConditionVariable.hpp>
#include <Nazara/Core/Config.hpp>
#include <Nazara/Core/Core.hpp>
#include <Nazara/Core/Directory.hpp>
#include <Nazara/Core/DynLib.hpp>
#include <Nazara/Core/EmptyStream.hpp>
#include <Nazara/Core/Endianness.hpp>
@ -56,7 +55,6 @@
#include <Nazara/Core/HandledObject.hpp>
#include <Nazara/Core/HardwareInfo.hpp>
#include <Nazara/Core/Initializer.hpp>
#include <Nazara/Core/LockGuard.hpp>
#include <Nazara/Core/Log.hpp>
#include <Nazara/Core/MemoryHelper.hpp>
#include <Nazara/Core/MemoryManager.hpp>
@ -64,13 +62,13 @@
#include <Nazara/Core/MemoryStream.hpp>
#include <Nazara/Core/MemoryView.hpp>
#include <Nazara/Core/MovablePtr.hpp>
#include <Nazara/Core/Mutex.hpp>
#include <Nazara/Core/ObjectHandle.hpp>
#include <Nazara/Core/ObjectLibrary.hpp>
#include <Nazara/Core/ObjectRef.hpp>
#include <Nazara/Core/OffsetOf.hpp>
#include <Nazara/Core/ParameterList.hpp>
#include <Nazara/Core/PluginManager.hpp>
#include <Nazara/Core/PoolByteStream.hpp>
#include <Nazara/Core/Primitive.hpp>
#include <Nazara/Core/PrimitiveList.hpp>
#include <Nazara/Core/RefCounted.hpp>
@ -79,7 +77,6 @@
#include <Nazara/Core/ResourceManager.hpp>
#include <Nazara/Core/ResourceParameters.hpp>
#include <Nazara/Core/ResourceSaver.hpp>
#include <Nazara/Core/Semaphore.hpp>
#include <Nazara/Core/SerializationContext.hpp>
#include <Nazara/Core/Signal.hpp>
#include <Nazara/Core/SparsePtr.hpp>
@ -88,9 +85,9 @@
#include <Nazara/Core/StdLogger.hpp>
#include <Nazara/Core/Stream.hpp>
#include <Nazara/Core/String.hpp>
#include <Nazara/Core/StringExt.hpp>
#include <Nazara/Core/StringStream.hpp>
#include <Nazara/Core/TaskScheduler.hpp>
#include <Nazara/Core/Thread.hpp>
#include <Nazara/Core/TypeTag.hpp>
#include <Nazara/Core/Unicode.hpp>
#include <Nazara/Core/Updatable.hpp>

View File

@ -31,6 +31,33 @@ namespace Nz
template<typename T> void HashCombine(std::size_t& seed, const T& v);
template<typename T> T ReverseBits(T integer);
template<typename T>
struct AlwaysFalse : std::false_type {};
template<typename... Args>
struct OverloadResolver
{
template<typename R, typename T>
constexpr auto operator()(R(T::* ptr)(Args...)) const noexcept
{
return ptr;
}
template<typename R, typename T>
constexpr auto operator()(R(T::* ptr)(Args...) const) const noexcept
{
return ptr;
}
template<typename R>
constexpr auto operator()(R(*ptr)(Args...)) const noexcept
{
return ptr;
}
};
template<typename... Args> constexpr OverloadResolver<Args...> Overload = {};
template<typename T>
struct PointedType
{

View File

@ -9,12 +9,6 @@
#include <Nazara/Prerequisites.hpp>
#if NAZARA_CORE_THREADSAFE && NAZARA_THREADSAFETY_CLOCK
#include <Nazara/Core/ThreadSafety.hpp>
#else
#include <Nazara/Core/ThreadSafetyOff.hpp>
#endif
namespace Nz
{
class NAZARA_CORE_API Clock
@ -39,8 +33,6 @@ namespace Nz
Clock& operator=(Clock&& clock) = default;
private:
NazaraMutexAttrib(m_mutex, mutable)
UInt64 m_elapsedTime;
UInt64 m_refTime;
bool m_paused;

View File

@ -1,42 +0,0 @@
// Copyright (C) 2017 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_CONDITIONVARIABLE_HPP
#define NAZARA_CONDITIONVARIABLE_HPP
#include <Nazara/Prerequisites.hpp>
#include <Nazara/Core/MovablePtr.hpp>
namespace Nz
{
class ConditionVariableImpl;
class Mutex;
class NAZARA_CORE_API ConditionVariable
{
public:
ConditionVariable();
ConditionVariable(const ConditionVariable&) = delete;
ConditionVariable(ConditionVariable&& condition) noexcept = default;
~ConditionVariable();
void Signal();
void SignalAll();
void Wait(Mutex* mutex);
bool Wait(Mutex* mutex, UInt32 timeout);
ConditionVariable& operator=(const ConditionVariable&) = delete;
ConditionVariable& operator=(ConditionVariable&& condition) noexcept = default;
private:
MovablePtr<ConditionVariableImpl> m_impl;
};
}
#include <Nazara/Core/ConditionVariable.inl>
#endif // NAZARA_CONDITIONVARIABLE_HPP

View File

@ -1,14 +0,0 @@
// Copyright (C) 2017 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/Debug.hpp>
namespace Nz
{
/*!
* \class Nz::ConditionVariable
*/
}
#include <Nazara/Core/DebugOff.hpp>

View File

@ -58,17 +58,6 @@
// Activate the security tests based on the code (Advised for development)
#define NAZARA_CORE_SAFE 1
// Protect the classes against data race
#define NAZARA_CORE_THREADSAFE 1
// Classes to protect against data race
#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
// Number of spinlocks to use with the Windows critical sections (0 to disable)
#define NAZARA_CORE_WINDOWS_CS_SPINLOCKS 4096

View File

@ -1,82 +0,0 @@
// Copyright (C) 2017 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_DIRECTORY_HPP
#define NAZARA_DIRECTORY_HPP
#include <Nazara/Prerequisites.hpp>
#include <Nazara/Core/MovablePtr.hpp>
#include <Nazara/Core/String.hpp>
#if defined(NAZARA_PLATFORM_WINDOWS)
#define NAZARA_DIRECTORY_SEPARATOR '\\'
#elif defined(NAZARA_PLATFORM_LINUX)
#define NAZARA_DIRECTORY_SEPARATOR '/'
#else
#error OS not handled
#define NAZARA_DIRECTORY_SEPARATOR '/'
#endif
#if NAZARA_CORE_THREADSAFE && NAZARA_THREADSAFETY_DIRECTORY
#include <Nazara/Core/ThreadSafety.hpp>
#else
#include <Nazara/Core/ThreadSafetyOff.hpp>
#endif
namespace Nz
{
class DirectoryImpl;
class NAZARA_CORE_API Directory
{
public:
Directory();
Directory(const String& dirPath);
Directory(const Directory&) = delete;
Directory(Directory&&) noexcept = default;
~Directory();
void Close();
bool Exists() const;
String GetPath() const;
String GetPattern() const;
String GetResultName() const;
String GetResultPath() const;
UInt64 GetResultSize() const;
bool IsOpen() const;
bool IsResultDirectory() const;
bool NextResult(bool skipDots = true);
bool Open();
void SetPath(const String& dirPath);
void SetPattern(const String& pattern);
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);
Directory& operator=(const Directory&) = delete;
Directory& operator=(Directory&&) noexcept = delete;
private:
NazaraMutexAttrib(m_mutex, mutable)
String m_dirPath;
String m_pattern;
MovablePtr<DirectoryImpl> m_impl;
};
}
#endif // NAZARA_DIRECTORY_HPP

View File

@ -9,7 +9,7 @@
#include <Nazara/Prerequisites.hpp>
#include <Nazara/Core/MovablePtr.hpp>
#include <Nazara/Core/String.hpp>
#include <filesystem>
#if defined(NAZARA_PLATFORM_WINDOWS)
#define NAZARA_DYNLIB_EXTENSION ".dll"
@ -21,12 +21,6 @@
#error OS not handled
#endif
#if NAZARA_CORE_THREADSAFE && NAZARA_THREADSAFETY_DYNLIB
#include <Nazara/Core/ThreadSafety.hpp>
#else
#include <Nazara/Core/ThreadSafetyOff.hpp>
#endif
namespace Nz
{
using DynLibFunc = int (*)(); // "Generic" type of pointer to function
@ -38,25 +32,23 @@ namespace Nz
public:
DynLib();
DynLib(const DynLib&) = delete;
DynLib(DynLib&&) noexcept = default;
DynLib(DynLib&&) noexcept;
~DynLib();
String GetLastError() const;
DynLibFunc GetSymbol(const String& symbol) const;
std::string GetLastError() const;
DynLibFunc GetSymbol(const char* symbol) const;
bool IsLoaded() const;
bool Load(const String& libraryPath);
bool Load(const std::filesystem::path& libraryPath);
void Unload();
DynLib& operator=(const DynLib&) = delete;
DynLib& operator=(DynLib&& lib) noexcept = default;
DynLib& operator=(DynLib&& lib) noexcept;
private:
NazaraMutexAttrib(m_mutex, mutable)
mutable String m_lastError;
MovablePtr<DynLibImpl> m_impl;
mutable std::string m_lastError;
std::unique_ptr<DynLibImpl> m_impl;
};
}

View File

@ -33,7 +33,7 @@ namespace Nz
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 std::string GetLastSystemError(unsigned int code = GetLastSystemErrorCode());
static void SetFlags(UInt32 flags);
@ -41,6 +41,8 @@ namespace Nz
static void Trigger(ErrorType type, const String& error, unsigned int line, const char* file, const char* function);
private:
static const char* GetCurrentFileRelativeToEngine(const char* file);
static UInt32 s_flags;
static String s_lastError;
static const char* s_lastErrorFunction;

View File

@ -13,14 +13,9 @@
#include <Nazara/Core/MovablePtr.hpp>
#include <Nazara/Core/Stream.hpp>
#include <Nazara/Core/String.hpp>
#if NAZARA_CORE_THREADSAFE && NAZARA_THREADSAFETY_FILE
#include <Nazara/Core/ThreadSafety.hpp>
#else
#include <Nazara/Core/ThreadSafetyOff.hpp>
#endif
#include <ctime>
#include <filesystem>
#include <fstream>
namespace Nz
{
@ -30,13 +25,13 @@ namespace Nz
{
public:
File();
File(const String& filePath);
File(const String& filePath, OpenModeFlags openMode);
File(const std::filesystem::path& filePath);
File(const std::filesystem::path& filePath, OpenModeFlags openMode);
File(const File&) = delete;
File(File&& file) noexcept = default;
File(File&& file) noexcept;
~File();
bool Copy(const String& newFilePath);
void Copy(const std::filesystem::path& newFilePath);
void Close();
bool Delete();
@ -46,56 +41,35 @@ namespace Nz
bool Exists() 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;
std::filesystem::path GetDirectory() const override;
std::filesystem::path GetFileName() const;
std::filesystem::path GetPath() const override;
UInt64 GetSize() const override;
bool IsOpen() const;
bool Open(OpenModeFlags openMode = OpenMode_NotOpen);
bool Open(const String& filePath, OpenModeFlags openMode = OpenMode_NotOpen);
bool Rename(const String& newFilePath);
bool Open(const std::filesystem::path& filePath, OpenModeFlags openMode = OpenMode_NotOpen);
bool SetCursorPos(CursorPosition pos, Int64 offset = 0);
bool SetCursorPos(UInt64 offset) override;
bool SetFile(const String& filePath);
bool SetFile(const std::filesystem::path& filePath);
bool SetSize(UInt64 size);
File& operator=(const String& filePath);
File& operator=(const File&) = delete;
File& operator=(File&& file) noexcept = default;
File& operator=(File&& 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 inline ByteArray ComputeHash(HashType hash, const std::filesystem::path& filePath);
static inline ByteArray ComputeHash(AbstractHash* hash, const std::filesystem::path& filePath);
private:
NazaraMutexAttrib(m_mutex, mutable)
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;
String m_filePath;
MovablePtr<FileImpl> m_impl;
std::filesystem::path m_filePath;
std::unique_ptr<FileImpl> m_impl;
};
NAZARA_CORE_API bool HashAppend(AbstractHash* hash, const File& originalFile);

View File

@ -15,7 +15,7 @@ namespace Nz
* \param filePath Path for the file
*/
inline ByteArray File::ComputeHash(HashType hash, const String& filePath)
inline ByteArray File::ComputeHash(HashType hash, const std::filesystem::path& filePath)
{
return ComputeHash(AbstractHash::Get(hash).get(), filePath);
}
@ -28,7 +28,7 @@ namespace Nz
* \param filePath Path for the file
*/
inline ByteArray File::ComputeHash(AbstractHash* hash, const String& filePath)
inline ByteArray File::ComputeHash(AbstractHash* hash, const std::filesystem::path& filePath)
{
return Nz::ComputeHash(hash, File(filePath));
}

View File

@ -9,8 +9,9 @@
#include <Nazara/Prerequisites.hpp>
#include <Nazara/Core/AbstractLogger.hpp>
#include <Nazara/Core/File.hpp>
#include <Nazara/Core/StdLogger.hpp>
#include <filesystem>
#include <fstream>
namespace Nz
{
@ -35,7 +36,8 @@ namespace Nz
FileLogger& operator=(FileLogger&&) noexcept = default;
private:
File m_outputFile;
std::fstream m_outputFile;
std::filesystem::path m_outputPath;
StdLogger m_stdLogger;
bool m_forceStdOutput;
bool m_stdReplicationEnabled;

View File

@ -1,34 +0,0 @@
// Copyright (C) 2017 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_LOCKGUARD_HPP
#define NAZARA_LOCKGUARD_HPP
#include <Nazara/Prerequisites.hpp>
namespace Nz
{
class Mutex;
class LockGuard
{
public:
inline LockGuard(Mutex& mutex, bool lock = true);
inline ~LockGuard();
inline void Lock();
inline bool TryLock();
inline void Unlock();
private:
Mutex& m_mutex;
bool m_locked;
};
}
#include <Nazara/Core/LockGuard.inl>
#endif // NAZARA_LOCKGUARD_HPP

View File

@ -1,83 +0,0 @@
// Copyright (C) 2017 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/LockGuard.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Core/Mutex.hpp>
#include <Nazara/Core/Debug.hpp>
namespace Nz
{
/*!
* \ingroup core
* \class Nz::LockGuard
* \brief Core class that represents a mutex wrapper that provides a convenient RAII-style mechanism
*/
/*!
* \brief Constructs a LockGuard object with a mutex
*
* \param mutex Mutex to lock
* \param lock Should the mutex be locked by the constructor
*/
inline LockGuard::LockGuard(Mutex& mutex, bool lock) :
m_mutex(mutex),
m_locked(false)
{
if (lock)
{
m_mutex.Lock();
m_locked = true;
}
}
/*!
* \brief Destructs a LockGuard object and unlocks the mutex if it was previously locked
*/
inline LockGuard::~LockGuard()
{
if (m_locked)
m_mutex.Unlock();
}
/*!
* \brief Locks the underlying mutex
*
* \see Mutex::Lock
*/
inline void LockGuard::Lock()
{
NazaraAssert(!m_locked, "Mutex is already locked");
m_mutex.Lock();
}
/*!
* \brief Tries to lock the underlying mutex
*
* \see Mutex::TryLock
*
* \return true if the lock was acquired successfully
*/
inline bool LockGuard::TryLock()
{
NazaraAssert(!m_locked, "Mutex is already locked");
return m_mutex.TryLock();
}
/*!
* \brief Unlocks the underlying mutex
*
* \see Mutex::Unlock
*/
inline void LockGuard::Unlock()
{
NazaraAssert(m_locked, "Mutex is not locked");
m_mutex.Unlock();
}
}
#include <Nazara/Core/DebugOff.hpp>

View File

@ -11,12 +11,6 @@
#include <Nazara/Core/Signal.hpp>
#include <Nazara/Core/String.hpp>
#if NAZARA_CORE_THREADSAFE && NAZARA_THREADSAFETY_LOG
#include <Nazara/Core/ThreadSafety.hpp>
#else
#include <Nazara/Core/ThreadSafetyOff.hpp>
#endif
#ifdef NAZARA_DEBUG
#define NazaraDebug(txt) NazaraNotice(txt)
#else

View File

@ -1,41 +0,0 @@
// Copyright (C) 2017 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_MUTEX_HPP
#define NAZARA_MUTEX_HPP
#include <Nazara/Prerequisites.hpp>
#include <Nazara/Core/MovablePtr.hpp>
namespace Nz
{
class MutexImpl;
class NAZARA_CORE_API Mutex
{
friend class ConditionVariable;
public:
Mutex();
Mutex(const Mutex&) = delete;
Mutex(Mutex&&) noexcept = default;
~Mutex();
void Lock();
bool TryLock();
void Unlock();
Mutex& operator=(const Mutex&) = delete;
Mutex& operator=(Mutex&&) noexcept = default;
private:
MovablePtr<MutexImpl> m_impl;
};
}
#include <Nazara/Core/Mutex.inl>
#endif // NAZARA_MUTEX_HPP

View File

@ -1,17 +0,0 @@
// Copyright (C) 2017 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/Mutex.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Core/Debug.hpp>
namespace Nz
{
/*!
* \ingroup core
* \class Nz::Mutex
*/
}
#include <Nazara/Core/DebugOff.hpp>

View File

@ -9,7 +9,7 @@
#include <Nazara/Prerequisites.hpp>
#include <Nazara/Core/Enums.hpp>
#include <Nazara/Core/String.hpp>
#include <filesystem>
#include <set>
#include <unordered_map>
@ -24,23 +24,32 @@ namespace Nz
PluginManager() = delete;
~PluginManager() = delete;
static void AddDirectory(const String& directoryPath);
static void AddDirectory(const std::filesystem::path& directoryPath);
static bool Initialize();
static bool Mount(Plugin plugin);
static bool Mount(const String& pluginPath, bool appendExtension = true);
static bool Mount(const std::filesystem::path& pluginPath, bool appendExtension = true);
static void RemoveDirectory(const String& directoryPath);
static void RemoveDirectory(const std::filesystem::path& directoryPath);
static void Unmount(Plugin plugin);
static void Unmount(const String& pluginPath);
static void Unmount(const std::filesystem::path& pluginPath);
static void Uninitialize();
private:
static std::set<String> s_directories;
static std::unordered_map<String, DynLib*> s_plugins;
// https://stackoverflow.com/questions/51065244/is-there-no-standard-hash-for-stdfilesystempath
struct PathHash
{
std::size_t operator()(const std::filesystem::path& p) const
{
return hash_value(p);
}
};
static std::set<std::filesystem::path> s_directories;
static std::unordered_map<std::filesystem::path, std::unique_ptr<DynLib>, PathHash> s_plugins;
static bool s_initialized;
};
}

View File

@ -10,12 +10,6 @@
#include <Nazara/Prerequisites.hpp>
#include <atomic>
#if NAZARA_CORE_THREADSAFE && NAZARA_THREADSAFETY_REFCOUNTED
#include <Nazara/Core/ThreadSafety.hpp>
#else
#include <Nazara/Core/ThreadSafetyOff.hpp>
#endif
namespace Nz
{
class NAZARA_CORE_API RefCounted

View File

@ -8,7 +8,7 @@
#define NAZARA_RESOURCE_HPP
#include <Nazara/Prerequisites.hpp>
#include <Nazara/Core/String.hpp>
#include <filesystem>
namespace Nz
{
@ -20,15 +20,15 @@ namespace Nz
Resource(Resource&&) noexcept = default;
virtual ~Resource();
const String& GetFilePath() const;
const std::filesystem::path& GetFilePath() const;
void SetFilePath(const String& filePath);
void SetFilePath(const std::filesystem::path& filePath);
Resource& operator=(const Resource&) = default;
Resource& operator=(Resource&&) noexcept = default;
private:
String m_filePath;
std::filesystem::path m_filePath;
};
}

View File

@ -12,7 +12,7 @@
#include <Nazara/Core/RefCounted.hpp>
#include <Nazara/Core/Resource.hpp>
#include <Nazara/Core/ResourceParameters.hpp>
#include <Nazara/Core/String.hpp>
#include <filesystem>
#include <list>
#include <tuple>
#include <type_traits>
@ -29,8 +29,8 @@ namespace Nz
friend Type;
public:
using ExtensionGetter = bool (*)(const String& extension);
using FileLoader = ObjectRef<Type> (*)(const String& filePath, const Parameters& parameters);
using ExtensionGetter = bool (*)(const std::string& extension);
using FileLoader = ObjectRef<Type> (*)(const std::filesystem::path& filePath, const Parameters& parameters);
using MemoryLoader = ObjectRef<Type> (*)(const void* data, std::size_t size, const Parameters& parameters);
using StreamChecker = Ternary (*)(Stream& stream, const Parameters& parameters);
using StreamLoader = ObjectRef<Type> (*)(Stream& stream, const Parameters& parameters);
@ -38,9 +38,9 @@ namespace Nz
ResourceLoader() = delete;
~ResourceLoader() = delete;
static bool IsExtensionSupported(const String& extension);
static bool IsExtensionSupported(const std::string& extension);
static ObjectRef<Type> LoadFromFile(const String& filePath, const Parameters& parameters = Parameters());
static ObjectRef<Type> LoadFromFile(const std::filesystem::path& filePath, const Parameters& parameters = Parameters());
static ObjectRef<Type> LoadFromMemory(const void* data, std::size_t size, const Parameters& parameters = Parameters());
static ObjectRef<Type> LoadFromStream(Stream& stream, const Parameters& parameters = Parameters());

View File

@ -7,6 +7,7 @@
#include <Nazara/Core/File.hpp>
#include <Nazara/Core/MemoryView.hpp>
#include <Nazara/Core/Stream.hpp>
#include <Nazara/Core/StringExt.hpp>
#include <Nazara/Core/Debug.hpp>
namespace Nz
@ -24,7 +25,7 @@ namespace Nz
* \param extension Extension of the file
*/
template<typename Type, typename Parameters>
bool ResourceLoader<Type, Parameters>::IsExtensionSupported(const String& extension)
bool ResourceLoader<Type, Parameters>::IsExtensionSupported(const std::string& extension)
{
for (Loader& loader : Type::s_loaders)
{
@ -53,19 +54,21 @@ namespace Nz
* \remark Produces a NazaraError if all loaders failed or no loader was found
*/
template<typename Type, typename Parameters>
ObjectRef<Type> ResourceLoader<Type, Parameters>::LoadFromFile(const String& filePath, const Parameters& parameters)
ObjectRef<Type> ResourceLoader<Type, Parameters>::LoadFromFile(const std::filesystem::path& filePath, const Parameters& parameters)
{
NazaraAssert(parameters.IsValid(), "Invalid parameters");
String path = File::NormalizePath(filePath);
String ext = path.SubStringFrom('.', -1, true).ToLower();
if (ext.IsEmpty())
std::string ext = ToLower(filePath.extension().generic_u8string());
if (ext.empty())
{
NazaraError("Failed to get file extension from \"" + filePath + '"');
NazaraError("Failed to get file extension from \"" + filePath.generic_u8string() + '"');
return nullptr;
}
File file(path); // Open only if needed
if (ext[0] == '.')
ext.erase(ext.begin());
File file(filePath.generic_u8string()); // Open only if needed
bool found = false;
for (Loader& loader : Type::s_loaders)
@ -82,7 +85,7 @@ namespace Nz
{
if (!file.Open(OpenMode_ReadOnly))
{
NazaraError("Failed to load file: unable to open \"" + filePath + '"');
NazaraError("Failed to load file: unable to open \"" + filePath.generic_u8string() + '"');
return nullptr;
}
}

View File

@ -25,19 +25,28 @@ namespace Nz
static void Clear();
static ObjectRef<Type> Get(const String& filePath);
static ObjectRef<Type> Get(const std::filesystem::path& filePath);
static const Parameters& GetDefaultParameters();
static void Purge();
static void Register(const String& filePath, ObjectRef<Type> resource);
static void Register(const std::filesystem::path& filePath, ObjectRef<Type> resource);
static void SetDefaultParameters(const Parameters& params);
static void Unregister(const String& filePath);
static void Unregister(const std::filesystem::path& filePath);
private:
static bool Initialize();
static void Uninitialize();
using ManagerMap = std::unordered_map<String, ObjectRef<Type>>;
// https://stackoverflow.com/questions/51065244/is-there-no-standard-hash-for-stdfilesystempath
struct PathHash
{
std::size_t operator()(const std::filesystem::path& p) const
{
return hash_value(p);
}
};
using ManagerMap = std::unordered_map<std::filesystem::path, ObjectRef<Type>, PathHash>;
using ManagerParams = Parameters;
};
}

View File

@ -31,20 +31,20 @@ namespace Nz
* \param filePath Path to the asset that will be loaded
*/
template<typename Type, typename Parameters>
ObjectRef<Type> ResourceManager<Type, Parameters>::Get(const String& filePath)
ObjectRef<Type> ResourceManager<Type, Parameters>::Get(const std::filesystem::path& filePath)
{
String absolutePath = File::AbsolutePath(filePath);
std::filesystem::path absolutePath = std::filesystem::canonical(filePath);
auto it = Type::s_managerMap.find(absolutePath);
if (it == Type::s_managerMap.end())
{
ObjectRef<Type> resource = Type::LoadFromFile(absolutePath, GetDefaultParameters());
if (!resource)
{
NazaraError("Failed to load resource from file: " + absolutePath);
NazaraError("Failed to load resource from file: " + absolutePath.generic_u8string());
return ObjectRef<Type>();
}
NazaraDebug("Loaded resource from file " + absolutePath);
NazaraDebug("Loaded resource from file " + absolutePath.generic_u8string());
it = Type::s_managerMap.insert(std::make_pair(absolutePath, resource)).first;
}
@ -74,7 +74,7 @@ namespace Nz
const ObjectRef<Type>& ref = it->second;
if (ref->GetReferenceCount() == 1) // Are we the only ones to own the resource ?
{
NazaraDebug("Purging resource from file " + ref->GetFilePath());
NazaraDebug("Purging resource from file " + ref->GetFilePath().generic_u8string());
Type::s_managerMap.erase(it++); // Then we erase it
}
else
@ -89,9 +89,9 @@ namespace Nz
* \param resource Object to associate with
*/
template<typename Type, typename Parameters>
void ResourceManager<Type, Parameters>::Register(const String& filePath, ObjectRef<Type> resource)
void ResourceManager<Type, Parameters>::Register(const std::filesystem::path& filePath, ObjectRef<Type> resource)
{
String absolutePath = File::AbsolutePath(filePath);
std::filesystem::path absolutePath = std::filesystem::canonical(filePath);
Type::s_managerMap[absolutePath] = resource;
}
@ -113,9 +113,9 @@ namespace Nz
* \param filePath Path for the resource
*/
template<typename Type, typename Parameters>
void ResourceManager<Type, Parameters>::Unregister(const String& filePath)
void ResourceManager<Type, Parameters>::Unregister(const std::filesystem::path& filePath)
{
String absolutePath = File::AbsolutePath(filePath);
std::filesystem::path absolutePath = std::filesystem::canonical(filePath);
Type::s_managerMap.erase(absolutePath);
}

View File

@ -11,6 +11,7 @@
#include <Nazara/Core/Resource.hpp>
#include <Nazara/Core/ResourceParameters.hpp>
#include <Nazara/Core/String.hpp>
#include <filesystem>
#include <list>
#include <tuple>
#include <type_traits>
@ -27,18 +28,18 @@ namespace Nz
friend Type;
public:
using ExtensionGetter = bool (*)(const String& extension);
using FormatQuerier = bool (*)(const String& format);
using FileSaver = bool (*)(const Type& resource, const String& filePath, const Parameters& parameters);
using StreamSaver = bool (*)(const Type& resource, const String& format, Stream& stream, const Parameters& parameters);
using ExtensionGetter = bool (*)(const std::string& extension);
using FormatQuerier = bool (*)(const std::string& format);
using FileSaver = bool (*)(const Type& resource, const std::filesystem::path& filePath, const Parameters& parameters);
using StreamSaver = bool (*)(const Type& resource, const std::string& format, Stream& stream, const Parameters& parameters);
ResourceSaver() = delete;
~ResourceSaver() = delete;
static bool IsFormatSupported(const String& extension);
static bool IsFormatSupported(const std::string& extension);
static bool SaveToFile(const Type& resource, const String& filePath, const Parameters& parameters = Parameters());
static bool SaveToStream(const Type& resource, Stream& stream, const String& format, const Parameters& parameters = Parameters());
static bool SaveToFile(const Type& resource, const std::filesystem::path& filePath, const Parameters& parameters = Parameters());
static bool SaveToStream(const Type& resource, Stream& stream, const std::string& format, const Parameters& parameters = Parameters());
static void RegisterSaver(FormatQuerier formatQuerier, StreamSaver streamSaver, FileSaver fileSaver = nullptr);
static void UnregisterSaver(FormatQuerier formatQuerier, StreamSaver streamSaver, FileSaver fileSaver = nullptr);

View File

@ -7,6 +7,7 @@
#include <Nazara/Core/File.hpp>
#include <Nazara/Core/MemoryView.hpp>
#include <Nazara/Core/Stream.hpp>
#include <Nazara/Core/StringExt.hpp>
#include <Nazara/Core/Debug.hpp>
namespace Nz
@ -24,7 +25,7 @@ namespace Nz
* \param extension Extension of the file
*/
template<typename Type, typename Parameters>
bool ResourceSaver<Type, Parameters>::IsFormatSupported(const String& extension)
bool ResourceSaver<Type, Parameters>::IsFormatSupported(const std::string& extension)
{
for (Saver& saver : Type::s_savers)
{
@ -51,19 +52,18 @@ namespace Nz
* \see SaveToStream
*/
template<typename Type, typename Parameters>
bool ResourceSaver<Type, Parameters>::SaveToFile(const Type& resource, const String& filePath, const Parameters& parameters)
bool ResourceSaver<Type, Parameters>::SaveToFile(const Type& resource, const std::filesystem::path& filePath, const Parameters& parameters)
{
NazaraAssert(parameters.IsValid(), "Invalid parameters");
String path = File::NormalizePath(filePath);
String ext = path.SubStringFrom('.', -1, true).ToLower();
if (ext.IsEmpty())
std::string ext = ToLower(filePath.extension().generic_u8string());
if (ext.empty())
{
NazaraError("Failed to get file extension from \"" + filePath + '"');
NazaraError("Failed to get file extension from \"" + filePath.generic_u8string() + '"');
return false;
}
File file(path); // Opened only is required
File file(filePath.generic_u8string()); // Opened only is required
bool found = false;
for (Saver& saver : Type::s_savers)
@ -86,7 +86,7 @@ namespace Nz
{
if (!file.Open(OpenMode_WriteOnly | OpenMode_Truncate))
{
NazaraError("Failed to save to file: unable to open \"" + filePath + "\" in write mode");
NazaraError("Failed to save to file: unable to open \"" + filePath.generic_u8string() + "\" in write mode");
return false;
}
@ -117,7 +117,7 @@ namespace Nz
* \see SaveToFile
*/
template<typename Type, typename Parameters>
bool ResourceSaver<Type, Parameters>::SaveToStream(const Type& resource, Stream& stream, const String& format, const Parameters& parameters)
bool ResourceSaver<Type, Parameters>::SaveToStream(const Type& resource, Stream& stream, const std::string& format, const Parameters& parameters)
{
NazaraAssert(stream.IsWritable(), "Stream is not writable");
NazaraAssert(parameters.IsValid(), "Invalid parameters");

View File

@ -1,40 +0,0 @@
// Copyright (C) 2017 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_SEMAPHORE_HPP
#define NAZARA_SEMAPHORE_HPP
#include <Nazara/Prerequisites.hpp>
#include <Nazara/Core/MovablePtr.hpp>
namespace Nz
{
class SemaphoreImpl;
class NAZARA_CORE_API Semaphore
{
public:
Semaphore(unsigned int count);
Semaphore(const Semaphore&) = delete;
Semaphore(Semaphore&&) noexcept = default;
~Semaphore();
unsigned int GetCount() const;
void Post();
void Wait();
bool Wait(UInt32 timeout);
Semaphore& operator=(const Semaphore&) = delete;
Semaphore& operator=(Semaphore&&) noexcept = default;
private:
MovablePtr<SemaphoreImpl> m_impl;
};
}
#endif // NAZARA_SEMAPHORE_HPP

View File

@ -46,7 +46,7 @@ namespace Nz
operator T*() const;
T& operator*() const;
T* operator->() const;
T& operator[](int index) const;
T& operator[](std::size_t index) const;
SparsePtr& operator=(const SparsePtr& ptr) = default;

View File

@ -247,7 +247,7 @@ namespace Nz
*/
template<typename T>
T& SparsePtr<T>::operator[](int index) const
T& SparsePtr<T>::operator[](std::size_t index) const
{
return *reinterpret_cast<T*>(m_ptr + index * m_stride);
}

View File

@ -10,11 +10,12 @@
#include <Nazara/Prerequisites.hpp>
#include <Nazara/Core/Endianness.hpp>
#include <Nazara/Core/Enums.hpp>
#include <Nazara/Core/String.hpp>
#include <filesystem>
namespace Nz
{
class ByteArray;
class String; //< Do not include String.hpp in this file
class NAZARA_CORE_API Stream
{
@ -30,15 +31,15 @@ namespace Nz
inline void Flush();
virtual UInt64 GetCursorPos() const = 0;
virtual String GetDirectory() const;
virtual String GetPath() const;
virtual std::filesystem::path GetDirectory() const;
virtual std::filesystem::path GetPath() const;
inline OpenModeFlags GetOpenMode() const;
inline StreamOptionFlags 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);
virtual std::string ReadLine(unsigned int lineSize = 0);
inline bool IsReadable() const;
inline bool IsSequential() const;

View File

@ -0,0 +1,61 @@
// Copyright (C) 2017 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_CORE_STRING_EXT_HPP
#define NAZARA_CORE_STRING_EXT_HPP
#include <Nazara/Prerequisites.hpp>
#include <Nazara/Core/Unicode.hpp>
#include <string>
namespace Nz
{
struct CaseIndependent {};
struct UnicodeAware {};
// std::string is assumed to contains UTF-8
NAZARA_CORE_API std::string FromUtf16String(const char16_t* u16str);
NAZARA_CORE_API std::string FromUtf16String(const std::u16string_view& u16str);
NAZARA_CORE_API std::string FromUtf32String(const char32_t* u32str);
NAZARA_CORE_API std::string FromUtf32String(const std::u32string_view& u32str);
NAZARA_CORE_API std::string FromWideString(const wchar_t* wstr);
NAZARA_CORE_API std::string FromWideString(const std::wstring_view& str);
inline bool IsNumber(const char* str);
inline bool IsNumber(const std::string_view& str);
template<typename... Args> bool StartsWith(const std::string_view& str, const char* s, Args&&... args);
inline bool StartsWith(const std::string_view& str, const std::string_view& s);
NAZARA_CORE_API bool StartsWith(const std::string_view& str, const std::string_view& s, CaseIndependent);
NAZARA_CORE_API bool StartsWith(const std::string_view& str, const std::string_view& s, CaseIndependent, UnicodeAware);
inline std::string ToLower(const char* str);
NAZARA_CORE_API std::string ToLower(const std::string_view& str);
inline std::string ToLower(const char* str, UnicodeAware);
NAZARA_CORE_API std::string ToLower(const std::string_view& str, UnicodeAware);
inline std::string ToUpper(const char* str);
NAZARA_CORE_API std::string ToUpper(const std::string_view& str);
inline std::string ToUpper(const char* str, UnicodeAware);
NAZARA_CORE_API std::string ToUpper(const std::string_view& str, UnicodeAware);
inline std::u16string ToUtf16String(const char* str);
NAZARA_CORE_API std::u16string ToUtf16String(const std::string_view& str);
inline std::u32string ToUtf32String(const char* str);
NAZARA_CORE_API std::u32string ToUtf32String(const std::string_view& str);
inline std::wstring ToWideString(const char* str);
NAZARA_CORE_API std::wstring ToWideString(const std::string_view& str);
}
#include <Nazara/Core/StringExt.inl>
#endif // NAZARA_ALGORITHM_CORE_HPP

View File

@ -0,0 +1,82 @@
// Copyright (C) 2017 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/StringExt.hpp>
#include <Nazara/Core/Debug.hpp>
namespace Nz
{
bool IsNumber(const char* str)
{
std::size_t size = std::strlen(str);
return IsNumber(std::string_view(str, size));
}
bool IsNumber(const std::string_view& str)
{
return !str.empty() && std::find_if(str.begin(), str.end(), [](unsigned char c) { return !std::isdigit(c); }) == str.end();
}
template<typename... Args> bool StartsWith(const std::string_view& str, const char* s, Args&&... args)
{
std::size_t size = std::strlen(s);
return StartsWith(str, std::string_view(s, size), std::forward<Args>(args)...);
}
bool StartsWith(const std::string_view& str, const std::string_view& s)
{
//FIXME: Replace with proper C++20 value once it's available
#if __cplusplus > 201703L
// C++20
return str.starts_with(s);
#else
return str.compare(0, s.size(), s.data()) == 0;
#endif
}
inline std::string ToLower(const char* str)
{
std::size_t size = std::strlen(str);
return ToLower(std::string_view(str, size));
}
inline std::string ToLower(const char* str, UnicodeAware)
{
std::size_t size = std::strlen(str);
return ToLower(std::string_view(str, size), UnicodeAware{});
}
inline std::string ToUpper(const char* str)
{
std::size_t size = std::strlen(str);
return ToUpper(std::string_view(str, size));
}
inline std::string ToUpper(const char* str, UnicodeAware)
{
std::size_t size = std::strlen(str);
return ToUpper(std::string_view(str, size), UnicodeAware{});
}
inline std::u16string ToUtf16String(const char* str)
{
std::size_t size = std::strlen(str);
return ToUtf16String(std::string_view(str, size));
}
inline std::u32string ToUtf32String(const char* str)
{
std::size_t size = std::strlen(str);
return ToUtf32String(std::string_view(str, size));
}
inline std::wstring ToWideString(const char* str)
{
std::size_t size = std::strlen(str);
return ToWideString(std::string_view(str, size));
}
}
#include <Nazara/Core/DebugOff.hpp>

View File

@ -1,75 +0,0 @@
// Copyright (C) 2017 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_THREAD_HPP
#define NAZARA_THREAD_HPP
#include <Nazara/Prerequisites.hpp>
#include <Nazara/Core/Functor.hpp>
#include <Nazara/Core/MovablePtr.hpp>
#include <iosfwd>
namespace Nz
{
class String;
class ThreadImpl;
class NAZARA_CORE_API Thread
{
public:
class Id;
Thread();
template<typename F> Thread(F function);
template<typename F, typename... Args> Thread(F function, Args&&... args);
template<typename C> Thread(void (C::*function)(), C* object);
Thread(const Thread&) = delete;
Thread(Thread&& other) noexcept = default;
~Thread();
void Detach();
Id GetId() const;
bool IsJoinable() const;
void Join();
void SetName(const String& name);
Thread& operator=(const Thread&) = delete;
Thread& operator=(Thread&& thread) noexcept = default;
static unsigned int HardwareConcurrency();
static void SetCurrentThreadName(const String& name);
static void Sleep(UInt32 milliseconds);
private:
void CreateImpl(Functor* functor);
MovablePtr<ThreadImpl> m_impl;
};
class NAZARA_CORE_API Thread::Id
{
friend Thread;
public:
NAZARA_CORE_API friend bool operator==(const Id& lhs, const Id& rhs);
NAZARA_CORE_API friend bool operator!=(const Id& lhs, const Id& rhs);
NAZARA_CORE_API friend bool operator<(const Id& lhs, const Id& rhs);
NAZARA_CORE_API friend bool operator<=(const Id& lhs, const Id& rhs);
NAZARA_CORE_API friend bool operator>(const Id& lhs, const Id& rhs);
NAZARA_CORE_API friend bool operator>=(const Id& lhs, const Id& rhs);
NAZARA_CORE_API friend std::ostream& operator<<(std::ostream& o, const Id& id);
private:
explicit Id(ThreadImpl* thread);
ThreadImpl* m_id = nullptr;
};
}
#include <Nazara/Core/Thread.inl>
#endif // NAZARA_THREAD_HPP

View File

@ -1,55 +0,0 @@
// Copyright (C) 2017 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 <utility>
#include <Nazara/Core/Debug.hpp>
namespace Nz
{
/*!
* \ingroup core
* \class Nz::Thread
* \brief Core class that represents a thread
*/
/*!
* \brief Constructs a Thread object with a function
*
* \param function Task the thread will execute in parallel
*/
template<typename F>
Thread::Thread(F function)
{
CreateImpl(new FunctorWithoutArgs<F>(function));
}
/*!
* \brief Constructs a Thread object with a function and its parameters
*
* \param function Task the thread will execute in parallel
* \param args Arguments of the function
*/
template<typename F, typename... Args>
Thread::Thread(F function, Args&&... args)
{
CreateImpl(new FunctorWithArgs<F, Args...>(function, std::forward<Args>(args)...));
}
/*!
* \brief Constructs a Thread object with a member function and its object
*
* \param function Task the thread will execute in parallel
* \param object Object on which the method will be called
*/
template<typename C>
Thread::Thread(void (C::*function)(), C* object)
{
CreateImpl(new MemberWithoutArgs<C>(function, object));
}
}
#include <Nazara/Core/DebugOff.hpp>

View File

@ -1,23 +0,0 @@
// Copyright (C) 2017 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
// No header guard
#include <Nazara/Core/LockGuard.hpp>
#include <Nazara/Core/Mutex.hpp>
// These macroes can change for any file which uses it in the same unit of compilation
#undef NazaraLock
#undef NazaraMutex
#undef NazaraMutexAttrib
#undef NazaraMutexLock
#undef NazaraMutexUnlock
#undef NazaraNamedLock
#define NazaraLock(mutex) Nz::LockGuard lock_mutex(mutex);
#define NazaraMutex(name) Nz::Mutex name;
#define NazaraMutexAttrib(name, attribute) attribute Mutex name;
#define NazaraMutexLock(mutex) mutex.Lock();
#define NazaraMutexUnlock(mutex) mutex.Unlock();
#define NazaraNamedLock(mutex, name) Nz::LockGuard lock_##name(mutex);

View File

@ -1,21 +0,0 @@
// Copyright (C) 2017 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
// No header guard
// These macroes can change for any file which uses it in the same unit of compilation
#undef NazaraLock
#undef NazaraMutex
#undef NazaraMutexAttrib
#undef NazaraMutexLock
#undef NazaraMutexUnlock
#undef NazaraNamedLock
#define NazaraLock(mutex)
#define NazaraMutex(name)
#define NazaraMutexAttrib(name, attribute)
#define NazaraMutexLock(mutex)
#define NazaraMutexUnlock(mutex)
#define NazaraNamedLock(mutex, name)

View File

@ -17,7 +17,6 @@
#include <Nazara/Core/ResourceManager.hpp>
#include <Nazara/Core/ResourceParameters.hpp>
#include <Nazara/Core/Signal.hpp>
#include <Nazara/Core/String.hpp>
#include <Nazara/Graphics/Config.hpp>
#include <Nazara/Graphics/Enums.hpp>
#include <Nazara/Graphics/MaterialPipeline.hpp>
@ -35,7 +34,7 @@ namespace Nz
bool loadHeightMap = true;
bool loadNormalMap = true;
bool loadSpecularMap = true;
String shaderName = "Basic";
std::string shaderName = "Basic";
bool IsValid() const;
};
@ -59,7 +58,7 @@ namespace Nz
inline Material();
inline Material(const MaterialPipeline* pipeline);
inline Material(const MaterialPipelineInfo& pipelineInfo);
inline Material(const String& pipelineName);
inline Material(const std::string& pipelineName);
inline Material(const Material& material);
inline ~Material();
@ -69,7 +68,7 @@ namespace Nz
inline void Configure(const MaterialPipeline* pipeline);
inline void Configure(const MaterialPipelineInfo& pipelineInfo);
inline bool Configure(const String& pipelineName);
inline bool Configure(const std::string& pipelineName);
inline void EnableAlphaTest(bool alphaTest);
inline void EnableBlending(bool blending);
@ -141,33 +140,33 @@ namespace Nz
void SaveToParameters(ParameterList* matData);
inline bool SetAlphaMap(const String& textureName);
inline bool SetAlphaMap(const std::string& textureName);
inline void SetAlphaMap(TextureRef alphaMap);
inline void SetAlphaThreshold(float alphaThreshold);
inline void SetAmbientColor(const Color& ambient);
inline void SetDepthFunc(RendererComparison depthFunc);
inline void SetDepthMaterial(MaterialRef depthMaterial);
inline void SetDiffuseColor(const Color& diffuse);
inline bool SetDiffuseMap(const String& textureName);
inline bool SetDiffuseMap(const std::string& textureName);
inline void SetDiffuseMap(TextureRef diffuseMap);
inline void SetDiffuseSampler(const TextureSampler& sampler);
inline void SetDstBlend(BlendFunc func);
inline bool SetEmissiveMap(const String& textureName);
inline bool SetEmissiveMap(const std::string& textureName);
inline void SetEmissiveMap(TextureRef textureName);
inline void SetFaceCulling(FaceSide faceSide);
inline void SetFaceFilling(FaceFilling filling);
inline bool SetHeightMap(const String& textureName);
inline bool SetHeightMap(const std::string& textureName);
inline void SetHeightMap(TextureRef textureName);
inline void SetLineWidth(float lineWidth);
inline bool SetNormalMap(const String& textureName);
inline bool SetNormalMap(const std::string& textureName);
inline void SetNormalMap(TextureRef textureName);
inline void SetPointSize(float pointSize);
inline void SetReflectionMode(ReflectionMode reflectionMode);
inline void SetShader(UberShaderConstRef uberShader);
inline bool SetShader(const String& uberShaderName);
inline bool SetShader(const std::string& uberShaderName);
inline void SetShininess(float shininess);
inline void SetSpecularColor(const Color& specular);
inline bool SetSpecularMap(const String& textureName);
inline bool SetSpecularMap(const std::string& textureName);
inline void SetSpecularMap(TextureRef specularMap);
inline void SetSpecularSampler(const TextureSampler& sampler);
inline void SetSrcBlend(BlendFunc func);
@ -177,7 +176,7 @@ namespace Nz
inline static MaterialRef GetDefault();
inline static int GetTextureUnit(TextureMap textureMap);
static inline MaterialRef LoadFromFile(const String& filePath, const MaterialParams& params = MaterialParams());
static inline MaterialRef LoadFromFile(const std::filesystem::path& filePath, const MaterialParams& params = MaterialParams());
static inline MaterialRef LoadFromMemory(const void* data, std::size_t size, const MaterialParams& params = MaterialParams());
static inline MaterialRef LoadFromStream(Stream& stream, const MaterialParams& params = MaterialParams());

View File

@ -57,7 +57,7 @@ namespace Nz
*
* \see Configure
*/
inline Material::Material(const String& pipelineName)
inline Material::Material(const std::string& pipelineName)
{
ErrorFlags errFlags(ErrorFlag_ThrowException, true);
@ -139,7 +139,7 @@ namespace Nz
*
* \see Configure
*/
inline bool Material::Configure(const String& pipelineName)
inline bool Material::Configure(const std::string& pipelineName)
{
MaterialPipelineRef pipeline = MaterialPipelineLibrary::Query(pipelineName);
if (!pipeline)
@ -909,7 +909,7 @@ namespace Nz
*
* \param textureName Named texture
*/
inline bool Material::SetAlphaMap(const String& textureName)
inline bool Material::SetAlphaMap(const std::string& textureName)
{
TextureRef texture = TextureLibrary::Query(textureName);
if (!texture)
@ -1005,7 +1005,7 @@ namespace Nz
*
* \remark Invalidates the pipeline
*/
inline bool Material::SetDiffuseMap(const String& textureName)
inline bool Material::SetDiffuseMap(const std::string& textureName)
{
TextureRef texture = TextureLibrary::Query(textureName);
if (!texture)
@ -1071,7 +1071,7 @@ namespace Nz
*
* \see GetEmissiveMap
*/
inline bool Material::SetEmissiveMap(const String& textureName)
inline bool Material::SetEmissiveMap(const std::string& textureName)
{
TextureRef texture = TextureLibrary::Query(textureName);
if (!texture)
@ -1140,7 +1140,7 @@ namespace Nz
*
* \see GetHeightMap
*/
inline bool Material::SetHeightMap(const String& textureName)
inline bool Material::SetHeightMap(const std::string& textureName)
{
TextureRef texture = TextureLibrary::Query(textureName);
if (!texture)
@ -1202,7 +1202,7 @@ namespace Nz
*
* \see GetNormalMap
*/
inline bool Material::SetNormalMap(const String& textureName)
inline bool Material::SetNormalMap(const std::string& textureName)
{
TextureRef texture = TextureLibrary::Query(textureName);
if (!texture)
@ -1305,7 +1305,7 @@ namespace Nz
*
* \param uberShaderName Named shader
*/
inline bool Material::SetShader(const String& uberShaderName)
inline bool Material::SetShader(const std::string& uberShaderName)
{
UberShaderConstRef uberShader = UberShaderLibrary::Get(uberShaderName);
if (!uberShader)
@ -1343,7 +1343,7 @@ namespace Nz
*
* \remark Invalidates the pipeline
*/
inline bool Material::SetSpecularMap(const String& textureName)
inline bool Material::SetSpecularMap(const std::string& textureName)
{
TextureRef texture = TextureLibrary::Query(textureName);
if (!texture)
@ -1444,7 +1444,7 @@ namespace Nz
* \param filePath Path to the file
* \param params Parameters for the material
*/
inline MaterialRef Material::LoadFromFile(const String& filePath, const MaterialParams& params)
inline MaterialRef Material::LoadFromFile(const std::filesystem::path& filePath, const MaterialParams& params)
{
return MaterialLoader::LoadFromFile(filePath, params);
}

View File

@ -59,22 +59,22 @@ namespace Nz
std::unique_ptr<InstancedRenderable> Clone() const override;
using InstancedRenderable::GetMaterial;
const MaterialRef& GetMaterial(const String& subMeshName) const;
const MaterialRef& GetMaterial(std::size_t skinIndex, const String& subMeshName) const;
const MaterialRef& GetMaterial(const std::string& subMeshName) const;
const MaterialRef& GetMaterial(std::size_t skinIndex, const std::string& subMeshName) const;
Mesh* GetMesh() const;
virtual bool IsAnimated() const;
using InstancedRenderable::SetMaterial;
bool SetMaterial(const String& subMeshName, MaterialRef material);
bool SetMaterial(std::size_t skinIndex, const String& subMeshName, MaterialRef material);
bool SetMaterial(const std::string& subMeshName, MaterialRef material);
bool SetMaterial(std::size_t skinIndex, const std::string& subMeshName, MaterialRef material);
virtual void SetMesh(Mesh* mesh);
Model& operator=(const Model& node) = default;
Model& operator=(Model&& node) = delete;
static ModelRef LoadFromFile(const String& filePath, const ModelParameters& params = ModelParameters());
static ModelRef LoadFromFile(const std::filesystem::path& filePath, const ModelParameters& params = ModelParameters());
static ModelRef LoadFromMemory(const void* data, std::size_t size, const ModelParameters& params = ModelParameters());
static ModelRef LoadFromStream(Stream& stream, const ModelParameters& params = ModelParameters());

View File

@ -47,15 +47,15 @@ namespace Nz
inline void SetCornerColor(RectCorner corner, const Color& color);
inline void SetDefaultMaterial();
inline void SetMaterial(MaterialRef material, bool resizeSprite = true);
bool SetMaterial(String materialName, bool resizeSprite = true);
bool SetMaterial(std::string materialName, bool resizeSprite = true);
inline void SetMaterial(std::size_t skinIndex, MaterialRef material, bool resizeSprite = true);
bool SetMaterial(std::size_t skinIndex, String materialName, bool resizeSprite = true);
bool SetMaterial(std::size_t skinIndex, std::string materialName, bool resizeSprite = true);
inline void SetOrigin(const Vector3f& origin);
inline void SetSize(const Vector2f& size);
inline void SetSize(float sizeX, float sizeY);
bool SetTexture(String textureName, bool resizeSprite = true);
bool SetTexture(std::string textureName, bool resizeSprite = true);
inline void SetTexture(TextureRef texture, bool resizeSprite = true);
bool SetTexture(std::size_t skinIndex, String textureName, bool resizeSprite = true);
bool SetTexture(std::size_t skinIndex, std::string textureName, bool resizeSprite = true);
inline void SetTexture(std::size_t skinIndex, TextureRef texture, bool resizeSprite = true);
inline void SetTextureCoords(const Rectf& coords);
inline void SetTextureRect(const Rectui& rect);

View File

@ -13,6 +13,7 @@
#include <Nazara/Lua/Config.hpp>
#include <Nazara/Lua/Enums.hpp>
#include <cstddef>
#include <filesystem>
#include <functional>
#include <type_traits>
@ -87,7 +88,7 @@ namespace Nz
void Error(const String& message) const;
bool Execute(const String& code, int errorHandler = 0);
bool ExecuteFromFile(const String& filePath, int errorHandler = 0);
bool ExecuteFromFile(const std::filesystem::path& filePath, int errorHandler = 0);
bool ExecuteFromMemory(const void* data, std::size_t size, int errorHandler = 0);
bool ExecuteFromStream(Stream& stream, int errorHandler = 0);
@ -115,7 +116,7 @@ namespace Nz
bool IsValid(int index) const;
bool Load(const String& code);
bool LoadFromFile(const String& filePath);
bool LoadFromFile(const std::filesystem::path& filePath);
bool LoadFromMemory(const void* data, std::size_t size);
bool LoadFromStream(Stream& stream);

View File

@ -43,6 +43,16 @@ namespace Nz
return 1;
}
inline unsigned int LuaImplQueryArg(const LuaState& instance, int index, std::filesystem::path* arg, TypeTag<std::filesystem::path>)
{
std::size_t strLength = 0;
const char* str = instance.CheckString(index, &strLength);
arg->assign(std::string_view(str, strLength));
return 1;
}
inline unsigned int LuaImplQueryArg(const LuaState& instance, int index, std::string* arg, TypeTag<std::string>)
{
std::size_t strLength = 0;
@ -272,6 +282,11 @@ namespace Nz
return 1;
}
inline int LuaImplReplyVal(const LuaState& instance, std::filesystem::path&& val, TypeTag<std::filesystem::path>)
{
return LuaImplReplyVal(instance, val.generic_u8string(), TypeTag<std::string>());
}
template<typename T>
inline int LuaImplReplyVal(const LuaState& instance, std::vector<T>&& valContainer, TypeTag<std::vector<T>>)
{

View File

@ -10,8 +10,8 @@
#include <Nazara/Prerequisites.hpp>
#include <Nazara/Core/ByteStream.hpp>
#include <Nazara/Core/MemoryStream.hpp>
#include <Nazara/Core/Mutex.hpp>
#include <Nazara/Network/Config.hpp>
#include <mutex>
namespace Nz
{
@ -64,7 +64,7 @@ namespace Nz
MemoryStream m_memoryStream;
UInt16 m_netCode;
static std::unique_ptr<Mutex> s_availableBuffersMutex;
static std::mutex s_availableBuffersMutex;
static std::vector<std::pair<std::size_t, std::unique_ptr<ByteArray>>> s_availableBuffers;
};
}

View File

@ -10,9 +10,7 @@
#define NAZARA_WINDOW_HPP
#include <Nazara/Prerequisites.hpp>
#include <Nazara/Core/ConditionVariable.hpp>
#include <Nazara/Core/MovablePtr.hpp>
#include <Nazara/Core/Mutex.hpp>
#include <Nazara/Core/String.hpp>
#include <Nazara/Math/Vector2.hpp>
#include <Nazara/Platform/Config.hpp>
@ -23,6 +21,8 @@
#include <Nazara/Platform/Icon.hpp>
#include <Nazara/Platform/VideoMode.hpp>
#include <Nazara/Platform/WindowHandle.hpp>
#include <condition_variable>
#include <mutex>
#include <queue>
namespace Nz
@ -126,13 +126,13 @@ namespace Nz
std::queue<WindowEvent> m_events;
std::vector<WindowEvent> m_pendingEvents;
ConditionVariable m_eventCondition;
std::condition_variable m_eventCondition;
CursorController m_cursorController;
CursorRef m_cursor;
EventHandler m_eventHandler;
IconRef m_icon;
Mutex m_eventMutex;
Mutex m_eventConditionMutex;
std::mutex m_eventMutex;
std::mutex m_eventConditionMutex;
bool m_asyncWindow;
bool m_closed;
bool m_closeOnQuit;

View File

@ -4,7 +4,6 @@
#include <Nazara/Platform/Window.hpp>
#include <Nazara/Core/ErrorFlags.hpp>
#include <Nazara/Core/LockGuard.hpp>
#include <Nazara/Platform/Debug.hpp>
namespace Nz
@ -98,16 +97,15 @@ namespace Nz
else
{
{
LockGuard eventLock(m_eventMutex);
std::lock_guard<std::mutex> eventLock(m_eventMutex);
m_pendingEvents.push_back(event);
}
if (m_waitForEvent)
{
m_eventConditionMutex.Lock();
m_eventCondition.Signal();
m_eventConditionMutex.Unlock();
std::lock_guard<std::mutex> lock(m_eventConditionMutex);
m_eventCondition.notify_all();
}
}
}

View File

@ -20,6 +20,7 @@
#include <Nazara/Math/Vector4.hpp>
#include <Nazara/Renderer/Config.hpp>
#include <Nazara/Renderer/Enums.hpp>
#include <filesystem>
namespace Nz
{
@ -43,7 +44,7 @@ namespace Nz
~Shader();
void AttachStage(ShaderStageType stage, const ShaderStage& shaderStage);
bool AttachStageFromFile(ShaderStageType stage, const String& filePath);
bool AttachStageFromFile(ShaderStageType stage, const std::filesystem::path& filePath);
bool AttachStageFromSource(ShaderStageType stage, const char* source, unsigned int length);
bool AttachStageFromSource(ShaderStageType stage, const String& source);

View File

@ -11,6 +11,7 @@
#include <Nazara/Core/String.hpp>
#include <Nazara/Renderer/Config.hpp>
#include <Nazara/Renderer/Enums.hpp>
#include <filesystem>
namespace Nz
{
@ -36,7 +37,7 @@ namespace Nz
void SetSource(const char* source, unsigned int length);
void SetSource(const String& source);
bool SetSourceFromFile(const String& filePath);
bool SetSourceFromFile(const std::filesystem::path& filePath);
ShaderStage& operator=(const ShaderStage&) = delete;
ShaderStage& operator=(ShaderStage&& shader);

View File

@ -68,13 +68,13 @@ namespace Nz
bool IsValid() const;
// LoadFace
bool LoadFaceFromFile(CubemapFace face, const String& filePath, const ImageParams& params = ImageParams());
bool LoadFaceFromFile(CubemapFace face, const std::filesystem::path& filePath, const ImageParams& params = ImageParams());
bool LoadFaceFromMemory(CubemapFace face, const void* data, std::size_t size, const ImageParams& params = ImageParams());
bool LoadFaceFromStream(CubemapFace face, Stream& stream, const ImageParams& params = ImageParams());
// Save
bool SaveToFile(const String& filePath, const ImageParams& params = ImageParams());
bool SaveToStream(Stream& stream, const String& format, const ImageParams& params = ImageParams());
bool SaveToFile(const std::filesystem::path& filePath, const ImageParams& params = ImageParams());
bool SaveToStream(Stream& stream, const std::string& format, const ImageParams& params = ImageParams());
bool SetMipmapRange(UInt8 minLevel, UInt8 maxLevel);
@ -96,19 +96,19 @@ namespace Nz
static bool IsTypeSupported(ImageType type);
// Load
static TextureRef LoadFromFile(const String& filePath, const ImageParams& params = ImageParams(), bool generateMipmaps = true);
static TextureRef LoadFromFile(const std::filesystem::path& filePath, const ImageParams& params = ImageParams(), bool generateMipmaps = true);
static TextureRef LoadFromImage(const Image* image, bool generateMipmaps = true);
static TextureRef LoadFromMemory(const void* data, std::size_t size, const ImageParams& params = ImageParams(), bool generateMipmaps = true);
static TextureRef LoadFromStream(Stream& stream, const ImageParams& params = ImageParams(), bool generateMipmaps = true);
// LoadArray
static TextureRef LoadArrayFromFile(const String& filePath, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const Vector2ui& atlasSize = Vector2ui(2, 2));
static TextureRef LoadArrayFromFile(const std::filesystem::path& filePath, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const Vector2ui& atlasSize = Vector2ui(2, 2));
static TextureRef LoadArrayFromImage(const Image* image, bool generateMipmaps = true, const Vector2ui& atlasSize = Vector2ui(2, 2));
static TextureRef LoadArrayFromMemory(const void* data, std::size_t size, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const Vector2ui& atlasSize = Vector2ui(2, 2));
static TextureRef LoadArrayFromStream(Stream& stream, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const Vector2ui& atlasSize = Vector2ui(2, 2));
// LoadCubemap
static TextureRef LoadCubemapFromFile(const String& filePath, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const CubemapParams& cubemapParams = CubemapParams());
static TextureRef LoadCubemapFromFile(const std::filesystem::path& filePath, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const CubemapParams& cubemapParams = CubemapParams());
static TextureRef LoadCubemapFromImage(const Image* image, bool generateMipmaps = true, const CubemapParams& params = CubemapParams());
static TextureRef LoadCubemapFromMemory(const void* data, std::size_t size, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const CubemapParams& cubemapParams = CubemapParams());
static TextureRef LoadCubemapFromStream(Stream& stream, const ImageParams& imageParams = ImageParams(), bool generateMipmaps = true, const CubemapParams& cubemapParams = CubemapParams());

View File

@ -32,7 +32,7 @@ namespace Nz
UberShaderInstance* Get(const ParameterList& parameters) const override;
void SetShader(ShaderStageType stage, const String& source, const String& shaderFlags, const String& requiredFlags = String());
bool SetShaderFromFile(ShaderStageType stage, const String& filePath, const String& shaderFlags, const String& requiredFlags = String());
bool SetShaderFromFile(ShaderStageType stage, const std::filesystem::path& filePath, const String& shaderFlags, const String& requiredFlags = String());
static bool IsSupported();
template<typename... Args> static UberShaderPreprocessorRef New(Args&&... args);

View File

@ -26,9 +26,9 @@ namespace Nz
struct NAZARA_UTILITY_API AnimationParams : ResourceParameters
{
// La frame de fin à charger
UInt32 endFrame = 0xFFFFFFFF;
std::size_t endFrame = 0xFFFFFFFF;
// La frame de début à charger
UInt32 startFrame = 0;
std::size_t startFrame = 0;
bool IsValid() const;
};
@ -58,37 +58,37 @@ namespace Nz
~Animation();
bool AddSequence(const Sequence& sequence);
void AnimateSkeleton(Skeleton* targetSkeleton, UInt32 frameA, UInt32 frameB, float interpolation) const;
void AnimateSkeleton(Skeleton* targetSkeleton, std::size_t frameA, std::size_t frameB, float interpolation) const;
bool CreateSkeletal(UInt32 frameCount, UInt32 jointCount);
bool CreateSkeletal(std::size_t frameCount, std::size_t jointCount);
void Destroy();
void EnableLoopPointInterpolation(bool loopPointInterpolation);
UInt32 GetFrameCount() const;
UInt32 GetJointCount() const;
std::size_t GetFrameCount() const;
std::size_t GetJointCount() const;
Sequence* GetSequence(const String& sequenceName);
Sequence* GetSequence(UInt32 index);
Sequence* GetSequence(std::size_t index);
const Sequence* GetSequence(const String& sequenceName) const;
const Sequence* GetSequence(UInt32 index) const;
UInt32 GetSequenceCount() const;
UInt32 GetSequenceIndex(const String& sequenceName) const;
SequenceJoint* GetSequenceJoints(UInt32 frameIndex = 0);
const SequenceJoint* GetSequenceJoints(UInt32 frameIndex = 0) const;
const Sequence* GetSequence(std::size_t index) const;
std::size_t GetSequenceCount() const;
std::size_t GetSequenceIndex(const String& sequenceName) const;
SequenceJoint* GetSequenceJoints(std::size_t frameIndex = 0);
const SequenceJoint* GetSequenceJoints(std::size_t frameIndex = 0) const;
AnimationType GetType() const;
bool HasSequence(const String& sequenceName) const;
bool HasSequence(UInt32 index = 0) const;
bool HasSequence(std::size_t index = 0) const;
bool IsLoopPointInterpolationEnabled() const;
bool IsValid() const;
void RemoveSequence(const String& sequenceName);
void RemoveSequence(UInt32 index);
void RemoveSequence(std::size_t index);
template<typename... Args> static AnimationRef New(Args&&... args);
static AnimationRef LoadFromFile(const String& filePath, const AnimationParams& params = AnimationParams());
static AnimationRef LoadFromFile(const std::filesystem::path& filePath, const AnimationParams& params = AnimationParams());
static AnimationRef LoadFromMemory(const void* data, std::size_t size, const AnimationParams& params = AnimationParams());
static AnimationRef LoadFromStream(Stream& stream, const AnimationParams& params = AnimationParams());

View File

@ -89,7 +89,7 @@ namespace Nz
static unsigned int GetDefaultGlyphBorder();
static unsigned int GetDefaultMinimumStepSize();
static FontRef OpenFromFile(const String& filePath, const FontParams& params = FontParams());
static FontRef OpenFromFile(const std::filesystem::path& filePath, const FontParams& params = FontParams());
static FontRef OpenFromMemory(const void* data, std::size_t size, const FontParams& params = FontParams());
static FontRef OpenFromStream(Stream& stream, const FontParams& params = FontParams());

View File

@ -49,7 +49,7 @@ namespace Nz
std::vector<Triangle> triangles;
std::vector<Vertex> vertices;
std::vector<Weight> weights;
String shader;
std::string shader;
};
MD5MeshParser(Stream& stream);
@ -66,17 +66,17 @@ namespace Nz
private:
bool Advance(bool required = true);
void Error(const String& message);
void Error(const std::string& message);
bool ParseJoints();
bool ParseMesh();
void Warning(const String& message);
void Warning(const std::string& message);
void UnrecognizedLine(bool error = false);
std::vector<Joint> m_joints;
std::vector<Mesh> m_meshes;
Stream& m_stream;
StreamOptionFlags m_streamFlags;
String m_currentLine;
std::string m_currentLine;
bool m_keepLastLine;
unsigned int m_lineCount;
unsigned int m_meshIndex;

View File

@ -9,7 +9,6 @@
#include <Nazara/Prerequisites.hpp>
#include <Nazara/Core/Color.hpp>
#include <Nazara/Core/String.hpp>
#include <Nazara/Utility/Config.hpp>
#include <unordered_map>
@ -23,12 +22,12 @@ namespace Nz
MTLParser() = default;
~MTLParser() = default;
inline Material* AddMaterial(const String& matName);
inline Material* AddMaterial(const std::string& matName);
inline void Clear();
inline const Material* GetMaterial(const String& materialName) const;
inline const std::unordered_map<String, Material>& GetMaterials() const;
inline const Material* GetMaterial(const std::string& materialName) const;
inline const std::unordered_map<std::string, Material>& GetMaterials() const;
bool Parse(Stream& stream);
@ -39,17 +38,17 @@ namespace Nz
Color ambient = Color::White;
Color diffuse = Color::White;
Color specular = Color::White;
String alphaMap;
String ambientMap;
String bumpMap;
String decalMap;
String diffuseMap;
String displacementMap;
String emissiveMap; //< <!> Custom addition: not present in MTL
String normalMap; //< <!> Custom addition: not present in MTL
String reflectionMap;
String shininessMap;
String specularMap;
std::string alphaMap;
std::string ambientMap;
std::string bumpMap;
std::string decalMap;
std::string diffuseMap;
std::string displacementMap;
std::string emissiveMap; //< <!> Custom addition: not present in MTL
std::string normalMap; //< <!> Custom addition: not present in MTL
std::string reflectionMap;
std::string shininessMap;
std::string specularMap;
float alpha = 1.f;
float refractionIndex = 1.f;
float shininess = 1.f;
@ -61,14 +60,14 @@ namespace Nz
template<typename T> void Emit(const T& text) const;
inline void EmitLine() const;
template<typename T> void EmitLine(const T& line) const;
inline void Error(const String& message);
inline void Error(const std::string& message);
inline void Flush() const;
inline void Warning(const String& message);
inline void Warning(const std::string& message);
inline void UnrecognizedLine(bool error = false);
std::unordered_map<String, Material> m_materials;
std::unordered_map<std::string, Material> m_materials;
mutable Stream* m_currentStream;
String m_currentLine;
std::string m_currentLine;
mutable StringStream m_outputStream;
bool m_keepLastLine;
unsigned int m_lineCount;

View File

@ -7,7 +7,7 @@
namespace Nz
{
inline MTLParser::Material* MTLParser::AddMaterial(const String& matName)
inline MTLParser::Material* MTLParser::AddMaterial(const std::string& matName)
{
return &m_materials[matName];
}
@ -17,7 +17,7 @@ namespace Nz
m_materials.clear();
}
inline const MTLParser::Material* MTLParser::GetMaterial(const String& materialName) const
inline const MTLParser::Material* MTLParser::GetMaterial(const std::string& materialName) const
{
auto it = m_materials.find(materialName);
if (it != m_materials.end())
@ -26,7 +26,7 @@ namespace Nz
return nullptr;
}
inline const std::unordered_map<String, MTLParser::Material>& MTLParser::GetMaterials() const
inline const std::unordered_map<std::string, MTLParser::Material>& MTLParser::GetMaterials() const
{
return m_materials;
}
@ -51,9 +51,9 @@ namespace Nz
Emit('\n');
}
inline void MTLParser::Error(const String& message)
inline void MTLParser::Error(const std::string& message)
{
NazaraError(message + " at line #" + String::Number(m_lineCount));
NazaraError(message + " at line #" + std::to_string(m_lineCount));
}
inline void MTLParser::Flush() const
@ -62,14 +62,14 @@ namespace Nz
m_outputStream.Clear();
}
inline void MTLParser::Warning(const String& message)
inline void MTLParser::Warning(const std::string& message)
{
NazaraWarning(message + " at line #" + String::Number(m_lineCount));
NazaraWarning(message + " at line #" + std::to_string(m_lineCount));
}
inline void MTLParser::UnrecognizedLine(bool error)
{
String message = "Unrecognized \"" + m_currentLine + '"';
std::string message = "Unrecognized \"" + m_currentLine + '"';
if (error)
Error(message);

View File

@ -8,7 +8,6 @@
#define NAZARA_FORMATS_OBJPARSER_HPP
#include <Nazara/Prerequisites.hpp>
#include <Nazara/Core/String.hpp>
#include <Nazara/Math/Vector3.hpp>
#include <Nazara/Math/Vector4.hpp>
#include <Nazara/Utility/Config.hpp>
@ -28,53 +27,53 @@ namespace Nz
bool Check(Stream& stream);
inline String* GetMaterials();
inline const String* GetMaterials() const;
inline UInt32 GetMaterialCount() const;
inline std::string* GetMaterials();
inline const std::string* GetMaterials() const;
inline std::size_t GetMaterialCount() const;
inline Mesh* GetMeshes();
inline const Mesh* GetMeshes() const;
inline UInt32 GetMeshCount() const;
inline const String& GetMtlLib() const;
inline std::size_t GetMeshCount() const;
inline const std::filesystem::path& GetMtlLib() const;
inline Vector3f* GetNormals();
inline const Vector3f* GetNormals() const;
inline UInt32 GetNormalCount() const;
inline std::size_t GetNormalCount() const;
inline Vector4f* GetPositions();
inline const Vector4f* GetPositions() const;
inline UInt32 GetPositionCount() const;
inline std::size_t GetPositionCount() const;
inline Vector3f* GetTexCoords();
inline const Vector3f* GetTexCoords() const;
inline UInt32 GetTexCoordCount() const;
inline std::size_t GetTexCoordCount() const;
bool Parse(Stream& stream, UInt32 reservedVertexCount = 100);
bool Parse(Stream& stream, std::size_t reservedVertexCount = 100);
bool Save(Stream& stream) const;
inline String* SetMaterialCount(UInt32 materialCount);
inline Mesh* SetMeshCount(UInt32 meshCount);
inline void SetMtlLib(const String& mtlLib);
inline Vector3f* SetNormalCount(UInt32 normalCount);
inline Vector4f* SetPositionCount(UInt32 positionCount);
inline Vector3f* SetTexCoordCount(UInt32 texCoordCount);
inline std::string* SetMaterialCount(std::size_t materialCount);
inline Mesh* SetMeshCount(std::size_t meshCount);
inline void SetMtlLib(const std::filesystem::path& mtlLib);
inline Vector3f* SetNormalCount(std::size_t normalCount);
inline Vector4f* SetPositionCount(std::size_t positionCount);
inline Vector3f* SetTexCoordCount(std::size_t texCoordCount);
struct Face
{
UInt32 firstVertex;
UInt32 vertexCount;
std::size_t firstVertex;
std::size_t vertexCount;
};
struct FaceVertex
{
UInt32 normal;
UInt32 position;
UInt32 texCoord;
std::size_t normal;
std::size_t position;
std::size_t texCoord;
};
struct Mesh
{
std::vector<Face> faces;
std::vector<FaceVertex> vertices;
String name;
UInt32 material;
std::string name;
std::size_t material;
};
private:
@ -82,19 +81,19 @@ namespace Nz
template<typename T> void Emit(const T& text) const;
inline void EmitLine() const;
template<typename T> void EmitLine(const T& line) const;
inline void Error(const String& message);
inline void Error(const std::string& message);
inline void Flush() const;
inline void Warning(const String& message);
inline void Warning(const std::string& message);
inline bool UnrecognizedLine(bool error = false);
std::vector<Mesh> m_meshes;
std::vector<String> m_materials;
std::vector<std::string> m_materials;
std::vector<Vector3f> m_normals;
std::vector<Vector4f> m_positions;
std::vector<Vector3f> m_texCoords;
mutable Stream* m_currentStream;
String m_currentLine;
String m_mtlLib;
std::string m_currentLine;
std::filesystem::path m_mtlLib;
mutable StringStream m_outputStream;
bool m_keepLastLine;
unsigned int m_lineCount;

View File

@ -16,19 +16,19 @@ namespace Nz
m_texCoords.clear();
}
inline String* OBJParser::GetMaterials()
inline std::string* OBJParser::GetMaterials()
{
return m_materials.data();
}
inline const String* OBJParser::GetMaterials() const
inline const std::string* OBJParser::GetMaterials() const
{
return m_materials.data();
}
inline UInt32 OBJParser::GetMaterialCount() const
inline std::size_t OBJParser::GetMaterialCount() const
{
return static_cast<UInt32>(m_materials.size());
return m_materials.size();
}
inline OBJParser::Mesh* OBJParser::GetMeshes()
@ -41,12 +41,12 @@ namespace Nz
return m_meshes.data();
}
inline UInt32 OBJParser::GetMeshCount() const
inline std::size_t OBJParser::GetMeshCount() const
{
return static_cast<UInt32>(m_meshes.size());
return m_meshes.size();
}
inline const String& OBJParser::GetMtlLib() const
inline const std::filesystem::path& OBJParser::GetMtlLib() const
{
return m_mtlLib;
}
@ -61,9 +61,9 @@ namespace Nz
return m_normals.data();
}
inline UInt32 OBJParser::GetNormalCount() const
inline std::size_t OBJParser::GetNormalCount() const
{
return static_cast<UInt32>(m_normals.size());
return m_normals.size();
}
inline Vector4f* OBJParser::GetPositions()
@ -76,9 +76,9 @@ namespace Nz
return m_positions.data();
}
inline UInt32 OBJParser::GetPositionCount() const
inline std::size_t OBJParser::GetPositionCount() const
{
return static_cast<UInt32>(m_positions.size());
return m_positions.size();
}
inline Vector3f* OBJParser::GetTexCoords()
@ -91,41 +91,41 @@ namespace Nz
return m_texCoords.data();
}
inline UInt32 OBJParser::GetTexCoordCount() const
inline std::size_t OBJParser::GetTexCoordCount() const
{
return static_cast<UInt32>(m_texCoords.size());
return m_texCoords.size();
}
inline String* OBJParser::SetMaterialCount(UInt32 materialCount)
inline std::string* OBJParser::SetMaterialCount(std::size_t materialCount)
{
m_materials.resize(materialCount);
return m_materials.data();
}
inline OBJParser::Mesh* OBJParser::SetMeshCount(UInt32 meshCount)
inline OBJParser::Mesh* OBJParser::SetMeshCount(std::size_t meshCount)
{
m_meshes.resize(meshCount);
return m_meshes.data();
}
inline void OBJParser::SetMtlLib(const String& mtlLib)
inline void OBJParser::SetMtlLib(const std::filesystem::path& mtlLib)
{
m_mtlLib = mtlLib;
}
inline Vector3f* OBJParser::SetNormalCount(UInt32 normalCount)
inline Vector3f* OBJParser::SetNormalCount(std::size_t normalCount)
{
m_normals.resize(normalCount);
return m_normals.data();
}
inline Vector4f* OBJParser::SetPositionCount(UInt32 positionCount)
inline Vector4f* OBJParser::SetPositionCount(std::size_t positionCount)
{
m_positions.resize(positionCount);
return m_positions.data();
}
inline Vector3f* OBJParser::SetTexCoordCount(UInt32 texCoordCount)
inline Vector3f* OBJParser::SetTexCoordCount(std::size_t texCoordCount)
{
m_texCoords.resize(texCoordCount);
return m_texCoords.data();
@ -151,9 +151,9 @@ namespace Nz
Emit('\n');
}
inline void OBJParser::Error(const String& message)
inline void OBJParser::Error(const std::string& message)
{
NazaraError(message + " at line #" + String::Number(m_lineCount));
NazaraError(message + " at line #" + std::to_string(m_lineCount));
}
inline void OBJParser::Flush() const
@ -162,14 +162,14 @@ namespace Nz
m_outputStream.Clear();
}
inline void OBJParser::Warning(const String& message)
inline void OBJParser::Warning(const std::string& message)
{
NazaraWarning(message + " at line #" + String::Number(m_lineCount));
NazaraWarning(message + " at line #" + std::to_string(m_lineCount));
}
inline bool OBJParser::UnrecognizedLine(bool error)
{
String message = "Unrecognized \"" + m_currentLine + '"';
std::string message = "Unrecognized \"" + m_currentLine + '"';
if (error)
Error(message);

View File

@ -94,13 +94,13 @@ namespace Nz
bool IsValid() const;
// LoadFace
bool LoadFaceFromFile(CubemapFace face, const String& filePath, const ImageParams& params = ImageParams());
bool LoadFaceFromFile(CubemapFace face, const std::filesystem::path& filePath, const ImageParams& params = ImageParams());
bool LoadFaceFromMemory(CubemapFace face, const void* data, std::size_t size, const ImageParams& params = ImageParams());
bool LoadFaceFromStream(CubemapFace face, Stream& stream, const ImageParams& params = ImageParams());
// Save
bool SaveToFile(const String& filePath, const ImageParams& params = ImageParams());
bool SaveToStream(Stream& stream, const String& format, const ImageParams& params = ImageParams());
bool SaveToFile(const std::filesystem::path& filePath, const ImageParams& params = ImageParams());
bool SaveToStream(Stream& stream, const std::string& format, const ImageParams& params = ImageParams());
//TODO: SaveArray, SaveCubemap, SaveFace
@ -118,18 +118,18 @@ namespace Nz
static UInt8 GetMaxLevel(ImageType type, unsigned int width, unsigned int height, unsigned int depth = 1);
// Load
static ImageRef LoadFromFile(const String& filePath, const ImageParams& params = ImageParams());
static ImageRef LoadFromFile(const std::filesystem::path& filePath, const ImageParams& params = ImageParams());
static ImageRef LoadFromMemory(const void* data, std::size_t size, const ImageParams& params = ImageParams());
static ImageRef LoadFromStream(Stream& stream, const ImageParams& params = ImageParams());
// LoadArray
static ImageRef LoadArrayFromFile(const String& filePath, const ImageParams& imageParams = ImageParams(), const Vector2ui& atlasSize = Vector2ui(2, 2));
static ImageRef LoadArrayFromFile(const std::filesystem::path& filePath, const ImageParams& imageParams = ImageParams(), const Vector2ui& atlasSize = Vector2ui(2, 2));
static ImageRef LoadArrayFromImage(const Image* image, const Vector2ui& atlasSize = Vector2ui(2, 2));
static ImageRef LoadArrayFromMemory(const void* data, std::size_t size, const ImageParams& imageParams = ImageParams(), const Vector2ui& atlasSize = Vector2ui(2, 2));
static ImageRef LoadArrayFromStream(Stream& stream, const ImageParams& imageParams = ImageParams(), const Vector2ui& atlasSize = Vector2ui(2, 2));
// LoadCubemap
static ImageRef LoadCubemapFromFile(const String& filePath, const ImageParams& imageParams = ImageParams(), const CubemapParams& cubemapParams = CubemapParams());
static ImageRef LoadCubemapFromFile(const std::filesystem::path& filePath, const ImageParams& imageParams = ImageParams(), const CubemapParams& cubemapParams = CubemapParams());
static ImageRef LoadCubemapFromImage(const Image* image, const CubemapParams& params = CubemapParams());
static ImageRef LoadCubemapFromMemory(const void* data, std::size_t size, const ImageParams& imageParams = ImageParams(), const CubemapParams& cubemapParams = CubemapParams());
static ImageRef LoadCubemapFromStream(Stream& stream, const ImageParams& imageParams = ImageParams(), const CubemapParams& cubemapParams = CubemapParams());

View File

@ -24,39 +24,39 @@ namespace Nz
public:
IndexBuffer() = default;
IndexBuffer(bool largeIndices, BufferRef buffer);
IndexBuffer(bool largeIndices, BufferRef buffer, UInt32 offset, UInt32 size);
IndexBuffer(bool largeIndices, UInt32 length, DataStorage storage, BufferUsageFlags usage);
IndexBuffer(bool largeIndices, BufferRef buffer, std::size_t offset, std::size_t size);
IndexBuffer(bool largeIndices, std::size_t length, DataStorage storage, BufferUsageFlags usage);
IndexBuffer(const IndexBuffer& indexBuffer);
IndexBuffer(IndexBuffer&&) = delete;
~IndexBuffer();
unsigned int ComputeCacheMissCount() const;
bool Fill(const void* data, UInt32 startIndex, UInt32 length);
bool FillRaw(const void* data, UInt32 offset, UInt32 size);
bool Fill(const void* data, std::size_t startIndex, std::size_t length);
bool FillRaw(const void* data, std::size_t offset, std::size_t size);
inline const BufferRef& GetBuffer() const;
inline UInt32 GetEndOffset() const;
inline UInt32 GetIndexCount() const;
inline std::size_t GetEndOffset() const;
inline std::size_t GetIndexCount() const;
inline DataStorage GetStorage() const;
inline UInt32 GetStride() const;
inline UInt32 GetStartOffset() const;
inline std::size_t GetStride() const;
inline std::size_t GetStartOffset() const;
inline bool HasLargeIndices() const;
inline bool IsValid() const;
inline void* Map(BufferAccess access, UInt32 startVertex = 0, UInt32 length = 0);
inline void* Map(BufferAccess access, UInt32 startVertex = 0, UInt32 length = 0) const;
void* MapRaw(BufferAccess access, UInt32 offset = 0, UInt32 size = 0);
void* MapRaw(BufferAccess access, UInt32 offset = 0, UInt32 size = 0) const;
inline void* Map(BufferAccess access, std::size_t startVertex = 0, std::size_t length = 0);
inline void* Map(BufferAccess access, std::size_t startVertex = 0, std::size_t length = 0) const;
void* MapRaw(BufferAccess access, std::size_t offset = 0, std::size_t size = 0);
void* MapRaw(BufferAccess access, std::size_t offset = 0, std::size_t size = 0) const;
void Optimize();
void Reset();
void Reset(bool largeIndices, BufferRef buffer);
void Reset(bool largeIndices, BufferRef buffer, UInt32 offset, UInt32 size);
void Reset(bool largeIndices, UInt32 length, DataStorage storage, BufferUsageFlags usage);
void Reset(bool largeIndices, BufferRef buffer, std::size_t offset, std::size_t size);
void Reset(bool largeIndices, std::size_t length, DataStorage storage, BufferUsageFlags usage);
void Reset(const IndexBuffer& indexBuffer);
void Unmap() const;
@ -71,9 +71,9 @@ namespace Nz
private:
BufferRef m_buffer;
UInt32 m_endOffset;
UInt32 m_indexCount;
UInt32 m_startOffset;
std::size_t m_endOffset;
std::size_t m_indexCount;
std::size_t m_startOffset;
bool m_largeIndices;
};
}

View File

@ -12,12 +12,12 @@ namespace Nz
return m_buffer;
}
inline UInt32 IndexBuffer::GetEndOffset() const
inline std::size_t IndexBuffer::GetEndOffset() const
{
return m_endOffset;
}
inline UInt32 IndexBuffer::GetIndexCount() const
inline std::size_t IndexBuffer::GetIndexCount() const
{
return m_indexCount;
}
@ -27,12 +27,12 @@ namespace Nz
return DataStorage();
}
inline UInt32 IndexBuffer::GetStride() const
inline std::size_t IndexBuffer::GetStride() const
{
return static_cast<UInt32>((m_largeIndices) ? sizeof(UInt32) : sizeof(UInt16));
return static_cast<std::size_t>((m_largeIndices) ? sizeof(std::size_t) : sizeof(UInt16));
}
inline UInt32 IndexBuffer::GetStartOffset() const
inline std::size_t IndexBuffer::GetStartOffset() const
{
return m_startOffset;
}
@ -47,15 +47,15 @@ namespace Nz
return m_buffer.IsValid();
}
inline void* IndexBuffer::Map(BufferAccess access, UInt32 startIndex, UInt32 length)
inline void* IndexBuffer::Map(BufferAccess access, std::size_t startIndex, std::size_t length)
{
UInt32 stride = GetStride();
std::size_t stride = GetStride();
return MapRaw(access, startIndex*stride, length*stride);
}
inline void* IndexBuffer::Map(BufferAccess access, UInt32 startIndex, UInt32 length) const
inline void* IndexBuffer::Map(BufferAccess access, std::size_t startIndex, std::size_t length) const
{
UInt32 stride = GetStride();
std::size_t stride = GetStride();
return MapRaw(access, startIndex*stride, length*stride);
}

View File

@ -89,12 +89,12 @@ namespace Nz
inline ~Mesh();
void AddSubMesh(SubMesh* subMesh);
void AddSubMesh(const String& identifier, SubMesh* subMesh);
void AddSubMesh(const std::string& identifier, SubMesh* subMesh);
SubMesh* BuildSubMesh(const Primitive& primitive, const MeshParams& params = MeshParams());
void BuildSubMeshes(const PrimitiveList& list, const MeshParams& params = MeshParams());
bool CreateSkeletal(UInt32 jointCount);
bool CreateSkeletal(std::size_t jointCount);
bool CreateStatic();
void Destroy();
@ -103,25 +103,25 @@ namespace Nz
void GenerateTangents();
const Boxf& GetAABB() const;
String GetAnimation() const;
std::filesystem::path GetAnimation() const;
AnimationType GetAnimationType() const;
UInt32 GetJointCount() const;
ParameterList& GetMaterialData(UInt32 index);
const ParameterList& GetMaterialData(UInt32 index) const;
UInt32 GetMaterialCount() const;
std::size_t GetJointCount() const;
ParameterList& GetMaterialData(std::size_t index);
const ParameterList& GetMaterialData(std::size_t index) const;
std::size_t GetMaterialCount() const;
Skeleton* GetSkeleton();
const Skeleton* GetSkeleton() const;
SubMesh* GetSubMesh(const String& identifier);
SubMesh* GetSubMesh(UInt32 index);
const SubMesh* GetSubMesh(const String& identifier) const;
const SubMesh* GetSubMesh(UInt32 index) const;
UInt32 GetSubMeshCount() const;
UInt32 GetSubMeshIndex(const String& identifier) const;
UInt32 GetTriangleCount() const;
UInt32 GetVertexCount() const;
SubMesh* GetSubMesh(const std::string& identifier);
SubMesh* GetSubMesh(std::size_t index);
const SubMesh* GetSubMesh(const std::string& identifier) const;
const SubMesh* GetSubMesh(std::size_t index) const;
std::size_t GetSubMeshCount() const;
std::size_t GetSubMeshIndex(const std::string& identifier) const;
std::size_t GetTriangleCount() const;
std::size_t GetVertexCount() const;
bool HasSubMesh(const String& identifier) const;
bool HasSubMesh(UInt32 index = 0) const;
bool HasSubMesh(const std::string& identifier) const;
bool HasSubMesh(std::size_t index = 0) const;
void InvalidateAABB() const;
@ -130,22 +130,22 @@ namespace Nz
void Recenter();
void RemoveSubMesh(const String& identifier);
void RemoveSubMesh(UInt32 index);
void RemoveSubMesh(const std::string& identifier);
void RemoveSubMesh(std::size_t index);
bool SaveToFile(const String& filePath, const MeshParams& params = MeshParams());
bool SaveToStream(Stream& stream, const String& format, const MeshParams& params = MeshParams());
bool SaveToFile(const std::filesystem::path& filePath, const MeshParams& params = MeshParams());
bool SaveToStream(Stream& stream, const std::string& format, const MeshParams& params = MeshParams());
void SetAnimation(const String& animationPath);
void SetMaterialCount(UInt32 matCount);
void SetMaterialData(UInt32 matIndex, ParameterList data);
void SetAnimation(const std::filesystem::path& animationPath);
void SetMaterialCount(std::size_t matCount);
void SetMaterialData(std::size_t matIndex, ParameterList data);
void Transform(const Matrix4f& matrix);
Mesh& operator=(const Mesh&) = delete;
Mesh& operator=(Mesh&&) = delete;
static MeshRef LoadFromFile(const String& filePath, const MeshParams& params = MeshParams());
static MeshRef LoadFromFile(const std::filesystem::path& filePath, const MeshParams& params = MeshParams());
static MeshRef LoadFromMemory(const void* data, std::size_t size, const MeshParams& params = MeshParams());
static MeshRef LoadFromStream(Stream& stream, const MeshParams& params = MeshParams());
@ -164,16 +164,16 @@ namespace Nz
NazaraSlot(SubMesh, OnSubMeshInvalidateAABB, onSubMeshInvalidated);
};
std::unordered_map<String, UInt32> m_subMeshMap;
std::unordered_map<std::string, std::size_t> m_subMeshMap;
std::vector<ParameterList> m_materialData;
std::vector<SubMeshData> m_subMeshes;
AnimationType m_animationType;
mutable Boxf m_aabb;
Skeleton m_skeleton; // Only used by skeletal meshes
String m_animationPath;
std::filesystem::path m_animationPath;
mutable bool m_aabbUpdated;
bool m_isValid;
UInt32 m_jointCount; // Only used by skeletal meshes
std::size_t m_jointCount; // Only used by skeletal meshes
static bool Initialize();
static void Uninitialize();

View File

@ -36,13 +36,13 @@ namespace Nz
void Destroy();
const Boxf& GetAABB() const override;
AnimationType GetAnimationType() const final override;
AnimationType GetAnimationType() const final;
const IndexBuffer* GetIndexBuffer() const override;
VertexBuffer* GetVertexBuffer();
const VertexBuffer* GetVertexBuffer() const;
unsigned int GetVertexCount() const override;
std::size_t GetVertexCount() const override;
bool IsAnimated() const final override;
bool IsAnimated() const final;
bool IsValid() const;
void SetAABB(const Boxf& aabb);

View File

@ -37,21 +37,21 @@ namespace Nz
Skeleton(const Skeleton& skeleton);
~Skeleton();
bool Create(UInt32 jointCount);
bool Create(std::size_t jointCount);
void Destroy();
const Boxf& GetAABB() const;
Joint* GetJoint(const String& jointName);
Joint* GetJoint(UInt32 index);
Joint* GetJoint(std::size_t index);
const Joint* GetJoint(const String& jointName) const;
const Joint* GetJoint(UInt32 index) const;
const Joint* GetJoint(std::size_t index) const;
Joint* GetJoints();
const Joint* GetJoints() const;
UInt32 GetJointCount() const;
std::size_t GetJointCount() const;
int GetJointIndex(const String& jointName) const;
void Interpolate(const Skeleton& skeletonA, const Skeleton& skeletonB, float interpolation);
void Interpolate(const Skeleton& skeletonA, const Skeleton& skeletonB, float interpolation, UInt32* indices, UInt32 indiceCount);
void Interpolate(const Skeleton& skeletonA, const Skeleton& skeletonB, float interpolation, std::size_t* indices, std::size_t indiceCount);
bool IsValid() const;

View File

@ -37,13 +37,13 @@ namespace Nz
bool GenerateAABB();
const Boxf& GetAABB() const override;
AnimationType GetAnimationType() const final override;
AnimationType GetAnimationType() const final;
const IndexBuffer* GetIndexBuffer() const override;
VertexBuffer* GetVertexBuffer();
const VertexBuffer* GetVertexBuffer() const;
unsigned int GetVertexCount() const override;
std::size_t GetVertexCount() const override;
bool IsAnimated() const final override;
bool IsAnimated() const final;
bool IsValid() const;
void SetAABB(const Boxf& aabb);

View File

@ -44,14 +44,14 @@ namespace Nz
virtual const Boxf& GetAABB() const = 0;
virtual AnimationType GetAnimationType() const = 0;
virtual const IndexBuffer* GetIndexBuffer() const = 0;
UInt32 GetMaterialIndex() const;
std::size_t GetMaterialIndex() const;
PrimitiveMode GetPrimitiveMode() const;
UInt32 GetTriangleCount() const;
virtual UInt32 GetVertexCount() const = 0;
std::size_t GetTriangleCount() const;
virtual std::size_t GetVertexCount() const = 0;
virtual bool IsAnimated() const = 0;
void SetMaterialIndex(UInt32 matIndex);
void SetMaterialIndex(std::size_t matIndex);
void SetPrimitiveMode(PrimitiveMode mode);
SubMesh& operator=(const SubMesh&) = delete;
@ -63,7 +63,7 @@ namespace Nz
protected:
PrimitiveMode m_primitiveMode;
UInt32 m_matIndex;
std::size_t m_matIndex;
};
}

View File

@ -26,33 +26,33 @@ namespace Nz
public:
VertexBuffer() = default;
VertexBuffer(VertexDeclarationConstRef vertexDeclaration, BufferRef buffer);
VertexBuffer(VertexDeclarationConstRef vertexDeclaration, BufferRef buffer, UInt32 offset, UInt32 size);
VertexBuffer(VertexDeclarationConstRef vertexDeclaration, UInt32 length, DataStorage storage, BufferUsageFlags usage);
VertexBuffer(VertexDeclarationConstRef vertexDeclaration, BufferRef buffer, std::size_t offset, std::size_t size);
VertexBuffer(VertexDeclarationConstRef vertexDeclaration, std::size_t length, DataStorage storage, BufferUsageFlags usage);
VertexBuffer(const VertexBuffer& vertexBuffer);
VertexBuffer(VertexBuffer&&) = delete;
~VertexBuffer();
bool Fill(const void* data, UInt32 startVertex, UInt32 length);
bool FillRaw(const void* data, UInt32 offset, UInt32 size);
bool Fill(const void* data, std::size_t startVertex, std::size_t length);
bool FillRaw(const void* data, std::size_t offset, std::size_t size);
inline const BufferRef& GetBuffer() const;
inline UInt32 GetEndOffset() const;
inline UInt32 GetStartOffset() const;
inline UInt32 GetStride() const;
inline UInt32 GetVertexCount() const;
inline std::size_t GetEndOffset() const;
inline std::size_t GetStartOffset() const;
inline std::size_t GetStride() const;
inline std::size_t GetVertexCount() const;
inline const VertexDeclarationConstRef& GetVertexDeclaration() const;
inline bool IsValid() const;
void* Map(BufferAccess access, UInt32 startVertex = 0, UInt32 length = 0);
void* Map(BufferAccess access, UInt32 startVertex = 0, UInt32 length = 0) const;
void* MapRaw(BufferAccess access, UInt32 offset = 0, UInt32 size = 0);
void* MapRaw(BufferAccess access, UInt32 offset = 0, UInt32 size = 0) const;
void* Map(BufferAccess access, std::size_t startVertex = 0, std::size_t length = 0);
void* Map(BufferAccess access, std::size_t startVertex = 0, std::size_t length = 0) const;
void* MapRaw(BufferAccess access, std::size_t offset = 0, std::size_t size = 0);
void* MapRaw(BufferAccess access, std::size_t offset = 0, std::size_t size = 0) const;
void Reset();
void Reset(VertexDeclarationConstRef vertexDeclaration, BufferRef buffer);
void Reset(VertexDeclarationConstRef vertexDeclaration, BufferRef buffer, UInt32 offset, UInt32 size);
void Reset(VertexDeclarationConstRef vertexDeclaration, UInt32 length, DataStorage storage, BufferUsageFlags usage);
void Reset(VertexDeclarationConstRef vertexDeclaration, BufferRef buffer, std::size_t offset, std::size_t size);
void Reset(VertexDeclarationConstRef vertexDeclaration, std::size_t length, DataStorage storage, BufferUsageFlags usage);
void Reset(const VertexBuffer& vertexBuffer);
void SetVertexDeclaration(VertexDeclarationConstRef vertexDeclaration);
@ -69,9 +69,9 @@ namespace Nz
private:
BufferRef m_buffer;
UInt32 m_endOffset;
UInt32 m_startOffset;
UInt32 m_vertexCount;
std::size_t m_endOffset;
std::size_t m_startOffset;
std::size_t m_vertexCount;
VertexDeclarationConstRef m_vertexDeclaration;
};
}

View File

@ -12,22 +12,22 @@ namespace Nz
return m_buffer;
}
inline UInt32 VertexBuffer::GetEndOffset() const
inline std::size_t VertexBuffer::GetEndOffset() const
{
return m_endOffset;
}
inline UInt32 VertexBuffer::GetStride() const
inline std::size_t VertexBuffer::GetStride() const
{
return static_cast<UInt32>(m_vertexDeclaration->GetStride());
return static_cast<std::size_t>(m_vertexDeclaration->GetStride());
}
inline UInt32 VertexBuffer::GetStartOffset() const
inline std::size_t VertexBuffer::GetStartOffset() const
{
return m_startOffset;
}
inline UInt32 VertexBuffer::GetVertexCount() const
inline std::size_t VertexBuffer::GetVertexCount() const
{
return m_vertexCount;
}

View File

@ -1,4 +1,4 @@
// Copyright (C) 2017 Jérôme Leclercq
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Engine - Utility module"
// For conditions of distribution and use, see copyright notice in Config.hpp
@ -28,7 +28,7 @@ namespace Nz
template<typename T> SparsePtr<T> GetComponentPtr(VertexComponent component);
inline const VertexBuffer* GetVertexBuffer() const;
inline UInt32 GetVertexCount() const;
inline std::size_t GetVertexCount() const;
template<typename T> bool HasComponentOfType(VertexComponent component) const;

View File

@ -1,4 +1,4 @@
// Copyright (C) 2017 Jérôme Leclercq
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Nazara Engine - Utility module"
// For conditions of distribution and use, see copyright notice in Config.hpp
@ -32,7 +32,7 @@ namespace Nz
return m_mapper.GetBuffer();
}
inline UInt32 VertexMapper::GetVertexCount() const
inline std::size_t VertexMapper::GetVertexCount() const
{
return GetVertexBuffer()->GetVertexCount();
}

View File

@ -74,10 +74,10 @@ void ProcessJoints(aiNode* node, Skeleton* skeleton, const std::set<Nz::String>&
ProcessJoints(node->mChildren[i], skeleton, joints);
}
bool IsSupported(const String& extension)
bool IsSupported(const std::string& extension)
{
String dotExt = '.' + extension;
return (aiIsExtensionSupported(dotExt.GetConstBuffer()) == AI_TRUE);
std::string dotExt = '.' + extension;
return (aiIsExtensionSupported(dotExt.data()) == AI_TRUE);
}
Ternary CheckAnimation(Stream& /*stream*/, const AnimationParams& parameters)
@ -91,10 +91,10 @@ Ternary CheckAnimation(Stream& /*stream*/, const AnimationParams& parameters)
AnimationRef LoadAnimation(Stream& stream, const AnimationParams& parameters)
{
Nz::String streamPath = stream.GetPath();
std::string streamPath = stream.GetPath().generic_u8string();
FileIOUserdata userdata;
userdata.originalFilePath = (!streamPath.IsEmpty()) ? streamPath.GetConstBuffer() : StreamPath;
userdata.originalFilePath = (!streamPath.empty()) ? streamPath.data() : StreamPath;
userdata.originalStream = &stream;
aiFileIO fileIO;
@ -186,10 +186,10 @@ Ternary CheckMesh(Stream& /*stream*/, const MeshParams& parameters)
MeshRef LoadMesh(Stream& stream, const MeshParams& parameters)
{
Nz::String streamPath = stream.GetPath();
std::string streamPath = stream.GetPath().generic_u8string();
FileIOUserdata userdata;
userdata.originalFilePath = (!streamPath.IsEmpty()) ? streamPath.GetConstBuffer() : StreamPath;
userdata.originalFilePath = (!streamPath.empty()) ? streamPath.data() : StreamPath;
userdata.originalStream = &stream;
aiFileIO fileIO;
@ -377,7 +377,7 @@ MeshRef LoadMesh(Stream& stream, const MeshParams& parameters)
aiTextureMapMode mapMode[3];
if (aiGetMaterialTexture(aiMat, aiType, 0, &path, nullptr, nullptr, nullptr, nullptr, &mapMode[0], nullptr) == aiReturn_SUCCESS)
{
matData.SetParameter(textureKey, stream.GetDirectory() + String(path.data, path.length));
matData.SetParameter(textureKey, (stream.GetDirectory() / std::string_view(path.data, path.length)).generic_u8string());
if (wrapKey)
{
@ -563,7 +563,7 @@ MeshRef LoadMesh(Stream& stream, const MeshParams& parameters)
aiTextureMapMode mapMode[3];
if (aiGetMaterialTexture(aiMat, aiType, 0, &path, nullptr, nullptr, nullptr, nullptr, &mapMode[0], nullptr) == aiReturn_SUCCESS)
{
matData.SetParameter(textureKey, stream.GetDirectory() + String(path.data, path.length));
matData.SetParameter(textureKey, (stream.GetDirectory() / std::string_view(path.data, path.length)).generic_u8string());
if (wrapKey)
{

View File

@ -14,9 +14,7 @@
#include <Nazara/Core/Error.hpp>
#include <Nazara/Core/File.hpp>
#include <Nazara/Core/MemoryView.hpp>
#include <Nazara/Core/Mutex.hpp>
#include <Nazara/Core/Stream.hpp>
#include <iostream>
#include <memory>
#include <set>
#include <vector>
@ -99,7 +97,7 @@ namespace Nz
return m_format;
}
Mutex& GetMutex() override
std::mutex& GetMutex() override
{
return m_mutex;
}
@ -114,11 +112,11 @@ namespace Nz
return m_sampleRate;
}
bool Open(const String& filePath, bool forceMono)
bool Open(const std::filesystem::path& filePath, bool forceMono)
{
// Nous devons gérer nous-même le flux car il doit rester ouvert après le passage du loader
// (les flux automatiquement ouverts par le ResourceLoader étant fermés après celui-ci)
std::unique_ptr<File> file(new File);
std::unique_ptr<File> file = std::make_unique<File>();
if (!file->Open(filePath, OpenMode_ReadOnly))
{
NazaraError("Failed to open stream from file: " + Error::GetLastError());
@ -219,15 +217,15 @@ namespace Nz
AudioFormat m_format;
SNDFILE* m_handle;
bool m_mixToMono;
Mutex m_mutex;
std::mutex m_mutex;
UInt32 m_duration;
UInt32 m_sampleRate;
UInt64 m_sampleCount;
};
bool IsSupported(const String& extension)
bool IsSupported(const std::string& extension)
{
static std::set<String> supportedExtensions = {
static std::set<std::string> supportedExtensions = {
"aiff", "au", "avr", "caf", "flac", "htk", "ircam", "mat4", "mat5", "mpc2k",
"nist","ogg", "pvf", "raw", "rf64", "sd2", "sds", "svx", "voc", "w64", "wav", "wve"
};
@ -253,9 +251,9 @@ namespace Nz
return Ternary_False;
}
SoundStreamRef LoadSoundStreamFile(const String& filePath, const SoundStreamParams& parameters)
SoundStreamRef LoadSoundStreamFile(const std::filesystem::path& filePath, const SoundStreamParams& parameters)
{
std::unique_ptr<sndfileStream> soundStream(new sndfileStream);
std::unique_ptr<sndfileStream> soundStream = std::make_unique<sndfileStream>();
if (!soundStream->Open(filePath, parameters.forceMono))
{
NazaraError("Failed to open sound stream");

View File

@ -5,12 +5,11 @@
#include <Nazara/Audio/Music.hpp>
#include <Nazara/Audio/OpenAL.hpp>
#include <Nazara/Audio/SoundStream.hpp>
#include <Nazara/Core/LockGuard.hpp>
#include <Nazara/Core/Mutex.hpp>
#include <Nazara/Core/Thread.hpp>
#include <atomic>
#include <chrono>
#include <memory>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
#include <Nazara/Audio/Debug.hpp>
@ -29,9 +28,9 @@ namespace Nz
ALenum audioFormat;
std::atomic<UInt64> processedSamples;
std::vector<Int16> chunkSamples;
Mutex bufferLock;
std::mutex bufferLock;
SoundStreamRef stream;
Thread thread;
std::thread thread;
UInt64 playingOffset;
bool loop = false;
bool streaming = false;
@ -142,7 +141,7 @@ namespace Nz
NazaraAssert(m_impl, "Music not created");
// Prevent music thread from enqueing new buffers while we're getting the count
Nz::LockGuard lock(m_impl->bufferLock);
std::lock_guard<std::mutex> lock(m_impl->bufferLock);
ALint samples = 0;
alGetSourcei(m_source, AL_SAMPLE_OFFSET, &samples);
@ -215,7 +214,7 @@ namespace Nz
* \param filePath Path to the file
* \param params Parameters for the music
*/
bool Music::OpenFromFile(const String& filePath, const SoundStreamParams& params)
bool Music::OpenFromFile(const std::filesystem::path& filePath, const SoundStreamParams& params)
{
if (SoundStreamRef soundStream = SoundStream::OpenFromFile(filePath, params))
return Create(soundStream);
@ -305,7 +304,7 @@ namespace Nz
{
// Starting streaming's thread
m_impl->streaming = true;
m_impl->thread = Thread(&Music::MusicThread, this);
m_impl->thread = std::thread(&Music::MusicThread, this);
}
}
@ -351,30 +350,29 @@ namespace Nz
{
std::size_t sampleCount = m_impl->chunkSamples.size();
std::size_t sampleRead = 0;
Nz::LockGuard lock(m_impl->stream->GetMutex());
m_impl->stream->Seek(m_impl->playingOffset);
// Fill the buffer by reading from the stream
for (;;)
{
sampleRead += m_impl->stream->Read(&m_impl->chunkSamples[sampleRead], sampleCount - sampleRead);
if (sampleRead < sampleCount && m_impl->loop)
std::lock_guard<std::mutex> lock(m_impl->stream->GetMutex());
m_impl->stream->Seek(m_impl->playingOffset);
// Fill the buffer by reading from the stream
for (;;)
{
// In case we read less than expected, assume we reached the end of the stream and seek back to the beginning
m_impl->stream->Seek(0);
continue;
sampleRead += m_impl->stream->Read(&m_impl->chunkSamples[sampleRead], sampleCount - sampleRead);
if (sampleRead < sampleCount && m_impl->loop)
{
// In case we read less than expected, assume we reached the end of the stream and seek back to the beginning
m_impl->stream->Seek(0);
continue;
}
// Either we read the size we wanted, either we're not looping
break;
}
// Either we read the size we wanted, either we're not looping
break;
m_impl->playingOffset = m_impl->stream->Tell();
}
m_impl->playingOffset = m_impl->stream->Tell();
lock.Unlock();
// Update the buffer (send it to OpenAL) and queue it if we got any data
if (sampleRead > 0)
{
@ -410,31 +408,31 @@ namespace Nz
break;
}
Nz::LockGuard lock(m_impl->bufferLock);
// We treat read buffers
ALint processedCount = 0;
alGetSourcei(m_source, AL_BUFFERS_PROCESSED, &processedCount);
while (processedCount--)
{
ALuint buffer;
alSourceUnqueueBuffers(m_source, 1, &buffer);
std::lock_guard<std::mutex> lock(m_impl->bufferLock);
ALint bits, size;
alGetBufferi(buffer, AL_BITS, &bits);
alGetBufferi(buffer, AL_SIZE, &size);
// We treat read buffers
ALint processedCount = 0;
alGetSourcei(m_source, AL_BUFFERS_PROCESSED, &processedCount);
while (processedCount--)
{
ALuint buffer;
alSourceUnqueueBuffers(m_source, 1, &buffer);
if (bits != 0)
m_impl->processedSamples += (8 * size) / bits;
ALint bits, size;
alGetBufferi(buffer, AL_BITS, &bits);
alGetBufferi(buffer, AL_SIZE, &size);
if (FillAndQueueBuffer(buffer))
break;
if (bits != 0)
m_impl->processedSamples += (8 * size) / bits;
if (FillAndQueueBuffer(buffer))
break;
}
}
lock.Unlock();
// We go back to sleep
Thread::Sleep(50);
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
// Stop playing of the sound (in the case where it has not been already done)
@ -456,7 +454,7 @@ namespace Nz
if (m_impl->streaming)
{
m_impl->streaming = false;
m_impl->thread.Join();
m_impl->thread.join();
}
}
}

View File

@ -41,7 +41,7 @@ namespace Nz
std::size_t length;
while ((length = std::strlen(deviceString)) > 0)
{
devices.push_back(String(deviceString, length));
devices.emplace_back(deviceString, length);
deviceString += length + 1;
}
@ -140,7 +140,7 @@ namespace Nz
bool succeeded = false;
for (const char* path : libs)
{
String libPath(path);
std::filesystem::path libPath(path);
if (!s_library.Load(libPath))
continue;
@ -248,7 +248,7 @@ namespace Nz
}
catch (const std::exception& e)
{
NazaraWarning(libPath + " loading failed: " + String(e.what()));
NazaraWarning(libPath.generic_u8string() + " loading failed: " + std::string(e.what()));
continue;
}
}

View File

@ -149,12 +149,12 @@ namespace Nz
*
* \remark Produces a NazaraError if loading failed
*/
bool Sound::LoadFromFile(const String& filePath, const SoundBufferParams& params)
bool Sound::LoadFromFile(const std::filesystem::path& filePath, const SoundBufferParams& params)
{
SoundBufferRef buffer = SoundBuffer::LoadFromFile(filePath, params);
if (!buffer)
{
NazaraError("Failed to load buffer from file (" + filePath + ')');
NazaraError("Failed to load buffer from file (" + filePath.generic_u8string() + ')');
return false;
}

View File

@ -269,7 +269,7 @@ namespace Nz
* \param filePath Path to the file
* \param params Parameters for the sound buffer
*/
SoundBufferRef SoundBuffer::LoadFromFile(const String& filePath, const SoundBufferParams& params)
SoundBufferRef SoundBuffer::LoadFromFile(const std::filesystem::path& filePath, const SoundBufferParams& params)
{
return SoundBufferLoader::LoadFromFile(filePath, params);
}

View File

@ -21,7 +21,7 @@ namespace Nz
SoundStream::~SoundStream() = default;
SoundStreamRef SoundStream::OpenFromFile(const String& filePath, const SoundStreamParams& params)
SoundStreamRef SoundStream::OpenFromFile(const std::filesystem::path& filePath, const SoundStreamParams& params)
{
return SoundStreamLoader::LoadFromFile(filePath, params);
}

View File

@ -12,12 +12,6 @@
#error OS not handled
#endif
#if NAZARA_CORE_THREADSAFE && NAZARA_THREADSAFETY_CLOCK
#include <Nazara/Core/ThreadSafety.hpp>
#else
#include <Nazara/Core/ThreadSafetyOff.hpp>
#endif
#include <Nazara/Core/Debug.hpp>
namespace Nz
@ -78,8 +72,6 @@ namespace Nz
*/
UInt64 Clock::GetMicroseconds() const
{
NazaraLock(m_mutex);
UInt64 elapsedMicroseconds = m_elapsedTime;
if (!m_paused)
elapsedMicroseconds += (GetElapsedMicroseconds() - m_refTime);
@ -106,8 +98,6 @@ namespace Nz
*/
bool Clock::IsPaused() const
{
NazaraLock(m_mutex);
return m_paused;
}
@ -121,8 +111,6 @@ namespace Nz
*/
void Clock::Pause()
{
NazaraLock(m_mutex);
if (!m_paused)
{
m_elapsedTime += GetElapsedMicroseconds() - m_refTime;
@ -139,8 +127,6 @@ namespace Nz
*/
UInt64 Clock::Restart()
{
NazaraLock(m_mutex);
Nz::UInt64 now = GetElapsedMicroseconds();
Nz::UInt64 elapsedTime = m_elapsedTime;
@ -164,8 +150,6 @@ namespace Nz
*/
void Clock::Unpause()
{
NazaraLock(m_mutex);
if (m_paused)
{
m_refTime = GetElapsedMicroseconds();

View File

@ -1,105 +0,0 @@
// Copyright (C) 2017 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/ConditionVariable.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Core/Mutex.hpp>
#if defined(NAZARA_PLATFORM_WINDOWS)
#include <Nazara/Core/Win32/ConditionVariableImpl.hpp>
#elif defined(NAZARA_PLATFORM_POSIX)
#include <Nazara/Core/Posix/ConditionVariableImpl.hpp>
#else
#error Condition variable has no implementation
#endif
#include <Nazara/Core/Debug.hpp>
namespace Nz
{
/*!
* \ingroup core
* \class Nz::ConditionVariable
* \brief Core class that represents a condition variable
*
* The ConditionVariable class is a synchronization primitive that can be used to block a thread, or multiple threads at the same time, until another thread both modifies a shared variable (the condition), and notifies the ConditionVariable
*/
/*!
* \brief Constructs a ConditionVariable object by default
*/
ConditionVariable::ConditionVariable()
{
m_impl = new ConditionVariableImpl;
}
/*!
* \brief Destructs the object
*/
ConditionVariable::~ConditionVariable()
{
delete m_impl;
}
/*!
* \brief Sends a signal to one thread waiting on the condition
*
* If any threads are waiting on *this, calling Signal unblocks one of the waiting threads
*
* \see SignalAll
*/
void ConditionVariable::Signal()
{
m_impl->Signal();
}
/*!
* \brief Sends a signal to every threads waiting on the condition
*
* Unblocks all threads currently waiting for *this
*
* \see Signal
*/
void ConditionVariable::SignalAll()
{
m_impl->SignalAll();
}
/*!
* \brief Makes the thread wait on the condition
*
* Wait causes the current thread to block until the condition variable is notified or a spurious wakeup occurs
*
* \param mutex Mutex for the condition
*
* \remark Produces a NazaraAssert if mutex is invalid
*/
void ConditionVariable::Wait(Mutex* mutex)
{
NazaraAssert(mutex != nullptr, "Mutex must be valid");
m_impl->Wait(mutex->m_impl);
}
/*!
* \brief Makes the thread wait on the condition for a certain amount of time
*
* Wait causes the current thread to block until the condition variable is notified, a specific time is reached, or a spurious wakeup occurs
*
* \param mutex Mutex for the condition
* \param timeout Time before expiration of the waiting
*
* \remark Produces a NazaraAssert if mutex is invalid
*/
bool ConditionVariable::Wait(Mutex* mutex, UInt32 timeout)
{
NazaraAssert(mutex != nullptr, "Mutex must be valid");
return m_impl->Wait(mutex->m_impl, timeout);
}
}

View File

@ -1,535 +0,0 @@
// Copyright (C) 2017 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/Directory.hpp>
#include <Nazara/Core/Config.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Core/File.hpp>
#include <cstddef>
#include <cstring>
#include <string>
#if defined(NAZARA_PLATFORM_WINDOWS)
#include <Nazara/Core/Win32/DirectoryImpl.hpp>
#elif defined(NAZARA_PLATFORM_POSIX)
#include <Nazara/Core/Posix/DirectoryImpl.hpp>
#else
#error OS not handled
#endif
#if NAZARA_CORE_THREADSAFE && NAZARA_THREADSAFETY_DIRECTORY
#include <Nazara/Core/ThreadSafety.hpp>
#else
#include <Nazara/Core/ThreadSafetyOff.hpp>
#endif
#include <Nazara/Core/Debug.hpp>
namespace Nz
{
namespace
{
//FIXME: MinGW seems to dislike thread_local shared_ptr.. (using a std::string is a working hackfix)
thread_local std::string currentPath(DirectoryImpl::GetCurrent().ToStdString());
}
/*!
* \ingroup core
* \class Nz::Directory
* \brief Core class that represents a directory
*/
/*!
* \brief Constructs a Directory object by default
*/
Directory::Directory() :
m_pattern('*'),
m_impl(nullptr)
{
}
/*!
* \brief Constructs a Directory object with a path
*
* \param dirPath Path to the directory
*/
Directory::Directory(const String& dirPath) :
m_dirPath(dirPath),
m_pattern('*'),
m_impl(nullptr)
{
}
/*!
* \brief Destructs the object and calls Close
*
* \see Close
*/
Directory::~Directory()
{
Close();
}
/*!
* \brief Closes the directory
*/
void Directory::Close()
{
NazaraLock(m_mutex);
if (m_impl)
{
m_impl->Close();
delete m_impl;
m_impl = nullptr;
}
}
/*!
* \brief Checks whether the directory exists
* \return true if directory exists
*/
bool Directory::Exists() const
{
NazaraLock(m_mutex);
if (IsOpen())
return true; // If directory is open, then it exists
else
return Exists(m_dirPath);
}
/*!
* \brief Gets the path of the directory
* \return Path of the directory
*/
String Directory::GetPath() const
{
NazaraLock(m_mutex);
return m_dirPath;
}
/*!
* \brief Gets the pattern for the path of the directory
* \return Pattern for the path of the directory
*/
String Directory::GetPattern() const
{
NazaraLock(m_mutex);
return m_pattern;
}
/*!
* \brief Gets the result name of the directory
* \return Resulting name
*
* \remark Produces a NazaraError if directory is not open with NAZARA_CORE_SAFE defined
*/
String Directory::GetResultName() const
{
NazaraLock(m_mutex);
#if NAZARA_CORE_SAFE
if (!IsOpen())
{
NazaraError("Directory not opened");
return String();
}
#endif
return m_impl->GetResultName();
}
/*!
* \brief Gets the result path of the directory
* \return Resulting path
*
* \remark Produces a NazaraError if directory is not open with NAZARA_CORE_SAFE defined
*/
String Directory::GetResultPath() const
{
NazaraLock(m_mutex);
#if NAZARA_CORE_SAFE
if (!IsOpen())
{
NazaraError("Directory not opened");
return String();
}
#endif
return m_dirPath + NAZARA_DIRECTORY_SEPARATOR + m_impl->GetResultName();
}
/*!
* \brief Gets the resulting size of the directory
* \return Size of the directory
*
* \remark Produces a NazaraError if directory is not open with NAZARA_CORE_SAFE defined
*/
UInt64 Directory::GetResultSize() const
{
NazaraLock(m_mutex);
#if NAZARA_CORE_SAFE
if (!IsOpen())
{
NazaraError("Directory not opened");
return 0;
}
#endif
return m_impl->GetResultSize();
}
/*!
* \brief Checks whether the directory is open
* \return true if open
*/
bool Directory::IsOpen() const
{
NazaraLock(m_mutex);
return m_impl != nullptr;
}
/*!
* \brief Checks whether the directory is result
* \return true if result
*
* \remark Produces a NazaraError if directory is not open with NAZARA_CORE_SAFE defined
*/
bool Directory::IsResultDirectory() const
{
NazaraLock(m_mutex);
#if NAZARA_CORE_SAFE
if (!IsOpen())
{
NazaraError("Directory not opened");
return false;
}
#endif
return m_impl->IsResultDirectory();
}
/*!
* \brief Sets the next result in the directory
* \return true if directory has a next result
*
* \param skipDots Skips the dots in the path
*
* \remark Produces a NazaraError if directory is not open with NAZARA_CORE_SAFE defined
*/
bool Directory::NextResult(bool skipDots)
{
NazaraLock(m_mutex);
#if NAZARA_CORE_SAFE
if (!IsOpen())
{
NazaraError("Directory not opened");
return false;
}
#endif
String name;
for (;;)
{
if (!m_impl->NextResult())
return false;
name = m_impl->GetResultName();
if (skipDots && (name == '.' || name == ".."))
continue;
if (name.Match(m_pattern))
break;
}
return true;
}
/*!
* \brief Opens the directory
* \return true if opening is successful
*/
bool Directory::Open()
{
NazaraLock(m_mutex);
Close();
if (!Exists(m_dirPath))
return false;
m_impl = new DirectoryImpl(this);
if (!m_impl->Open(m_dirPath))
{
delete m_impl;
m_impl = nullptr;
return false;
}
return true;
}
/*!
* \brief Sets the path of the directory
*
* \param dirPath Path of the directory
*/
void Directory::SetPath(const String& dirPath)
{
NazaraLock(m_mutex);
Close();
m_dirPath = File::AbsolutePath(dirPath);
}
/*!
* \brief Sets the pattern of the directory
*
* \param pattern Pattern of the directory
*/
void Directory::SetPattern(const String& pattern)
{
NazaraLock(m_mutex);
m_pattern = pattern;
}
/*!
* \brief Copies the first directory to a new directory path
* \return true if copy is successful
*
* \param sourcePath Path of the original directory
* \param destPath Path of the copied directory
*
* \remark Produces a NazaraError if could not create destination directory
* \remark Produces a NazaraError if could not open origin directory
* \remark Produces a NazaraError if could not copy a file
*/
bool Directory::Copy(const String& sourcePath, const String& destPath)
{
if (sourcePath.IsEmpty() || destPath.IsEmpty())
return false;
String dirPath(sourcePath);
String dest(File::NormalizePath(destPath));
if (!Create(destPath, true))
{
NazaraError("Unable to create \"" + destPath + '"');
return false;
}
Directory dir(dirPath);
if (!dir.Open())
{
NazaraError("Unable to open \"" + destPath + '"');
return false;
}
while (dir.NextResult(true))
{
if (dir.IsResultDirectory())
{
if (!Copy(dir.GetResultPath(), dest + NAZARA_DIRECTORY_SEPARATOR + dir.GetResultName()))
return false;
}
else if (!File::Copy(dir.GetResultPath(), dest + NAZARA_DIRECTORY_SEPARATOR + dir.GetResultName()))
{
NazaraError("Failed to copy \"" + dir.GetResultPath() + "\" to \"" + dest + NAZARA_DIRECTORY_SEPARATOR + dir.GetResultName() + '"');
return false;
}
}
dir.Close();
return true;
}
/*!
* \brief Creates a directory from a path
* \return true if creation is successful
*
* \param dirPath Path of the directory
* \param recursive Creates subdirectories
*/
bool Directory::Create(const String& dirPath, bool recursive)
{
if (dirPath.IsEmpty())
return false;
if (recursive)
{
String path = File::NormalizePath(dirPath);
std::size_t foundPos = path.Find(NAZARA_DIRECTORY_SEPARATOR);
if (foundPos == String::npos)
return false;
#ifdef NAZARA_PLATFORM_WINDOWS
// Unlike to disk (Ex: "C:"), the network path is not considered as a directory (Ex: "\\Laptop")
if (path.Match("\\\\*"))
{
foundPos = path.Find('\\', 2);
if (foundPos == String::npos)
return false;
foundPos = path.Find('\\', foundPos + 1);
if (foundPos == String::npos)
return false;
}
#endif
for (;;)
{
String p = path.SubString(0, foundPos);
if (p.EndsWith(NAZARA_DIRECTORY_SEPARATOR))
p = p.SubString(0, -2);
if (!p.IsEmpty())
{
if (!DirectoryImpl::Exists(p) && !DirectoryImpl::Create(p))
return false;
if (foundPos == String::npos)
break;
}
foundPos = path.Find(NAZARA_DIRECTORY_SEPARATOR, foundPos + 1);
}
return true;
}
else
return DirectoryImpl::Create(File::NormalizePath(dirPath));
}
/*!
* \brief Checks whether the directory exists
* \return true if directory exists
*
* \param dirPath Path of the directory
*/
bool Directory::Exists(const String& dirPath)
{
if (dirPath.IsEmpty())
return false;
return DirectoryImpl::Exists(File::NormalizePath(dirPath));
}
/*!
* \brief Gets the current path of this directory
* \return Current path
*/
String Directory::GetCurrent()
{
return currentPath;
}
/*!
* \brief Gets this current file relative to the engine
* \return Path to this file
*/
const char* Directory::GetCurrentFileRelativeToEngine(const char* currentFile)
{
///FIXME: Is this method in the right place ?
const char* ptr = std::strstr(currentFile, "NazaraEngine/");
if (!ptr)
ptr = std::strstr(currentFile, "NazaraEngine\\");
if (!ptr)
ptr = currentFile;
return ptr;
}
/*!
* \brief Removes the directory
* \return true if remove is successful
*
* \param dirPath Path of the directory
* \param emptyDirectory Remove recursively
*/
bool Directory::Remove(const String& dirPath, bool emptyDirectory)
{
if (dirPath.IsEmpty())
return false;
if (emptyDirectory)
{
Directory dir(dirPath);
if (!dir.Open())
return DirectoryImpl::Remove(dirPath); // If we can't open the directory, we try to delete it
while (dir.NextResult(true))
{
if (dir.IsResultDirectory())
{
if (!Remove(dir.GetResultPath(), true))
return false;
}
else if (!File::Delete(dir.GetResultPath()))
{
NazaraError(dir.GetResultPath());
return false;
}
}
dir.Close();
}
return DirectoryImpl::Remove(File::NormalizePath(dirPath));
}
/*!
* \brief Sets the current directory
* \return true if directory path exists
*
* \param dirPath Path of the directory
*/
bool Directory::SetCurrent(const String& dirPath)
{
String path = File::AbsolutePath(dirPath);
if (DirectoryImpl::Exists(path))
{
currentPath = path.ToStdString();
return true;
}
else
return false;
}
}

View File

@ -15,12 +15,6 @@
#error No implementation for this platform
#endif
#if NAZARA_CORE_THREADSAFE && NAZARA_THREADSAFETY_DYNLIB
#include <Nazara/Core/ThreadSafety.hpp>
#else
#include <Nazara/Core/ThreadSafetyOff.hpp>
#endif
#include <Nazara/Core/Debug.hpp>
namespace Nz
@ -31,35 +25,16 @@ namespace Nz
* \brief Core class that represents a dynamic library loader
*/
/*!
* \brief Constructs a DynLib object by default
*/
DynLib::DynLib() :
m_impl(nullptr)
{
}
/*!
* \brief Destructs the object and calls Unload
*
* \see Unload
*/
DynLib::~DynLib()
{
Unload();
}
DynLib::DynLib() = default;
DynLib::DynLib(DynLib&&) noexcept = default;
DynLib::~DynLib() = default;
/*!
* \brief Gets the last error
* \return Last error
*/
String DynLib::GetLastError() const
std::string DynLib::GetLastError() const
{
NazaraLock(m_mutex)
return m_lastError;
}
@ -69,11 +44,8 @@ namespace Nz
*
* \remark Produces a NazaraError if library is not loaded with NAZARA_CORE_SAFE defined
*/
DynLibFunc DynLib::GetSymbol(const String& symbol) const
DynLibFunc DynLib::GetSymbol(const char* symbol) const
{
NazaraLock(m_mutex)
#if NAZARA_CORE_SAFE
if (!IsLoaded())
{
@ -89,7 +61,6 @@ namespace Nz
* \brief Checks whether the library is loaded
* \return true if loaded
*/
bool DynLib::IsLoaded() const
{
return m_impl != nullptr;
@ -103,38 +74,28 @@ namespace Nz
*
* \remark Produces a NazaraError if library is could not be loaded
*/
bool DynLib::Load(const String& libraryPath)
bool DynLib::Load(const std::filesystem::path& libraryPath)
{
NazaraLock(m_mutex)
Unload();
std::unique_ptr<DynLibImpl> impl(new DynLibImpl(this));
auto impl = std::make_unique<DynLibImpl>(this);
if (!impl->Load(libraryPath, &m_lastError))
{
NazaraError("Failed to load library: " + m_lastError);
return false;
}
m_impl = impl.release();
m_impl = std::move(impl);
return true;
}
/*!
* \brief Unloads the library
*/
void DynLib::Unload()
{
NazaraLock(m_mutex)
if (IsLoaded())
{
m_impl->Unload();
delete m_impl;
m_impl = nullptr;
}
m_impl.reset();
}
DynLib& DynLib::operator=(DynLib&&) noexcept = default;
}

View File

@ -3,8 +3,9 @@
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Core/Error.hpp>
#include <Nazara/Core/Directory.hpp>
#include <Nazara/Core/CallOnExit.hpp>
#include <Nazara/Core/Log.hpp>
#include <Nazara/Core/StringExt.hpp>
#include <cstdlib>
#include <stdexcept>
@ -82,25 +83,21 @@ namespace Nz
* \param code Code of the error
*/
String Error::GetLastSystemError(unsigned int code)
std::string Error::GetLastSystemError(unsigned int code)
{
#if defined(NAZARA_PLATFORM_WINDOWS)
wchar_t* buffer = nullptr;
FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr,
code,
0,
reinterpret_cast<LPWSTR>(&buffer),
0,
nullptr);
nullptr,
code,
0,
reinterpret_cast<LPWSTR>(&buffer),
0,
nullptr);
String error(String::Unicode(buffer));
LocalFree(buffer);
error.Trim(); // For an unknown reason, Windows put two-three line return after the message
return error;
CallOnExit freeOnExit([buffer] { LocalFree(buffer); });
return FromWideString(buffer);
#elif defined(NAZARA_PLATFORM_POSIX)
return std::strerror(code);
#else
@ -166,7 +163,7 @@ namespace Nz
void Error::Trigger(ErrorType type, const String& error, unsigned int line, const char* file, const char* function)
{
file = Nz::Directory::GetCurrentFileRelativeToEngine(file);
file = GetCurrentFileRelativeToEngine(file);
if (type == ErrorType_AssertFailed || (s_flags & ErrorFlag_Silent) == 0 || (s_flags & ErrorFlag_SilentDisabled) != 0)
Log::WriteError(type, error, line, file, function);
@ -186,6 +183,17 @@ namespace Nz
throw std::runtime_error(error.ToStdString());
}
const char* Error::GetCurrentFileRelativeToEngine(const char* file)
{
if (const char* ptr = std::strstr(file, "NazaraEngine/"))
return ptr;
if (const char* ptr = std::strstr(file, "NazaraEngine\\"))
return ptr;
return file;
}
UInt32 Error::s_flags = ErrorFlag_None;
String Error::s_lastError;
const char* Error::s_lastErrorFunction = "";

View File

@ -5,7 +5,6 @@
#include <Nazara/Core/File.hpp>
#include <Nazara/Core/AbstractHash.hpp>
#include <Nazara/Core/Config.hpp>
#include <Nazara/Core/Directory.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Core/ErrorFlags.hpp>
#include <Nazara/Core/StringStream.hpp>
@ -19,12 +18,6 @@
#error OS not handled
#endif
#if NAZARA_CORE_THREADSAFE && NAZARA_THREADSAFETY_FILE
#include <Nazara/Core/ThreadSafety.hpp>
#else
#include <Nazara/Core/ThreadSafetyOff.hpp>
#endif
#include <Nazara/Core/Debug.hpp>
namespace Nz
@ -39,10 +32,7 @@ namespace Nz
* \brief Constructs a File object by default
*/
File::File() :
m_impl(nullptr)
{
}
File::File() = default;
/*!
* \brief Constructs a File object with a file path
@ -50,7 +40,7 @@ namespace Nz
* \param filePath Path to the file
*/
File::File(const String& filePath) :
File::File(const std::filesystem::path& filePath) :
File()
{
SetFile(filePath);
@ -63,7 +53,7 @@ namespace Nz
* \param openMode Flag of the file
*/
File::File(const String& filePath, OpenModeFlags openMode) :
File::File(const std::filesystem::path& filePath, OpenModeFlags openMode) :
File()
{
Open(filePath, openMode);
@ -75,6 +65,8 @@ namespace Nz
* \see Close
*/
File::File(File&& file) noexcept = default;
File::~File()
{
Close();
@ -82,14 +74,12 @@ namespace Nz
/*!
* \brief Copies this file to a new file path
* \return true if copy is successful
*
* \param newFilePath Path of the new file
*/
bool File::Copy(const String& newFilePath)
void File::Copy(const std::filesystem::path& newFilePath)
{
return Copy(m_filePath, newFilePath);
std::filesystem::copy(m_filePath, newFilePath);
}
/*!
@ -98,13 +88,9 @@ namespace Nz
void File::Close()
{
NazaraLock(m_mutex)
if (m_impl)
{
m_impl->Close();
delete m_impl;
m_impl = nullptr;
m_impl.reset();
m_openMode = OpenMode_NotOpen;
}
@ -117,11 +103,9 @@ namespace Nz
bool File::Delete()
{
NazaraLock(m_mutex)
Close();
return Delete(m_filePath);
return std::filesystem::remove(m_filePath);
}
/*!
@ -133,8 +117,6 @@ namespace Nz
bool File::EndOfFile() const
{
NazaraLock(m_mutex)
#if NAZARA_CORE_SAFE
if (!IsOpen())
{
@ -167,24 +149,10 @@ namespace Nz
bool File::Exists() const
{
NazaraLock(m_mutex)
if (IsOpen())
return true; // Le fichier est ouvert, donc il existe
else
return Exists(m_filePath);
}
/*!
* \brief Gets the creation time of the file
* \return Information about the creation time
*/
time_t File::GetCreationTime() const
{
NazaraLock(m_mutex)
return GetCreationTime(m_filePath);
return std::filesystem::exists(m_filePath);
}
/*!
@ -196,8 +164,6 @@ namespace Nz
UInt64 File::GetCursorPos() const
{
NazaraLock(m_mutex)
NazaraAssert(IsOpen(), "File is not open");
return m_impl->GetCursorPos();
@ -207,72 +173,32 @@ namespace Nz
* \brief Gets the directory of the file
* \return Directory of the file
*/
String File::GetDirectory() const
std::filesystem::path File::GetDirectory() const
{
NazaraLock(m_mutex)
return m_filePath.SubStringTo(NAZARA_DIRECTORY_SEPARATOR, -1, true, true);
return m_filePath.parent_path();
}
/*!
* \brief Gets the name of the file
* \return Name of the file
*/
String File::GetFileName() const
std::filesystem::path File::GetFileName() const
{
NazaraLock(m_mutex)
return m_filePath.SubStringFrom(NAZARA_DIRECTORY_SEPARATOR, -1, true);
}
/*!
* \brief Gets the last time the file was accessed
* \return Information about the last access time
*/
time_t File::GetLastAccessTime() const
{
NazaraLock(m_mutex)
return GetLastAccessTime(m_filePath);
}
/*!
* \brief Gets the last time the file was written
* \return Information about the last writing time
*/
time_t File::GetLastWriteTime() const
{
NazaraLock(m_mutex)
return GetLastWriteTime(m_filePath);
return m_filePath.filename();
}
/*!
* \brief Gets the path of the file
* \return Path of the file
*/
String File::GetPath() const
std::filesystem::path File::GetPath() const
{
NazaraLock(m_mutex)
return m_filePath;
}
/*!
* \brief Gets the size of the file
* \return Size of the file
*/
UInt64 File::GetSize() const
{
NazaraLock(m_mutex)
return GetSize(m_filePath);
return std::filesystem::file_size(m_filePath);
}
/*!
@ -282,8 +208,6 @@ namespace Nz
bool File::IsOpen() const
{
NazaraLock(m_mutex)
return m_impl != nullptr;
}
@ -298,26 +222,24 @@ namespace Nz
bool File::Open(OpenModeFlags openMode)
{
NazaraLock(m_mutex)
Close();
if (m_filePath.IsEmpty())
if (m_filePath.empty())
return false;
if (openMode == OpenMode_NotOpen)
return false;
std::unique_ptr<FileImpl> impl(new FileImpl(this));
std::unique_ptr<FileImpl> impl = std::make_unique<FileImpl>(this);
if (!impl->Open(m_filePath, openMode))
{
ErrorFlags flags(ErrorFlag_Silent); // Silent by default
NazaraError("Failed to open \"" + m_filePath + "\": " + Error::GetLastSystemError());
NazaraError("Failed to open \"" + m_filePath.generic_u8string() + "\": " + Error::GetLastSystemError());
return false;
}
m_openMode = openMode;
m_impl = impl.release();
m_impl = std::move(impl);
if (m_openMode & OpenMode_Text)
m_streamOptions |= StreamOption_Text;
@ -337,38 +259,14 @@ namespace Nz
* \remark Produces a NazaraError if OS error to open a file
*/
bool File::Open(const String& filePath, OpenModeFlags openMode)
bool File::Open(const std::filesystem::path& filePath, OpenModeFlags openMode)
{
NazaraLock(m_mutex)
Close();
SetFile(filePath);
return Open(openMode);
}
/*!
* \brief Renames the file with a new name
* \return true if rename is successful
*/
bool File::Rename(const String& newFilePath)
{
NazaraLock(m_mutex)
bool open = IsOpen();
Close();
bool success = Rename(m_filePath, newFilePath);
if (success)
m_filePath = NormalizePath(newFilePath);
if (open)
Open();
return success;
}
/*!
* \brief Sets the position of the cursor
* \return true if cursor is successfully positioned
@ -381,8 +279,6 @@ namespace Nz
bool File::SetCursorPos(CursorPosition pos, Int64 offset)
{
NazaraLock(m_mutex)
NazaraAssert(IsOpen(), "File is not open");
return m_impl->SetCursorPos(pos, offset);
@ -399,8 +295,6 @@ namespace Nz
bool File::SetCursorPos(UInt64 offset)
{
NazaraLock(m_mutex)
NazaraAssert(IsOpen(), "File is not open");
return m_impl->SetCursorPos(CursorPosition_AtBegin, offset);
@ -413,29 +307,24 @@ namespace Nz
* \remark Produces a NazaraError if file path can not be open
*/
bool File::SetFile(const String& filePath)
bool File::SetFile(const std::filesystem::path& filePath)
{
NazaraLock(m_mutex)
if (IsOpen())
{
if (filePath.IsEmpty())
if (filePath.empty())
return false;
std::unique_ptr<FileImpl> impl(new FileImpl(this));
std::unique_ptr<FileImpl> impl = std::make_unique<FileImpl>(this);
if (!impl->Open(filePath, m_openMode))
{
NazaraError("Failed to open new file; " + Error::GetLastSystemError());
return false;
}
m_impl->Close();
delete m_impl;
m_impl = impl.release();
m_impl = std::move(impl);
}
m_filePath = AbsolutePath(filePath);
m_filePath = std::filesystem::absolute(filePath);
return true;
}
@ -450,317 +339,13 @@ namespace Nz
*/
bool File::SetSize(UInt64 size)
{
NazaraLock(m_mutex)
NazaraAssert(IsOpen(), "File is not open");
NazaraAssert(IsWritable(), "File is not writable");
return m_impl->SetSize(size);
}
/*!
* \brief Sets the file path
* \return A reference to this
*
* \remark Produces a NazaraError if file path can not be open
*/
File& File::operator=(const String& filePath)
{
SetFile(filePath);
return *this;
}
/*!
* \brief Gets the absolute path of the file
* \return Absolute path of the file
*
* \param filePath Path of the file
*
* \remark Produces a NazaraError if filePath is weird with NAZARA_PLATFORM_WINDOWS defined
*/
String File::AbsolutePath(const String& filePath)
{
// We don't use OS functions because they only work for existing path
String path = NormalizePath(filePath);
if (path.IsEmpty())
return String();
String base;
unsigned int start;
#ifdef NAZARA_PLATFORM_WINDOWS
if (path.Match("?:*"))
start = 1;
else if (path.Match("\\\\*"))
{
base = "\\\\";
start = 2;
}
else if (path.StartsWith('\\')) // Special : '\' refering to root
{
String drive = Directory::GetCurrent().SubStringTo('\\');
String end = path.SubString(1, -1);
if (end.IsEmpty())
path = drive;
else
path = drive + '\\' + end;
start = 1;
}
else
{
NazaraError("Path unrecognized");
return path;
}
#elif defined(NAZARA_PLATFORM_POSIX)
base = '/';
start = 0;
#else
#error OS case not implemented
#endif
static String upDir = NAZARA_DIRECTORY_SEPARATOR + String('.');
if (path.Find(upDir) == String::npos)
return path;
std::vector<String> sep;
if (path.Split(sep, NAZARA_DIRECTORY_SEPARATOR) <= 1)
return path;
// We have the absolute path, but we need to clean it up
for (unsigned int i = 0; i < sep.size(); ++i)
{
if (sep[i] == '.')
sep.erase(sep.begin() + i--);
else if (sep[i] == "..")
{
if (i > start) // If we are not in the protected area
sep.erase(sep.begin() + i--);
sep.erase(sep.begin() + i--);
}
}
StringStream stream(base);
for (unsigned int i = 0; i < sep.size(); ++i)
{
if (i != sep.size()-1)
stream << sep[i] << NAZARA_DIRECTORY_SEPARATOR;
else
stream << sep[i];
}
return stream;
}
/*!
* \brief Copies the first file to a new file path
* \return true if copy is successful
*
* \param sourcePath Path of the original file
* \param targetPath Path of the copied file
*/
bool File::Copy(const String& sourcePath, const String& targetPath)
{
if (sourcePath.IsEmpty() || targetPath.IsEmpty())
return false;
return FileImpl::Copy(NormalizePath(sourcePath), NormalizePath(targetPath));
}
/*!
* \brief Deletes the file
* \return true if delete is successful
*
* \param filePath Path of the file
*/
bool File::Delete(const String& filePath)
{
if (filePath.IsEmpty())
return false;
return FileImpl::Delete(NormalizePath(filePath));
}
/*!
* \brief Checks whether the file exists
* \return true if file exists
*
* \param filePath Path of the file
*/
bool File::Exists(const String& filePath)
{
if (filePath.IsEmpty())
return false;
return FileImpl::Exists(NormalizePath(filePath));
}
/*!
* \brief Gets the creation time of the file
* \return Information about the creation time
*
* \param filePath Path of the file
*/
time_t File::GetCreationTime(const String& filePath)
{
if (filePath.IsEmpty())
return 0;
return FileImpl::GetCreationTime(NormalizePath(filePath));
}
/*!
* \brief Gets the directory of the file
* \return Directory of the file
*
* \param filePath Path of the file
*/
String File::GetDirectory(const String& filePath)
{
return filePath.SubStringTo(NAZARA_DIRECTORY_SEPARATOR, -1, true, true);
}
/*!
* \brief Gets the last time the file was accessed
* \return Information about the last access time
*
* \param filePath Path of the file
*/
time_t File::GetLastAccessTime(const String& filePath)
{
if (filePath.IsEmpty())
return 0;
return FileImpl::GetLastAccessTime(NormalizePath(filePath));
}
/*!
* \brief Gets the last time the file was written
* \return Information about the last writing time
*
* \param filePath Path of the file
*/
time_t File::GetLastWriteTime(const String& filePath)
{
if (filePath.IsEmpty())
return 0;
return FileImpl::GetLastWriteTime(NormalizePath(filePath));
}
/*!
* \brief Gets the size of the file
* \return Size of the file
*
* \param filePath Path of the file
*/
UInt64 File::GetSize(const String& filePath)
{
if (filePath.IsEmpty())
return 0;
return FileImpl::GetSize(NormalizePath(filePath));
}
/*!
* \brief Checks whether the file path is absolute
* \return true if path is absolute
*
* \param filePath Path to test
*/
bool File::IsAbsolute(const String& filePath)
{
String path(filePath.Trimmed());
if (path.IsEmpty())
return false;
path = NormalizeSeparators(path);
#ifdef NAZARA_PLATFORM_WINDOWS
if (path.Match("?:*")) // Ex: C:\Hello
return true;
else if (path.Match("\\\\*")) // Ex: \\Laptop
return true;
else if (path.StartsWith('\\')) // Special : '\' referring to the root
return true;
else
return false;
#elif defined(NAZARA_PLATFORM_POSIX)
return path.StartsWith('/');
#else
#error OS case not implemented
#endif
}
/*!
* \brief Normalizes the file path
* \return Path normalized (replacing '/' with '\\' on Windows, ...)
*
* \param filePath Path to normalize
*/
String File::NormalizePath(const String& filePath)
{
String path = NormalizeSeparators(filePath.Trimmed());
if (!IsAbsolute(path))
path = Directory::GetCurrent() + NAZARA_DIRECTORY_SEPARATOR + path;
while (path.EndsWith(NAZARA_DIRECTORY_SEPARATOR))
path.Resize(-1);
return path;
}
/*!
* \brief Normalizes the path separator
* \return Path normalized (replacing '/' with '\\' on Windows, ...)
*
* \param filePath Path to normalize
*/
String File::NormalizeSeparators(const String& filePath)
{
String path(filePath);
#if defined(NAZARA_PLATFORM_WINDOWS)
path.Replace('/', '\\');
#elif defined(NAZARA_PLATFORM_LINUX)
path.Replace('\\', '/');
#else
#error OS case not implemented
#endif
return path;
}
/*!
* \brief Renames the file with a new name
* \return true if rename is successful
*
* \param sourcePath Path of the original file
* \param targetPath Path of the renamed file
*/
bool File::Rename(const String& sourcePath, const String& targetPath)
{
if (sourcePath.IsEmpty() || targetPath.IsEmpty())
return false;
return FileImpl::Rename(NormalizePath(sourcePath), NormalizePath(targetPath));
}
File& File::operator=(File&& file) noexcept = default;
/*!
* \brief Flushes the stream
@ -770,8 +355,6 @@ namespace Nz
void File::FlushStream()
{
NazaraLock(m_mutex)
NazaraAssert(IsOpen(), "File is not open");
m_impl->Flush();
@ -789,8 +372,6 @@ namespace Nz
std::size_t File::ReadBlock(void* buffer, std::size_t size)
{
NazaraLock(m_mutex)
NazaraAssert(IsOpen(), "File is not open");
if (size == 0)
@ -822,8 +403,6 @@ namespace Nz
std::size_t File::WriteBlock(const void* buffer, std::size_t size)
{
NazaraLock(m_mutex)
NazaraAssert(IsOpen(), "File is not open");
if (size == 0)

View File

@ -8,6 +8,8 @@
#include <Nazara/Core/StringStream.hpp>
#include <array>
#include <ctime>
#include <filesystem>
#include <sstream>
#include <Nazara/Core/Debug.hpp>
namespace Nz
@ -25,7 +27,7 @@ namespace Nz
*/
FileLogger::FileLogger(const String& logPath) :
m_outputFile(logPath),
m_outputPath(logPath.ToStdString()),
m_forceStdOutput(false),
m_stdReplicationEnabled(true),
m_timeLoggingEnabled(true)
@ -107,9 +109,10 @@ namespace Nz
m_forceStdOutput = false;
});
if (!m_outputFile.IsOpen())
if (!m_outputFile.is_open())
{
if (!m_outputFile.Open(OpenMode_Text | OpenMode_Truncate | OpenMode_WriteOnly))
m_outputFile.open(m_outputPath, std::ios_base::trunc | std::ios_base::out);
if (!m_outputFile.is_open())
{
NazaraError("Failed to open output file");
return;
@ -117,7 +120,7 @@ namespace Nz
}
// Apply some processing before writing
StringStream stream;
std::ostringstream stream;
if (m_timeLoggingEnabled)
{
std::array<char, 24> buffer;
@ -130,7 +133,7 @@ namespace Nz
stream << string << '\n';
m_outputFile.Write(stream);
m_outputFile << stream.str();
}
/*!
@ -148,6 +151,6 @@ namespace Nz
void FileLogger::WriteError(ErrorType type, const String& error, unsigned int line, const char* file, const char* function)
{
AbstractLogger::WriteError(type, error, line, file, function);
m_outputFile.Flush();
m_outputFile.flush();
}
}

View File

@ -1,80 +0,0 @@
// Copyright (C) 2017 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/Mutex.hpp>
#include <Nazara/Core/Error.hpp>
#if defined(NAZARA_PLATFORM_WINDOWS)
#include <Nazara/Core/Win32/MutexImpl.hpp>
#elif defined(NAZARA_PLATFORM_POSIX)
#include <Nazara/Core/Posix/MutexImpl.hpp>
#else
#error Lack of implementation: Mutex
#endif
#include <Nazara/Core/Debug.hpp>
namespace Nz
{
/*!
* \ingroup core
* \class Nz::Mutex
* \brief Core class that represents a binary semaphore, a mutex
*
* \remark The mutex is recursive, it means that a thread who owns the mutex can call the same function which needs the same mutex
*/
/*!
* \brief Constructs a Mutex object by default
*/
Mutex::Mutex()
{
m_impl = new MutexImpl;
}
/*!
* \brief Destructs the object
*/
Mutex::~Mutex()
{
delete m_impl;
}
/*!
* \brief Locks the mutex
*
* If another thread has already locked the mutex, a call to lock will block execution until the lock is acquired. A thread may call lock on a recursive mutex repeatedly. Ownership will only be released after the thread makes a matching number of calls to unlock
*/
void Mutex::Lock()
{
NazaraAssert(m_impl, "Cannot lock a moved mutex");
m_impl->Lock();
}
/*!
* \brief Tries to lock the mutex
* \return true if the lock was acquired successfully
*/
bool Mutex::TryLock()
{
NazaraAssert(m_impl, "Cannot lock a moved mutex");
return m_impl->TryLock();
}
/*!
* \brief Unlocks the mutex
*
* Unlocks the mutex if its level of ownership is 1 (there was exactly one more call to Lock() than there were calls to Unlock() made by this thread), reduces the level of ownership by 1 otherwise
*/
void Mutex::Unlock()
{
NazaraAssert(m_impl, "Cannot unlock a moved mutex");
m_impl->Unlock();
}
}

View File

@ -3,10 +3,8 @@
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Core/PluginManager.hpp>
#include <Nazara/Core/Directory.hpp>
#include <Nazara/Core/DynLib.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Core/File.hpp>
#include <memory>
#include <Nazara/Core/Debug.hpp>
@ -17,7 +15,7 @@ namespace Nz
using PluginLoad = int (*)();
using PluginUnload = void (*)();
String s_pluginFiles[] =
std::filesystem::path s_pluginFiles[] =
{
"PluginAssimp", // Plugin_Assimp
};
@ -37,7 +35,7 @@ namespace Nz
* \remark Produces a NazaraError if not initialized
*/
void PluginManager::AddDirectory(const String& directoryPath)
void PluginManager::AddDirectory(const std::filesystem::path& directoryPath)
{
if (!Initialize())
{
@ -45,7 +43,7 @@ namespace Nz
return;
}
s_directories.insert(File::AbsolutePath(directoryPath));
s_directories.insert(std::filesystem::absolute(directoryPath));
}
/*!
@ -79,9 +77,13 @@ namespace Nz
bool PluginManager::Mount(Plugin plugin)
{
Nz::String pluginName = s_pluginFiles[plugin];
std::filesystem::path pluginName = s_pluginFiles[plugin];
#ifdef NAZARA_DEBUG
if (Mount(pluginName + "-d", true))
std::filesystem::path debugPath = pluginName;
debugPath += "-d";
if (Mount(debugPath, true))
return true;
#endif
@ -102,7 +104,7 @@ namespace Nz
* \remark Produces a NazaraError if fail to initialize the plugin with PluginLoad
*/
bool PluginManager::Mount(const String& pluginPath, bool appendExtension)
bool PluginManager::Mount(const std::filesystem::path& pluginPath, bool appendExtension)
{
if (!Initialize())
{
@ -110,23 +112,17 @@ namespace Nz
return false;
}
String path = pluginPath;
if (appendExtension && !path.EndsWith(NAZARA_DYNLIB_EXTENSION))
std::filesystem::path path = pluginPath;
if (appendExtension && path.extension() == NAZARA_DYNLIB_EXTENSION)
path += NAZARA_DYNLIB_EXTENSION;
bool exists = false;
if (!File::IsAbsolute(path))
if (!path.is_absolute())
{
for (const String& dir : s_directories)
for (const std::filesystem::path& dir : s_directories)
{
String testPath;
testPath.Reserve(dir.GetSize() + path.GetSize() + 10);
testPath = dir;
testPath += NAZARA_DIRECTORY_SEPARATOR;
testPath += path;
if (File::Exists(testPath))
std::filesystem::path testPath = dir / path;
if (std::filesystem::exists(testPath))
{
path = testPath;
exists = true;
@ -134,7 +130,7 @@ namespace Nz
}
}
}
else if (File::Exists(path))
else if (std::filesystem::exists(path))
exists = true;
if (!exists)
@ -143,7 +139,7 @@ namespace Nz
return false;
}
std::unique_ptr<DynLib> library(new DynLib);
std::unique_ptr<DynLib> library = std::make_unique<DynLib>();
if (!library->Load(path))
{
NazaraError("Failed to load plugin");
@ -163,7 +159,8 @@ namespace Nz
return false;
}
s_plugins[pluginPath] = library.release();
std::filesystem::path canonicalPath = std::filesystem::canonical(pluginPath);
s_plugins[canonicalPath] = std::move(library);
return true;
}
@ -176,7 +173,7 @@ namespace Nz
* \remark Produces a NazaraError if not initialized
*/
void PluginManager::RemoveDirectory(const String& directoryPath)
void PluginManager::RemoveDirectory(const std::filesystem::path& directoryPath)
{
if (!Initialize())
{
@ -184,7 +181,7 @@ namespace Nz
return;
}
s_directories.erase(File::AbsolutePath(directoryPath));
s_directories.erase(std::filesystem::canonical(directoryPath));
}
/*!
@ -210,7 +207,7 @@ namespace Nz
* \remark Produces a NazaraError if plugin is not loaded
*/
void PluginManager::Unmount(const String& pluginPath)
void PluginManager::Unmount(const std::filesystem::path& pluginPath)
{
if (!Initialize())
{
@ -218,7 +215,8 @@ namespace Nz
return;
}
auto it = s_plugins.find(pluginPath);
std::filesystem::path canonicalPath = std::filesystem::canonical(pluginPath);
auto it = s_plugins.find(canonicalPath);
if (it == s_plugins.end())
{
NazaraError("Plugin not loaded");
@ -229,9 +227,6 @@ namespace Nz
if (func)
func();
it->second->Unload();
delete it->second;
s_plugins.erase(it);
}
@ -253,15 +248,12 @@ namespace Nz
PluginUnload func = reinterpret_cast<PluginUnload>(pair.second->GetSymbol("PluginUnload"));
if (func)
func();
pair.second->Unload();
delete pair.second;
}
s_plugins.clear();
}
std::set<String> PluginManager::s_directories;
std::unordered_map<String, DynLib*> PluginManager::s_plugins;
std::set<std::filesystem::path> PluginManager::s_directories;
std::unordered_map<std::filesystem::path, std::unique_ptr<DynLib>, PluginManager::PathHash> PluginManager::s_plugins;
bool PluginManager::s_initialized = false;
}

View File

@ -1,52 +0,0 @@
// Copyright (C) 2015 Alexandre Janniaux
// 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/Posix/ConditionVariableImpl.hpp>
#include <Nazara/Core/Posix/MutexImpl.hpp>
#include <sys/time.h>
#include <time.h>
#include <Nazara/Core/Debug.hpp>
namespace Nz
{
ConditionVariableImpl::ConditionVariableImpl()
{
pthread_cond_init(&m_cv, nullptr);
}
ConditionVariableImpl::~ConditionVariableImpl()
{
pthread_cond_destroy(&m_cv);
}
void ConditionVariableImpl::Signal()
{
pthread_cond_signal(&m_cv);
}
void ConditionVariableImpl::SignalAll()
{
pthread_cond_broadcast(&m_cv);
}
void ConditionVariableImpl::Wait(MutexImpl* mutex)
{
pthread_cond_wait(&m_cv, &mutex->m_handle);
}
bool ConditionVariableImpl::Wait(MutexImpl* mutex, UInt32 timeout)
{
// get the current time
timeval tv;
gettimeofday(&tv, nullptr);
// construct the time limit (current time + time to wait)
timespec ti;
ti.tv_nsec = (tv.tv_usec + (timeout % 1000)) * 1000000;
ti.tv_sec = tv.tv_sec + (timeout / 1000) + (ti.tv_nsec / 1000000000);
ti.tv_nsec %= 1000000000;
return pthread_cond_timedwait(&m_cv,&mutex->m_handle, &ti) != 0;
}
}

View File

@ -1,36 +0,0 @@
// Copyright (C) 2015 Alexandre Janniaux
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp
// http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
#pragma once
#ifndef NAZARA_CONDITIONVARIABLEIMPL_HPP
#define NAZARA_CONDITIONVARIABLEIMPL_HPP
#include <Nazara/Prerequisites.hpp>
#include <pthread.h>
namespace Nz
{
class MutexImpl;
class ConditionVariableImpl
{
public:
ConditionVariableImpl();
~ConditionVariableImpl();
void Signal();
void SignalAll();
void Wait(MutexImpl* mutex);
bool Wait(MutexImpl* mutex, UInt32 timeout);
private:
pthread_cond_t m_cv;
};
}
#endif // NAZARA_CONDITIONVARIABLEIMPL_HPP

View File

@ -1,120 +0,0 @@
// Copyright (C) 2015 Alexandre Janniaux
// 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/Posix/DirectoryImpl.hpp>
#include <Nazara/Core/Directory.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Core/StackArray.hpp>
#include <Nazara/Core/String.hpp>
#include <cstring>
#include <errno.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <unistd.h>
#include <Nazara/Core/Debug.hpp>
namespace Nz
{
DirectoryImpl::DirectoryImpl(const Directory* parent) :
m_parent(parent)
{
}
void DirectoryImpl::Close()
{
closedir(m_handle);
}
String DirectoryImpl::GetResultName() const
{
return m_result->d_name;
}
UInt64 DirectoryImpl::GetResultSize() const
{
String path = m_parent->GetPath();
std::size_t pathSize = path.GetSize();
std::size_t resultNameSize = std::strlen(m_result->d_name);
std::size_t fullNameSize = pathSize + 1 + resultNameSize;
StackArray<char> fullName = NazaraStackArrayNoInit(char, fullNameSize + 1);
std::memcpy(&fullName[0], path.GetConstBuffer(), pathSize * sizeof(char));
fullName[pathSize] = '/';
std::memcpy(&fullName[pathSize + 1], m_result->d_name, resultNameSize * sizeof(char));
fullName[fullNameSize] = '\0';
struct stat64 results;
stat64(fullName.data(), &results);
return results.st_size;
}
bool DirectoryImpl::IsResultDirectory() const
{
//TODO: Fix d_type handling (field can be missing or be a symbolic link, both cases which must be handled by calling stat)
return m_result->d_type == DT_DIR;
}
bool DirectoryImpl::NextResult()
{
if ((m_result = readdir64(m_handle)))
return true;
else
{
if (errno == EBADF || errno == EOVERFLOW)
NazaraError("Unable to get next result: " + Error::GetLastSystemError());
return false;
}
}
bool DirectoryImpl::Open(const String& dirPath)
{
m_handle = opendir(dirPath.GetConstBuffer());
if (!m_handle)
{
NazaraError("Unable to open directory: " + Error::GetLastSystemError());
return false;
}
return true;
}
bool DirectoryImpl::Create(const String& dirPath)
{
mode_t permissions = S_IRWXU | S_IRWXG | S_IRWXO; // 777
return mkdir(dirPath.GetConstBuffer(), permissions) != -1;
}
bool DirectoryImpl::Exists(const String& dirPath)
{
struct stat64 filestats;
if (stat64(dirPath.GetConstBuffer(), &filestats) == -1) // error
return false;
return S_ISDIR(filestats.st_mode) || S_ISREG(filestats.st_mode);
}
String DirectoryImpl::GetCurrent()
{
String currentPath;
char path[MAXPATHLEN];
if (getcwd(path, MAXPATHLEN))
currentPath = path;
else
NazaraError("Unable to get current directory: " + Error::GetLastSystemError()); // Bug: initialisation -> if no path for log !
return currentPath;
}
bool DirectoryImpl::Remove(const String& dirPath)
{
bool success = rmdir(dirPath.GetConstBuffer()) != -1;
return success;
}
}

View File

@ -1,52 +0,0 @@
// Copyright (C) 2015 Alexandre Janniaux
// 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_DIRECTORYIMPL_HPP
#define NAZARA_DIRECTORYIMPL_HPP
#include <Nazara/Prerequisites.hpp>
#include <dirent.h>
namespace Nz
{
class Directory;
class String;
class DirectoryImpl
{
public:
DirectoryImpl(const Directory* parent);
DirectoryImpl(const DirectoryImpl&) = delete;
DirectoryImpl(DirectoryImpl&&) = delete; ///TODO
~DirectoryImpl() = default;
void Close();
String GetResultName() const;
UInt64 GetResultSize() const;
bool IsResultDirectory() const;
bool NextResult();
bool Open(const String& dirPath);
DirectoryImpl& operator=(const DirectoryImpl&) = delete;
DirectoryImpl& operator=(DirectoryImpl&&) = delete; ///TODO
static bool Create(const String& dirPath);
static bool Exists(const String& dirPath);
static String GetCurrent();
static bool Remove(const String& dirPath);
private:
const Directory* m_parent;
DIR* m_handle;
dirent64* m_result;
};
}
#endif // NAZARA_DIRECTORYIMPL_HPP

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