Convert all remaining enums to enum classes (!)

This commit is contained in:
Jérôme Leclercq 2021-05-25 00:08:50 +02:00
parent 8cdd0b51cb
commit 874fb3542e
122 changed files with 1082 additions and 2169 deletions

View File

@ -368,7 +368,7 @@ namespace Nz
// Flush bits in case a writing is in progress // Flush bits in case a writing is in progress
context.FlushBits(); context.FlushBits();
if (context.endianness != Endianness_Unknown && context.endianness != GetPlatformEndianness()) if (context.endianness != Endianness::Unknown && context.endianness != GetPlatformEndianness())
SwapBytes(&value, sizeof(T)); SwapBytes(&value, sizeof(T));
return context.stream->Write(&value, sizeof(T)) == sizeof(T); return context.stream->Write(&value, sizeof(T)) == sizeof(T);
@ -447,7 +447,7 @@ namespace Nz
if (context.stream->Read(value, sizeof(T)) == sizeof(T)) if (context.stream->Read(value, sizeof(T)) == sizeof(T))
{ {
if (context.endianness != Endianness_Unknown && context.endianness != GetPlatformEndianness()) if (context.endianness != Endianness::Unknown && context.endianness != GetPlatformEndianness())
SwapBytes(value, sizeof(T)); SwapBytes(value, sizeof(T));
return true; return true;

View File

@ -15,9 +15,9 @@ namespace Nz
inline constexpr Endianness GetPlatformEndianness() inline constexpr Endianness GetPlatformEndianness()
{ {
#if defined(NAZARA_BIG_ENDIAN) #if defined(NAZARA_BIG_ENDIAN)
return Endianness_BigEndian; return Endianness::BigEndian;
#elif defined(NAZARA_LITTLE_ENDIAN) #elif defined(NAZARA_LITTLE_ENDIAN)
return Endianness_LittleEndian; return Endianness::LittleEndian;
#endif #endif
} }

View File

@ -11,193 +11,213 @@
namespace Nz namespace Nz
{ {
enum CoordSys enum class CoordSys
{ {
CoordSys_Global, Global,
CoordSys_Local, Local,
CoordSys_Max = CoordSys_Local Max = Local
}; };
enum CursorPosition enum class CursorPosition
{ {
CursorPosition_AtBegin, // beginning of the file AtBegin, // beginning of the file
CursorPosition_AtCurrent, // Position of the cursor AtCurrent, // Position of the cursor
CursorPosition_AtEnd, // End of the file AtEnd, // End of the file
CursorPosition_Max = CursorPosition_AtEnd Max = AtEnd
}; };
enum Endianness enum class Endianness
{ {
Endianness_Unknown = -1, Unknown = -1,
Endianness_BigEndian, BigEndian,
Endianness_LittleEndian, LittleEndian,
Endianness_Max = Endianness_LittleEndian Max = LittleEndian
}; };
enum ErrorFlag enum class ErrorMode
{ {
ErrorFlag_None = 0, None,
ErrorFlag_Silent = 0x1, Silent,
ErrorFlag_SilentDisabled = 0x2, SilentDisabled,
ErrorFlag_ThrowException = 0x4, ThrowException,
ErrorFlag_ThrowExceptionDisabled = 0x8, ThrowExceptionDisabled,
ErrorFlag_Max = ErrorFlag_ThrowExceptionDisabled * 2 - 1 Max = ThrowExceptionDisabled
}; };
enum ErrorType template<>
struct EnumAsFlags<ErrorMode>
{ {
ErrorType_AssertFailed, static constexpr ErrorMode max = ErrorMode::Max;
ErrorType_Internal,
ErrorType_Normal,
ErrorType_Warning,
ErrorType_Max = ErrorType_Warning
}; };
enum HashType using ErrorModeFlags = Flags<ErrorMode>;
{
HashType_CRC32,
HashType_CRC64,
HashType_Fletcher16,
HashType_MD5,
HashType_SHA1,
HashType_SHA224,
HashType_SHA256,
HashType_SHA384,
HashType_SHA512,
HashType_Whirlpool,
HashType_Max = HashType_Whirlpool enum class ErrorType
{
AssertFailed,
Internal,
Normal,
Warning,
Max = Warning
}; };
enum OpenMode constexpr std::size_t ErrorTypeCount = static_cast<std::size_t>(ErrorType::Max) + 1;
enum class HashType
{ {
OpenMode_NotOpen, // Use the current mod of opening CRC32,
CRC64,
Fletcher16,
MD5,
SHA1,
SHA224,
SHA256,
SHA384,
SHA512,
Whirlpool,
OpenMode_Append, // Disable writing on existing parts and put the cursor at the end Max = Whirlpool
OpenMode_Lock, // Disable modifying the file before it is open };
OpenMode_MustExist, // Fail if the file doesn't exists, even if opened in write mode
OpenMode_ReadOnly, // Open in read only
OpenMode_Text, // Open in text mod
OpenMode_Truncate, // Create the file if it doesn't exist and empty it if it exists
OpenMode_WriteOnly, // Open in write only, create the file if it doesn't exist
OpenMode_Max = OpenMode_WriteOnly constexpr std::size_t HashTypeCount = static_cast<std::size_t>(HashType::Max) + 1;
enum class OpenMode
{
NotOpen, // Use the current mod of opening
Append, // Disable writing on existing parts and put the cursor at the end
Lock, // Disable modifying the file before it is open
MustExist, // Fail if the file doesn't exists, even if opened in write mode
ReadOnly, // Open in read only
Text, // Open in text mod
Truncate, // Create the file if it doesn't exist and empty it if it exists
WriteOnly, // Open in write only, create the file if it doesn't exist
Max = WriteOnly
}; };
template<> template<>
struct EnumAsFlags<OpenMode> struct EnumAsFlags<OpenMode>
{ {
static constexpr OpenMode max = OpenMode_Max; static constexpr OpenMode max = OpenMode::Max;
}; };
using OpenModeFlags = Flags<OpenMode>; using OpenModeFlags = Flags<OpenMode>;
constexpr OpenModeFlags OpenMode_ReadWrite = OpenMode_ReadOnly | OpenMode_WriteOnly; constexpr OpenModeFlags OpenMode_ReadWrite = OpenMode::ReadOnly | OpenMode::WriteOnly;
enum ParameterType enum class ParameterType
{ {
ParameterType_Boolean, Boolean,
ParameterType_Color, Color,
ParameterType_Double, Double,
ParameterType_Integer, Integer,
ParameterType_None, None,
ParameterType_Pointer, Pointer,
ParameterType_String, String,
ParameterType_Userdata, Userdata,
ParameterType_Max = ParameterType_Userdata Max = Userdata
}; };
enum Plugin enum class Plugin
{ {
Plugin_Assimp, Assimp,
Plugin_Count Max = Assimp
}; };
enum PrimitiveType constexpr std::size_t PluginCount = static_cast<std::size_t>(Plugin::Max) + 1;
{
PrimitiveType_Box,
PrimitiveType_Cone,
PrimitiveType_Plane,
PrimitiveType_Sphere,
PrimitiveType_Max = PrimitiveType_Sphere enum class PrimitiveType
{
Box,
Cone,
Plane,
Sphere,
Max = Sphere
}; };
enum ProcessorCap constexpr std::size_t PrimitiveTypeCount = static_cast<std::size_t>(PrimitiveType::Max) + 1;
{
ProcessorCap_x64,
ProcessorCap_AVX,
ProcessorCap_FMA3,
ProcessorCap_FMA4,
ProcessorCap_MMX,
ProcessorCap_XOP,
ProcessorCap_SSE,
ProcessorCap_SSE2,
ProcessorCap_SSE3,
ProcessorCap_SSSE3,
ProcessorCap_SSE41,
ProcessorCap_SSE42,
ProcessorCap_SSE4a,
ProcessorCap_Max = ProcessorCap_SSE4a enum class ProcessorCap
{
x64,
AVX,
FMA3,
FMA4,
MMX,
XOP,
SSE,
SSE2,
SSE3,
SSSE3,
SSE41,
SSE42,
SSE4a,
Max = SSE4a
}; };
enum ProcessorVendor constexpr std::size_t ProcessorCapCount = static_cast<std::size_t>(ProcessorCap::Max) + 1;
enum class ProcessorVendor
{ {
ProcessorVendor_Unknown = -1, Unknown = -1,
ProcessorVendor_AMD, AMD,
ProcessorVendor_Centaur, Centaur,
ProcessorVendor_Cyrix, Cyrix,
ProcessorVendor_Intel, Intel,
ProcessorVendor_KVM, KVM,
ProcessorVendor_HyperV, HyperV,
ProcessorVendor_NSC, NSC,
ProcessorVendor_NexGen, NexGen,
ProcessorVendor_Rise, Rise,
ProcessorVendor_SIS, SIS,
ProcessorVendor_Transmeta, Transmeta,
ProcessorVendor_UMC, UMC,
ProcessorVendor_VIA, VIA,
ProcessorVendor_VMware, VMware,
ProcessorVendor_Vortex, Vortex,
ProcessorVendor_XenHVM, XenHVM,
ProcessorVendor_Max = ProcessorVendor_XenHVM Max = XenHVM
}; };
enum SphereType constexpr std::size_t ProcessorVendorCount = static_cast<std::size_t>(ProcessorVendor::Max) + 1;
{
SphereType_Cubic,
SphereType_Ico,
SphereType_UV,
SphereType_Max = SphereType_UV enum class SphereType
{
Cubic,
Ico,
UV,
Max = UV
}; };
enum StreamOption enum class StreamOption
{ {
StreamOption_None, None,
StreamOption_Sequential, Sequential,
StreamOption_Text, Text,
StreamOption_Max = StreamOption_Text Max = Text
}; };
template<> template<>
struct EnumAsFlags<StreamOption> struct EnumAsFlags<StreamOption>
{ {
static constexpr StreamOption max = StreamOption_Max; static constexpr StreamOption max = StreamOption::Max;
}; };
using StreamOptionFlags = Flags<StreamOption>; using StreamOptionFlags = Flags<StreamOption>;

View File

@ -13,14 +13,14 @@
#include <string> #include <string>
#if NAZARA_CORE_ENABLE_ASSERTS || defined(NAZARA_DEBUG) #if NAZARA_CORE_ENABLE_ASSERTS || defined(NAZARA_DEBUG)
#define NazaraAssert(a, err) if (!(a)) Nz::Error::Trigger(Nz::ErrorType_AssertFailed, err, __LINE__, __FILE__, NAZARA_FUNCTION) #define NazaraAssert(a, err) if (!(a)) Nz::Error::Trigger(Nz::ErrorType::AssertFailed, err, __LINE__, __FILE__, NAZARA_FUNCTION)
#else #else
#define NazaraAssert(a, err) for (;;) break #define NazaraAssert(a, err) for (;;) break
#endif #endif
#define NazaraError(err) Nz::Error::Trigger(Nz::ErrorType_Normal, err, __LINE__, __FILE__, NAZARA_FUNCTION) #define NazaraError(err) Nz::Error::Trigger(Nz::ErrorType::Normal, err, __LINE__, __FILE__, NAZARA_FUNCTION)
#define NazaraInternalError(err) Nz::Error::Trigger(Nz::ErrorType_Internal, err, __LINE__, __FILE__, NAZARA_FUNCTION) #define NazaraInternalError(err) Nz::Error::Trigger(Nz::ErrorType::Internal, err, __LINE__, __FILE__, NAZARA_FUNCTION)
#define NazaraWarning(err) Nz::Error::Trigger(Nz::ErrorType_Warning, err, __LINE__, __FILE__, NAZARA_FUNCTION) #define NazaraWarning(err) Nz::Error::Trigger(Nz::ErrorType::Warning, err, __LINE__, __FILE__, NAZARA_FUNCTION)
namespace Nz namespace Nz
{ {
@ -30,12 +30,12 @@ namespace Nz
Error() = delete; Error() = delete;
~Error() = delete; ~Error() = delete;
static UInt32 GetFlags(); static ErrorModeFlags GetFlags();
static std::string GetLastError(const char** file = nullptr, unsigned int* line = nullptr, const char** function = nullptr); static std::string GetLastError(const char** file = nullptr, unsigned int* line = nullptr, const char** function = nullptr);
static unsigned int GetLastSystemErrorCode(); static unsigned int GetLastSystemErrorCode();
static std::string GetLastSystemError(unsigned int code = GetLastSystemErrorCode()); static std::string GetLastSystemError(unsigned int code = GetLastSystemErrorCode());
static void SetFlags(UInt32 flags); static void SetFlags(ErrorModeFlags flags);
static void Trigger(ErrorType type, std::string error); static void Trigger(ErrorType type, std::string error);
static void Trigger(ErrorType type, std::string error, unsigned int line, const char* file, const char* function); static void Trigger(ErrorType type, std::string error, unsigned int line, const char* file, const char* function);
@ -43,7 +43,7 @@ namespace Nz
private: private:
static const char* GetCurrentFileRelativeToEngine(const char* file); static const char* GetCurrentFileRelativeToEngine(const char* file);
static UInt32 s_flags; static ErrorModeFlags s_flags;
static std::string s_lastError; static std::string s_lastError;
static const char* s_lastErrorFunction; static const char* s_lastErrorFunction;
static const char* s_lastErrorFile; static const char* s_lastErrorFile;

View File

@ -8,26 +8,27 @@
#define NAZARA_ERRORFLAGS_HPP #define NAZARA_ERRORFLAGS_HPP
#include <Nazara/Prerequisites.hpp> #include <Nazara/Prerequisites.hpp>
#include <Nazara/Core/Enums.hpp>
namespace Nz namespace Nz
{ {
class NAZARA_CORE_API ErrorFlags class NAZARA_CORE_API ErrorFlags
{ {
public: public:
ErrorFlags(UInt32 flags, bool replace = false); ErrorFlags(ErrorModeFlags flags, bool replace = false);
ErrorFlags(const ErrorFlags&) = delete; ErrorFlags(const ErrorFlags&) = delete;
ErrorFlags(ErrorFlags&&) = delete; ErrorFlags(ErrorFlags&&) = delete;
~ErrorFlags(); ~ErrorFlags();
UInt32 GetPreviousFlags() const; ErrorModeFlags GetPreviousFlags() const;
void SetFlags(UInt32 flags, bool replace = false); void SetFlags(ErrorModeFlags flags, bool replace = false);
ErrorFlags& operator=(const ErrorFlags&) = delete; ErrorFlags& operator=(const ErrorFlags&) = delete;
ErrorFlags& operator=(ErrorFlags&&) = delete; ErrorFlags& operator=(ErrorFlags&&) = delete;
private: private:
UInt32 m_previousFlags; ErrorModeFlags m_previousFlags;
}; };
} }

View File

@ -48,8 +48,8 @@ namespace Nz
bool IsOpen() const; bool IsOpen() const;
bool Open(OpenModeFlags openMode = OpenMode_NotOpen); bool Open(OpenModeFlags openMode = OpenMode::NotOpen);
bool Open(const std::filesystem::path& filePath, OpenModeFlags openMode = OpenMode_NotOpen); bool Open(const std::filesystem::path& filePath, OpenModeFlags openMode = OpenMode::NotOpen);
bool SetCursorPos(CursorPosition pos, Int64 offset = 0); bool SetCursorPos(CursorPosition pos, Int64 offset = 0);
bool SetCursorPos(UInt64 offset) override; bool SetCursorPos(UInt64 offset) override;

View File

@ -13,7 +13,7 @@ namespace Nz
* \brief Constructs a MemoryStream object by default * \brief Constructs a MemoryStream object by default
*/ */
inline MemoryStream::MemoryStream() : inline MemoryStream::MemoryStream() :
Stream(StreamOption_None, OpenMode_ReadWrite), Stream(StreamOption::None, OpenMode_ReadWrite),
m_pos(0) m_pos(0)
{ {
} }

View File

@ -24,7 +24,7 @@ namespace Nz
{ {
matrix = transformMatrix; matrix = transformMatrix;
textureCoords = uvCoords; textureCoords = uvCoords;
type = PrimitiveType_Box; type = PrimitiveType::Box;
box.lengths = lengths; box.lengths = lengths;
box.subdivision = subdivision; box.subdivision = subdivision;
} }
@ -56,7 +56,7 @@ namespace Nz
{ {
matrix = transformMatrix; matrix = transformMatrix;
textureCoords = uvCoords; textureCoords = uvCoords;
type = PrimitiveType_Cone; type = PrimitiveType::Cone;
cone.length = length; cone.length = length;
cone.radius = radius; cone.radius = radius;
cone.subdivision = subdivision; cone.subdivision = subdivision;
@ -89,9 +89,9 @@ namespace Nz
{ {
matrix = transformMatrix; matrix = transformMatrix;
textureCoords = uvCoords; textureCoords = uvCoords;
type = PrimitiveType_Sphere; type = PrimitiveType::Sphere;
sphere.size = size; sphere.size = size;
sphere.type = SphereType_Cubic; sphere.type = SphereType::Cubic;
sphere.cubic.subdivision = subdivision; sphere.cubic.subdivision = subdivision;
} }
@ -121,9 +121,9 @@ namespace Nz
{ {
matrix = transformMatrix; matrix = transformMatrix;
textureCoords = uvCoords; textureCoords = uvCoords;
type = PrimitiveType_Sphere; type = PrimitiveType::Sphere;
sphere.size = size; sphere.size = size;
sphere.type = SphereType_Ico; sphere.type = SphereType::Ico;
sphere.ico.recursionLevel = recursionLevel; sphere.ico.recursionLevel = recursionLevel;
} }
@ -153,7 +153,7 @@ namespace Nz
{ {
matrix = transformMatrix; matrix = transformMatrix;
textureCoords = uvCoords; textureCoords = uvCoords;
type = PrimitiveType_Plane; type = PrimitiveType::Plane;
plane.size = size; plane.size = size;
plane.subdivision = subdivision; plane.subdivision = subdivision;
} }
@ -198,9 +198,9 @@ namespace Nz
{ {
matrix = transformMatrix; matrix = transformMatrix;
textureCoords = uvCoords; textureCoords = uvCoords;
type = PrimitiveType_Sphere; type = PrimitiveType::Sphere;
sphere.size = size; sphere.size = size;
sphere.type = SphereType_UV; sphere.type = SphereType::UV;
sphere.uv.sliceCount = sliceCount; sphere.uv.sliceCount = sliceCount;
sphere.uv.stackCount = stackCount; sphere.uv.stackCount = stackCount;
} }

View File

@ -89,7 +89,7 @@ namespace Nz
if (loader.streamChecker && !file.IsOpen()) if (loader.streamChecker && !file.IsOpen())
{ {
if (!file.Open(OpenMode_ReadOnly)) if (!file.Open(OpenMode::ReadOnly))
{ {
NazaraError("Failed to load file: unable to open \"" + filePath.generic_u8string() + '"'); NazaraError("Failed to load file: unable to open \"" + filePath.generic_u8string() + '"');
return nullptr; return nullptr;

View File

@ -89,7 +89,7 @@ namespace Nz
{ {
File file(filePath.generic_u8string()); File file(filePath.generic_u8string());
if (!file.Open(OpenMode_WriteOnly | OpenMode_Truncate)) if (!file.Open(OpenMode::WriteOnly | OpenMode::Truncate))
{ {
NazaraError("Failed to save to file: unable to open \"" + filePath.generic_u8string() + "\" in write mode"); NazaraError("Failed to save to file: unable to open \"" + filePath.generic_u8string() + "\" in write mode");
return false; return false;

View File

@ -20,7 +20,7 @@ namespace Nz
struct NAZARA_CORE_API SerializationContext struct NAZARA_CORE_API SerializationContext
{ {
MovablePtr<Stream> stream; MovablePtr<Stream> stream;
Endianness endianness = Endianness_BigEndian; //< Default to Big Endian encoding Endianness endianness = Endianness::BigEndian; //< Default to Big Endian encoding
UInt8 readBitPos = 8; //< 8 means no bit is currently read UInt8 readBitPos = 8; //< 8 means no bit is currently read
UInt8 readByte; //< Undefined value, will be initialized at the first bit read UInt8 readByte; //< Undefined value, will be initialized at the first bit read
UInt8 writeBitPos = 8; //< 8 means no bit is currently wrote UInt8 writeBitPos = 8; //< 8 means no bit is currently wrote

View File

@ -56,7 +56,7 @@ namespace Nz
Stream& operator=(Stream&&) noexcept = default; Stream& operator=(Stream&&) noexcept = default;
protected: protected:
inline Stream(StreamOptionFlags streamOptions = StreamOption_None, OpenModeFlags openMode = OpenMode_NotOpen); inline Stream(StreamOptionFlags streamOptions = StreamOption::None, OpenModeFlags openMode = OpenMode::NotOpen);
virtual void FlushStream() = 0; virtual void FlushStream() = 0;
virtual std::size_t ReadBlock(void* buffer, std::size_t size) = 0; virtual std::size_t ReadBlock(void* buffer, std::size_t size) = 0;

View File

@ -29,9 +29,9 @@ namespace Nz
inline void Stream::EnableTextMode(bool textMode) inline void Stream::EnableTextMode(bool textMode)
{ {
if (textMode) if (textMode)
m_streamOptions |= StreamOption_Text; m_streamOptions |= StreamOption::Text;
else else
m_streamOptions &= ~StreamOption_Text; m_streamOptions &= ~StreamOption::Text;
} }
/*! /*!
@ -74,7 +74,7 @@ namespace Nz
inline bool Stream::IsReadable() const inline bool Stream::IsReadable() const
{ {
return (m_openMode & OpenMode_ReadOnly) != 0; return (m_openMode & OpenMode::ReadOnly) != 0;
} }
/*! /*!
@ -84,7 +84,7 @@ namespace Nz
inline bool Stream::IsSequential() const inline bool Stream::IsSequential() const
{ {
return (m_streamOptions & StreamOption_Sequential) != 0; return (m_streamOptions & StreamOption::Sequential) != 0;
} }
/*! /*!
@ -94,7 +94,7 @@ namespace Nz
inline bool Stream::IsTextModeEnabled() const inline bool Stream::IsTextModeEnabled() const
{ {
return (m_streamOptions & StreamOption_Text) != 0; return (m_streamOptions & StreamOption::Text) != 0;
} }
/*! /*!
@ -104,7 +104,7 @@ namespace Nz
inline bool Stream::IsWritable() const inline bool Stream::IsWritable() const
{ {
return (m_openMode & OpenMode_WriteOnly) != 0; return (m_openMode & OpenMode::WriteOnly) != 0;
} }
/*! /*!

View File

@ -51,7 +51,7 @@ namespace Nz
bool CheckEvents(ENetEvent* event); bool CheckEvents(ENetEvent* event);
ENetPeer* Connect(const IpAddress& remoteAddress, std::size_t channelCount = 0, UInt32 data = 0); ENetPeer* Connect(const IpAddress& remoteAddress, std::size_t channelCount = 0, UInt32 data = 0);
ENetPeer* Connect(const std::string& hostName, NetProtocol protocol = NetProtocol_Any, const std::string& service = "http", ResolveError* error = nullptr, std::size_t channelCount = 0, UInt32 data = 0); ENetPeer* Connect(const std::string& hostName, NetProtocol protocol = NetProtocol::Any, const std::string& service = "http", ResolveError* error = nullptr, std::size_t channelCount = 0, UInt32 data = 0);
inline bool Create(NetProtocol protocol, UInt16 port, std::size_t peerCount, std::size_t channelCount = 0); inline bool Create(NetProtocol protocol, UInt16 port, std::size_t peerCount, std::size_t channelCount = 0);
bool Create(const IpAddress& listenAddress, std::size_t peerCount, std::size_t channelCount = 0); bool Create(const IpAddress& listenAddress, std::size_t peerCount, std::size_t channelCount = 0);

View File

@ -29,23 +29,23 @@ namespace Nz
inline bool ENetHost::Create(NetProtocol protocol, UInt16 port, std::size_t peerCount, std::size_t channelCount) inline bool ENetHost::Create(NetProtocol protocol, UInt16 port, std::size_t peerCount, std::size_t channelCount)
{ {
NazaraAssert(protocol != NetProtocol_Unknown, "Invalid protocol"); NazaraAssert(protocol != NetProtocol::Unknown, "Invalid protocol");
IpAddress any; IpAddress any;
switch (protocol) switch (protocol)
{ {
case NetProtocol_Unknown: case NetProtocol::Unknown:
NazaraInternalError("Invalid protocol"); NazaraInternalError("Invalid protocol");
return false; return false;
case NetProtocol_IPv4: case NetProtocol::IPv4:
any = IpAddress::AnyIpV4; any = IpAddress::AnyIpV4;
break; break;
case NetProtocol_Any: case NetProtocol::Any:
m_isUsingDualStack = true; m_isUsingDualStack = true;
// fallthrough // fallthrough
case NetProtocol_IPv6: case NetProtocol::IPv6:
any = IpAddress::AnyIpV6; any = IpAddress::AnyIpV6;
break; break;
} }

View File

@ -11,123 +11,114 @@
namespace Nz namespace Nz
{ {
enum NetCode : UInt16 enum class NetProtocol
{ {
NetCode_Acknowledge = 0x9A4E, Any,
NetCode_AcknowledgeConnection = 0xC108, IPv4,
NetCode_Ping = 0x96AC, IPv6,
NetCode_Pong = 0x974C, Unknown,
NetCode_RequestConnection = 0xF27D,
NetCode_Invalid = 0x0000 Max = Unknown
}; };
enum NetProtocol constexpr std::size_t NetProtocolCount = static_cast<std::size_t>(NetProtocol::Max) + 1;
{
NetProtocol_Any,
NetProtocol_IPv4,
NetProtocol_IPv6,
NetProtocol_Unknown,
NetProtocol_Max = NetProtocol_Unknown enum class PacketReliability
{
Reliable, //< Packet will be resent if lost
ReliableOrdered, //< Packet will be resent if lost and will only arrive in order
Unreliable, //< Packet won't be resent if lost
Max = Unreliable
}; };
enum PacketPriority constexpr std::size_t PacketReliabilityCount = static_cast<std::size_t>(PacketReliability::Max) + 1;
{
PacketPriority_High = 1, //< High-priority packet, will be sent quickly
PacketPriority_Immediate = 0, //< Immediate priority, will be sent immediately
PacketPriority_Medium = 2, //< Medium-priority packet, will be sent as regular
PacketPriority_Low = 3, //< Low-priority packet, may take some time to be sent
PacketPriority_Lowest = PacketPriority_Low, enum class ResolveError
PacketPriority_Highest = PacketPriority_Immediate, {
PacketPriority_Max = PacketPriority_Low NoError,
Internal, //< An internal error occurred
ResourceError, //< The operating system lacks the resources to proceed (insufficient memory)
NonRecoverable, //< An nonrecoverable error occurred
NotFound, //< No such host is known
NotInitialized, //< Nazara network has not been initialized
ProtocolNotSupported, //< A specified protocol is not supported by the server
TemporaryFailure, //< A temporary failure occurred, try again
Unknown, //< The last operation failed with an unlisted error code
Max = Unknown
}; };
enum PacketReliability constexpr std::size_t ResolveErrorCount = static_cast<std::size_t>(ResolveError::Max) + 1;
{
PacketReliability_Reliable, //< Packet will be resent if lost
PacketReliability_ReliableOrdered, //< Packet will be resent if lost and will only arrive in order
PacketReliability_Unreliable, //< Packet won't be resent if lost
PacketReliability_Max = PacketReliability_Unreliable enum class SocketError
{
NoError,
AddressNotAvailable, //< The address is already in use (when binding/listening)
ConnectionClosed, //< The connection has been closed
ConnectionRefused, //< The connection attempt was refused
DatagramSize, //< The datagram size is over the system limit
Internal, //< The error is coming from the engine
Interrupted, //< The operation was interrupted by a signal
Packet, //< The packet encoding/decoding failed, probably because of corrupted data
NetworkError, //< The network system has failed (maybe network is down)
NotInitialized, //< Nazara network has not been initialized
NotSupported, //< The operation is not supported (e.g. creating a bluetooth socket on a system without any bluetooth adapter)
ResolveError, //< The hostname couldn't be resolved (more information in ResolveError code)
ResourceError, //< The operating system lacks the resources to proceed (e.g. memory/socket descriptor)
TimedOut, //< The operation timed out
Unknown, //< The last operation failed with an unlisted error code
UnreachableHost, //< The host is not reachable
Max = UnreachableHost
}; };
enum ResolveError constexpr std::size_t SocketErrorCount = static_cast<std::size_t>(SocketError::Max) + 1;
enum class SocketPollEvent
{ {
ResolveError_NoError, Read, //< One or more sockets is ready for a read operation
Write, //< One or more sockets is ready for a write operation
ResolveError_Internal, //< An internal error occurred Max = Write
ResolveError_ResourceError, //< The operating system lacks the resources to proceed (insufficient memory)
ResolveError_NonRecoverable, //< An nonrecoverable error occurred
ResolveError_NotFound, //< No such host is known
ResolveError_NotInitialized, //< Nazara network has not been initialized
ResolveError_ProtocolNotSupported, //< A specified protocol is not supported by the server
ResolveError_TemporaryFailure, //< A temporary failure occurred, try again
ResolveError_Unknown, //< The last operation failed with an unlisted error code
ResolveError_Max = ResolveError_Unknown
}; };
enum SocketError constexpr std::size_t SocketPollEventCount = static_cast<std::size_t>(SocketPollEvent::Max) + 1;
{
SocketError_NoError,
SocketError_AddressNotAvailable, //< The address is already in use (when binding/listening)
SocketError_ConnectionClosed, //< The connection has been closed
SocketError_ConnectionRefused, //< The connection attempt was refused
SocketError_DatagramSize, //< The datagram size is over the system limit
SocketError_Internal, //< The error is coming from the engine
SocketError_Interrupted, //< The operation was interrupted by a signal
SocketError_Packet, //< The packet encoding/decoding failed, probably because of corrupted data
SocketError_NetworkError, //< The network system has failed (maybe network is down)
SocketError_NotInitialized, //< Nazara network has not been initialized
SocketError_NotSupported, //< The operation is not supported (e.g. creating a bluetooth socket on a system without any bluetooth adapter)
SocketError_ResolveError, //< The hostname couldn't be resolved (more information in ResolveError code)
SocketError_ResourceError, //< The operating system lacks the resources to proceed (e.g. memory/socket descriptor)
SocketError_TimedOut, //< The operation timed out
SocketError_Unknown, //< The last operation failed with an unlisted error code
SocketError_UnreachableHost, //< The host is not reachable
SocketError_Max = SocketError_UnreachableHost
};
enum SocketPollEvent
{
SocketPollEvent_Read, //< One or more sockets is ready for a read operation
SocketPollEvent_Write, //< One or more sockets is ready for a write operation
SocketPollEvent_Max = SocketPollEvent_Write
};
template<> template<>
struct EnumAsFlags<SocketPollEvent> struct EnumAsFlags<SocketPollEvent>
{ {
static constexpr SocketPollEvent max = SocketPollEvent_Max; static constexpr SocketPollEvent max = SocketPollEvent::Max;
}; };
using SocketPollEventFlags = Flags<SocketPollEvent>; using SocketPollEventFlags = Flags<SocketPollEvent>;
enum SocketState enum class SocketState
{ {
SocketState_Bound, //< The socket is currently bound Bound, //< The socket is currently bound
SocketState_Connecting, //< The socket is currently connecting Connecting, //< The socket is currently connecting
SocketState_Connected, //< The socket is currently connected Connected, //< The socket is currently connected
SocketState_NotConnected, //< The socket is not connected (or has been disconnected) NotConnected, //< The socket is not connected (or has been disconnected)
SocketState_Resolving, //< The socket is currently resolving a host name Resolving, //< The socket is currently resolving a host name
SocketState_Max = SocketState_Resolving Max = Resolving
}; };
enum SocketType constexpr std::size_t SocketStateCount = static_cast<std::size_t>(SocketState::Max) + 1;
{
SocketType_Raw,
SocketType_TCP,
SocketType_UDP,
SocketType_Unknown,
SocketType_Max = SocketType_Unknown enum class SocketType
{
Raw,
TCP,
UDP,
Unknown,
Max = Unknown
}; };
constexpr std::size_t SocketTypeCount = static_cast<std::size_t>(SocketType::Max) + 1;
} }
#endif // NAZARA_ENUMS_NETWORK_HPP #endif // NAZARA_ENUMS_NETWORK_HPP

View File

@ -27,7 +27,7 @@ namespace Nz
inline IpAddress::IpAddress(const IPv4& ip, UInt16 port) : inline IpAddress::IpAddress(const IPv4& ip, UInt16 port) :
m_ipv4(ip), m_ipv4(ip),
m_protocol(NetProtocol_IPv4), m_protocol(NetProtocol::IPv4),
m_port(port), m_port(port),
m_isValid(true) m_isValid(true)
{ {
@ -42,7 +42,7 @@ namespace Nz
inline IpAddress::IpAddress(const IPv6& ip, UInt16 port) : inline IpAddress::IpAddress(const IPv6& ip, UInt16 port) :
m_ipv6(ip), m_ipv6(ip),
m_protocol(NetProtocol_IPv6), m_protocol(NetProtocol::IPv6),
m_port(port), m_port(port),
m_isValid(true) m_isValid(true)
{ {
@ -149,7 +149,7 @@ namespace Nz
inline IpAddress::IPv4 IpAddress::ToIPv4() const inline IpAddress::IPv4 IpAddress::ToIPv4() const
{ {
NazaraAssert(m_isValid && m_protocol == NetProtocol_IPv4, "Address is not a valid IPv4"); NazaraAssert(m_isValid && m_protocol == NetProtocol::IPv4, "Address is not a valid IPv4");
return m_ipv4; return m_ipv4;
} }
@ -163,7 +163,7 @@ namespace Nz
inline IpAddress::IPv6 IpAddress::ToIPv6() const inline IpAddress::IPv6 IpAddress::ToIPv6() const
{ {
NazaraAssert(m_isValid && m_protocol == NetProtocol_IPv6, "IP is not a valid IPv6"); NazaraAssert(m_isValid && m_protocol == NetProtocol::IPv6, "IP is not a valid IPv6");
return m_ipv6; return m_ipv6;
} }
@ -177,7 +177,7 @@ namespace Nz
inline UInt32 IpAddress::ToUInt32() const inline UInt32 IpAddress::ToUInt32() const
{ {
NazaraAssert(m_isValid && m_protocol == NetProtocol_IPv4, "Address is not a valid IPv4"); NazaraAssert(m_isValid && m_protocol == NetProtocol::IPv4, "Address is not a valid IPv4");
return UInt32(m_ipv4[0]) << 24 | return UInt32(m_ipv4[0]) << 24 |
UInt32(m_ipv4[1]) << 16 | UInt32(m_ipv4[1]) << 16 |
@ -231,11 +231,11 @@ namespace Nz
// Each protocol has its variables to compare // Each protocol has its variables to compare
switch (first.m_protocol) switch (first.m_protocol)
{ {
case NetProtocol_Any: case NetProtocol::Any:
case NetProtocol_Unknown: case NetProtocol::Unknown:
break; break;
case NetProtocol_IPv4: case NetProtocol::IPv4:
{ {
if (first.m_ipv4 != second.m_ipv4) if (first.m_ipv4 != second.m_ipv4)
return false; return false;
@ -243,7 +243,7 @@ namespace Nz
break; break;
} }
case NetProtocol_IPv6: case NetProtocol::IPv6:
{ {
if (first.m_ipv6 != second.m_ipv6) if (first.m_ipv6 != second.m_ipv6)
return false; return false;
@ -297,11 +297,11 @@ namespace Nz
// Compare IP (thanks to std::array comparison operator) // Compare IP (thanks to std::array comparison operator)
switch (first.m_protocol) switch (first.m_protocol)
{ {
case NetProtocol_Any: case NetProtocol::Any:
case NetProtocol_Unknown: case NetProtocol::Unknown:
break; break;
case NetProtocol_IPv4: case NetProtocol::IPv4:
{ {
if (first.m_ipv4 != second.m_ipv4) if (first.m_ipv4 != second.m_ipv4)
return first.m_ipv4 < second.m_ipv4; return first.m_ipv4 < second.m_ipv4;
@ -309,7 +309,7 @@ namespace Nz
break; break;
} }
case NetProtocol_IPv6: case NetProtocol::IPv6:
{ {
if (first.m_ipv6 != second.m_ipv6) if (first.m_ipv6 != second.m_ipv6)
return first.m_ipv6 < second.m_ipv6; return first.m_ipv6 < second.m_ipv6;
@ -387,16 +387,16 @@ namespace std
std::size_t h = 0; std::size_t h = 0;
switch (ip.GetProtocol()) switch (ip.GetProtocol())
{ {
case Nz::NetProtocol_Any: case Nz::NetProtocol::Any:
case Nz::NetProtocol_Unknown: case Nz::NetProtocol::Unknown:
return std::numeric_limits<size_t>::max(); return std::numeric_limits<size_t>::max();
case Nz::NetProtocol_IPv4: case Nz::NetProtocol::IPv4:
{ {
h = ip.ToUInt32() + (h << 6) + (h << 16) - h; h = ip.ToUInt32() + (h << 6) + (h << 16) - h;
break; break;
} }
case Nz::NetProtocol_IPv6: case Nz::NetProtocol::IPv6:
{ {
Nz::IpAddress::IPv6 v6 = ip.ToIPv6(); Nz::IpAddress::IPv6 v6 = ip.ToIPv6();
for (std::size_t i = 0; i < v6.size(); i++) for (std::size_t i = 0; i < v6.size(); i++)

View File

@ -12,9 +12,8 @@ namespace Nz
/*! /*!
* \brief Constructs a NetPacket object by default * \brief Constructs a NetPacket object by default
*/ */
inline NetPacket::NetPacket() : inline NetPacket::NetPacket() :
m_netCode(NetCode_Invalid) m_netCode(0)
{ {
} }
@ -156,7 +155,7 @@ namespace Nz
inline void NetPacket::Reset(UInt16 netCode, const void* ptr, std::size_t size) inline void NetPacket::Reset(UInt16 netCode, const void* ptr, std::size_t size)
{ {
InitStream(HeaderSize + size, HeaderSize, OpenMode_ReadOnly); InitStream(HeaderSize + size, HeaderSize, OpenMode::ReadOnly);
m_buffer->Resize(HeaderSize + size); m_buffer->Resize(HeaderSize + size);
if (ptr) if (ptr)

View File

@ -1,164 +0,0 @@
// Copyright (C) 2020 Jérôme Leclercq
// This file is part of the "Nazara Engine - Network module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#pragma once
#ifndef NAZARA_RUDPSERVER_HPP
#define NAZARA_RUDPSERVER_HPP
#include <Nazara/Prerequisites.hpp>
#include <Nazara/Core/Bitset.hpp>
#include <Nazara/Core/Clock.hpp>
#include <Nazara/Network/IpAddress.hpp>
#include <Nazara/Network/NetPacket.hpp>
#include <Nazara/Network/RUdpMessage.hpp>
#include <Nazara/Network/UdpSocket.hpp>
#include <deque>
#include <queue>
#include <random>
#include <set>
#include <unordered_map>
namespace Nz
{
class NAZARA_NETWORK_API RUdpConnection
{
friend class Network;
public:
using SequenceIndex = UInt16;
RUdpConnection();
RUdpConnection(const RUdpConnection&) = delete;
RUdpConnection(RUdpConnection&&) = default;
~RUdpConnection() = default;
inline void Close();
bool Connect(const IpAddress& remoteAddress);
bool Connect(const std::string& hostName, NetProtocol protocol = NetProtocol_Any, const std::string& service = "http", ResolveError* error = nullptr);
inline void Disconnect();
inline IpAddress GetBoundAddress() const;
inline UInt16 GetBoundPort() const;
inline SocketError GetLastError() const;
inline bool Listen(NetProtocol protocol, UInt16 port = 64266);
bool Listen(const IpAddress& address);
bool PollMessage(RUdpMessage* message);
bool Send(const IpAddress& clientIp, PacketPriority priority, PacketReliability reliability, const NetPacket& packet);
inline void SetProtocolId(UInt32 protocolId);
inline void SetTimeBeforeAck(UInt32 ms);
inline void SimulateNetwork(double packetLoss);
void Update();
RUdpConnection& operator=(const RUdpConnection&) = delete;
RUdpConnection& operator=(RUdpConnection&&) = default;
static constexpr std::size_t MessageHeader = sizeof(UInt16) + 2 * sizeof(SequenceIndex) + sizeof(UInt32); //< Protocol ID (begin) + Sequence ID + Remote Sequence ID + Ack bitfield
static constexpr std::size_t MessageFooter = sizeof(UInt16); //< Protocol ID (end)
// Signals:
NazaraSignal(OnConnectedToPeer, RUdpConnection* /*connection*/);
NazaraSignal(OnPeerAcknowledged, RUdpConnection* /*connection*/, const IpAddress& /*adress*/);
NazaraSignal(OnPeerConnection, RUdpConnection* /*connection*/, const IpAddress& /*adress*/);
NazaraSignal(OnPeerDisconnected, RUdpConnection* /*connection*/, const IpAddress& /*adress*/);
private:
struct PeerData;
struct PendingAckPacket;
struct PendingPacket;
enum PeerState
{
PeerState_Aknowledged, //< A connection request from this peer has been received, we're waiting for another packet to validate
PeerState_Connected, //< Connection is working in both-ways
PeerState_Connecting, //< A connection request has been made
PeerState_WillAck //< Connected, received one or more packets and has no packets to send, waiting before sending an empty ack packet
};
void DisconnectPeer(std::size_t peerIndex);
void EnqueuePacket(PeerData& peer, PacketPriority priority, PacketReliability reliability, const NetPacket& packet);
void EnqueuePacketInternal(PeerData& peer, PacketPriority priority, PacketReliability reliability, NetPacket&& data);
bool InitSocket(NetProtocol protocol);
void ProcessAcks(PeerData& peer, SequenceIndex lastAck, UInt32 ackBits);
PeerData& RegisterPeer(const IpAddress& address, PeerState state);
void OnClientRequestingConnection(const IpAddress& address, SequenceIndex sequenceId, UInt64 token);
void OnPacketLost(PeerData& peer, PendingAckPacket&& packet);
void OnPacketReceived(const IpAddress& peerIp, NetPacket&& packet);
void SendPacket(PeerData& peer, PendingPacket&& packet);
static inline unsigned int ComputeSequenceDifference(SequenceIndex sequence, SequenceIndex sequence2);
static inline bool HasPendingPackets(PeerData& peer);
static bool Initialize();
static inline bool IsAckMoreRecent(SequenceIndex ack, SequenceIndex ack2);
static inline bool IsReliable(PacketReliability reliability);
static void Uninitialize();
struct PendingPacket
{
PacketPriority priority;
PacketReliability reliability;
NetPacket data;
};
struct PendingAckPacket
{
PacketPriority priority;
PacketReliability reliability;
NetPacket data;
SequenceIndex sequenceId;
UInt64 timeSent;
};
struct PeerData //TODO: Move this to RUdpClient
{
PeerData() = default;
PeerData(PeerData&& other) = default;
PeerData& operator=(PeerData&& other) = default;
std::array<std::vector<PendingPacket>, PacketPriority_Max + 1> pendingPackets;
std::deque<PendingAckPacket> pendingAckQueue;
std::set<UInt16> receivedQueue;
std::size_t index;
PeerState state;
IpAddress address;
SequenceIndex localSequence;
SequenceIndex remoteSequence;
UInt32 roundTripTime;
UInt64 lastPacketTime;
UInt64 lastPingTime;
UInt64 stateData1;
};
std::bernoulli_distribution m_packetLossProbability;
std::queue<RUdpMessage> m_receivedMessages;
std::size_t m_peerIterator;
std::unordered_map<IpAddress, std::size_t> m_peerByIP;
std::vector<PeerData> m_peers;
Bitset<UInt64> m_activeClients;
Clock m_clock;
SocketError m_lastError;
UdpSocket m_socket;
UInt32 m_forceAckSendTime;
UInt32 m_pingInterval;
UInt32 m_protocol;
UInt32 m_timeBeforePing;
UInt32 m_timeBeforeTimeOut;
UInt64 m_currentTime;
bool m_isSimulationEnabled;
bool m_shouldAcceptConnections;
static std::mt19937_64 s_randomGenerator;
};
}
#include <Nazara/Network/RUdpConnection.inl>
#endif // NAZARA_RUDPSERVER_HPP

View File

@ -1,220 +0,0 @@
// Copyright (C) 2020 Jérôme Leclercq
// This file is part of the "Nazara Engine - Network module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Network/Debug.hpp>
namespace Nz
{
/*!
* \brief Closes the connection
*/
inline void RUdpConnection::Close()
{
m_socket.Close();
}
/*!
* \brief Disconnects the connection
*
* \see Close
*/
inline void RUdpConnection::Disconnect()
{
Close();
}
/*!
* \brief Gets the bound address
* \return IpAddress we are linked to
*/
inline IpAddress RUdpConnection::GetBoundAddress() const
{
return m_socket.GetBoundAddress();
}
/*!
* \brief Gets the port of the bound address
* \return Port we are linked to
*/
inline UInt16 RUdpConnection::GetBoundPort() const
{
return m_socket.GetBoundPort();
}
/*!
* \brief Gets the last error
* \return Socket error
*/
inline SocketError RUdpConnection::GetLastError() const
{
return m_lastError;
}
/*!
* \brief Listens to a socket
* \return true If successfully bound
*
* \param protocol Net protocol to listen to
* \param port Port to listen to
*
* \remark Produces a NazaraAssert if protocol is unknown or any
*/
inline bool RUdpConnection::Listen(NetProtocol protocol, UInt16 port)
{
NazaraAssert(protocol != NetProtocol_Any, "Any protocol not supported for Listen"); //< TODO
NazaraAssert(protocol != NetProtocol_Unknown, "Invalid protocol");
IpAddress any;
switch (protocol)
{
case NetProtocol_Any:
case NetProtocol_Unknown:
NazaraInternalError("Invalid protocol Any at this point");
return false;
case NetProtocol_IPv4:
any = IpAddress::AnyIpV4;
break;
case NetProtocol_IPv6:
any = IpAddress::AnyIpV6;
break;
}
any.SetPort(port);
return Listen(any);
}
/*!
* \brief Sets the protocol id
*
* \param protocolId Protocol ID like NNet
*/
inline void RUdpConnection::SetProtocolId(UInt32 protocolId)
{
m_protocol = protocolId;
}
/*!
* \brief Sets the time before ack
*
* \param Time before acking to send many together (in ms)
*/
inline void RUdpConnection::SetTimeBeforeAck(UInt32 ms)
{
m_forceAckSendTime = ms * 1000; //< Store in microseconds for easier handling
}
/*!
* \brief Computes the difference of sequence
* \return Delta between the two sequences
*
* \param sequence First sequence
* \param sequence2 Second sequence
*/
inline unsigned int RUdpConnection::ComputeSequenceDifference(SequenceIndex sequence, SequenceIndex sequence2)
{
unsigned int difference;
if (sequence2 > sequence)
difference = std::numeric_limits<SequenceIndex>::max() - sequence2 + sequence;
else
difference = sequence - sequence2;
return difference;
}
/*!
* \brief Checks whether the peer has pending packets
* \return true If it is the case
*
* \param peer Data relative to the peer
*/
inline bool RUdpConnection::HasPendingPackets(PeerData& peer)
{
for (unsigned int priority = PacketPriority_Highest; priority <= PacketPriority_Lowest; ++priority)
{
std::vector<PendingPacket>& pendingPackets = peer.pendingPackets[priority];
if (!pendingPackets.empty())
return true;
}
return false;
}
/*!
* \brief Checks whether the ack is more recent
* \return true If it is the case
*
* \param ack First sequence
* \param ack2 Second sequence
*/
inline bool RUdpConnection::IsAckMoreRecent(SequenceIndex ack, SequenceIndex ack2)
{
constexpr SequenceIndex maxDifference = std::numeric_limits<SequenceIndex>::max() / 2;
if (ack > ack2)
return ack - ack2 <= maxDifference;
else if (ack2 > ack)
return ack2 - ack > maxDifference;
else
return false; ///< Same ack
}
/*!
* \brief Checks whether the connection is reliable
* \return true If it is the case
*
* \remark Produces a NazaraError if enumeration is invalid
*/
inline bool RUdpConnection::IsReliable(PacketReliability reliability)
{
switch (reliability)
{
case PacketReliability_Reliable:
case PacketReliability_ReliableOrdered:
return true;
case PacketReliability_Unreliable:
return false;
}
NazaraError("PacketReliability not handled (0x" + NumberToString(reliability, 16) + ')');
return false;
}
/*!
* \brief Simulates the loss of packets on network
*
* \param packetLoss Ratio of packet loss according to bernoulli distribution
*
* \remark Produces a NazaraAssert if packetLoss is not in between 0.0 and 1.0
*/
inline void RUdpConnection::SimulateNetwork(double packetLoss)
{
NazaraAssert(packetLoss >= 0.0 && packetLoss <= 1.0, "Packet loss must be in range [0..1]");
if (packetLoss > 0.0)
{
m_isSimulationEnabled = true;
m_packetLossProbability = std::bernoulli_distribution(packetLoss);
}
else
m_isSimulationEnabled = false;
}
}
#include <Nazara/Network/DebugOff.hpp>

View File

@ -1,23 +0,0 @@
// Copyright (C) 2020 Jérôme Leclercq
// This file is part of the "Nazara Engine - Network module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#pragma once
#ifndef NAZARA_RUDMESSAGE_HPP
#define NAZARA_RUDMESSAGE_HPP
#include <Nazara/Prerequisites.hpp>
#include <Nazara/Network/IpAddress.hpp>
#include <Nazara/Network/NetPacket.hpp>
namespace Nz
{
struct RUdpMessage
{
IpAddress from;
NetPacket data;
};
}
#endif // NAZARA_RUDMESSAGE_HPP

View File

@ -29,7 +29,7 @@ namespace Nz
~TcpClient() = default; ~TcpClient() = default;
SocketState Connect(const IpAddress& remoteAddress); SocketState Connect(const IpAddress& remoteAddress);
SocketState Connect(const std::string& hostName, NetProtocol protocol = NetProtocol_Any, const std::string& service = "http", ResolveError* error = nullptr); SocketState Connect(const std::string& hostName, NetProtocol protocol = NetProtocol::Any, const std::string& service = "http", ResolveError* error = nullptr);
inline void Disconnect(); inline void Disconnect();
void EnableLowDelay(bool lowDelay); void EnableLowDelay(bool lowDelay);

View File

@ -11,8 +11,8 @@ namespace Nz
*/ */
inline TcpClient::TcpClient() : inline TcpClient::TcpClient() :
AbstractSocket(SocketType_TCP), AbstractSocket(SocketType::TCP),
Stream(StreamOption_Sequential), Stream(StreamOption::Sequential),
m_keepAliveInterval(1000), //TODO: Query OS default value m_keepAliveInterval(1000), //TODO: Query OS default value
m_keepAliveTime(7'200'000), //TODO: Query OS default value m_keepAliveTime(7'200'000), //TODO: Query OS default value
m_isKeepAliveEnabled(false), //TODO: Query OS default value m_isKeepAliveEnabled(false), //TODO: Query OS default value

View File

@ -12,7 +12,7 @@ namespace Nz
*/ */
inline TcpServer::TcpServer() : inline TcpServer::TcpServer() :
AbstractSocket(SocketType_TCP) AbstractSocket(SocketType::TCP)
{ {
} }
@ -61,22 +61,22 @@ namespace Nz
inline SocketState TcpServer::Listen(NetProtocol protocol, UInt16 port, unsigned int queueSize) inline SocketState TcpServer::Listen(NetProtocol protocol, UInt16 port, unsigned int queueSize)
{ {
NazaraAssert(protocol != NetProtocol_Any, "Any protocol not supported for Listen"); //< TODO NazaraAssert(protocol != NetProtocol::Any, "Any protocol not supported for Listen"); //< TODO
NazaraAssert(protocol != NetProtocol_Unknown, "Invalid protocol"); NazaraAssert(protocol != NetProtocol::Unknown, "Invalid protocol");
IpAddress any; IpAddress any;
switch (protocol) switch (protocol)
{ {
case NetProtocol_Any: case NetProtocol::Any:
case NetProtocol_Unknown: case NetProtocol::Unknown:
NazaraInternalError("Invalid protocol Any at this point"); NazaraInternalError("Invalid protocol Any at this point");
return SocketState_NotConnected; return SocketState::NotConnected;
case NetProtocol_IPv4: case NetProtocol::IPv4:
any = IpAddress::AnyIpV4; any = IpAddress::AnyIpV4;
break; break;
case NetProtocol_IPv6: case NetProtocol::IPv6:
any = IpAddress::AnyIpV6; any = IpAddress::AnyIpV6;
break; break;
} }

View File

@ -11,7 +11,7 @@ namespace Nz
*/ */
inline UdpSocket::UdpSocket() : inline UdpSocket::UdpSocket() :
AbstractSocket(SocketType_UDP) AbstractSocket(SocketType::UDP)
{ {
} }
@ -51,16 +51,16 @@ namespace Nz
IpAddress any; IpAddress any;
switch (m_protocol) switch (m_protocol)
{ {
case NetProtocol_Unknown: case NetProtocol::Unknown:
NazaraInternalError("Invalid protocol"); NazaraInternalError("Invalid protocol");
return SocketState_NotConnected; return SocketState::NotConnected;
case NetProtocol_IPv4: case NetProtocol::IPv4:
any = IpAddress::AnyIpV4; any = IpAddress::AnyIpV4;
break; break;
case NetProtocol_Any: case NetProtocol::Any:
case NetProtocol_IPv6: case NetProtocol::IPv6:
any = IpAddress::AnyIpV6; any = IpAddress::AnyIpV6;
break; break;
} }
@ -78,7 +78,7 @@ namespace Nz
bool UdpSocket::Create(NetProtocol protocol) bool UdpSocket::Create(NetProtocol protocol)
{ {
NazaraAssert(protocol != NetProtocol_Unknown, "Invalid protocol"); NazaraAssert(protocol != NetProtocol::Unknown, "Invalid protocol");
return Open(protocol); return Open(protocol);
} }

View File

@ -35,10 +35,10 @@ namespace Nz
RigidBody2D(RigidBody2D&& object) noexcept; RigidBody2D(RigidBody2D&& object) noexcept;
~RigidBody2D(); ~RigidBody2D();
void AddForce(const Vector2f& force, CoordSys coordSys = CoordSys_Global); void AddForce(const Vector2f& force, CoordSys coordSys = CoordSys::Global);
void AddForce(const Vector2f& force, const Vector2f& point, CoordSys coordSys = CoordSys_Global); void AddForce(const Vector2f& force, const Vector2f& point, CoordSys coordSys = CoordSys::Global);
void AddImpulse(const Vector2f& impulse, CoordSys coordSys = CoordSys_Global); void AddImpulse(const Vector2f& impulse, CoordSys coordSys = CoordSys::Global);
void AddImpulse(const Vector2f& impulse, const Vector2f& point, CoordSys coordSys = CoordSys_Global); void AddImpulse(const Vector2f& impulse, const Vector2f& point, CoordSys coordSys = CoordSys::Global);
void AddTorque(const RadianAnglef& torque); void AddTorque(const RadianAnglef& torque);
bool ClosestPointQuery(const Nz::Vector2f& position, Nz::Vector2f* closestPoint = nullptr, float* closestDistance = nullptr) const; bool ClosestPointQuery(const Nz::Vector2f& position, Nz::Vector2f* closestPoint = nullptr, float* closestDistance = nullptr) const;
@ -52,13 +52,13 @@ namespace Nz
inline float GetAngularDamping() const; inline float GetAngularDamping() const;
RadianAnglef GetAngularVelocity() const; RadianAnglef GetAngularVelocity() const;
NAZARA_DEPRECATED("Name error, please use GetMassCenter") NAZARA_DEPRECATED("Name error, please use GetMassCenter")
inline Vector2f GetCenterOfGravity(CoordSys coordSys = CoordSys_Local) const; inline Vector2f GetCenterOfGravity(CoordSys coordSys = CoordSys::Local) const;
float GetElasticity(std::size_t shapeIndex = 0) const; float GetElasticity(std::size_t shapeIndex = 0) const;
float GetFriction(std::size_t shapeIndex = 0) const; float GetFriction(std::size_t shapeIndex = 0) const;
const std::shared_ptr<Collider2D>& GetGeom() const; const std::shared_ptr<Collider2D>& GetGeom() const;
cpBody* GetHandle() const; cpBody* GetHandle() const;
float GetMass() const; float GetMass() const;
Vector2f GetMassCenter(CoordSys coordSys = CoordSys_Local) const; Vector2f GetMassCenter(CoordSys coordSys = CoordSys::Local) const;
float GetMomentOfInertia() const; float GetMomentOfInertia() const;
Vector2f GetPosition() const; Vector2f GetPosition() const;
inline const Vector2f& GetPositionOffset() const; inline const Vector2f& GetPositionOffset() const;
@ -86,7 +86,7 @@ namespace Nz
void SetFriction(std::size_t shapeIndex, float friction); void SetFriction(std::size_t shapeIndex, float friction);
void SetGeom(std::shared_ptr<Collider2D> geom, bool recomputeMoment = true, bool recomputeMassCenter = true); void SetGeom(std::shared_ptr<Collider2D> geom, bool recomputeMoment = true, bool recomputeMassCenter = true);
void SetMass(float mass, bool recomputeMoment = true); void SetMass(float mass, bool recomputeMoment = true);
void SetMassCenter(const Vector2f& center, CoordSys coordSys = CoordSys_Local); void SetMassCenter(const Vector2f& center, CoordSys coordSys = CoordSys::Local);
void SetMomentOfInertia(float moment); void SetMomentOfInertia(float moment);
void SetPosition(const Vector2f& position); void SetPosition(const Vector2f& position);
void SetPositionOffset(const Vector2f& offset); void SetPositionOffset(const Vector2f& offset);

View File

@ -30,9 +30,9 @@ namespace Nz
RigidBody3D(RigidBody3D&& object); RigidBody3D(RigidBody3D&& object);
~RigidBody3D(); ~RigidBody3D();
void AddForce(const Vector3f& force, CoordSys coordSys = CoordSys_Global); void AddForce(const Vector3f& force, CoordSys coordSys = CoordSys::Global);
void AddForce(const Vector3f& force, const Vector3f& point, CoordSys coordSys = CoordSys_Global); void AddForce(const Vector3f& force, const Vector3f& point, CoordSys coordSys = CoordSys::Global);
void AddTorque(const Vector3f& torque, CoordSys coordSys = CoordSys_Global); void AddTorque(const Vector3f& torque, CoordSys coordSys = CoordSys::Global);
void EnableAutoSleep(bool autoSleep); void EnableAutoSleep(bool autoSleep);
void EnableSimulation(bool simulation); void EnableSimulation(bool simulation);
@ -46,7 +46,7 @@ namespace Nz
float GetLinearDamping() const; float GetLinearDamping() const;
Vector3f GetLinearVelocity() const; Vector3f GetLinearVelocity() const;
float GetMass() const; float GetMass() const;
Vector3f GetMassCenter(CoordSys coordSys = CoordSys_Local) const; Vector3f GetMassCenter(CoordSys coordSys = CoordSys::Local) const;
int GetMaterial() const; int GetMaterial() const;
const Matrix4f& GetMatrix() const; const Matrix4f& GetMatrix() const;
Vector3f GetPosition() const; Vector3f GetPosition() const;

View File

@ -15,14 +15,14 @@ namespace Nz
inline Window::Window(VideoMode mode, const std::string& title, WindowStyleFlags style) : inline Window::Window(VideoMode mode, const std::string& title, WindowStyleFlags style) :
Window() Window()
{ {
ErrorFlags flags(ErrorFlag_ThrowException, true); ErrorFlags flags(ErrorMode::ThrowException, true);
Create(mode, title, style); Create(mode, title, style);
} }
inline Window::Window(void* handle) : inline Window::Window(void* handle) :
Window() Window()
{ {
ErrorFlags flags(ErrorFlag_ThrowException, true); ErrorFlags flags(ErrorMode::ThrowException, true);
Create(handle); Create(handle);
} }

View File

@ -15,14 +15,14 @@ namespace Nz
inline RenderWindow::RenderWindow(std::shared_ptr<RenderDevice> renderDevice, VideoMode mode, const std::string& title, WindowStyleFlags style, const RenderWindowParameters& parameters) : inline RenderWindow::RenderWindow(std::shared_ptr<RenderDevice> renderDevice, VideoMode mode, const std::string& title, WindowStyleFlags style, const RenderWindowParameters& parameters) :
RenderWindow() RenderWindow()
{ {
ErrorFlags errFlags(ErrorFlag_ThrowException, true); ErrorFlags errFlags(ErrorMode::ThrowException, true);
Create(std::move(renderDevice), mode, title, style, parameters); Create(std::move(renderDevice), mode, title, style, parameters);
} }
inline RenderWindow::RenderWindow(std::shared_ptr<RenderDevice> renderDevice, void* handle, const RenderWindowParameters& parameters) inline RenderWindow::RenderWindow(std::shared_ptr<RenderDevice> renderDevice, void* handle, const RenderWindowParameters& parameters)
{ {
ErrorFlags errFlags(ErrorFlag_ThrowException, true); ErrorFlags errFlags(ErrorMode::ThrowException, true);
Create(std::move(renderDevice), handle, parameters); Create(std::move(renderDevice), handle, parameters);
} }

View File

@ -13,6 +13,7 @@
#include <Nazara/Utility/Enums.hpp> #include <Nazara/Utility/Enums.hpp>
#include <array> #include <array>
#include <functional> #include <functional>
#include <memory>
namespace Nz namespace Nz
{ {

View File

@ -41,21 +41,21 @@ namespace Nz
virtual Vector3f GetLeft() const; virtual Vector3f GetLeft() const;
virtual NodeType GetNodeType() const; virtual NodeType GetNodeType() const;
const Node* GetParent() const; const Node* GetParent() const;
Vector3f GetPosition(CoordSys coordSys = CoordSys_Local) const; Vector3f GetPosition(CoordSys coordSys = CoordSys::Local) const;
virtual Vector3f GetRight() const; virtual Vector3f GetRight() const;
Quaternionf GetRotation(CoordSys coordSys = CoordSys_Local) const; Quaternionf GetRotation(CoordSys coordSys = CoordSys::Local) const;
Vector3f GetScale(CoordSys coordSys = CoordSys_Local) const; Vector3f GetScale(CoordSys coordSys = CoordSys::Local) const;
const Matrix4f& GetTransformMatrix() const; const Matrix4f& GetTransformMatrix() const;
virtual Vector3f GetUp() const; virtual Vector3f GetUp() const;
bool HasChilds() const; bool HasChilds() const;
Node& Interpolate(const Node& nodeA, const Node& nodeB, float interpolation, CoordSys coordSys = CoordSys_Global); Node& Interpolate(const Node& nodeA, const Node& nodeB, float interpolation, CoordSys coordSys = CoordSys::Global);
Node& Move(const Vector3f& movement, CoordSys coordSys = CoordSys_Local); Node& Move(const Vector3f& movement, CoordSys coordSys = CoordSys::Local);
Node& Move(float movementX, float movementY, float movementZ = 0.f, CoordSys coordSys = CoordSys_Local); Node& Move(float movementX, float movementY, float movementZ = 0.f, CoordSys coordSys = CoordSys::Local);
Node& Rotate(const Quaternionf& rotation, CoordSys coordSys = CoordSys_Local); Node& Rotate(const Quaternionf& rotation, CoordSys coordSys = CoordSys::Local);
Node& Scale(const Vector3f& scale); Node& Scale(const Vector3f& scale);
Node& Scale(float scale); Node& Scale(float scale);
@ -72,13 +72,13 @@ namespace Nz
void SetInitialPosition(float translationX, float translationXY, float translationZ = 0.f); void SetInitialPosition(float translationX, float translationXY, float translationZ = 0.f);
void SetParent(const Node* node = nullptr, bool keepDerived = false); void SetParent(const Node* node = nullptr, bool keepDerived = false);
void SetParent(const Node& node, bool keepDerived = false); void SetParent(const Node& node, bool keepDerived = false);
void SetPosition(const Vector3f& translation, CoordSys coordSys = CoordSys_Local); void SetPosition(const Vector3f& translation, CoordSys coordSys = CoordSys::Local);
void SetPosition(float translationX, float translationY, float translationZ = 0.f, CoordSys coordSys = CoordSys_Local); void SetPosition(float translationX, float translationY, float translationZ = 0.f, CoordSys coordSys = CoordSys::Local);
void SetRotation(const Quaternionf& quat, CoordSys coordSys = CoordSys_Local); void SetRotation(const Quaternionf& quat, CoordSys coordSys = CoordSys::Local);
void SetScale(const Vector2f& scale, CoordSys coordSys = CoordSys_Local); void SetScale(const Vector2f& scale, CoordSys coordSys = CoordSys::Local);
void SetScale(const Vector3f& scale, CoordSys coordSys = CoordSys_Local); void SetScale(const Vector3f& scale, CoordSys coordSys = CoordSys::Local);
void SetScale(float scale, CoordSys coordSys = CoordSys_Local); void SetScale(float scale, CoordSys coordSys = CoordSys::Local);
void SetScale(float scaleX, float scaleY, float scaleZ = 1.f, CoordSys coordSys = CoordSys_Local); void SetScale(float scaleX, float scaleY, float scaleZ = 1.f, CoordSys coordSys = CoordSys::Local);
void SetTransformMatrix(const Matrix4f& matrix); void SetTransformMatrix(const Matrix4f& matrix);
// Local -> global // Local -> global

View File

@ -13,6 +13,7 @@
#include <Nazara/Utility/Config.hpp> #include <Nazara/Utility/Config.hpp>
#include <Nazara/Utility/Enums.hpp> #include <Nazara/Utility/Enums.hpp>
#include <array> #include <array>
#include <vector>
namespace Nz namespace Nz
{ {

View File

@ -30,10 +30,10 @@ namespace Ndk
PhysicsComponent2D(const PhysicsComponent2D& physics); PhysicsComponent2D(const PhysicsComponent2D& physics);
~PhysicsComponent2D() = default; ~PhysicsComponent2D() = default;
inline void AddForce(const Nz::Vector2f& force, Nz::CoordSys coordSys = Nz::CoordSys_Global); inline void AddForce(const Nz::Vector2f& force, Nz::CoordSys coordSys = Nz::CoordSys::Global);
inline void AddForce(const Nz::Vector2f& force, const Nz::Vector2f& point, Nz::CoordSys coordSys = Nz::CoordSys_Global); inline void AddForce(const Nz::Vector2f& force, const Nz::Vector2f& point, Nz::CoordSys coordSys = Nz::CoordSys::Global);
inline void AddImpulse(const Nz::Vector2f& impulse, Nz::CoordSys coordSys = Nz::CoordSys_Global); inline void AddImpulse(const Nz::Vector2f& impulse, Nz::CoordSys coordSys = Nz::CoordSys::Global);
inline void AddImpulse(const Nz::Vector2f& impulse, const Nz::Vector2f& point, Nz::CoordSys coordSys = Nz::CoordSys_Global); inline void AddImpulse(const Nz::Vector2f& impulse, const Nz::Vector2f& point, Nz::CoordSys coordSys = Nz::CoordSys::Global);
inline void AddTorque(const Nz::RadianAnglef& torque); inline void AddTorque(const Nz::RadianAnglef& torque);
inline bool ClosestPointQuery(const Nz::Vector2f& position, Nz::Vector2f* closestPoint, float* closestDistance) const; inline bool ClosestPointQuery(const Nz::Vector2f& position, Nz::Vector2f* closestPoint, float* closestDistance) const;
@ -47,11 +47,11 @@ namespace Ndk
inline float GetAngularDamping() const; inline float GetAngularDamping() const;
inline Nz::RadianAnglef GetAngularVelocity() const; inline Nz::RadianAnglef GetAngularVelocity() const;
NAZARA_DEPRECATED("Name error, please use GetMassCenter") NAZARA_DEPRECATED("Name error, please use GetMassCenter")
inline Nz::Vector2f GetCenterOfGravity(Nz::CoordSys coordSys = Nz::CoordSys_Local) const; inline Nz::Vector2f GetCenterOfGravity(Nz::CoordSys coordSys = Nz::CoordSys::Local) const;
inline float GetElasticity(std::size_t shapeIndex = 0) const; inline float GetElasticity(std::size_t shapeIndex = 0) const;
inline float GetFriction(std::size_t shapeIndex = 0) const; inline float GetFriction(std::size_t shapeIndex = 0) const;
inline float GetMass() const; inline float GetMass() const;
inline Nz::Vector2f GetMassCenter(Nz::CoordSys coordSys = Nz::CoordSys_Local) const; inline Nz::Vector2f GetMassCenter(Nz::CoordSys coordSys = Nz::CoordSys::Local) const;
inline float GetMomentOfInertia() const; inline float GetMomentOfInertia() const;
inline Nz::Vector2f GetPosition() const; inline Nz::Vector2f GetPosition() const;
inline Nz::RadianAnglef GetRotation() const; inline Nz::RadianAnglef GetRotation() const;
@ -73,7 +73,7 @@ namespace Ndk
inline void SetFriction(float friction); inline void SetFriction(float friction);
inline void SetFriction(std::size_t shapeIndex, float friction); inline void SetFriction(std::size_t shapeIndex, float friction);
inline void SetMass(float mass, bool recomputeMoment = true); inline void SetMass(float mass, bool recomputeMoment = true);
inline void SetMassCenter(const Nz::Vector2f& center, Nz::CoordSys coordSys = Nz::CoordSys_Local); inline void SetMassCenter(const Nz::Vector2f& center, Nz::CoordSys coordSys = Nz::CoordSys::Local);
inline void SetMomentOfInertia(float moment); inline void SetMomentOfInertia(float moment);
inline void SetPosition(const Nz::Vector2f& position); inline void SetPosition(const Nz::Vector2f& position);
inline void SetRotation(const Nz::RadianAnglef& rotation); inline void SetRotation(const Nz::RadianAnglef& rotation);

View File

@ -27,9 +27,9 @@ namespace Ndk
PhysicsComponent3D(const PhysicsComponent3D& physics); PhysicsComponent3D(const PhysicsComponent3D& physics);
~PhysicsComponent3D() = default; ~PhysicsComponent3D() = default;
inline void AddForce(const Nz::Vector3f& force, Nz::CoordSys coordSys = Nz::CoordSys_Global); inline void AddForce(const Nz::Vector3f& force, Nz::CoordSys coordSys = Nz::CoordSys::Global);
inline void AddForce(const Nz::Vector3f& force, const Nz::Vector3f& point, Nz::CoordSys coordSys = Nz::CoordSys_Global); inline void AddForce(const Nz::Vector3f& force, const Nz::Vector3f& point, Nz::CoordSys coordSys = Nz::CoordSys::Global);
inline void AddTorque(const Nz::Vector3f& torque, Nz::CoordSys coordSys = Nz::CoordSys_Global); inline void AddTorque(const Nz::Vector3f& torque, Nz::CoordSys coordSys = Nz::CoordSys::Global);
inline void EnableAutoSleep(bool autoSleep); inline void EnableAutoSleep(bool autoSleep);
inline void EnableNodeSynchronization(bool nodeSynchronization); inline void EnableNodeSynchronization(bool nodeSynchronization);
@ -41,7 +41,7 @@ namespace Ndk
inline float GetLinearDamping() const; inline float GetLinearDamping() const;
inline Nz::Vector3f GetLinearVelocity() const; inline Nz::Vector3f GetLinearVelocity() const;
inline float GetMass() const; inline float GetMass() const;
inline Nz::Vector3f GetMassCenter(Nz::CoordSys coordSys = Nz::CoordSys_Local) const; inline Nz::Vector3f GetMassCenter(Nz::CoordSys coordSys = Nz::CoordSys::Local) const;
inline const Nz::Matrix4f& GetMatrix() const; inline const Nz::Matrix4f& GetMatrix() const;
inline Nz::Vector3f GetPosition() const; inline Nz::Vector3f GetPosition() const;
inline Nz::Quaternionf GetRotation() const; inline Nz::Quaternionf GetRotation() const;

View File

@ -480,7 +480,7 @@ namespace Ndk
m_pendingStates.gravityFactor = rigidBody.GetGravityFactor(); m_pendingStates.gravityFactor = rigidBody.GetGravityFactor();
m_pendingStates.linearDamping = rigidBody.GetLinearDamping(); m_pendingStates.linearDamping = rigidBody.GetLinearDamping();
m_pendingStates.mass = rigidBody.GetMass(); m_pendingStates.mass = rigidBody.GetMass();
m_pendingStates.massCenter = rigidBody.GetMassCenter(Nz::CoordSys_Local); m_pendingStates.massCenter = rigidBody.GetMassCenter(Nz::CoordSys::Local);
m_pendingStates.valid = true; m_pendingStates.valid = true;
} }

View File

@ -19,7 +19,7 @@ namespace Ndk
class NDK_API VelocityComponent : public Component<VelocityComponent> class NDK_API VelocityComponent : public Component<VelocityComponent>
{ {
public: public:
VelocityComponent(const Nz::Vector3f& velocity = Nz::Vector3f::Zero(), Nz::CoordSys coordSystem = Nz::CoordSys_Global); VelocityComponent(const Nz::Vector3f& velocity = Nz::Vector3f::Zero(), Nz::CoordSys coordSystem = Nz::CoordSys::Global);
~VelocityComponent() = default; ~VelocityComponent() = default;
Nz::Vector3f linearVelocity; Nz::Vector3f linearVelocity;

View File

@ -79,28 +79,28 @@ aiFile* StreamOpener(aiFileIO* fileIO, const char* filePath, const char* openMod
stream = reinterpret_cast<aiUserData>(fileIOUserdata->originalStream); stream = reinterpret_cast<aiUserData>(fileIOUserdata->originalStream);
else else
{ {
ErrorFlags errFlags(ErrorFlag_ThrowExceptionDisabled, true); ErrorFlags errFlags(ErrorMode::ThrowExceptionDisabled, true);
///TODO: Move to File::DecodeOpenMode ///TODO: Move to File::DecodeOpenMode
OpenModeFlags openModeEnum = 0; OpenModeFlags openModeEnum = 0;
if (std::strchr(openMode, 'r')) if (std::strchr(openMode, 'r'))
{ {
openModeEnum |= OpenMode_ReadOnly; openModeEnum |= OpenMode::ReadOnly;
if (std::strchr(openMode, '+')) if (std::strchr(openMode, '+'))
openModeEnum |= OpenMode_ReadWrite | OpenMode_MustExist; openModeEnum |= OpenMode_ReadWrite | OpenMode::MustExist;
} }
else if (std::strchr(openMode, 'w')) else if (std::strchr(openMode, 'w'))
{ {
openModeEnum |= OpenMode_WriteOnly | OpenMode_Truncate; openModeEnum |= OpenMode::WriteOnly | OpenMode::Truncate;
if (std::strchr(openMode, '+')) if (std::strchr(openMode, '+'))
openModeEnum |= OpenMode_ReadOnly; openModeEnum |= OpenMode::ReadOnly;
} }
else if (std::strchr(openMode, 'a')) else if (std::strchr(openMode, 'a'))
{ {
openModeEnum |= OpenMode_WriteOnly | OpenMode_Append; openModeEnum |= OpenMode::WriteOnly | OpenMode::Append;
if (std::strchr(openMode, '+')) if (std::strchr(openMode, '+'))
openModeEnum |= OpenMode_ReadOnly; openModeEnum |= OpenMode::ReadOnly;
} }
else else
{ {
@ -109,7 +109,7 @@ aiFile* StreamOpener(aiFileIO* fileIO, const char* filePath, const char* openMod
} }
if (!std::strchr(openMode, 'b')) if (!std::strchr(openMode, 'b'))
openModeEnum |= OpenMode_Text; openModeEnum |= OpenMode::Text;
std::unique_ptr<File> file = std::make_unique<File>(); std::unique_ptr<File> file = std::make_unique<File>();
if (!file->Open(filePath, openModeEnum)) if (!file->Open(filePath, openModeEnum))

View File

@ -146,7 +146,7 @@ namespace Nz
// Nous devons gérer nous-même le flux car il doit rester ouvert après le passage du loader // 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) // (les flux automatiquement ouverts par le ResourceLoader étant fermés après celui-ci)
std::unique_ptr<File> file = std::make_unique<File>(); std::unique_ptr<File> file = std::make_unique<File>();
if (!file->Open(filePath, OpenMode_ReadOnly)) if (!file->Open(filePath, OpenMode::ReadOnly))
{ {
NazaraError("Failed to open stream from file: " + Error::GetLastError()); NazaraError("Failed to open stream from file: " + Error::GetLastError());
return false; return false;

View File

@ -3,6 +3,7 @@
// For conditions of distribution and use, see copyright notice in Config.hpp // For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Core/AbstractHash.hpp> #include <Nazara/Core/AbstractHash.hpp>
#include <Nazara/Core/Algorithm.hpp>
#include <Nazara/Core/Error.hpp> #include <Nazara/Core/Error.hpp>
#include <Nazara/Core/Hash/CRC32.hpp> #include <Nazara/Core/Hash/CRC32.hpp>
#include <Nazara/Core/Hash/CRC64.hpp> #include <Nazara/Core/Hash/CRC64.hpp>
@ -40,42 +41,42 @@ namespace Nz
std::unique_ptr<AbstractHash> AbstractHash::Get(HashType type) std::unique_ptr<AbstractHash> AbstractHash::Get(HashType type)
{ {
NazaraAssert(type <= HashType_Max, "Hash type value out of enum"); NazaraAssert(type <= HashType::Max, "Hash type value out of enum");
switch (type) switch (type)
{ {
case HashType_Fletcher16: case HashType::Fletcher16:
return std::make_unique<HashFletcher16>(); return std::make_unique<HashFletcher16>();
case HashType_CRC32: case HashType::CRC32:
return std::make_unique<HashCRC32>(); return std::make_unique<HashCRC32>();
case HashType_CRC64: case HashType::CRC64:
return std::make_unique<HashCRC64>(); return std::make_unique<HashCRC64>();
case HashType_MD5: case HashType::MD5:
return std::make_unique<HashMD5>(); return std::make_unique<HashMD5>();
case HashType_SHA1: case HashType::SHA1:
return std::make_unique<HashSHA1>(); return std::make_unique<HashSHA1>();
case HashType_SHA224: case HashType::SHA224:
return std::make_unique<HashSHA224>(); return std::make_unique<HashSHA224>();
case HashType_SHA256: case HashType::SHA256:
return std::make_unique<HashSHA256>(); return std::make_unique<HashSHA256>();
case HashType_SHA384: case HashType::SHA384:
return std::make_unique<HashSHA384>(); return std::make_unique<HashSHA384>();
case HashType_SHA512: case HashType::SHA512:
return std::make_unique<HashSHA512>(); return std::make_unique<HashSHA512>();
case HashType_Whirlpool: case HashType::Whirlpool:
return std::make_unique<HashWhirlpool>(); return std::make_unique<HashWhirlpool>();
} }
NazaraInternalError("Hash type not handled (0x" + NumberToString(type, 16) + ')'); NazaraInternalError("Hash type not handled (0x" + NumberToString(UnderlyingCast(type), 16) + ')');
return nullptr; return nullptr;
} }
} }

View File

@ -3,6 +3,7 @@
// For conditions of distribution and use, see copyright notice in Config.hpp // For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Core/AbstractLogger.hpp> #include <Nazara/Core/AbstractLogger.hpp>
#include <Nazara/Core/Algorithm.hpp>
#include <sstream> #include <sstream>
#include <Nazara/Core/Debug.hpp> #include <Nazara/Core/Debug.hpp>
@ -11,13 +12,13 @@ namespace Nz
namespace namespace
{ {
const char* errorType[] = { const char* errorType[] = {
"Assert failed: ", // ErrorType_AssertFailed "Assert failed: ", // ErrorType::AssertFailed
"Internal error: ", // ErrorType_Internal "Internal error: ", // ErrorType::Internal
"Error: ", // ErrorType_Normal "Error: ", // ErrorType::Normal
"Warning: " // ErrorType_Warning "Warning: " // ErrorType::Warning
}; };
static_assert(sizeof(errorType) / sizeof(const char*) == ErrorType_Max + 1, "Error type array is incomplete"); static_assert(sizeof(errorType) / sizeof(const char*) == ErrorTypeCount, "Error type array is incomplete");
} }
/*! /*!
@ -27,7 +28,6 @@ namespace Nz
* *
* \remark This class is abstract * \remark This class is abstract
*/ */
AbstractLogger::~AbstractLogger() = default; AbstractLogger::~AbstractLogger() = default;
/*! /*!
@ -39,11 +39,10 @@ namespace Nz
* \param file Filename * \param file Filename
* \param function Name of the function throwing the error * \param function Name of the function throwing the error
*/ */
void AbstractLogger::WriteError(ErrorType type, const std::string_view& error, unsigned int line, const char* file, const char* function) void AbstractLogger::WriteError(ErrorType type, const std::string_view& error, unsigned int line, const char* file, const char* function)
{ {
std::ostringstream ss; std::ostringstream ss;
ss << errorType[type] << error; ss << errorType[UnderlyingCast(type)] << error;
if (line != 0 && file && function) if (line != 0 && file && function)
ss << " (" << file << ':' << line << ": " << function << ')'; ss << " (" << file << ':' << line << ": " << function << ')';

View File

@ -31,7 +31,7 @@ namespace Nz
* \return Flag * \return Flag
*/ */
UInt32 Error::GetFlags() ErrorModeFlags Error::GetFlags()
{ {
return s_flags; return s_flags;
} }
@ -116,7 +116,7 @@ namespace Nz
* \param flags Flags for the error * \param flags Flags for the error
*/ */
void Error::SetFlags(UInt32 flags) void Error::SetFlags(ErrorModeFlags flags)
{ {
s_flags = flags; s_flags = flags;
} }
@ -133,7 +133,7 @@ namespace Nz
void Error::Trigger(ErrorType type, std::string error) void Error::Trigger(ErrorType type, std::string error)
{ {
if (type == ErrorType_AssertFailed || (s_flags & ErrorFlag_Silent) == 0 || (s_flags & ErrorFlag_SilentDisabled) != 0) if (type == ErrorType::AssertFailed || (s_flags & ErrorMode::Silent) == 0 || (s_flags & ErrorMode::SilentDisabled) != 0)
Log::WriteError(type, error); Log::WriteError(type, error);
s_lastError = std::move(error); s_lastError = std::move(error);
@ -142,12 +142,12 @@ namespace Nz
s_lastErrorLine = 0; s_lastErrorLine = 0;
#if NAZARA_CORE_EXIT_ON_ASSERT_FAILURE #if NAZARA_CORE_EXIT_ON_ASSERT_FAILURE
if (type == ErrorType_AssertFailed) if (type == ErrorType::AssertFailed)
std::abort(); std::abort();
#endif #endif
if (type == ErrorType_AssertFailed || (type != ErrorType_Warning && if (type == ErrorType::AssertFailed || (type != ErrorType::Warning &&
(s_flags & ErrorFlag_ThrowException) != 0 && (s_flags & ErrorFlag_ThrowExceptionDisabled) == 0)) (s_flags & ErrorMode::ThrowException) != 0 && (s_flags & ErrorMode::ThrowExceptionDisabled) == 0))
throw std::runtime_error(s_lastError); throw std::runtime_error(s_lastError);
} }
@ -168,7 +168,7 @@ namespace Nz
{ {
file = GetCurrentFileRelativeToEngine(file); file = GetCurrentFileRelativeToEngine(file);
if (type == ErrorType_AssertFailed || (s_flags & ErrorFlag_Silent) == 0 || (s_flags & ErrorFlag_SilentDisabled) != 0) if (type == ErrorType::AssertFailed || (s_flags & ErrorMode::Silent) == 0 || (s_flags & ErrorMode::SilentDisabled) != 0)
Log::WriteError(type, error, line, file, function); Log::WriteError(type, error, line, file, function);
s_lastError = std::move(error); s_lastError = std::move(error);
@ -177,12 +177,12 @@ namespace Nz
s_lastErrorLine = line; s_lastErrorLine = line;
#if NAZARA_CORE_EXIT_ON_ASSERT_FAILURE #if NAZARA_CORE_EXIT_ON_ASSERT_FAILURE
if (type == ErrorType_AssertFailed) if (type == ErrorType::AssertFailed)
std::abort(); std::abort();
#endif #endif
if (type == ErrorType_AssertFailed || (type != ErrorType_Warning && if (type == ErrorType::AssertFailed || (type != ErrorType::Warning &&
(s_flags & ErrorFlag_ThrowException) != 0 && (s_flags & ErrorFlag_ThrowExceptionDisabled) == 0)) (s_flags & ErrorMode::ThrowException) != 0 && (s_flags & ErrorMode::ThrowExceptionDisabled) == 0))
throw std::runtime_error(s_lastError); throw std::runtime_error(s_lastError);
} }
@ -197,7 +197,7 @@ namespace Nz
return file; return file;
} }
UInt32 Error::s_flags = ErrorFlag_None; ErrorModeFlags Error::s_flags = ErrorMode::None;
std::string Error::s_lastError; std::string Error::s_lastError;
const char* Error::s_lastErrorFunction = ""; const char* Error::s_lastErrorFunction = "";
const char* Error::s_lastErrorFile = ""; const char* Error::s_lastErrorFile = "";

View File

@ -21,7 +21,7 @@ namespace Nz
* \param replace Replace the entirely the old flag if true, else do a "OR" * \param replace Replace the entirely the old flag if true, else do a "OR"
*/ */
ErrorFlags::ErrorFlags(UInt32 flags, bool replace) : ErrorFlags::ErrorFlags(ErrorModeFlags flags, bool replace) :
m_previousFlags(Error::GetFlags()) m_previousFlags(Error::GetFlags())
{ {
SetFlags(flags, replace); SetFlags(flags, replace);
@ -40,8 +40,7 @@ namespace Nz
* \brief Gets the previous flag * \brief Gets the previous flag
* \return Previous flag * \return Previous flag
*/ */
ErrorModeFlags ErrorFlags::GetPreviousFlags() const
UInt32 ErrorFlags::GetPreviousFlags() const
{ {
return m_previousFlags; return m_previousFlags;
} }
@ -52,8 +51,7 @@ namespace Nz
* \param flags Flags for the error * \param flags Flags for the error
* \param replace Replace the entirely the old flag if true, else do a "OR" * \param replace Replace the entirely the old flag if true, else do a "OR"
*/ */
void ErrorFlags::SetFlags(ErrorModeFlags flags, bool replace)
void ErrorFlags::SetFlags(UInt32 flags, bool replace)
{ {
if (!replace) if (!replace)
flags |= m_previousFlags; flags |= m_previousFlags;

View File

@ -91,7 +91,7 @@ namespace Nz
{ {
m_impl.reset(); m_impl.reset();
m_openMode = OpenMode_NotOpen; m_openMode = OpenMode::NotOpen;
} }
} }
@ -226,13 +226,13 @@ namespace Nz
if (m_filePath.empty()) if (m_filePath.empty())
return false; return false;
if (openMode == OpenMode_NotOpen) if (openMode == OpenMode::NotOpen)
return false; return false;
std::unique_ptr<FileImpl> impl = std::make_unique<FileImpl>(this); std::unique_ptr<FileImpl> impl = std::make_unique<FileImpl>(this);
if (!impl->Open(m_filePath, openMode)) if (!impl->Open(m_filePath, openMode))
{ {
ErrorFlags flags(ErrorFlag_Silent); // Silent by default ErrorFlags flags(ErrorMode::Silent); // Silent by default
NazaraError("Failed to open \"" + m_filePath.generic_u8string() + "\": " + Error::GetLastSystemError()); NazaraError("Failed to open \"" + m_filePath.generic_u8string() + "\": " + Error::GetLastSystemError());
return false; return false;
} }
@ -240,10 +240,10 @@ namespace Nz
m_openMode = openMode; m_openMode = openMode;
m_impl = std::move(impl); m_impl = std::move(impl);
if (m_openMode & OpenMode_Text) if (m_openMode & OpenMode::Text)
m_streamOptions |= StreamOption_Text; m_streamOptions |= StreamOption::Text;
else else
m_streamOptions &= ~StreamOption_Text; m_streamOptions &= ~StreamOption::Text;
return true; return true;
} }
@ -296,7 +296,7 @@ namespace Nz
{ {
NazaraAssert(IsOpen(), "File is not open"); NazaraAssert(IsOpen(), "File is not open");
return m_impl->SetCursorPos(CursorPosition_AtBegin, offset); return m_impl->SetCursorPos(CursorPosition::AtBegin, offset);
} }
/*! /*!
@ -383,7 +383,7 @@ namespace Nz
// If we don't have to read, we move forward // If we don't have to read, we move forward
UInt64 currentPos = m_impl->GetCursorPos(); UInt64 currentPos = m_impl->GetCursorPos();
m_impl->SetCursorPos(CursorPosition_AtCurrent, size); m_impl->SetCursorPos(CursorPosition::AtCurrent, size);
return static_cast<std::size_t>(m_impl->GetCursorPos() - currentPos); return static_cast<std::size_t>(m_impl->GetCursorPos() - currentPos);
} }
@ -429,7 +429,7 @@ namespace Nz
NazaraAssert(hash, "Invalid hash"); NazaraAssert(hash, "Invalid hash");
File file(originalFile.GetPath()); File file(originalFile.GetPath());
if (!file.Open(OpenMode_ReadOnly)) if (!file.Open(OpenMode::ReadOnly))
{ {
NazaraError("Unable to open file"); NazaraError("Unable to open file");
return false; return false;

View File

@ -3,6 +3,7 @@
// For conditions of distribution and use, see copyright notice in Config.hpp // For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Core/HardwareInfo.hpp> #include <Nazara/Core/HardwareInfo.hpp>
#include <Nazara/Core/Algorithm.hpp>
#include <Nazara/Core/Error.hpp> #include <Nazara/Core/Error.hpp>
#include <algorithm> #include <algorithm>
#include <cstring> #include <cstring>
@ -27,55 +28,53 @@ namespace Nz
ProcessorVendor vendorEnum; ProcessorVendor vendorEnum;
}; };
// Exceptionellement, la valeur "unknown" est intégrée const char* s_vendorNames[] =
const char* vendorNames[] =
{ {
"Unknown", // ProcessorVendor_Unknown "Advanced Micro Devices", // ProcessorVendor::AMD
"Advanced Micro Devices", // ProcessorVendor_AMD "Centaur Technology", // ProcessorVendor::Centaur
"Centaur Technology", // ProcessorVendor_Centaur "Cyrix Corporation", // ProcessorVendor::Cyrix
"Cyrix Corporation", // ProcessorVendor_Cyrix "Intel Corporation", // ProcessorVendor::Intel
"Intel Corporation", // ProcessorVendor_Intel "Kernel-based Virtual Machine", // ProcessorVendor::KVM
"Kernel-based Virtual Machine", // ProcessorVendor_KVM "Microsoft Hyper-V", // ProcessorVendor::HyperV
"Microsoft Hyper-V", // ProcessorVendor_HyperV "National Semiconductor", // ProcessorVendor::NSC
"National Semiconductor", // ProcessorVendor_NSC "NexGen", // ProcessorVendor::NexGen
"NexGen", // ProcessorVendor_NexGen "Rise Technology", // ProcessorVendor::Rise
"Rise Technology", // ProcessorVendor_Rise "Silicon Integrated Systems", // ProcessorVendor::SIS
"Silicon Integrated Systems", // ProcessorVendor_SIS "Transmeta Corporation", // ProcessorVendor::Transmeta
"Transmeta Corporation", // ProcessorVendor_Transmeta "United Microelectronics Corporation", // ProcessorVendor::UMC
"United Microelectronics Corporation", // ProcessorVendor_UMC "VIA Technologies", // ProcessorVendor::VIA
"VIA Technologies", // ProcessorVendor_VIA "VMware", // ProcessorVendor::VMware
"VMware", // ProcessorVendor_VMware "Vortex86", // ProcessorVendor::Vortex
"Vortex86", // ProcessorVendor_Vortex "Xen" // ProcessorVendor::XenHVM
"Xen" // ProcessorVendor_XenHVM
}; };
static_assert(sizeof(vendorNames)/sizeof(const char*) == ProcessorVendor_Max+2, "Processor vendor name array is incomplete"); static_assert(sizeof(s_vendorNames)/sizeof(const char*) == ProcessorVendorCount, "Processor vendor name array is incomplete");
VendorString vendorStrings[] = VendorString vendorStrings[] =
{ {
// Triés par ordre alphabétique (Majuscules primant sur minuscules) // Triés par ordre alphabétique (Majuscules primant sur minuscules)
{"AMDisbetter!", ProcessorVendor_AMD}, {"AMDisbetter!", ProcessorVendor::AMD},
{"AuthenticAMD", ProcessorVendor_AMD}, {"AuthenticAMD", ProcessorVendor::AMD},
{"CentaurHauls", ProcessorVendor_Centaur}, {"CentaurHauls", ProcessorVendor::Centaur},
{"CyrixInstead", ProcessorVendor_Cyrix}, {"CyrixInstead", ProcessorVendor::Cyrix},
{"GenuineIntel", ProcessorVendor_Intel}, {"GenuineIntel", ProcessorVendor::Intel},
{"GenuineTMx86", ProcessorVendor_Transmeta}, {"GenuineTMx86", ProcessorVendor::Transmeta},
{"Geode by NSC", ProcessorVendor_NSC}, {"Geode by NSC", ProcessorVendor::NSC},
{"KVMKVMKVMKVM", ProcessorVendor_KVM}, {"KVMKVMKVMKVM", ProcessorVendor::KVM},
{"Microsoft Hv", ProcessorVendor_HyperV}, {"Microsoft Hv", ProcessorVendor::HyperV},
{"NexGenDriven", ProcessorVendor_NexGen}, {"NexGenDriven", ProcessorVendor::NexGen},
{"RiseRiseRise", ProcessorVendor_Rise}, {"RiseRiseRise", ProcessorVendor::Rise},
{"SiS SiS SiS ", ProcessorVendor_SIS}, {"SiS SiS SiS ", ProcessorVendor::SIS},
{"TransmetaCPU", ProcessorVendor_Transmeta}, {"TransmetaCPU", ProcessorVendor::Transmeta},
{"UMC UMC UMC ", ProcessorVendor_UMC}, {"UMC UMC UMC ", ProcessorVendor::UMC},
{"VIA VIA VIA ", ProcessorVendor_VIA}, {"VIA VIA VIA ", ProcessorVendor::VIA},
{"VMwareVMware", ProcessorVendor_VMware}, {"VMwareVMware", ProcessorVendor::VMware},
{"Vortex86 SoC", ProcessorVendor_Vortex}, {"Vortex86 SoC", ProcessorVendor::Vortex},
{"XenVMMXenVMM", ProcessorVendor_XenHVM} {"XenVMMXenVMM", ProcessorVendor::XenHVM}
}; };
ProcessorVendor s_vendorEnum = ProcessorVendor_Unknown; ProcessorVendor s_vendorEnum = ProcessorVendor::Unknown;
bool s_capabilities[ProcessorCap_Max+1] = {false}; bool s_capabilities[ProcessorCapCount] = {false};
bool s_initialized = false; bool s_initialized = false;
char s_brandString[48] = "Not initialized"; char s_brandString[48] = "Not initialized";
@ -155,7 +154,7 @@ namespace Nz
if (!Initialize()) if (!Initialize())
NazaraError("Failed to initialize HardwareInfo"); NazaraError("Failed to initialize HardwareInfo");
return vendorNames[s_vendorEnum+1]; return s_vendorNames[UnderlyingCast(s_vendorEnum)];
} }
/*! /*!
@ -180,15 +179,7 @@ namespace Nz
bool HardwareInfo::HasCapability(ProcessorCap capability) bool HardwareInfo::HasCapability(ProcessorCap capability)
{ {
#ifdef NAZARA_DEBUG return s_capabilities[UnderlyingCast(capability)];
if (capability > ProcessorCap_Max)
{
NazaraError("Capability type out of enum");
return false;
}
#endif
return s_capabilities[capability];
} }
/*! /*!
@ -226,7 +217,7 @@ namespace Nz
UInt32 manufacturerId[3] = {ebx, edx, ecx}; UInt32 manufacturerId[3] = {ebx, edx, ecx};
// Identification of conceptor // Identification of conceptor
s_vendorEnum = ProcessorVendor_Unknown; s_vendorEnum = ProcessorVendor::Unknown;
for (const VendorString& vendorString : vendorStrings) for (const VendorString& vendorString : vendorStrings)
{ {
if (std::memcmp(manufacturerId, vendorString.vendor, 12) == 0) if (std::memcmp(manufacturerId, vendorString.vendor, 12) == 0)
@ -238,18 +229,18 @@ namespace Nz
if (eax >= 1) if (eax >= 1)
{ {
// Retrieval of certain capacities of the processor (ECX et EDX, function 1) // Retrieval of certain capacities of the processor (ECX and EDX, function 1)
HardwareInfoImpl::Cpuid(1, 0, registers); HardwareInfoImpl::Cpuid(1, 0, registers);
s_capabilities[ProcessorCap_AVX] = (ecx & (1U << 28)) != 0; s_capabilities[UnderlyingCast(ProcessorCap::AVX)] = (ecx & (1U << 28)) != 0;
s_capabilities[ProcessorCap_FMA3] = (ecx & (1U << 12)) != 0; s_capabilities[UnderlyingCast(ProcessorCap::FMA3)] = (ecx & (1U << 12)) != 0;
s_capabilities[ProcessorCap_MMX] = (edx & (1U << 23)) != 0; s_capabilities[UnderlyingCast(ProcessorCap::MMX)] = (edx & (1U << 23)) != 0;
s_capabilities[ProcessorCap_SSE] = (edx & (1U << 25)) != 0; s_capabilities[UnderlyingCast(ProcessorCap::SSE)] = (edx & (1U << 25)) != 0;
s_capabilities[ProcessorCap_SSE2] = (edx & (1U << 26)) != 0; s_capabilities[UnderlyingCast(ProcessorCap::SSE2)] = (edx & (1U << 26)) != 0;
s_capabilities[ProcessorCap_SSE3] = (ecx & (1U << 0)) != 0; s_capabilities[UnderlyingCast(ProcessorCap::SSE3)] = (ecx & (1U << 0)) != 0;
s_capabilities[ProcessorCap_SSSE3] = (ecx & (1U << 9)) != 0; s_capabilities[UnderlyingCast(ProcessorCap::SSSE3)] = (ecx & (1U << 9)) != 0;
s_capabilities[ProcessorCap_SSE41] = (ecx & (1U << 19)) != 0; s_capabilities[UnderlyingCast(ProcessorCap::SSE41)] = (ecx & (1U << 19)) != 0;
s_capabilities[ProcessorCap_SSE42] = (ecx & (1U << 20)) != 0; s_capabilities[UnderlyingCast(ProcessorCap::SSE42)] = (ecx & (1U << 20)) != 0;
} }
// Retrieval of biggest extended function handled (EAX, function 0x80000000) // Retrieval of biggest extended function handled (EAX, function 0x80000000)
@ -261,10 +252,10 @@ namespace Nz
// Retrieval of extended capabilities of the processor (ECX and EDX, function 0x80000001) // Retrieval of extended capabilities of the processor (ECX and EDX, function 0x80000001)
HardwareInfoImpl::Cpuid(0x80000001, 0, registers); HardwareInfoImpl::Cpuid(0x80000001, 0, registers);
s_capabilities[ProcessorCap_x64] = (edx & (1U << 29)) != 0; // Support of 64bits, independent of the OS s_capabilities[UnderlyingCast(ProcessorCap::x64)] = (edx & (1U << 29)) != 0; // Support of 64bits, independent of the OS
s_capabilities[ProcessorCap_FMA4] = (ecx & (1U << 16)) != 0; s_capabilities[UnderlyingCast(ProcessorCap::FMA4)] = (ecx & (1U << 16)) != 0;
s_capabilities[ProcessorCap_SSE4a] = (ecx & (1U << 6)) != 0; s_capabilities[UnderlyingCast(ProcessorCap::SSE4a)] = (ecx & (1U << 6)) != 0;
s_capabilities[ProcessorCap_XOP] = (ecx & (1U << 11)) != 0; s_capabilities[UnderlyingCast(ProcessorCap::XOP)] = (ecx & (1U << 11)) != 0;
if (maxSupportedExtendedFunction >= 0x80000004) if (maxSupportedExtendedFunction >= 0x80000004)
{ {

View File

@ -25,7 +25,7 @@ namespace Nz
*/ */
MemoryView::MemoryView(void* ptr, UInt64 size) : MemoryView::MemoryView(void* ptr, UInt64 size) :
Stream(StreamOption_None, OpenMode_ReadWrite), Stream(StreamOption::None, OpenMode_ReadWrite),
m_ptr(static_cast<UInt8*>(ptr)), m_ptr(static_cast<UInt8*>(ptr)),
m_pos(0), m_pos(0),
m_size(size) m_size(size)
@ -42,7 +42,7 @@ namespace Nz
*/ */
MemoryView::MemoryView(const void* ptr, UInt64 size) : MemoryView::MemoryView(const void* ptr, UInt64 size) :
Stream(StreamOption_None, OpenMode_ReadOnly), Stream(StreamOption::None, OpenMode::ReadOnly),
m_ptr(static_cast<UInt8*>(const_cast<void*>(ptr))), //< Okay, right, const_cast is bad, but this pointer is still read-only m_ptr(static_cast<UInt8*>(const_cast<void*>(ptr))), //< Okay, right, const_cast is bad, but this pointer is still read-only
m_pos(0), m_pos(0),
m_size(size) m_size(size)

View File

@ -62,7 +62,7 @@ namespace Nz
{ {
NazaraAssert(value, "Invalid pointer"); NazaraAssert(value, "Invalid pointer");
ErrorFlags flags(ErrorFlag_Silent | ErrorFlag_ThrowExceptionDisabled); ErrorFlags flags(ErrorMode::Silent | ErrorMode::ThrowExceptionDisabled);
auto it = m_parameters.find(name); auto it = m_parameters.find(name);
if (it == m_parameters.end()) if (it == m_parameters.end())
@ -73,15 +73,15 @@ namespace Nz
switch (it->second.type) switch (it->second.type)
{ {
case ParameterType_Boolean: case ParameterType::Boolean:
*value = it->second.value.boolVal; *value = it->second.value.boolVal;
return true; return true;
case ParameterType_Integer: case ParameterType::Integer:
*value = (it->second.value.intVal != 0); *value = (it->second.value.intVal != 0);
return true; return true;
case ParameterType_String: case ParameterType::String:
{ {
if (it->second.value.stringVal == "1" || it->second.value.stringVal == "yes" || it->second.value.stringVal == "true") if (it->second.value.stringVal == "1" || it->second.value.stringVal == "yes" || it->second.value.stringVal == "true")
{ {
@ -97,11 +97,11 @@ namespace Nz
break; break;
} }
case ParameterType_Color: case ParameterType::Color:
case ParameterType_Double: case ParameterType::Double:
case ParameterType_None: case ParameterType::None:
case ParameterType_Pointer: case ParameterType::Pointer:
case ParameterType_Userdata: case ParameterType::Userdata:
break; break;
} }
@ -124,7 +124,7 @@ namespace Nz
{ {
NazaraAssert(value, "Invalid pointer"); NazaraAssert(value, "Invalid pointer");
ErrorFlags flags(ErrorFlag_Silent | ErrorFlag_ThrowExceptionDisabled); ErrorFlags flags(ErrorMode::Silent | ErrorMode::ThrowExceptionDisabled);
auto it = m_parameters.find(name); auto it = m_parameters.find(name);
if (it == m_parameters.end()) if (it == m_parameters.end())
@ -135,17 +135,17 @@ namespace Nz
switch (it->second.type) switch (it->second.type)
{ {
case ParameterType_Color: case ParameterType::Color:
*value = it->second.value.colorVal; *value = it->second.value.colorVal;
return true; return true;
case ParameterType_Boolean: case ParameterType::Boolean:
case ParameterType_Double: case ParameterType::Double:
case ParameterType_Integer: case ParameterType::Integer:
case ParameterType_String: case ParameterType::String:
case ParameterType_None: case ParameterType::None:
case ParameterType_Pointer: case ParameterType::Pointer:
case ParameterType_Userdata: case ParameterType::Userdata:
break; break;
} }
@ -170,7 +170,7 @@ namespace Nz
{ {
NazaraAssert(value, "Invalid pointer"); NazaraAssert(value, "Invalid pointer");
ErrorFlags flags(ErrorFlag_Silent | ErrorFlag_ThrowExceptionDisabled); ErrorFlags flags(ErrorMode::Silent | ErrorMode::ThrowExceptionDisabled);
auto it = m_parameters.find(name); auto it = m_parameters.find(name);
if (it == m_parameters.end()) if (it == m_parameters.end())
@ -181,15 +181,15 @@ namespace Nz
switch (it->second.type) switch (it->second.type)
{ {
case ParameterType_Double: case ParameterType::Double:
*value = it->second.value.doubleVal; *value = it->second.value.doubleVal;
return true; return true;
case ParameterType_Integer: case ParameterType::Integer:
*value = static_cast<double>(it->second.value.intVal); *value = static_cast<double>(it->second.value.intVal);
return true; return true;
case ParameterType_String: case ParameterType::String:
{ {
const std::string& str = it->second.value.stringVal; const std::string& str = it->second.value.stringVal;
@ -206,11 +206,11 @@ namespace Nz
return true; return true;
} }
case ParameterType_Boolean: case ParameterType::Boolean:
case ParameterType_Color: case ParameterType::Color:
case ParameterType_None: case ParameterType::None:
case ParameterType_Pointer: case ParameterType::Pointer:
case ParameterType_Userdata: case ParameterType::Userdata:
break; break;
} }
@ -236,7 +236,7 @@ namespace Nz
{ {
NazaraAssert(value, "Invalid pointer"); NazaraAssert(value, "Invalid pointer");
ErrorFlags flags(ErrorFlag_Silent | ErrorFlag_ThrowExceptionDisabled); ErrorFlags flags(ErrorMode::Silent | ErrorMode::ThrowExceptionDisabled);
auto it = m_parameters.find(name); auto it = m_parameters.find(name);
if (it == m_parameters.end()) if (it == m_parameters.end())
@ -247,19 +247,19 @@ namespace Nz
switch (it->second.type) switch (it->second.type)
{ {
case ParameterType_Boolean: case ParameterType::Boolean:
*value = (it->second.value.boolVal) ? 1 : 0; *value = (it->second.value.boolVal) ? 1 : 0;
return true; return true;
case ParameterType_Double: case ParameterType::Double:
*value = static_cast<long long>(it->second.value.doubleVal); *value = static_cast<long long>(it->second.value.doubleVal);
return true; return true;
case ParameterType_Integer: case ParameterType::Integer:
*value = it->second.value.intVal; *value = it->second.value.intVal;
return true; return true;
case ParameterType_String: case ParameterType::String:
{ {
const std::string& str = it->second.value.stringVal; const std::string& str = it->second.value.stringVal;
@ -276,10 +276,10 @@ namespace Nz
return true; return true;
} }
case ParameterType_Color: case ParameterType::Color:
case ParameterType_None: case ParameterType::None:
case ParameterType_Pointer: case ParameterType::Pointer:
case ParameterType_Userdata: case ParameterType::Userdata:
break; break;
} }
@ -325,7 +325,7 @@ namespace Nz
{ {
NazaraAssert(value, "Invalid pointer"); NazaraAssert(value, "Invalid pointer");
ErrorFlags flags(ErrorFlag_Silent | ErrorFlag_ThrowExceptionDisabled); ErrorFlags flags(ErrorMode::Silent | ErrorMode::ThrowExceptionDisabled);
auto it = m_parameters.find(name); auto it = m_parameters.find(name);
if (it == m_parameters.end()) if (it == m_parameters.end())
@ -336,20 +336,20 @@ namespace Nz
switch (it->second.type) switch (it->second.type)
{ {
case ParameterType_Pointer: case ParameterType::Pointer:
*value = it->second.value.ptrVal; *value = it->second.value.ptrVal;
return true; return true;
case ParameterType_Userdata: case ParameterType::Userdata:
*value = it->second.value.userdataVal->ptr; *value = it->second.value.userdataVal->ptr;
return true; return true;
case ParameterType_Boolean: case ParameterType::Boolean:
case ParameterType_Color: case ParameterType::Color:
case ParameterType_Double: case ParameterType::Double:
case ParameterType_Integer: case ParameterType::Integer:
case ParameterType_None: case ParameterType::None:
case ParameterType_String: case ParameterType::String:
break; break;
} }
@ -379,7 +379,7 @@ namespace Nz
{ {
NazaraAssert(value, "Invalid pointer"); NazaraAssert(value, "Invalid pointer");
ErrorFlags flags(ErrorFlag_Silent | ErrorFlag_ThrowExceptionDisabled); ErrorFlags flags(ErrorMode::Silent | ErrorMode::ThrowExceptionDisabled);
auto it = m_parameters.find(name); auto it = m_parameters.find(name);
if (it == m_parameters.end()) if (it == m_parameters.end())
@ -390,35 +390,35 @@ namespace Nz
switch (it->second.type) switch (it->second.type)
{ {
case ParameterType_Boolean: case ParameterType::Boolean:
*value = (it->second.value.boolVal) ? "true" : "false"; *value = (it->second.value.boolVal) ? "true" : "false";
return true; return true;
case ParameterType_Color: case ParameterType::Color:
*value = it->second.value.colorVal.ToString(); *value = it->second.value.colorVal.ToString();
return true; return true;
case ParameterType_Double: case ParameterType::Double:
*value = std::to_string(it->second.value.doubleVal); *value = std::to_string(it->second.value.doubleVal);
return true; return true;
case ParameterType_Integer: case ParameterType::Integer:
*value = std::to_string(it->second.value.intVal); *value = std::to_string(it->second.value.intVal);
return true; return true;
case ParameterType_String: case ParameterType::String:
*value = it->second.value.stringVal; *value = it->second.value.stringVal;
return true; return true;
case ParameterType_Pointer: case ParameterType::Pointer:
*value = PointerToString(it->second.value.ptrVal); *value = PointerToString(it->second.value.ptrVal);
return true; return true;
case ParameterType_Userdata: case ParameterType::Userdata:
*value = PointerToString(it->second.value.userdataVal->ptr); *value = PointerToString(it->second.value.userdataVal->ptr);
return true; return true;
case ParameterType_None: case ParameterType::None:
*value = std::string(); *value = std::string();
return true; return true;
} }
@ -444,7 +444,7 @@ namespace Nz
{ {
NazaraAssert(value, "Invalid pointer"); NazaraAssert(value, "Invalid pointer");
ErrorFlags flags(ErrorFlag_Silent | ErrorFlag_ThrowExceptionDisabled); ErrorFlags flags(ErrorMode::Silent | ErrorMode::ThrowExceptionDisabled);
auto it = m_parameters.find(name); auto it = m_parameters.find(name);
if (it == m_parameters.end()) if (it == m_parameters.end())
@ -455,7 +455,7 @@ namespace Nz
const auto& parameter = it->second; const auto& parameter = it->second;
if (parameter.type == ParameterType_Userdata) if (parameter.type == ParameterType::Userdata)
{ {
*value = parameter.value.userdataVal->ptr; *value = parameter.value.userdataVal->ptr;
return true; return true;
@ -506,7 +506,7 @@ namespace Nz
void ParameterList::SetParameter(const std::string& name) void ParameterList::SetParameter(const std::string& name)
{ {
Parameter& parameter = CreateValue(name); Parameter& parameter = CreateValue(name);
parameter.type = ParameterType_None; parameter.type = ParameterType::None;
} }
/*! /*!
@ -520,7 +520,7 @@ namespace Nz
void ParameterList::SetParameter(const std::string& name, const Color& value) void ParameterList::SetParameter(const std::string& name, const Color& value)
{ {
Parameter& parameter = CreateValue(name); Parameter& parameter = CreateValue(name);
parameter.type = ParameterType_Color; parameter.type = ParameterType::Color;
PlacementNew(&parameter.value.colorVal, value); PlacementNew(&parameter.value.colorVal, value);
} }
@ -536,7 +536,7 @@ namespace Nz
void ParameterList::SetParameter(const std::string& name, const std::string& value) void ParameterList::SetParameter(const std::string& name, const std::string& value)
{ {
Parameter& parameter = CreateValue(name); Parameter& parameter = CreateValue(name);
parameter.type = ParameterType_String; parameter.type = ParameterType::String;
PlacementNew(&parameter.value.stringVal, value); PlacementNew(&parameter.value.stringVal, value);
} }
@ -552,7 +552,7 @@ namespace Nz
void ParameterList::SetParameter(const std::string& name, const char* value) void ParameterList::SetParameter(const std::string& name, const char* value)
{ {
Parameter& parameter = CreateValue(name); Parameter& parameter = CreateValue(name);
parameter.type = ParameterType_String; parameter.type = ParameterType::String;
PlacementNew(&parameter.value.stringVal, value); PlacementNew(&parameter.value.stringVal, value);
} }
@ -568,7 +568,7 @@ namespace Nz
void ParameterList::SetParameter(const std::string& name, bool value) void ParameterList::SetParameter(const std::string& name, bool value)
{ {
Parameter& parameter = CreateValue(name); Parameter& parameter = CreateValue(name);
parameter.type = ParameterType_Boolean; parameter.type = ParameterType::Boolean;
parameter.value.boolVal = value; parameter.value.boolVal = value;
} }
@ -583,7 +583,7 @@ namespace Nz
void ParameterList::SetParameter(const std::string& name, double value) void ParameterList::SetParameter(const std::string& name, double value)
{ {
Parameter& parameter = CreateValue(name); Parameter& parameter = CreateValue(name);
parameter.type = ParameterType_Double; parameter.type = ParameterType::Double;
parameter.value.doubleVal = value; parameter.value.doubleVal = value;
} }
@ -598,7 +598,7 @@ namespace Nz
void ParameterList::SetParameter(const std::string& name, long long value) void ParameterList::SetParameter(const std::string& name, long long value)
{ {
Parameter& parameter = CreateValue(name); Parameter& parameter = CreateValue(name);
parameter.type = ParameterType_Integer; parameter.type = ParameterType::Integer;
parameter.value.intVal = value; parameter.value.intVal = value;
} }
@ -616,7 +616,7 @@ namespace Nz
void ParameterList::SetParameter(const std::string& name, void* value) void ParameterList::SetParameter(const std::string& name, void* value)
{ {
Parameter& parameter = CreateValue(name); Parameter& parameter = CreateValue(name);
parameter.type = ParameterType_Pointer; parameter.type = ParameterType::Pointer;
parameter.value.ptrVal = value; parameter.value.ptrVal = value;
} }
@ -637,28 +637,28 @@ namespace Nz
ss << it->first << ": "; ss << it->first << ": ";
switch (it->second.type) switch (it->second.type)
{ {
case ParameterType_Boolean: case ParameterType::Boolean:
ss << "Boolean(" << parameter.value.boolVal << ")"; ss << "Boolean(" << parameter.value.boolVal << ")";
break; break;
case ParameterType_Color: case ParameterType::Color:
ss << "Color(" << parameter.value.colorVal << ")"; ss << "Color(" << parameter.value.colorVal << ")";
break; break;
case ParameterType_Double: case ParameterType::Double:
ss << "Double(" << parameter.value.doubleVal << ")"; ss << "Double(" << parameter.value.doubleVal << ")";
break; break;
case ParameterType_Integer: case ParameterType::Integer:
ss << "Integer(" << parameter.value.intVal << ")"; ss << "Integer(" << parameter.value.intVal << ")";
break; break;
case ParameterType_String: case ParameterType::String:
ss << "std::string(" << parameter.value.stringVal << ")"; ss << "std::string(" << parameter.value.stringVal << ")";
break; break;
case ParameterType_Pointer: case ParameterType::Pointer:
ss << "Pointer(" << parameter.value.ptrVal << ")"; ss << "Pointer(" << parameter.value.ptrVal << ")";
break; break;
case ParameterType_Userdata: case ParameterType::Userdata:
ss << "Userdata(" << parameter.value.userdataVal->ptr << ")"; ss << "Userdata(" << parameter.value.userdataVal->ptr << ")";
break; break;
case ParameterType_None: case ParameterType::None:
ss << "None"; ss << "None";
break; break;
} }
@ -686,7 +686,7 @@ namespace Nz
void ParameterList::SetParameter(const std::string& name, void* value, Destructor destructor) void ParameterList::SetParameter(const std::string& name, void* value, Destructor destructor)
{ {
Parameter& parameter = CreateValue(name); Parameter& parameter = CreateValue(name);
parameter.type = ParameterType_Userdata; parameter.type = ParameterType::Userdata;
parameter.value.userdataVal = new Parameter::UserdataValue(destructor, value); parameter.value.userdataVal = new Parameter::UserdataValue(destructor, value);
} }
@ -706,28 +706,28 @@ namespace Nz
switch (it->second.type) switch (it->second.type)
{ {
case ParameterType_Boolean: case ParameterType::Boolean:
case ParameterType_Color: case ParameterType::Color:
case ParameterType_Double: case ParameterType::Double:
case ParameterType_Integer: case ParameterType::Integer:
case ParameterType_Pointer: case ParameterType::Pointer:
std::memcpy(&parameter, &it->second, sizeof(Parameter)); std::memcpy(&parameter, &it->second, sizeof(Parameter));
break; break;
case ParameterType_String: case ParameterType::String:
parameter.type = ParameterType_String; parameter.type = ParameterType::String;
PlacementNew(&parameter.value.stringVal, it->second.value.stringVal); PlacementNew(&parameter.value.stringVal, it->second.value.stringVal);
break; break;
case ParameterType_Userdata: case ParameterType::Userdata:
parameter.type = ParameterType_Userdata; parameter.type = ParameterType::Userdata;
parameter.value.userdataVal = it->second.value.userdataVal; parameter.value.userdataVal = it->second.value.userdataVal;
++(parameter.value.userdataVal->counter); ++(parameter.value.userdataVal->counter);
break; break;
case ParameterType_None: case ParameterType::None:
parameter.type = ParameterType_None; parameter.type = ParameterType::None;
break; break;
} }
} }
@ -762,11 +762,11 @@ namespace Nz
{ {
switch (parameter.type) switch (parameter.type)
{ {
case ParameterType_String: case ParameterType::String:
PlacementDestroy(&parameter.value.stringVal); PlacementDestroy(&parameter.value.stringVal);
break; break;
case ParameterType_Userdata: case ParameterType::Userdata:
{ {
Parameter::UserdataValue* userdata = parameter.value.userdataVal; Parameter::UserdataValue* userdata = parameter.value.userdataVal;
if (--userdata->counter == 0) if (--userdata->counter == 0)
@ -777,12 +777,12 @@ namespace Nz
break; break;
} }
case ParameterType_Boolean: case ParameterType::Boolean:
case ParameterType_Color: case ParameterType::Color:
case ParameterType_Double: case ParameterType::Double:
case ParameterType_Integer: case ParameterType::Integer:
case ParameterType_None: case ParameterType::None:
case ParameterType_Pointer: case ParameterType::Pointer:
break; break;
} }
} }

View File

@ -3,6 +3,7 @@
// For conditions of distribution and use, see copyright notice in Config.hpp // For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Core/PluginManager.hpp> #include <Nazara/Core/PluginManager.hpp>
#include <Nazara/Core/Algorithm.hpp>
#include <Nazara/Core/DynLib.hpp> #include <Nazara/Core/DynLib.hpp>
#include <Nazara/Core/Error.hpp> #include <Nazara/Core/Error.hpp>
#include <memory> #include <memory>
@ -15,9 +16,9 @@ namespace Nz
using PluginLoad = int (*)(); using PluginLoad = int (*)();
using PluginUnload = void (*)(); using PluginUnload = void (*)();
std::filesystem::path s_pluginFiles[] = const char* s_pluginFiles[] =
{ {
"PluginAssimp", // Plugin_Assimp "PluginAssimp", // Plugin::Assimp
}; };
} }
@ -77,7 +78,7 @@ namespace Nz
bool PluginManager::Mount(Plugin plugin) bool PluginManager::Mount(Plugin plugin)
{ {
std::filesystem::path pluginName = s_pluginFiles[plugin]; std::filesystem::path pluginName = s_pluginFiles[UnderlyingCast(plugin)];
#ifdef NAZARA_DEBUG #ifdef NAZARA_DEBUG
std::filesystem::path debugPath = pluginName; std::filesystem::path debugPath = pluginName;
@ -195,7 +196,7 @@ namespace Nz
void PluginManager::Unmount(Plugin plugin) void PluginManager::Unmount(Plugin plugin)
{ {
Unmount(s_pluginFiles[plugin]); Unmount(s_pluginFiles[UnderlyingCast(plugin)]);
} }
/*! /*!

View File

@ -3,11 +3,12 @@
// For conditions of distribution and use, see copyright notice in Config.hpp // For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Core/Posix/FileImpl.hpp> #include <Nazara/Core/Posix/FileImpl.hpp>
#include <Nazara/Core/Algorithm.hpp>
#include <Nazara/Core/Error.hpp> #include <Nazara/Core/Error.hpp>
#include <Nazara/Core/StringExt.hpp> #include <Nazara/Core/StringExt.hpp>
#include <fcntl.h> #include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h> #include <unistd.h>
#include <sys/stat.h>
#include <cstdio> #include <cstdio>
#include <Nazara/Core/Debug.hpp> #include <Nazara/Core/Debug.hpp>
@ -61,20 +62,20 @@ namespace Nz
if ((mode & OpenMode_ReadWrite) == OpenMode_ReadWrite) if ((mode & OpenMode_ReadWrite) == OpenMode_ReadWrite)
flags = O_CREAT | O_RDWR; flags = O_CREAT | O_RDWR;
else if ((mode & OpenMode_ReadOnly) == OpenMode_ReadOnly) else if ((mode & OpenMode::ReadOnly) == OpenMode::ReadOnly)
flags = O_RDONLY; flags = O_RDONLY;
else if ((mode & OpenMode_WriteOnly) == OpenMode_WriteOnly) else if ((mode & OpenMode::WriteOnly) == OpenMode::WriteOnly)
flags = O_CREAT | O_WRONLY; flags = O_CREAT | O_WRONLY;
else else
return false; return false;
if (mode & OpenMode_Append) if (mode & OpenMode::Append)
flags |= O_APPEND; flags |= O_APPEND;
if (mode & OpenMode_MustExist) if (mode & OpenMode::MustExist)
flags &= ~O_CREAT; flags &= ~O_CREAT;
if (mode & OpenMode_Truncate) if (mode & OpenMode::Truncate)
flags |= O_TRUNC; flags |= O_TRUNC;
int fileDescriptor = Open_def(filePath.generic_u8string().data(), flags, permissions); int fileDescriptor = Open_def(filePath.generic_u8string().data(), flags, permissions);
@ -111,7 +112,7 @@ namespace Nz
return false; return false;
} }
if (mode & OpenMode_Lock) if (mode & OpenMode::Lock)
{ {
initialize_flock(lock); initialize_flock(lock);
@ -147,20 +148,20 @@ namespace Nz
int moveMethod; int moveMethod;
switch (pos) switch (pos)
{ {
case CursorPosition_AtBegin: case CursorPosition::AtBegin:
moveMethod = SEEK_SET; moveMethod = SEEK_SET;
break; break;
case CursorPosition_AtCurrent: case CursorPosition::AtCurrent:
moveMethod = SEEK_CUR; moveMethod = SEEK_CUR;
break; break;
case CursorPosition_AtEnd: case CursorPosition::AtEnd:
moveMethod = SEEK_END; moveMethod = SEEK_END;
break; break;
default: default:
NazaraInternalError("Cursor position not handled (0x" + NumberToString(pos, 16) + ')'); NazaraInternalError("Cursor position not handled (0x" + NumberToString(UnderlyingCast(pos), 16) + ')');
return false; return false;
} }

View File

@ -3,6 +3,7 @@
// For conditions of distribution and use, see copyright notice in Config.hpp // For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Core/StdLogger.hpp> #include <Nazara/Core/StdLogger.hpp>
#include <Nazara/Core/Algorithm.hpp>
#include <cstdio> #include <cstdio>
#include <Nazara/Core/Debug.hpp> #include <Nazara/Core/Debug.hpp>
@ -11,13 +12,13 @@ namespace Nz
namespace namespace
{ {
const char* errorType[] = { const char* errorType[] = {
"Assert failed", // ErrorType_AssertFailed "Assert failed", // ErrorType::AssertFailed
"Internal error", // ErrorType_Internal "Internal error", // ErrorType::Internal
"Error", // ErrorType_Normal "Error", // ErrorType::Normal
"Warning" // ErrorType_Warning "Warning" // ErrorType::Warning
}; };
static_assert(sizeof(errorType) / sizeof(const char*) == ErrorType_Max + 1, "Error type array is incomplete"); static_assert(sizeof(errorType) / sizeof(const char*) == ErrorTypeCount, "Error type array is incomplete");
} }
/*! /*!
@ -80,7 +81,7 @@ namespace Nz
void StdLogger::WriteError(ErrorType type, const std::string_view& error, unsigned int line, const char* file, const char* function) void StdLogger::WriteError(ErrorType type, const std::string_view& error, unsigned int line, const char* file, const char* function)
{ {
fprintf(stderr, "%s: ", errorType[type]); fprintf(stderr, "%s: ", errorType[UnderlyingCast(type)]);
fwrite(error.data(), sizeof(char), error.size(), stdout); fwrite(error.data(), sizeof(char), error.size(), stdout);
if (line != 0 && file && function) if (line != 0 && file && function)

View File

@ -78,7 +78,7 @@ namespace Nz
std::ptrdiff_t pos = ptr - buffer; std::ptrdiff_t pos = ptr - buffer;
if (ptr != buffer) if (ptr != buffer)
{ {
if (m_streamOptions & StreamOption_Text && buffer[pos - 1] == '\r') if (m_streamOptions & StreamOption::Text && buffer[pos - 1] == '\r')
line.append(buffer, pos - 1); line.append(buffer, pos - 1);
else else
line.append(buffer, pos); line.append(buffer, pos);
@ -92,7 +92,7 @@ namespace Nz
else else
{ {
std::size_t length = readSize; std::size_t length = readSize;
if (m_streamOptions & StreamOption_Text && buffer[length - 1] == '\r') if (m_streamOptions & StreamOption::Text && buffer[length - 1] == '\r')
{ {
if (!SetCursorPos(GetCursorPos() - 1)) if (!SetCursorPos(GetCursorPos() - 1))
NazaraWarning("Failed to reset cursor pos"); NazaraWarning("Failed to reset cursor pos");
@ -112,7 +112,7 @@ namespace Nz
std::size_t pos = line.find('\n'); std::size_t pos = line.find('\n');
if (pos <= readSize) // False only if the character is not available (npos being the biggest integer) if (pos <= readSize) // False only if the character is not available (npos being the biggest integer)
{ {
if (m_streamOptions & StreamOption_Text && pos > 0 && line[pos - 1] == '\r') if (m_streamOptions & StreamOption::Text && pos > 0 && line[pos - 1] == '\r')
line.resize(pos); line.resize(pos);
else else
line.resize(pos + 1); line.resize(pos + 1);
@ -149,7 +149,7 @@ namespace Nz
bool Stream::Write(const std::string_view& string) bool Stream::Write(const std::string_view& string)
{ {
if (m_streamOptions & StreamOption_Text) if (m_streamOptions & StreamOption::Text)
{ {
#if defined(NAZARA_PLATFORM_WINDOWS) #if defined(NAZARA_PLATFORM_WINDOWS)
std::string temp(string); std::string temp(string);

View File

@ -63,30 +63,30 @@ namespace Nz
DWORD shareMode = FILE_SHARE_READ; DWORD shareMode = FILE_SHARE_READ;
DWORD openMode = 0; DWORD openMode = 0;
if (mode & OpenMode_ReadOnly) if (mode & OpenMode::ReadOnly)
{ {
access |= GENERIC_READ; access |= GENERIC_READ;
if (mode & OpenMode_MustExist || (mode & OpenMode_WriteOnly) == 0) if (mode & OpenMode::MustExist || (mode & OpenMode::WriteOnly) == 0)
openMode |= OPEN_EXISTING; openMode |= OPEN_EXISTING;
} }
if (mode & OpenMode_WriteOnly) if (mode & OpenMode::WriteOnly)
{ {
if (mode & OpenMode_Append) if (mode & OpenMode::Append)
access |= FILE_APPEND_DATA; access |= FILE_APPEND_DATA;
else else
access |= GENERIC_WRITE; access |= GENERIC_WRITE;
if (mode & OpenMode_Truncate) if (mode & OpenMode::Truncate)
openMode |= CREATE_ALWAYS; openMode |= CREATE_ALWAYS;
else if (mode & OpenMode_MustExist) else if (mode & OpenMode::MustExist)
openMode |= OPEN_EXISTING; openMode |= OPEN_EXISTING;
else else
openMode |= OPEN_ALWAYS; openMode |= OPEN_ALWAYS;
} }
if ((mode & OpenMode_Lock) == 0) if ((mode & OpenMode::Lock) == 0)
shareMode |= FILE_SHARE_WRITE; shareMode |= FILE_SHARE_WRITE;
m_handle = CreateFileW(ToWideString(filePath.generic_u8string()).data(), access, shareMode, nullptr, openMode, 0, nullptr); m_handle = CreateFileW(ToWideString(filePath.generic_u8string()).data(), access, shareMode, nullptr, openMode, 0, nullptr);
@ -136,20 +136,20 @@ namespace Nz
DWORD moveMethod; DWORD moveMethod;
switch (pos) switch (pos)
{ {
case CursorPosition_AtBegin: case CursorPosition::AtBegin:
moveMethod = FILE_BEGIN; moveMethod = FILE_BEGIN;
break; break;
case CursorPosition_AtCurrent: case CursorPosition::AtCurrent:
moveMethod = FILE_CURRENT; moveMethod = FILE_CURRENT;
break; break;
case CursorPosition_AtEnd: case CursorPosition::AtEnd:
moveMethod = FILE_END; moveMethod = FILE_END;
break; break;
default: default:
NazaraInternalError("Cursor position not handled (0x" + NumberToString(pos, 16) + ')'); NazaraInternalError("Cursor position not handled (0x" + NumberToString(UnderlyingCast(pos), 16) + ')');
return false; return false;
} }
@ -167,11 +167,11 @@ namespace Nz
CallOnExit resetCursor([this, cursorPos] () CallOnExit resetCursor([this, cursorPos] ()
{ {
if (!SetCursorPos(CursorPosition_AtBegin, cursorPos)) if (!SetCursorPos(CursorPosition::AtBegin, cursorPos))
NazaraWarning("Failed to reset cursor position to previous position: " + Error::GetLastSystemError()); NazaraWarning("Failed to reset cursor position to previous position: " + Error::GetLastSystemError());
}); });
if (!SetCursorPos(CursorPosition_AtBegin, size)) if (!SetCursorPos(CursorPosition::AtBegin, size))
{ {
NazaraError("Failed to set file size: failed to move cursor position: " + Error::GetLastSystemError()); NazaraError("Failed to set file size: failed to move cursor position: " + Error::GetLastSystemError());
return false; return false;

View File

@ -3,6 +3,7 @@
// For conditions of distribution and use, see copyright notice in Config.hpp // For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Network/AbstractSocket.hpp> #include <Nazara/Network/AbstractSocket.hpp>
#include <Nazara/Core/Algorithm.hpp>
#include <Nazara/Core/Error.hpp> #include <Nazara/Core/Error.hpp>
#include <Nazara/Core/StringExt.hpp> #include <Nazara/Core/StringExt.hpp>
#include <Nazara/Network/Algorithm.hpp> #include <Nazara/Network/Algorithm.hpp>
@ -32,9 +33,9 @@ namespace Nz
*/ */
AbstractSocket::AbstractSocket(SocketType type) : AbstractSocket::AbstractSocket(SocketType type) :
m_lastError(SocketError_NoError), m_lastError(SocketError::NoError),
m_handle(SocketImpl::InvalidHandle), m_handle(SocketImpl::InvalidHandle),
m_state(SocketState_NotConnected), m_state(SocketState::NotConnected),
m_type(type), m_type(type),
m_isBlockingEnabled(true) m_isBlockingEnabled(true)
{ {
@ -165,7 +166,7 @@ namespace Nz
void AbstractSocket::OnClose() void AbstractSocket::OnClose()
{ {
UpdateState(SocketState_NotConnected); UpdateState(SocketState::NotConnected);
} }
/*! /*!
@ -178,7 +179,7 @@ namespace Nz
{ {
SocketError errorCode; SocketError errorCode;
if (!SocketImpl::SetBlocking(m_handle, m_isBlockingEnabled, &errorCode)) if (!SocketImpl::SetBlocking(m_handle, m_isBlockingEnabled, &errorCode))
NazaraWarning("Failed to set socket blocking mode (0x" + NumberToString(errorCode, 16) + ')'); NazaraWarning("Failed to set socket blocking mode (0x" + NumberToString(UnderlyingCast(errorCode), 16) + ')');
} }
/*! /*!
@ -190,11 +191,11 @@ namespace Nz
{ {
if (m_handle == SocketImpl::InvalidHandle || m_protocol != protocol) if (m_handle == SocketImpl::InvalidHandle || m_protocol != protocol)
{ {
SocketHandle handle = SocketImpl::Create((protocol == NetProtocol_Any) ? NetProtocol_IPv6 : protocol, m_type, &m_lastError); SocketHandle handle = SocketImpl::Create((protocol == NetProtocol::Any) ? NetProtocol::IPv6 : protocol, m_type, &m_lastError);
if (handle == SocketImpl::InvalidHandle) if (handle == SocketImpl::InvalidHandle)
return false; return false;
if (protocol == NetProtocol_Any) if (protocol == NetProtocol::Any)
{ {
if (!SocketImpl::SetIPv6Only(handle, false, &m_lastError)) if (!SocketImpl::SetIPv6Only(handle, false, &m_lastError))
{ {
@ -204,7 +205,7 @@ namespace Nz
return false; return false;
} }
protocol = NetProtocol_IPv6; protocol = NetProtocol::IPv6;
} }
m_protocol = protocol; m_protocol = protocol;

View File

@ -88,31 +88,31 @@ namespace Nz
{ {
switch (resolveError) switch (resolveError)
{ {
case ResolveError_NoError: case ResolveError::NoError:
return "No error"; return "No error";
case ResolveError_Internal: case ResolveError::Internal:
return "An internal error occurred"; return "An internal error occurred";
case ResolveError_ResourceError: case ResolveError::ResourceError:
return "The operating system lacks the resources to proceed"; return "The operating system lacks the resources to proceed";
case ResolveError_NonRecoverable: case ResolveError::NonRecoverable:
return "A nonrecoverable error occurred"; return "A nonrecoverable error occurred";
case ResolveError_NotFound: case ResolveError::NotFound:
return "No such host is known"; return "No such host is known";
case ResolveError_NotInitialized: case ResolveError::NotInitialized:
return "Nazara Network has not been initialized"; return "Nazara Network has not been initialized";
case ResolveError_ProtocolNotSupported: case ResolveError::ProtocolNotSupported:
return "A specified protocol is not supported by the server"; return "A specified protocol is not supported by the server";
case ResolveError_TemporaryFailure: case ResolveError::TemporaryFailure:
return "A temporary failure occurred, try again"; return "A temporary failure occurred, try again";
case ResolveError_Unknown: case ResolveError::Unknown:
return "An unknown error occurred"; return "An unknown error occurred";
default: default:
@ -131,52 +131,52 @@ namespace Nz
{ {
switch (socketError) switch (socketError)
{ {
case SocketError_NoError: case SocketError::NoError:
return "No error"; return "No error";
case SocketError_AddressNotAvailable: case SocketError::AddressNotAvailable:
return "The address is already in use"; return "The address is already in use";
case SocketError_ConnectionClosed: case SocketError::ConnectionClosed:
return "The connection has been closed"; return "The connection has been closed";
case SocketError_ConnectionRefused: case SocketError::ConnectionRefused:
return "The connection attempt was refused"; return "The connection attempt was refused";
case SocketError_DatagramSize: case SocketError::DatagramSize:
return "The datagram size is over the system limit"; return "The datagram size is over the system limit";
case SocketError_Internal: case SocketError::Internal:
return "An internal error occurred"; return "An internal error occurred";
case SocketError_Interrupted: case SocketError::Interrupted:
return "The operation was interrupted by a signal"; return "The operation was interrupted by a signal";
case SocketError_Packet: case SocketError::Packet:
return "Packet encoding or decoding failed"; return "Packet encoding or decoding failed";
case SocketError_NetworkError: case SocketError::NetworkError:
return "Networking subsystem failed"; return "Networking subsystem failed";
case SocketError_NotInitialized: case SocketError::NotInitialized:
return "Network module has not been initialized"; return "Network module has not been initialized";
case SocketError_NotSupported: case SocketError::NotSupported:
return "This operation is not supported"; return "This operation is not supported";
case SocketError_ResolveError: case SocketError::ResolveError:
return "The hostname couldn't be resolved"; return "The hostname couldn't be resolved";
case SocketError_ResourceError: case SocketError::ResourceError:
return "The operating system lacks the resources to proceed"; return "The operating system lacks the resources to proceed";
case SocketError_TimedOut: case SocketError::TimedOut:
return "The operation timed out"; return "The operation timed out";
case SocketError_Unknown: case SocketError::Unknown:
return "An unknown error occurred"; return "An unknown error occurred";
case SocketError_UnreachableHost: case SocketError::UnreachableHost:
return "The host is not reachable"; return "The host is not reachable";
default: default:

View File

@ -89,9 +89,9 @@ namespace Nz
UInt32 windowSize; UInt32 windowSize;
if (m_outgoingBandwidth == 0) if (m_outgoingBandwidth == 0)
windowSize = ENetProtocol_MaximumWindowSize; windowSize = ENetConstants::ENetProtocol_MaximumWindowSize;
else else
windowSize = (m_outgoingBandwidth / ENetConstants::ENetPeer_WindowSizeScale) * ENetProtocol_MinimumWindowSize; windowSize = (m_outgoingBandwidth / ENetConstants::ENetPeer_WindowSizeScale) * ENetConstants::ENetProtocol_MinimumWindowSize;
ENetPeer& peer = m_peers[peerId]; ENetPeer& peer = m_peers[peerId];
peer.InitOutgoing(channelCount, remoteAddress, ++m_randomSeed, windowSize); peer.InitOutgoing(channelCount, remoteAddress, ++m_randomSeed, windowSize);
@ -134,7 +134,7 @@ namespace Nz
if (!hostnameAddress.IsValid()) if (!hostnameAddress.IsValid())
{ {
if (error) if (error)
*error = ResolveError_NotFound; *error = ResolveError::NotFound;
return nullptr; return nullptr;
} }
@ -320,7 +320,7 @@ namespace Nz
bool ENetHost::InitSocket(const IpAddress& address) bool ENetHost::InitSocket(const IpAddress& address)
{ {
if (!m_socket.Create((m_isUsingDualStack) ? NetProtocol_Any : address.GetProtocol())) if (!m_socket.Create((m_isUsingDualStack) ? NetProtocol::Any : address.GetProtocol()))
return false; return false;
m_socket.EnableBlocking(false); m_socket.EnableBlocking(false);
@ -330,14 +330,14 @@ namespace Nz
if (address.IsValid() && !address.IsLoopback()) if (address.IsValid() && !address.IsLoopback())
{ {
if (m_socket.Bind(address) != SocketState_Bound) if (m_socket.Bind(address) != SocketState::Bound)
{ {
NazaraError("Failed to bind address " + address.ToString()); NazaraError("Failed to bind address " + address.ToString());
return false; return false;
} }
} }
m_poller.RegisterSocket(m_socket, SocketPollEvent_Read); m_poller.RegisterSocket(m_socket, SocketPollEvent::Read);
return true; return true;
} }
@ -417,7 +417,7 @@ namespace Nz
UInt32 channelCount = NetToHost(command->connect.channelCount); UInt32 channelCount = NetToHost(command->connect.channelCount);
if (channelCount < ENetProtocol_MinimumChannelCount || channelCount > ENetProtocol_MaximumChannelCount) if (channelCount < ENetConstants::ENetProtocol_MinimumChannelCount || channelCount > ENetConstants::ENetProtocol_MaximumChannelCount)
return nullptr; return nullptr;
std::size_t duplicatePeers = 0; std::size_t duplicatePeers = 0;

View File

@ -3,6 +3,7 @@
// For conditions of distribution and use, see copyright notice in Config.hpp // For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Network/IpAddress.hpp> #include <Nazara/Network/IpAddress.hpp>
#include <Nazara/Core/Algorithm.hpp>
#include <Nazara/Core/Error.hpp> #include <Nazara/Core/Error.hpp>
#include <Nazara/Core/StringExt.hpp> #include <Nazara/Core/StringExt.hpp>
#include <Nazara/Network/Algorithm.hpp> #include <Nazara/Network/Algorithm.hpp>
@ -47,14 +48,14 @@ namespace Nz
m_isValid = true; m_isValid = true;
if (isIPv6) if (isIPv6)
{ {
m_protocol = NetProtocol_IPv6; m_protocol = NetProtocol::IPv6;
for (unsigned int i = 0; i < 8; ++i) for (unsigned int i = 0; i < 8; ++i)
m_ipv6[i] = UInt32(result[i*2]) << 8 | result[i*2 + 1]; m_ipv6[i] = UInt32(result[i*2]) << 8 | result[i*2 + 1];
} }
else else
{ {
m_protocol = NetProtocol_IPv4; m_protocol = NetProtocol::IPv4;
for (unsigned int i = 0; i < 4; ++i) for (unsigned int i = 0; i < 4; ++i)
m_ipv4[i] = result[i]; m_ipv4[i] = result[i];
@ -75,21 +76,21 @@ namespace Nz
if (!m_isValid) if (!m_isValid)
return false; return false;
NazaraAssert(m_protocol <= NetProtocol_Max, "Protocol has value out of enum"); NazaraAssert(m_protocol <= NetProtocol::Max, "Protocol has value out of enum");
switch (m_protocol) switch (m_protocol)
{ {
case NetProtocol_Any: case NetProtocol::Any:
case NetProtocol_Unknown: case NetProtocol::Unknown:
break; break;
case NetProtocol_IPv4: case NetProtocol::IPv4:
return m_ipv4[0] == 127; return m_ipv4[0] == 127;
case NetProtocol_IPv6: case NetProtocol::IPv6:
return m_ipv6 == LoopbackIpV6.m_ipv6; // Only compare the ip value return m_ipv6 == LoopbackIpV6.m_ipv6; // Only compare the ip value
} }
NazaraInternalError("Invalid protocol for IpAddress (0x" + NumberToString(m_protocol) + ')'); NazaraInternalError("Invalid protocol for IpAddress (0x" + NumberToString(UnderlyingCast(m_protocol), 16) + ')');
return false; return false;
} }
@ -106,14 +107,14 @@ namespace Nz
if (m_isValid) if (m_isValid)
{ {
NazaraAssert(m_protocol <= NetProtocol_Max, "Protocol has value out of enum"); NazaraAssert(m_protocol <= NetProtocol::Max, "Protocol has value out of enum");
switch (m_protocol) switch (m_protocol)
{ {
case NetProtocol_Any: case NetProtocol::Any:
case NetProtocol_Unknown: case NetProtocol::Unknown:
break; break;
case NetProtocol_IPv4: case NetProtocol::IPv4:
for (unsigned int i = 0; i < 4; ++i) for (unsigned int i = 0; i < 4; ++i)
{ {
stream << int(m_ipv4[i]); stream << int(m_ipv4[i]);
@ -122,7 +123,7 @@ namespace Nz
} }
break; break;
case NetProtocol_IPv6: case NetProtocol::IPv6:
// Canonical representation of an IPv6 // Canonical representation of an IPv6
// https://tools.ietf.org/html/rfc5952 // https://tools.ietf.org/html/rfc5952
@ -213,7 +214,7 @@ namespace Nz
*/ */
std::vector<HostnameInfo> IpAddress::ResolveHostname(NetProtocol protocol, const std::string& hostname, const std::string& service, ResolveError* error) std::vector<HostnameInfo> IpAddress::ResolveHostname(NetProtocol protocol, const std::string& hostname, const std::string& service, ResolveError* error)
{ {
NazaraAssert(protocol != NetProtocol_Unknown, "Invalid protocol"); NazaraAssert(protocol != NetProtocol::Unknown, "Invalid protocol");
return IpAddressImpl::ResolveHostname(protocol, hostname, service, error); return IpAddressImpl::ResolveHostname(protocol, hostname, service, error);
} }

View File

@ -53,10 +53,10 @@ namespace Nz
entry.data.fd = socket; entry.data.fd = socket;
if (eventFlags & SocketPollEvent_Read) if (eventFlags & SocketPollEvent::Read)
entry.events |= EPOLLIN; entry.events |= EPOLLIN;
if (eventFlags & SocketPollEvent_Write) if (eventFlags & SocketPollEvent::Write)
entry.events |= EPOLLOUT; entry.events |= EPOLLOUT;
if (epoll_ctl(m_handle, EPOLL_CTL_ADD, socket, &entry) != 0) if (epoll_ctl(m_handle, EPOLL_CTL_ADD, socket, &entry) != 0)
@ -123,7 +123,7 @@ namespace Nz
} }
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return activeSockets; return activeSockets;
} }

View File

@ -41,7 +41,7 @@ namespace Nz
const void* NetPacket::OnSend(std::size_t* newSize) const const void* NetPacket::OnSend(std::size_t* newSize) const
{ {
NazaraAssert(newSize, "Invalid size pointer"); NazaraAssert(newSize, "Invalid size pointer");
NazaraAssert(m_netCode != NetCode_Invalid, "Invalid NetCode"); NazaraAssert(m_netCode != 0, "Invalid NetCode");
std::size_t size = m_buffer->GetSize(); std::size_t size = m_buffer->GetSize();
if (!EncodeHeader(m_buffer->GetBuffer(), static_cast<UInt32>(size), m_netCode)) if (!EncodeHeader(m_buffer->GetBuffer(), static_cast<UInt32>(size), m_netCode))

View File

@ -9,7 +9,6 @@
#include <Nazara/Core/Log.hpp> #include <Nazara/Core/Log.hpp>
#include <Nazara/Network/Config.hpp> #include <Nazara/Network/Config.hpp>
#include <Nazara/Network/NetPacket.hpp> #include <Nazara/Network/NetPacket.hpp>
#include <Nazara/Network/RUdpConnection.hpp>
#if defined(NAZARA_PLATFORM_WINDOWS) #if defined(NAZARA_PLATFORM_WINDOWS)
#include <Nazara/Network/Win32/SocketImpl.hpp> #include <Nazara/Network/Win32/SocketImpl.hpp>
@ -40,15 +39,11 @@ namespace Nz
if (!NetPacket::Initialize()) if (!NetPacket::Initialize())
throw std::runtime_error("failed to initialize packets"); throw std::runtime_error("failed to initialize packets");
if (!RUdpConnection::Initialize())
throw std::runtime_error("failed to initialize RUDP protocol");
} }
Network::~Network() Network::~Network()
{ {
// Uninitialize module here // Uninitialize module here
RUdpConnection::Uninitialize();
NetPacket::Uninitialize(); NetPacket::Uninitialize();
SocketImpl::Uninitialize(); SocketImpl::Uninitialize();
} }

View File

@ -3,6 +3,7 @@
// For conditions of distribution and use, see copyright notice in Config.hpp // For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Network/Posix/IpAddressImpl.hpp> #include <Nazara/Network/Posix/IpAddressImpl.hpp>
#include <Nazara/Core/Algorithm.hpp>
#include <Nazara/Core/CallOnExit.hpp> #include <Nazara/Core/CallOnExit.hpp>
#include <Nazara/Core/Error.hpp> #include <Nazara/Core/Error.hpp>
#include <Nazara/Core/StringExt.hpp> #include <Nazara/Core/StringExt.hpp>
@ -132,7 +133,7 @@ namespace Nz
} }
if (error) if (error)
*error = ResolveError_NoError; *error = ResolveError::NoError;
return true; return true;
} }
@ -174,7 +175,7 @@ namespace Nz
} }
if (error) if (error)
*error = ResolveError_NoError; *error = ResolveError::NoError;
return results; return results;
} }
@ -185,7 +186,7 @@ namespace Nz
{ {
switch (ipAddress.GetProtocol()) switch (ipAddress.GetProtocol())
{ {
case NetProtocol_IPv4: case NetProtocol::IPv4:
{ {
sockaddr_in* socketAddress = reinterpret_cast<sockaddr_in*>(buffer); sockaddr_in* socketAddress = reinterpret_cast<sockaddr_in*>(buffer);
@ -197,7 +198,7 @@ namespace Nz
return sizeof(sockaddr_in); return sizeof(sockaddr_in);
} }
case NetProtocol_IPv6: case NetProtocol::IPv6:
{ {
sockaddr_in6* socketAddress = reinterpret_cast<sockaddr_in6*>(buffer); sockaddr_in6* socketAddress = reinterpret_cast<sockaddr_in6*>(buffer);
@ -217,7 +218,7 @@ namespace Nz
} }
default: default:
NazaraInternalError("Unhandled ip protocol (0x" + NumberToString(ipAddress.GetProtocol(), 16) + ')'); NazaraInternalError("Unhandled ip protocol (0x" + NumberToString(UnderlyingCast(ipAddress.GetProtocol()), 16) + ')');
break; break;
} }
} }
@ -231,13 +232,13 @@ namespace Nz
switch (family) switch (family)
{ {
case PF_INET: case PF_INET:
return NetProtocol_IPv4; return NetProtocol::IPv4;
case PF_INET6: case PF_INET6:
return NetProtocol_IPv6; return NetProtocol::IPv6;
default: default:
return NetProtocol_Unknown; return NetProtocol::Unknown;
} }
} }
@ -246,16 +247,16 @@ namespace Nz
switch (socketType) switch (socketType)
{ {
case SOCK_STREAM: case SOCK_STREAM:
return SocketType_TCP; return SocketType::TCP;
case SOCK_DGRAM: case SOCK_DGRAM:
return SocketType_UDP; return SocketType::UDP;
case SOCK_RAW: case SOCK_RAW:
return SocketType_Raw; return SocketType::Raw;
default: default:
return SocketType_Unknown; return SocketType::Unknown;
} }
} }
@ -265,35 +266,35 @@ namespace Nz
switch (error) switch (error)
{ {
case 0: case 0:
return ResolveError_NoError; return ResolveError::NoError;
// Engine error // Engine error
case EAI_BADFLAGS: case EAI_BADFLAGS:
case EAI_SYSTEM: case EAI_SYSTEM:
return ResolveError_Internal; return ResolveError::Internal;
case EAI_FAMILY: case EAI_FAMILY:
case EAI_SERVICE: case EAI_SERVICE:
case EAI_SOCKTYPE: case EAI_SOCKTYPE:
return ResolveError_ProtocolNotSupported; return ResolveError::ProtocolNotSupported;
case EAI_NONAME: case EAI_NONAME:
return ResolveError_NotFound; return ResolveError::NotFound;
case EAI_FAIL: case EAI_FAIL:
return ResolveError_NonRecoverable; return ResolveError::NonRecoverable;
case EAI_NODATA: case EAI_NODATA:
return ResolveError_NotInitialized; return ResolveError::NotInitialized;
case EAI_MEMORY: case EAI_MEMORY:
return ResolveError_ResourceError; return ResolveError::ResourceError;
case EAI_AGAIN: case EAI_AGAIN:
return ResolveError_TemporaryFailure; return ResolveError::TemporaryFailure;
} }
NazaraWarning("Unhandled EAI error: " + Error::GetLastSystemError(error) + " (" + NumberToString(error) + ") as " + gai_strerror(error)); NazaraWarning("Unhandled EAI error: " + Error::GetLastSystemError(error) + " (" + NumberToString(error) + ") as " + gai_strerror(error));
return ResolveError_Unknown; return ResolveError::Unknown;
} }
} }

View File

@ -3,6 +3,7 @@
// For conditions of distribution and use, see copyright notice in Config.hpp // For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Network/Posix/SocketImpl.hpp> #include <Nazara/Network/Posix/SocketImpl.hpp>
#include <Nazara/Core/Algorithm.hpp>
#include <Nazara/Core/Error.hpp> #include <Nazara/Core/Error.hpp>
#include <Nazara/Core/StackArray.hpp> #include <Nazara/Core/StackArray.hpp>
#include <Nazara/Core/StringExt.hpp> #include <Nazara/Core/StringExt.hpp>
@ -41,7 +42,7 @@ namespace Nz
*address = IpAddressImpl::FromSockAddr(reinterpret_cast<const sockaddr*>(&nameBuffer)); *address = IpAddressImpl::FromSockAddr(reinterpret_cast<const sockaddr*>(&nameBuffer));
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
} }
else else
{ {
@ -65,19 +66,19 @@ namespace Nz
if (error) if (error)
*error = TranslateErrnoToSocketError(GetLastErrorCode()); *error = TranslateErrnoToSocketError(GetLastErrorCode());
return SocketState_NotConnected; return SocketState::NotConnected;
} }
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return SocketState_Bound; return SocketState::Bound;
} }
SocketHandle SocketImpl::Create(NetProtocol protocol, SocketType type, SocketError* error) SocketHandle SocketImpl::Create(NetProtocol protocol, SocketType type, SocketError* error)
{ {
NazaraAssert(protocol != NetProtocol_Any, "Any protocol is not supported for socket creation"); NazaraAssert(protocol != NetProtocol::Any, "Any protocol is not supported for socket creation");
NazaraAssert(type <= SocketType_Max, "Type has value out of enum"); NazaraAssert(type <= SocketType::Max, "Type has value out of enum");
SocketHandle handle = socket(TranslateNetProtocolToAF(protocol), TranslateSocketTypeToSock(type), 0); SocketHandle handle = socket(TranslateNetProtocolToAF(protocol), TranslateSocketTypeToSock(type), 0);
if (handle == InvalidHandle && error != nullptr) if (handle == InvalidHandle && error != nullptr)
@ -98,7 +99,7 @@ namespace Nz
{ {
NazaraAssert(handle != InvalidHandle, "Invalid handle"); NazaraAssert(handle != InvalidHandle, "Invalid handle");
if (GetLastError(handle, nullptr) < 0) if (GetLastError(handle, nullptr) != SocketError::Internal)
NazaraWarning("Failed to clear socket error code: " + Error::GetLastSystemError(GetLastErrorCode())); NazaraWarning("Failed to clear socket error code: " + Error::GetLastSystemError(GetLastErrorCode()));
} }
@ -111,7 +112,7 @@ namespace Nz
int bufferLength = IpAddressImpl::ToSockAddr(address, nameBuffer.data()); int bufferLength = IpAddressImpl::ToSockAddr(address, nameBuffer.data());
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
// Clear socket error status // Clear socket error status
ClearErrorCode(handle); ClearErrorCode(handle);
@ -123,24 +124,24 @@ namespace Nz
{ {
case EALREADY: case EALREADY:
case EINPROGRESS: case EINPROGRESS:
return SocketState_Connecting; return SocketState::Connecting;
case EISCONN: case EISCONN:
return SocketState_Connected; return SocketState::Connected;
} }
if (error) if (error)
{ {
if (errorCode == EADDRNOTAVAIL) if (errorCode == EADDRNOTAVAIL)
*error = SocketError_ConnectionRefused; //< ConnectionRefused seems more legit than AddressNotAvailable in connect case *error = SocketError::ConnectionRefused; //< ConnectionRefused seems more legit than AddressNotAvailable in connect case
else else
*error = TranslateErrnoToSocketError(errorCode); *error = TranslateErrnoToSocketError(errorCode);
} }
return SocketState_NotConnected; return SocketState::NotConnected;
} }
return SocketState_Connected; return SocketState::Connected;
} }
bool SocketImpl::Initialize() bool SocketImpl::Initialize()
@ -152,7 +153,7 @@ namespace Nz
{ {
int code = GetLastErrorCode(handle, error); int code = GetLastErrorCode(handle, error);
if (code < 0) if (code < 0)
return SocketError_Internal; return SocketError::Internal;
return TranslateErrnoToSocketError(code); return TranslateErrnoToSocketError(code);
} }
@ -176,7 +177,7 @@ namespace Nz
} }
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return code; return code;
} }
@ -194,7 +195,7 @@ namespace Nz
if (error) if (error)
*error = TranslateErrnoToSocketError(GetLastErrorCode()); *error = TranslateErrnoToSocketError(GetLastErrorCode());
return SocketState_NotConnected; return SocketState::NotConnected;
} }
if (listen(handle, queueSize) == SOCKET_ERROR) if (listen(handle, queueSize) == SOCKET_ERROR)
@ -202,13 +203,13 @@ namespace Nz
if (error) if (error)
*error = TranslateErrnoToSocketError(GetLastErrorCode()); *error = TranslateErrnoToSocketError(GetLastErrorCode());
return SocketState_NotConnected; return SocketState::NotConnected;
} }
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return SocketState_Bound; return SocketState::Bound;
} }
std::size_t SocketImpl::QueryAvailableBytes(SocketHandle handle, SocketError* error) std::size_t SocketImpl::QueryAvailableBytes(SocketHandle handle, SocketError* error)
@ -225,7 +226,7 @@ namespace Nz
} }
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return availableBytes; return availableBytes;
} }
@ -244,7 +245,7 @@ namespace Nz
} }
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return code; return code;
} }
@ -263,7 +264,7 @@ namespace Nz
} }
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return code; return code;
} }
@ -286,7 +287,7 @@ namespace Nz
#endif #endif
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return code; return code;
} }
@ -305,7 +306,7 @@ namespace Nz
} }
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return code; return code;
} }
@ -324,7 +325,7 @@ namespace Nz
} }
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return code; return code;
} }
@ -347,7 +348,7 @@ namespace Nz
} }
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return IpAddressImpl::FromSockAddr(reinterpret_cast<sockaddr*>(nameBuffer.data())); return IpAddressImpl::FromSockAddr(reinterpret_cast<sockaddr*>(nameBuffer.data()));
} }
@ -366,7 +367,7 @@ namespace Nz
} }
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return code; return code;
} }
@ -386,7 +387,7 @@ namespace Nz
{ {
int errorCode = GetLastErrorCode(); int errorCode = GetLastErrorCode();
if (errorCode == EINVAL) if (errorCode == EINVAL)
*error = SocketError_NoError; *error = SocketError::NoError;
else else
*error = TranslateErrnoToSocketError(errorCode); *error = TranslateErrnoToSocketError(errorCode);
} }
@ -395,7 +396,7 @@ namespace Nz
} }
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return IpAddressImpl::FromSockAddr(reinterpret_cast<sockaddr*>(nameBuffer.data())); return IpAddressImpl::FromSockAddr(reinterpret_cast<sockaddr*>(nameBuffer.data()));
} }
@ -432,7 +433,7 @@ namespace Nz
if (error) if (error)
*error = TranslateErrnoToSocketError(GetLastErrorCode()); *error = TranslateErrnoToSocketError(GetLastErrorCode());
return SocketState_NotConnected; return SocketState::NotConnected;
} }
else if (ret > 0) else if (ret > 0)
{ {
@ -441,14 +442,14 @@ namespace Nz
if (error) if (error)
*error = GetLastError(handle); *error = GetLastError(handle);
return SocketState_NotConnected; return SocketState::NotConnected;
} }
else if (descriptor.revents & POLLOUT) else if (descriptor.revents & POLLOUT)
return SocketState_Connected; return SocketState::Connected;
else else
{ {
NazaraWarning("Socket " + std::to_string(handle) + " was returned by poll without POLLOUT nor error events (events: 0x" + NumberToString(descriptor.revents, 16) + ')'); NazaraWarning("Socket " + std::to_string(handle) + " was returned by poll without POLLOUT nor error events (events: 0x" + NumberToString(descriptor.revents, 16) + ')');
return SocketState_NotConnected; return SocketState::NotConnected;
} }
} }
else else
@ -457,12 +458,12 @@ namespace Nz
if (error) if (error)
{ {
if (msTimeout > 0) if (msTimeout > 0)
*error = SocketError_TimedOut; *error = SocketError::TimedOut;
else else
*error = SocketError_NoError; *error = SocketError::NoError;
} }
return SocketState_Connecting; return SocketState::Connecting;
} }
} }
@ -499,7 +500,7 @@ namespace Nz
else if (byteRead == 0) else if (byteRead == 0)
{ {
if (error) if (error)
*error = SocketError_ConnectionClosed; *error = SocketError::ConnectionClosed;
return false; //< Connection has been closed return false; //< Connection has been closed
} }
@ -508,7 +509,7 @@ namespace Nz
*read = byteRead; *read = byteRead;
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return true; return true;
} }
@ -554,7 +555,7 @@ namespace Nz
else if (byteRead == 0) else if (byteRead == 0)
{ {
if (error) if (error)
*error = SocketError_ConnectionClosed; *error = SocketError::ConnectionClosed;
return false; //< Connection closed return false; //< Connection closed
} }
@ -568,7 +569,7 @@ namespace Nz
*read = byteRead; *read = byteRead;
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return true; return true;
} }
@ -634,7 +635,7 @@ namespace Nz
else if (byteRead == 0) else if (byteRead == 0)
{ {
if (error) if (error)
*error = SocketError_ConnectionClosed; *error = SocketError::ConnectionClosed;
return false; //< Connection closed return false; //< Connection closed
} }
@ -645,7 +646,7 @@ namespace Nz
if (msgHdr.msg_flags & MSG_TRUNC) if (msgHdr.msg_flags & MSG_TRUNC)
{ {
if (error) if (error)
*error = SocketError_DatagramSize; *error = SocketError::DatagramSize;
return false; return false;
} }
@ -658,7 +659,7 @@ namespace Nz
*read = byteRead; *read = byteRead;
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return true; return true;
} }
@ -695,7 +696,7 @@ namespace Nz
*sent = byteSent; *sent = byteSent;
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return true; return true;
} }
@ -753,7 +754,7 @@ namespace Nz
*sent = static_cast<int>(byteSent); *sent = static_cast<int>(byteSent);
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return true; return true;
} }
@ -793,7 +794,7 @@ namespace Nz
*sent = byteSent; *sent = byteSent;
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return true; return true;
} }
@ -812,7 +813,7 @@ namespace Nz
} }
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return true; return true;
} }
@ -831,7 +832,7 @@ namespace Nz
} }
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return true; return true;
} }
@ -850,7 +851,7 @@ namespace Nz
} }
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return true; return true;
} }
@ -888,7 +889,7 @@ namespace Nz
} }
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return true; return true;
} }
@ -907,7 +908,7 @@ namespace Nz
} }
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
#if not defined(MSG_NOSIGNAL) // -> https://github.com/intel/parameter-framework/pull/133/files #if not defined(MSG_NOSIGNAL) // -> https://github.com/intel/parameter-framework/pull/133/files
//There is no MSG_NOSIGNAL on macos //There is no MSG_NOSIGNAL on macos
@ -938,7 +939,7 @@ namespace Nz
} }
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return true; return true;
} }
@ -957,7 +958,7 @@ namespace Nz
} }
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return true; return true;
} }
@ -967,7 +968,7 @@ namespace Nz
switch (error) switch (error)
{ {
case 0: case 0:
return SocketError_NoError; return SocketError::NoError;
// Engine error // Engine error
case EACCES: case EACCES:
@ -981,83 +982,83 @@ namespace Nz
case EISCONN: case EISCONN:
case EWOULDBLOCK: case EWOULDBLOCK:
NazaraWarning("Internal error occurred: " + Error::GetLastSystemError(error) + " (" + NumberToString(error)+')'); NazaraWarning("Internal error occurred: " + Error::GetLastSystemError(error) + " (" + NumberToString(error)+')');
return SocketError_Internal; return SocketError::Internal;
case EADDRNOTAVAIL: case EADDRNOTAVAIL:
case EADDRINUSE: case EADDRINUSE:
return SocketError_AddressNotAvailable; return SocketError::AddressNotAvailable;
case EAFNOSUPPORT: case EAFNOSUPPORT:
case EPFNOSUPPORT: case EPFNOSUPPORT:
case EOPNOTSUPP: case EOPNOTSUPP:
case EPROTONOSUPPORT: case EPROTONOSUPPORT:
case ESOCKTNOSUPPORT: case ESOCKTNOSUPPORT:
return SocketError_NotSupported; return SocketError::NotSupported;
case ECONNREFUSED: case ECONNREFUSED:
return SocketError_ConnectionRefused; return SocketError::ConnectionRefused;
case EINTR: case EINTR:
return SocketError_Interrupted; return SocketError::Interrupted;
case EMSGSIZE: case EMSGSIZE:
return SocketError_DatagramSize; return SocketError::DatagramSize;
case EMFILE: case EMFILE:
case ENOBUFS: case ENOBUFS:
case ENOMEM: case ENOMEM:
return SocketError_ResourceError; return SocketError::ResourceError;
case ENOTCONN: case ENOTCONN:
case ESHUTDOWN: case ESHUTDOWN:
return SocketError_ConnectionClosed; return SocketError::ConnectionClosed;
case EHOSTUNREACH: case EHOSTUNREACH:
return SocketError_UnreachableHost; return SocketError::UnreachableHost;
case ENETDOWN: case ENETDOWN:
case ENETUNREACH: case ENETUNREACH:
return SocketError_NetworkError; return SocketError::NetworkError;
case ENODATA: case ENODATA:
return SocketError_NotInitialized; return SocketError::NotInitialized;
case ETIMEDOUT: case ETIMEDOUT:
return SocketError_TimedOut; return SocketError::TimedOut;
} }
NazaraWarning("Unhandled POSIX error: " + Error::GetLastSystemError(error) + " (" + NumberToString(error) + ')'); NazaraWarning("Unhandled POSIX error: " + Error::GetLastSystemError(error) + " (" + NumberToString(error) + ')');
return SocketError_Unknown; return SocketError::Unknown;
} }
int SocketImpl::TranslateNetProtocolToAF(NetProtocol protocol) int SocketImpl::TranslateNetProtocolToAF(NetProtocol protocol)
{ {
NazaraAssert(protocol <= NetProtocol_Max, "Protocol has value out of enum"); NazaraAssert(protocol <= NetProtocol::Max, "Protocol has value out of enum");
static int addressFamily[] = { static int addressFamily[] = {
AF_UNSPEC, //< NetProtocol_Any AF_UNSPEC, //< NetProtocol::Any
AF_INET, //< NetProtocol_IPv4 AF_INET, //< NetProtocol::IPv4
AF_INET6, //< NetProtocol_IPv6 AF_INET6, //< NetProtocol::IPv6
-1 //< NetProtocol_Unknown -1 //< NetProtocol::Unknown
}; };
static_assert(sizeof(addressFamily) / sizeof(int) == NetProtocol_Max + 1, "Address family array is incomplete"); static_assert(sizeof(addressFamily) / sizeof(int) == NetProtocolCount, "Address family array is incomplete");
return addressFamily[protocol]; return addressFamily[UnderlyingCast(protocol)];
} }
int SocketImpl::TranslateSocketTypeToSock(SocketType type) int SocketImpl::TranslateSocketTypeToSock(SocketType type)
{ {
NazaraAssert(type <= SocketType_Max, "Socket type has value out of enum"); NazaraAssert(type <= SocketType::Max, "Socket type has value out of enum");
static int socketType[] = { static int socketType[] = {
SOCK_RAW, //< SocketType_Raw SOCK_RAW, //< SocketType::Raw
SOCK_STREAM, //< SocketType_TCP SOCK_STREAM, //< SocketType::TCP
SOCK_DGRAM, //< SocketType_UDP SOCK_DGRAM, //< SocketType::UDP
-1 //< SocketType_Unknown -1 //< SocketType::Unknown
}; };
static_assert(sizeof(socketType) / sizeof(int) == SocketType_Max + 1, "Socket type array is incomplete"); static_assert(sizeof(socketType) / sizeof(int) == SocketTypeCount, "Socket type array is incomplete");
return socketType[type]; return socketType[UnderlyingCast(type)];
} }
void SocketImpl::Uninitialize() void SocketImpl::Uninitialize()

View File

@ -42,10 +42,10 @@ namespace Nz
0 0
}; };
if (eventFlags & SocketPollEvent_Read) if (eventFlags & SocketPollEvent::Read)
entry.events |= POLLRDNORM; entry.events |= POLLRDNORM;
if (eventFlags & SocketPollEvent_Write) if (eventFlags & SocketPollEvent::Write)
entry.events |= POLLWRNORM; entry.events |= POLLWRNORM;
m_allSockets[socket] = m_sockets.size(); m_allSockets[socket] = m_sockets.size();

View File

@ -1,640 +0,0 @@
// Copyright (C) 2020 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
#include <Nazara/Network/RUdpConnection.hpp>
#include <Nazara/Core/CallOnExit.hpp>
#include <Nazara/Core/Log.hpp>
#include <Nazara/Network/NetPacket.hpp>
#include <Nazara/Network/Debug.hpp>
namespace Nz
{
/*!
* \ingroup network
* \class Nz::RUdpConnection
* \brief Network class that represents a reliable UDP connection
*/
/*!
* \brief Constructs a RUdpConnection object by default
*/
RUdpConnection::RUdpConnection() :
m_peerIterator(0),
m_forceAckSendTime(10'000), //< 10ms
m_pingInterval(1'000'000), //< 1s
m_protocol(0x4E4E6574), //< "NNet"
m_timeBeforePing(500'000), //< 0.5s
m_timeBeforeTimeOut(10'000'000), //< 10s
m_currentTime(0),
m_isSimulationEnabled(false),
m_shouldAcceptConnections(true)
{
}
/*!
* \brief Connects to the IpAddress
* \return true
*
* \param remoteAddress Address to connect to
*
* \remark Produces a NazaraAssert if socket is not bound
* \remark Produces a NazaraAssert if remote is invalid
* \remark Produces a NazaraAssert if port is not specified
*/
bool RUdpConnection::Connect(const IpAddress& remoteAddress)
{
NazaraAssert(m_socket.GetState() == SocketState_Bound, "Socket must be bound first");
NazaraAssert(remoteAddress.IsValid(), "Invalid remote address");
NazaraAssert(remoteAddress.GetPort() != 0, "Remote address has no port");
PeerData& client = RegisterPeer(remoteAddress, PeerState_Connecting);
client.stateData1 = s_randomGenerator();
NetPacket connectionRequestPacket(NetCode_RequestConnection);
connectionRequestPacket << client.stateData1;
EnqueuePacket(client, PacketPriority_Immediate, PacketReliability_Reliable, connectionRequestPacket);
return true;
}
/*!
* \brief Connects to the hostname
* \return true If successful
*
* \param hostName Hostname of the remote
* \param protocol Net protocol to use
* \param service Specify the protocol used
* \param error Optional argument to get the error
*/
bool RUdpConnection::Connect(const std::string& hostName, NetProtocol protocol, const std::string& service, ResolveError* error)
{
std::vector<HostnameInfo> results = IpAddress::ResolveHostname(protocol, hostName, service, error);
if (results.empty())
{
m_lastError = SocketError_ResolveError;
return false;
}
IpAddress hostnameAddress;
for (const HostnameInfo& result : results)
{
if (!result.address)
continue;
if (result.socketType != SocketType_UDP)
continue;
hostnameAddress = result.address;
break; //< Take first valid address
}
return Connect(hostnameAddress);
}
/*!
* \brief Listens to a socket
* \return true If successfully bound
*
* \param remoteAddress Address to listen to
*/
bool RUdpConnection::Listen(const IpAddress& address)
{
if (!InitSocket(address.GetProtocol()))
return false;
return m_socket.Bind(address) == SocketState_Bound;
}
/*!
* \brief Polls the message
* \return true If there is a message
*
* \param message Message to poll
*
* \remark Produces a NazaraAssert if message is invalid
*/
bool RUdpConnection::PollMessage(RUdpMessage* message)
{
NazaraAssert(message, "Invalid message");
if (m_receivedMessages.empty())
return false;
*message = std::move(m_receivedMessages.front());
m_receivedMessages.pop();
return true;
}
/*!
* \brief Sends the packet to a peer
* \return true If peer exists (false may result from disconnected client)
*
* \param peerIp IpAddress of the peer
* \param priority Priority of the packet
* \param reliability Policy of reliability of the packet
* \param packet Packet to send
*/
bool RUdpConnection::Send(const IpAddress& peerIp, PacketPriority priority, PacketReliability reliability, const NetPacket& packet)
{
auto it = m_peerByIP.find(peerIp);
if (it == m_peerByIP.end())
return false; /// Silently fail (probably a disconnected client)
EnqueuePacket(m_peers[it->second], priority, reliability, packet);
return true;
}
/*!
* \brief Updates the reliable connection
*/
void RUdpConnection::Update()
{
m_currentTime = m_clock.GetMicroseconds();
NetPacket receivedPacket;
IpAddress senderIp;
while (m_socket.ReceivePacket(&receivedPacket, &senderIp))
OnPacketReceived(senderIp, std::move(receivedPacket));
//for (unsigned int i = m_activeClients.FindFirst(); i != m_activeClients.npos; i = m_activeClients.FindNext(i))
//{
// PeerData& clientData = m_peers[i];
CallOnExit resetIterator([this] () { m_peerIterator = m_peers.size(); });
for (m_peerIterator = 0; m_peerIterator < m_peers.size(); ++m_peerIterator)
{
PeerData& peer = m_peers[m_peerIterator];
UInt32 timeSinceLastPacket = static_cast<UInt32>(m_currentTime - peer.lastPacketTime);
if (timeSinceLastPacket > m_timeBeforeTimeOut)
{
DisconnectPeer(peer.index);
continue;
}
else if (timeSinceLastPacket > m_timeBeforePing)
{
if (m_currentTime - peer.lastPingTime > m_pingInterval)
{
NetPacket pingPacket(NetCode_Ping);
EnqueuePacket(peer, PacketPriority_Low, PacketReliability_Unreliable, pingPacket);
}
}
if (peer.state == PeerState_WillAck && m_currentTime - peer.stateData1 > m_forceAckSendTime)
{
NetPacket acknowledgePacket(NetCode_Acknowledge);
EnqueuePacket(peer, PacketPriority_Low, PacketReliability_Reliable, acknowledgePacket);
}
for (unsigned int priority = PacketPriority_Highest; priority <= PacketPriority_Lowest; ++priority)
{
std::vector<PendingPacket>& pendingPackets = peer.pendingPackets[priority];
for (PendingPacket& packetData : pendingPackets)
SendPacket(peer, std::move(packetData));
pendingPackets.clear();
}
auto it = peer.pendingAckQueue.begin();
while (it != peer.pendingAckQueue.end())
{
if (m_currentTime - it->timeSent > 2 * peer.roundTripTime)
{
OnPacketLost(peer, std::move(*it));
it = peer.pendingAckQueue.erase(it);
}
else
++it;
}
}
//m_activeClients.Reset();
}
/*!
* \brief Disconnects a peer
*
* \param peerIndex Index of the peer
*
* \remark Produces a NazaraNotice
*/
void RUdpConnection::DisconnectPeer(std::size_t peerIndex)
{
PeerData& peer = m_peers[peerIndex];
NazaraNotice(m_socket.GetBoundAddress().ToString() + ": " + peer.address.ToString() + " has been disconnected due to time-out");
OnPeerDisconnected(this, peer.address);
// Remove from IP lookup table
m_peerByIP.erase(peer.address);
// Can we safely "remove" this slot?
if (m_peerIterator >= m_peers.size() - 1 || peerIndex > m_peerIterator)
{
// Yes we can
PeerData& newSlot = m_peers[peerIndex];
newSlot = std::move(m_peers.back());
newSlot.index = peerIndex; //< Update the moved slot index before resizing (in case it's the last one)
}
else
{
// Nope, let's be tricky
PeerData& current = m_peers[m_peerIterator];
PeerData& newSlot = m_peers[peerIndex];
newSlot = std::move(current);
newSlot.index = peerIndex; //< Update the moved slot index
current = std::move(m_peers.back());
current.index = m_peerIterator; //< Update the moved slot index
--m_peerIterator;
}
// Pop the last entry (from where we moved our slot)
m_peers.pop_back();
}
/*!
* \brief Enqueues a packet in the sending list
*
* \param peer Data relative to the peer
* \param priority Priority of the packet
* \param reliability Policy of reliability of the packet
* \param packet Packet to send
*/
void RUdpConnection::EnqueuePacket(PeerData& peer, PacketPriority priority, PacketReliability reliability, const NetPacket& packet)
{
UInt16 protocolBegin = static_cast<UInt16>(m_protocol & 0xFFFF);
UInt16 protocolEnd = static_cast<UInt16>((m_protocol & 0xFFFF0000) >> 16);
NetPacket data(packet.GetNetCode(), MessageHeader + packet.GetDataSize() + MessageFooter);
data << protocolBegin;
data.GetStream()->SetCursorPos(NetPacket::HeaderSize + MessageHeader);
data.Write(packet.GetConstData() + NetPacket::HeaderSize, packet.GetDataSize());
data << protocolEnd;
EnqueuePacketInternal(peer, priority, reliability, std::move(data));
}
/*!
* \brief Enqueues internally a packet in the sending list
*
* \param peer Data relative to the peer
* \param priority Priority of the packet
* \param reliability Policy of reliability of the packet
* \param packet Packet to send
*/
void RUdpConnection::EnqueuePacketInternal(PeerData& peer, PacketPriority priority, PacketReliability reliability, NetPacket&& data)
{
PendingPacket pendingPacket;
pendingPacket.data = std::move(data);
pendingPacket.priority = priority;
pendingPacket.reliability = reliability;
peer.pendingPackets[priority].emplace_back(std::move(pendingPacket));
m_activeClients.UnboundedSet(peer.index);
}
/*!
* \brief Inits the internal socket
* \return true If successful
*
* \param protocol Net protocol to use
*/
bool RUdpConnection::InitSocket(NetProtocol protocol)
{
CallOnExit updateLastError([this]
{
m_lastError = m_socket.GetLastError();
});
if (!m_socket.Create(protocol))
return false;
m_socket.EnableBlocking(false);
return true;
}
/*!
* \brief Processes the acks
*
* \param peer Data relative to the peer
* \param lastAck Last index of the ack
* \param ackBits Bits for acking
*/
void RUdpConnection::ProcessAcks(PeerData& peer, SequenceIndex lastAck, UInt32 ackBits)
{
auto it = peer.pendingAckQueue.begin();
while (it != peer.pendingAckQueue.end())
{
bool acked = false;
if (lastAck == it->sequenceId)
acked = true;
else if (!IsAckMoreRecent(it->sequenceId, lastAck))
{
unsigned int difference = ComputeSequenceDifference(lastAck, it->sequenceId);
if (difference <= 32)
acked = (ackBits >> (difference - 1)) & 1;
}
if (acked)
{
it = peer.pendingAckQueue.erase(it);
}
else
++it;
}
}
/*!
* \brief Registers a peer
* \return Data relative to the peer
*
* \param address Address of the peer
* \param state Status of the peer
*/
RUdpConnection::PeerData& RUdpConnection::RegisterPeer(const IpAddress& address, PeerState state)
{
PeerData data;
data.address = address;
data.localSequence = 0;
data.remoteSequence = 0;
data.index = m_peers.size();
data.lastPacketTime = m_currentTime;
data.lastPingTime = m_currentTime;
data.roundTripTime = 1'000'000; ///< Okay that's quite a lot
data.state = state;
m_activeClients.UnboundedSet(data.index);
m_peerByIP[address] = data.index;
m_peers.emplace_back(std::move(data));
return m_peers.back();
}
/*!
* \brief Operation to do when client requests a connection
*
* \param address Address of the peer
* \param sequenceId Sequence index for the ack
* \param token Token for connection
*/
void RUdpConnection::OnClientRequestingConnection(const IpAddress& address, SequenceIndex sequenceId, UInt64 token)
{
// Call hook to check if client should be accepted or not
OnPeerConnection(this, address);
PeerData& client = RegisterPeer(address, PeerState_Aknowledged);
client.remoteSequence = sequenceId;
/// Acknowledge connection
NetPacket connectionAcceptedPacket(NetCode_AcknowledgeConnection);
//connectionAcceptedPacket << address;
connectionAcceptedPacket << ~token;
EnqueuePacket(client, PacketPriority_Immediate, PacketReliability_Reliable, connectionAcceptedPacket);
}
/*!
* \brief Operation to do when a packet is lost
*
* \param peer Data relative to the peer
* \param packet Pending packet
*/
void RUdpConnection::OnPacketLost(PeerData& peer, PendingAckPacket&& packet)
{
//NazaraNotice(m_socket.GetBoundAddress().ToString() + ": Lost packet " + NumberToString(packet.sequenceId));
if (IsReliable(packet.reliability))
EnqueuePacketInternal(peer, packet.priority, packet.reliability, std::move(packet.data));
}
/*!
* \brief Operation to do when receiving a packet
*
* \param peerIndex Index of the peer
*
* \remark Produces a NazaraNotice
*/
void RUdpConnection::OnPacketReceived(const IpAddress& peerIp, NetPacket&& packet)
{
UInt16 protocolBegin;
UInt16 protocolEnd;
SequenceIndex sequenceId;
SequenceIndex lastAck;
UInt32 ackBits;
packet.GetStream()->SetCursorPos(packet.GetSize() - MessageFooter);
packet >> protocolEnd;
packet.GetStream()->SetCursorPos(NetPacket::HeaderSize);
packet >> protocolBegin;
UInt32 protocolId = static_cast<UInt32>(protocolEnd) << 16 | protocolBegin;
if (protocolId != m_protocol)
return; ///< Ignore
packet >> sequenceId >> lastAck >> ackBits;
auto it = m_peerByIP.find(peerIp);
if (it == m_peerByIP.end())
{
switch (packet.GetNetCode())
{
case NetCode_RequestConnection:
{
UInt64 token;
packet >> token;
NazaraNotice(m_socket.GetBoundAddress().ToString() + ": Received NetCode_RequestConnection from " + peerIp.ToString() + ": " + NumberToString(token));
if (!m_shouldAcceptConnections)
return; //< Ignore
OnClientRequestingConnection(peerIp, sequenceId, token);
break;
}
default:
return; //< Ignore
}
}
else
{
PeerData& peer = m_peers[it->second];
peer.lastPacketTime = m_currentTime;
if (peer.receivedQueue.find(sequenceId) != peer.receivedQueue.end())
return; //< Ignore
if (m_isSimulationEnabled && m_packetLossProbability(s_randomGenerator))
{
NazaraNotice(m_socket.GetBoundAddress().ToString() + ": Lost packet " + NumberToString(sequenceId) + " from " + peerIp.ToString() + " for simulation purpose");
return;
}
///< Receiving a packet from an acknowledged client means the connection works in both ways
if (peer.state == PeerState_Aknowledged && packet.GetNetCode() != NetCode_RequestConnection)
{
peer.state = PeerState_Connected;
OnPeerAcknowledged(this, peerIp);
}
if (IsAckMoreRecent(sequenceId, peer.remoteSequence))
peer.remoteSequence = sequenceId;
ProcessAcks(peer, lastAck, ackBits);
peer.receivedQueue.insert(sequenceId);
switch (packet.GetNetCode())
{
case NetCode_Acknowledge:
return; //< Do not switch to will ack mode (to prevent infinite replies, just let's ping/pong do that)
case NetCode_AcknowledgeConnection:
{
if (peer.state == PeerState_Connected)
break;
IpAddress externalAddress;
UInt64 token;
packet /*>> externalAddress*/ >> token;
NazaraNotice(m_socket.GetBoundAddress().ToString() + ": Received NetCode_AcknowledgeConnection from " + peerIp.ToString() + ": " + NumberToString(token));
if (token == ~peer.stateData1)
{
peer.state = PeerState_Connected;
OnConnectedToPeer(this);
}
else
{
NazaraNotice("Received wrong token (" + NumberToString(token) + " instead of " + NumberToString(~peer.stateData1) + ") from client " + peer.address.ToString());
return; //< Ignore
}
break;
}
case NetCode_RequestConnection:
NazaraNotice(m_socket.GetBoundAddress().ToString() + ": Received NetCode_RequestConnection from " + peerIp.ToString());
return; //< Ignore
case NetCode_Ping:
{
NazaraNotice(m_socket.GetBoundAddress().ToString() + ": Received NetCode_Ping from " + peerIp.ToString());
NetPacket pongPacket(NetCode_Pong);
EnqueuePacket(peer, PacketPriority_Low, PacketReliability_Unreliable, pongPacket);
break;
}
case NetCode_Pong:
NazaraNotice(m_socket.GetBoundAddress().ToString() + ": Received NetCode_Pong from " + peerIp.ToString());
break;
default:
{
NazaraNotice(m_socket.GetBoundAddress().ToString() + ": Received 0x" + NumberToString(packet.GetNetCode(), 16) + " from " + peerIp.ToString());
RUdpMessage receivedMessage;
receivedMessage.from = peerIp;
receivedMessage.data = std::move(packet);
m_receivedMessages.emplace(std::move(receivedMessage));
break;
}
}
if (!HasPendingPackets(peer))
{
peer.state = PeerState_WillAck;
peer.stateData1 = m_currentTime;
}
}
}
/*!
* \brief Sends a packet to a peer
*
* \param peer Data relative to the peer
* \param packet Pending packet
*/
void RUdpConnection::SendPacket(PeerData& peer, PendingPacket&& packet)
{
if (peer.state == PeerState_WillAck)
peer.state = PeerState_Connected;
SequenceIndex remoteSequence = peer.remoteSequence;
UInt32 previousAcks = 0;
for (SequenceIndex ack : peer.receivedQueue)
{
if (ack == remoteSequence)
continue;
unsigned int difference = ComputeSequenceDifference(remoteSequence, ack);
if (difference <= 32U)
previousAcks |= (1U << (difference - 1));
}
SequenceIndex sequenceId = ++peer.localSequence;
packet.data.GetStream()->SetCursorPos(NetPacket::HeaderSize + sizeof(UInt16)); ///< Protocol begin has already been filled
packet.data << sequenceId;
packet.data << remoteSequence;
packet.data << previousAcks;
m_socket.SendPacket(peer.address, packet.data);
PendingAckPacket pendingAckPacket;
pendingAckPacket.data = std::move(packet.data);
pendingAckPacket.priority = packet.priority;
pendingAckPacket.reliability = packet.reliability;
pendingAckPacket.sequenceId = sequenceId;
pendingAckPacket.timeSent = m_currentTime;
peer.pendingAckQueue.emplace_back(std::move(pendingAckPacket));
}
/*!
* \brief Initializes the RUdpConnection class
* \return true
*/
bool RUdpConnection::Initialize()
{
std::random_device device;
s_randomGenerator.seed(device());
return true;
}
/*!
* \brief Uninitializes the RUdpConnection class
*/
void RUdpConnection::Uninitialize()
{
}
std::mt19937_64 RUdpConnection::s_randomGenerator;
}

View File

@ -3,6 +3,7 @@
// For conditions of distribution and use, see copyright notice in Config.hpp // For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Network/SocketPoller.hpp> #include <Nazara/Network/SocketPoller.hpp>
#include <Nazara/Core/Algorithm.hpp>
#include <Nazara/Core/Error.hpp> #include <Nazara/Core/Error.hpp>
#include <Nazara/Core/StringExt.hpp> #include <Nazara/Core/StringExt.hpp>
#include <Nazara/Network/Algorithm.hpp> #include <Nazara/Network/Algorithm.hpp>
@ -24,7 +25,7 @@ namespace Nz
/*! /*!
* \ingroup network * \ingroup network
* \class Nz::SocketPoller * \class Nz::SocketPoller
* \brief Network class allowing an application to wait on multiples sockets for them to become active (readable) * \brief Network class allowing an application to wait on multiples sockets for them to become active (readable/writeable)
*/ */
/*! /*!
@ -194,10 +195,10 @@ namespace Nz
if (error) if (error)
*error = waitError; *error = waitError;
if (waitError != SocketError_NoError) if (waitError != SocketError::NoError)
{ {
if (waitError != SocketError_Interrupted) //< Do not log interrupted error if (waitError != SocketError::Interrupted) //< Do not log interrupted error
NazaraError("SocketPoller encountered an error (code: 0x" + NumberToString(waitError, 16) + "): " + ErrorToString(waitError)); NazaraError("SocketPoller encountered an error (code: 0x" + NumberToString(UnderlyingCast(waitError), 16) + "): " + ErrorToString(waitError));
return 0; return 0;
} }

View File

@ -56,7 +56,7 @@ namespace Nz
} }
SocketState state = SocketImpl::Connect(m_handle, remoteAddress, &m_lastError); SocketState state = SocketImpl::Connect(m_handle, remoteAddress, &m_lastError);
m_peerAddress = (state != SocketState_NotConnected) ? remoteAddress : IpAddress::Invalid; m_peerAddress = (state != SocketState::NotConnected) ? remoteAddress : IpAddress::Invalid;
UpdateState(state); UpdateState(state);
return state; return state;
@ -75,13 +75,13 @@ namespace Nz
SocketState TcpClient::Connect(const std::string& hostName, NetProtocol protocol, const std::string& service, ResolveError* error) SocketState TcpClient::Connect(const std::string& hostName, NetProtocol protocol, const std::string& service, ResolveError* error)
{ {
UpdateState(SocketState_Resolving); UpdateState(SocketState::Resolving);
std::vector<HostnameInfo> results = IpAddress::ResolveHostname(protocol, hostName, service, error); std::vector<HostnameInfo> results = IpAddress::ResolveHostname(protocol, hostName, service, error);
if (results.empty()) if (results.empty())
{ {
m_lastError = SocketError_ResolveError; m_lastError = SocketError::ResolveError;
UpdateState(SocketState_NotConnected); UpdateState(SocketState::NotConnected);
return m_state; return m_state;
} }
@ -91,7 +91,7 @@ namespace Nz
if (!result.address) if (!result.address)
continue; continue;
if (result.socketType != SocketType_TCP) if (result.socketType != SocketType::TCP)
continue; continue;
hostnameAddress = result.address; hostnameAddress = result.address;
@ -176,7 +176,7 @@ namespace Nz
/*! /*!
* \brief Polls the connection status of the currently connecting socket * \brief Polls the connection status of the currently connecting socket
* \return New socket state, which maybe unchanged (if connecting is still pending), SocketState_Connected if connection is successful or SocketState_NotConnected if connection failed * \return New socket state, which maybe unchanged (if connecting is still pending), SocketState::Connected if connection is successful or SocketState::NotConnected if connection failed
* *
* This functions checks if the pending connection has either succeeded, failed or is still processing at the time of the call. * This functions checks if the pending connection has either succeeded, failed or is still processing at the time of the call.
* *
@ -188,16 +188,16 @@ namespace Nz
{ {
switch (m_state) switch (m_state)
{ {
case SocketState_Connecting: case SocketState::Connecting:
{ {
NazaraAssert(m_handle != SocketImpl::InvalidHandle, "Invalid handle"); NazaraAssert(m_handle != SocketImpl::InvalidHandle, "Invalid handle");
SocketState newState = SocketImpl::PollConnection(m_handle, m_peerAddress, waitDuration, &m_lastError); SocketState newState = SocketImpl::PollConnection(m_handle, m_peerAddress, waitDuration, &m_lastError);
// Prevent valid peer address in non-connected state // Prevent valid peer address in non-connected state
if (newState == SocketState_NotConnected) if (newState == SocketState::NotConnected)
{ {
m_openMode = OpenMode_NotOpen; m_openMode = OpenMode::NotOpen;
m_peerAddress = IpAddress::Invalid; m_peerAddress = IpAddress::Invalid;
} }
@ -205,16 +205,16 @@ namespace Nz
return newState; return newState;
} }
case SocketState_Connected: case SocketState::Connected:
case SocketState_NotConnected: case SocketState::NotConnected:
return m_state; return m_state;
case SocketState_Bound: case SocketState::Bound:
case SocketState_Resolving: case SocketState::Resolving:
break; break;
} }
NazaraInternalError("Unexpected socket state (0x" + NumberToString(m_state, 16) + ')'); NazaraInternalError("Unexpected socket state (0x" + NumberToString(UnderlyingCast(m_state), 16) + ')');
return m_state; return m_state;
} }
@ -240,9 +240,9 @@ namespace Nz
{ {
switch (m_lastError) switch (m_lastError)
{ {
case SocketError_ConnectionClosed: case SocketError::ConnectionClosed:
case SocketError_ConnectionRefused: case SocketError::ConnectionRefused:
UpdateState(SocketState_NotConnected); UpdateState(SocketState::NotConnected);
break; break;
default: default:
@ -255,7 +255,7 @@ namespace Nz
if (received) if (received)
*received = read; *received = read;
UpdateState(SocketState_Connected); UpdateState(SocketState::Connected);
return true; return true;
} }
@ -292,7 +292,7 @@ namespace Nz
UInt32 size; UInt32 size;
if (!NetPacket::DecodeHeader(m_pendingPacket.data.GetConstBuffer(), &size, &m_pendingPacket.netcode)) if (!NetPacket::DecodeHeader(m_pendingPacket.data.GetConstBuffer(), &size, &m_pendingPacket.netcode))
{ {
m_lastError = SocketError_Packet; m_lastError = SocketError::Packet;
NazaraWarning("Invalid header data"); NazaraWarning("Invalid header data");
return false; return false;
} }
@ -379,9 +379,9 @@ namespace Nz
{ {
switch (m_lastError) switch (m_lastError)
{ {
case SocketError_ConnectionClosed: case SocketError::ConnectionClosed:
case SocketError_ConnectionRefused: case SocketError::ConnectionRefused:
UpdateState(SocketState_NotConnected); UpdateState(SocketState::NotConnected);
break; break;
default: default:
@ -394,7 +394,7 @@ namespace Nz
totalByteSent += sentSize; totalByteSent += sentSize;
} }
UpdateState(SocketState_Connected); UpdateState(SocketState::Connected);
return true; return true;
} }
@ -415,9 +415,9 @@ namespace Nz
{ {
switch (m_lastError) switch (m_lastError)
{ {
case SocketError_ConnectionClosed: case SocketError::ConnectionClosed:
case SocketError_ConnectionRefused: case SocketError::ConnectionRefused:
UpdateState(SocketState_NotConnected); UpdateState(SocketState::NotConnected);
break; break;
default: default:
@ -433,7 +433,7 @@ namespace Nz
if (sent) if (sent)
*sent = byteSent; *sent = byteSent;
UpdateState(SocketState_Connected); UpdateState(SocketState::Connected);
return true; return true;
} }
@ -452,7 +452,7 @@ namespace Nz
const UInt8* ptr = static_cast<const UInt8*>(packet.OnSend(&size)); const UInt8* ptr = static_cast<const UInt8*>(packet.OnSend(&size));
if (!ptr) if (!ptr)
{ {
m_lastError = SocketError_Packet; m_lastError = SocketError::Packet;
NazaraError("Failed to prepare packet"); NazaraError("Failed to prepare packet");
return false; return false;
} }
@ -491,20 +491,20 @@ namespace Nz
{ {
switch (m_state) switch (m_state)
{ {
case SocketState_Connecting: case SocketState::Connecting:
{ {
NazaraAssert(m_handle != SocketImpl::InvalidHandle, "Invalid handle"); NazaraAssert(m_handle != SocketImpl::InvalidHandle, "Invalid handle");
SocketState newState = SocketImpl::PollConnection(m_handle, m_peerAddress, (msTimeout > 0) ? msTimeout : std::numeric_limits<UInt64>::max(), &m_lastError); SocketState newState = SocketImpl::PollConnection(m_handle, m_peerAddress, (msTimeout > 0) ? msTimeout : std::numeric_limits<UInt64>::max(), &m_lastError);
// If connection is still pending after waiting, cancel it // If connection is still pending after waiting, cancel it
if (newState == SocketState_Connecting) if (newState == SocketState::Connecting)
newState = SocketState_NotConnected; newState = SocketState::NotConnected;
// Prevent valid stats in non-connected state // Prevent valid stats in non-connected state
if (newState == SocketState_NotConnected) if (newState == SocketState::NotConnected)
{ {
m_openMode = OpenMode_NotOpen; m_openMode = OpenMode::NotOpen;
m_peerAddress = IpAddress::Invalid; m_peerAddress = IpAddress::Invalid;
} }
@ -512,16 +512,16 @@ namespace Nz
return newState; return newState;
} }
case SocketState_Connected: case SocketState::Connected:
case SocketState_NotConnected: case SocketState::NotConnected:
return m_state; return m_state;
case SocketState_Bound: case SocketState::Bound:
case SocketState_Resolving: case SocketState::Resolving:
break; break;
} }
NazaraInternalError("Unhandled socket state (0x" + NumberToString(m_state, 16) + ')'); NazaraInternalError("Unhandled socket state (0x" + NumberToString(UnderlyingCast(m_state), 16) + ')');
return m_state; return m_state;
} }
@ -541,7 +541,7 @@ namespace Nz
{ {
AbstractSocket::OnClose(); AbstractSocket::OnClose();
m_openMode = OpenMode_NotOpen; m_openMode = OpenMode::NotOpen;
m_peerAddress = IpAddress::Invalid; m_peerAddress = IpAddress::Invalid;
} }
@ -558,10 +558,10 @@ namespace Nz
SocketError errorCode; SocketError errorCode;
if (!SocketImpl::SetNoDelay(m_handle, m_isLowDelayEnabled, &errorCode)) if (!SocketImpl::SetNoDelay(m_handle, m_isLowDelayEnabled, &errorCode))
NazaraWarning("Failed to set socket no delay mode (0x" + NumberToString(errorCode, 16) + ')'); NazaraWarning("Failed to set socket no delay mode (0x" + NumberToString(UnderlyingCast(errorCode), 16) + ')');
if (!SocketImpl::SetKeepAlive(m_handle, m_isKeepAliveEnabled, m_keepAliveTime, m_keepAliveInterval, &errorCode)) if (!SocketImpl::SetKeepAlive(m_handle, m_isKeepAliveEnabled, m_keepAliveTime, m_keepAliveInterval, &errorCode))
NazaraWarning("Failed to set socket keep alive mode (0x" + NumberToString(errorCode, 16) + ')'); NazaraWarning("Failed to set socket keep alive mode (0x" + NumberToString(UnderlyingCast(errorCode), 16) + ')');
m_peerAddress = IpAddress::Invalid; m_peerAddress = IpAddress::Invalid;
m_openMode = OpenMode_ReadWrite; m_openMode = OpenMode_ReadWrite;
@ -610,7 +610,7 @@ namespace Nz
Open(handle); Open(handle);
m_peerAddress = peerAddress; m_peerAddress = peerAddress;
m_openMode = OpenMode_ReadWrite; m_openMode = OpenMode_ReadWrite;
UpdateState(SocketState_Connected); UpdateState(SocketState::Connected);
} }
/*! /*!

View File

@ -66,7 +66,7 @@ namespace Nz
Open(address.GetProtocol()); Open(address.GetProtocol());
SocketState state = SocketImpl::Listen(m_handle, address, queueSize, &m_lastError); SocketState state = SocketImpl::Listen(m_handle, address, queueSize, &m_lastError);
if (state == SocketState_Bound) if (state == SocketState::Bound)
m_boundAddress = SocketImpl::QuerySocketAddress(m_handle); m_boundAddress = SocketImpl::QuerySocketAddress(m_handle);
UpdateState(state); UpdateState(state);

View File

@ -41,7 +41,7 @@ namespace Nz
NazaraAssert(address.IsValid(), "Invalid address"); NazaraAssert(address.IsValid(), "Invalid address");
SocketState state = SocketImpl::Bind(m_handle, address, &m_lastError); SocketState state = SocketImpl::Bind(m_handle, address, &m_lastError);
if (state == SocketState_Bound) if (state == SocketState::Bound)
m_boundAddress = SocketImpl::QuerySocketAddress(m_handle); m_boundAddress = SocketImpl::QuerySocketAddress(m_handle);
UpdateState(state); UpdateState(state);
@ -104,8 +104,8 @@ namespace Nz
{ {
switch (m_lastError) switch (m_lastError)
{ {
case SocketError_ConnectionClosed: case SocketError::ConnectionClosed:
m_lastError = SocketError_NoError; m_lastError = SocketError::NoError;
read = 0; read = 0;
break; break;
@ -140,8 +140,8 @@ namespace Nz
{ {
switch (m_lastError) switch (m_lastError)
{ {
case SocketError_ConnectionClosed: case SocketError::ConnectionClosed:
m_lastError = SocketError_NoError; m_lastError = SocketError::NoError;
read = 0; read = 0;
break; break;
@ -166,14 +166,13 @@ namespace Nz
* \remark Produces a NazaraAssert if packet is invalid * \remark Produces a NazaraAssert if packet is invalid
* \remark Produces a NazaraWarning if packet's header is invalid * \remark Produces a NazaraWarning if packet's header is invalid
*/ */
bool UdpSocket::ReceivePacket(NetPacket* packet, IpAddress* from) bool UdpSocket::ReceivePacket(NetPacket* packet, IpAddress* from)
{ {
NazaraAssert(packet, "Invalid packet"); NazaraAssert(packet, "Invalid packet");
// I'm not sure what's the best between having a 65k bytes buffer ready for any datagram size // I'm not sure what's the best between having a 65k bytes buffer ready for any datagram size
// or querying the next datagram size every time, for now I'll leave it as is // or querying the next datagram size every time, for now I'll leave it as is
packet->Reset(NetCode_Invalid, std::numeric_limits<UInt16>::max()); packet->Reset(0, std::numeric_limits<UInt16>::max());
packet->Resize(std::numeric_limits<UInt16>::max()); packet->Resize(std::numeric_limits<UInt16>::max());
std::size_t received; std::size_t received;
@ -187,14 +186,14 @@ namespace Nz
Nz::UInt32 packetSize; Nz::UInt32 packetSize;
if (!NetPacket::DecodeHeader(packet->GetConstData(), &packetSize, &netCode)) if (!NetPacket::DecodeHeader(packet->GetConstData(), &packetSize, &netCode))
{ {
m_lastError = SocketError_Packet; m_lastError = SocketError::Packet;
NazaraWarning("Invalid header data"); NazaraWarning("Invalid header data");
return false; return false;
} }
if (packetSize != received) if (packetSize != received)
{ {
m_lastError = SocketError_Packet; m_lastError = SocketError::Packet;
NazaraWarning("Invalid packet size (packet size is " + NumberToString(packetSize) + " bytes, received " + NumberToString(received) + " bytes)"); NazaraWarning("Invalid packet size (packet size is " + NumberToString(packetSize) + " bytes, received " + NumberToString(received) + " bytes)");
return false; return false;
} }
@ -275,7 +274,7 @@ namespace Nz
const UInt8* ptr = static_cast<const UInt8*>(packet.OnSend(&size)); const UInt8* ptr = static_cast<const UInt8*>(packet.OnSend(&size));
if (!ptr) if (!ptr)
{ {
m_lastError = SocketError_Packet; m_lastError = SocketError::Packet;
NazaraError("Failed to prepare packet"); NazaraError("Failed to prepare packet");
return false; return false;
} }

View File

@ -3,6 +3,7 @@
// For conditions of distribution and use, see copyright notice in Config.hpp // For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Network/Win32/IpAddressImpl.hpp> #include <Nazara/Network/Win32/IpAddressImpl.hpp>
#include <Nazara/Core/Algorithm.hpp>
#include <Nazara/Core/CallOnExit.hpp> #include <Nazara/Core/CallOnExit.hpp>
#include <Nazara/Core/Error.hpp> #include <Nazara/Core/Error.hpp>
#include <Nazara/Core/StringExt.hpp> #include <Nazara/Core/StringExt.hpp>
@ -187,7 +188,7 @@ namespace Nz
} }
if (error) if (error)
*error = ResolveError_NoError; *error = ResolveError::NoError;
return true; return true;
} }
@ -228,7 +229,7 @@ namespace Nz
} }
if (error) if (error)
*error = ResolveError_NoError; *error = ResolveError::NoError;
return results; return results;
} }
@ -239,7 +240,7 @@ namespace Nz
{ {
switch (ipAddress.GetProtocol()) switch (ipAddress.GetProtocol())
{ {
case NetProtocol_IPv4: case NetProtocol::IPv4:
{ {
sockaddr_in* socketAddress = reinterpret_cast<sockaddr_in*>(buffer); sockaddr_in* socketAddress = reinterpret_cast<sockaddr_in*>(buffer);
@ -251,7 +252,7 @@ namespace Nz
return sizeof(sockaddr_in); return sizeof(sockaddr_in);
} }
case NetProtocol_IPv6: case NetProtocol::IPv6:
{ {
sockaddr_in6* socketAddress = reinterpret_cast<sockaddr_in6*>(buffer); sockaddr_in6* socketAddress = reinterpret_cast<sockaddr_in6*>(buffer);
@ -271,7 +272,7 @@ namespace Nz
} }
default: default:
NazaraInternalError("Unhandled ip protocol (0x" + NumberToString(ipAddress.GetProtocol()) + ')'); NazaraInternalError("Unhandled ip protocol (0x" + NumberToString(UnderlyingCast(ipAddress.GetProtocol())) + ')');
break; break;
} }
} }
@ -285,13 +286,13 @@ namespace Nz
switch (family) switch (family)
{ {
case PF_INET: case PF_INET:
return NetProtocol_IPv4; return NetProtocol::IPv4;
case PF_INET6: case PF_INET6:
return NetProtocol_IPv6; return NetProtocol::IPv6;
default: default:
return NetProtocol_Unknown; return NetProtocol::Unknown;
} }
} }
@ -300,16 +301,16 @@ namespace Nz
switch (socketType) switch (socketType)
{ {
case SOCK_STREAM: case SOCK_STREAM:
return SocketType_TCP; return SocketType::TCP;
case SOCK_DGRAM: case SOCK_DGRAM:
return SocketType_UDP; return SocketType::UDP;
case SOCK_RAW: case SOCK_RAW:
return SocketType_Raw; return SocketType::Raw;
default: default:
return SocketType_Unknown; return SocketType::Unknown;
} }
} }
@ -318,35 +319,35 @@ namespace Nz
switch (error) switch (error)
{ {
case 0: case 0:
return ResolveError_NoError; return ResolveError::NoError;
// Engine error // Engine error
case WSAEFAULT: case WSAEFAULT:
case WSAEINVAL: case WSAEINVAL:
return ResolveError_Internal; return ResolveError::Internal;
case WSAEAFNOSUPPORT: case WSAEAFNOSUPPORT:
case WSAESOCKTNOSUPPORT: case WSAESOCKTNOSUPPORT:
case WSASERVICE_NOT_FOUND: case WSASERVICE_NOT_FOUND:
return ResolveError_ProtocolNotSupported; return ResolveError::ProtocolNotSupported;
case WSAHOST_NOT_FOUND: case WSAHOST_NOT_FOUND:
return ResolveError_NotFound; return ResolveError::NotFound;
case WSANO_RECOVERY: case WSANO_RECOVERY:
return ResolveError_NonRecoverable; return ResolveError::NonRecoverable;
case WSANOTINITIALISED: case WSANOTINITIALISED:
return ResolveError_NotInitialized; return ResolveError::NotInitialized;
case WSA_NOT_ENOUGH_MEMORY: case WSA_NOT_ENOUGH_MEMORY:
return ResolveError_ResourceError; return ResolveError::ResourceError;
case WSATRY_AGAIN: case WSATRY_AGAIN:
return ResolveError_TemporaryFailure; return ResolveError::TemporaryFailure;
} }
NazaraWarning("Unhandled WinSock error: " + Error::GetLastSystemError(error) + " (" + NumberToString(error) + ')'); NazaraWarning("Unhandled WinSock error: " + Error::GetLastSystemError(error) + " (" + NumberToString(error) + ')');
return ResolveError_Unknown; return ResolveError::Unknown;
} }
} }

View File

@ -3,6 +3,7 @@
// For conditions of distribution and use, see copyright notice in Config.hpp // For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Network/Win32/SocketImpl.hpp> #include <Nazara/Network/Win32/SocketImpl.hpp>
#include <Nazara/Core/Algorithm.hpp>
#include <Nazara/Core/Error.hpp> #include <Nazara/Core/Error.hpp>
#include <Nazara/Core/Log.hpp> #include <Nazara/Core/Log.hpp>
#include <Nazara/Core/StackArray.hpp> #include <Nazara/Core/StackArray.hpp>
@ -52,7 +53,7 @@ namespace Nz
*address = IpAddressImpl::FromSockAddr(reinterpret_cast<const sockaddr*>(&nameBuffer)); *address = IpAddressImpl::FromSockAddr(reinterpret_cast<const sockaddr*>(&nameBuffer));
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
} }
else else
{ {
@ -76,19 +77,19 @@ namespace Nz
if (error) if (error)
*error = TranslateWSAErrorToSocketError(WSAGetLastError()); *error = TranslateWSAErrorToSocketError(WSAGetLastError());
return SocketState_NotConnected; return SocketState::NotConnected;
} }
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return SocketState_Bound; return SocketState::Bound;
} }
SocketHandle SocketImpl::Create(NetProtocol protocol, SocketType type, SocketError* error) SocketHandle SocketImpl::Create(NetProtocol protocol, SocketType type, SocketError* error)
{ {
NazaraAssert(protocol != NetProtocol_Any, "Any protocol is not supported for socket creation"); NazaraAssert(protocol != NetProtocol::Any, "Any protocol is not supported for socket creation");
NazaraAssert(type <= SocketType_Max, "Type has value out of enum"); NazaraAssert(type <= SocketType::Max, "Type has value out of enum");
SocketHandle handle = socket(TranslateNetProtocolToAF(protocol), TranslateSocketTypeToSock(type), 0); SocketHandle handle = socket(TranslateNetProtocolToAF(protocol), TranslateSocketTypeToSock(type), 0);
if (handle == InvalidHandle && error != nullptr) if (handle == InvalidHandle && error != nullptr)
@ -109,7 +110,7 @@ namespace Nz
{ {
NazaraAssert(handle != InvalidHandle, "Invalid handle"); NazaraAssert(handle != InvalidHandle, "Invalid handle");
if (GetLastError(handle, nullptr) < 0) if (GetLastError(handle, nullptr) != SocketError::Internal)
NazaraWarning("Failed to clear socket error code: " + Error::GetLastSystemError(WSAGetLastError())); NazaraWarning("Failed to clear socket error code: " + Error::GetLastSystemError(WSAGetLastError()));
} }
@ -122,7 +123,7 @@ namespace Nz
int bufferLength = IpAddressImpl::ToSockAddr(address, nameBuffer.data()); int bufferLength = IpAddressImpl::ToSockAddr(address, nameBuffer.data());
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
// Clear socket error status // Clear socket error status
ClearErrorCode(handle); ClearErrorCode(handle);
@ -135,24 +136,24 @@ namespace Nz
case WSAEALREADY: case WSAEALREADY:
case WSAEINVAL: //< In case of connect, WSAEINVAL may be returned instead of WSAEALREADY case WSAEINVAL: //< In case of connect, WSAEINVAL may be returned instead of WSAEALREADY
case WSAEWOULDBLOCK: case WSAEWOULDBLOCK:
return SocketState_Connecting; return SocketState::Connecting;
case WSAEISCONN: case WSAEISCONN:
return SocketState_Connected; return SocketState::Connected;
} }
if (error) if (error)
{ {
if (errorCode == WSAEADDRNOTAVAIL) if (errorCode == WSAEADDRNOTAVAIL)
*error = SocketError_ConnectionRefused; //< ConnectionRefused seems more legit than AddressNotAvailable in connect case *error = SocketError::ConnectionRefused; //< ConnectionRefused seems more legit than AddressNotAvailable in connect case
else else
*error = TranslateWSAErrorToSocketError(errorCode); *error = TranslateWSAErrorToSocketError(errorCode);
} }
return SocketState_NotConnected; return SocketState::NotConnected;
} }
return SocketState_Connected; return SocketState::Connected;
} }
bool SocketImpl::Initialize() bool SocketImpl::Initialize()
@ -172,7 +173,7 @@ namespace Nz
{ {
int code = GetLastErrorCode(handle, error); int code = GetLastErrorCode(handle, error);
if (code < 0) if (code < 0)
return SocketError_Internal; return SocketError::Internal;
return TranslateWSAErrorToSocketError(code); return TranslateWSAErrorToSocketError(code);
} }
@ -196,7 +197,7 @@ namespace Nz
} }
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return code; return code;
} }
@ -214,7 +215,7 @@ namespace Nz
if (error) if (error)
*error = TranslateWSAErrorToSocketError(WSAGetLastError()); *error = TranslateWSAErrorToSocketError(WSAGetLastError());
return SocketState_NotConnected; return SocketState::NotConnected;
} }
if (listen(handle, queueSize) == SOCKET_ERROR) if (listen(handle, queueSize) == SOCKET_ERROR)
@ -222,13 +223,13 @@ namespace Nz
if (error) if (error)
*error = TranslateWSAErrorToSocketError(WSAGetLastError()); *error = TranslateWSAErrorToSocketError(WSAGetLastError());
return SocketState_NotConnected; return SocketState::NotConnected;
} }
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return SocketState_Bound; return SocketState::Bound;
} }
std::size_t SocketImpl::QueryAvailableBytes(SocketHandle handle, SocketError* error) std::size_t SocketImpl::QueryAvailableBytes(SocketHandle handle, SocketError* error)
@ -245,7 +246,7 @@ namespace Nz
} }
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return availableBytes; return availableBytes;
} }
@ -264,7 +265,7 @@ namespace Nz
} }
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return code == TRUE; return code == TRUE;
} }
@ -283,7 +284,7 @@ namespace Nz
} }
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return code == TRUE; return code == TRUE;
} }
@ -302,7 +303,7 @@ namespace Nz
} }
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return code; return code;
} }
@ -321,7 +322,7 @@ namespace Nz
} }
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return code == TRUE; return code == TRUE;
} }
@ -340,7 +341,7 @@ namespace Nz
} }
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return code; return code;
} }
@ -363,7 +364,7 @@ namespace Nz
} }
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return IpAddressImpl::FromSockAddr(reinterpret_cast<sockaddr*>(nameBuffer.data())); return IpAddressImpl::FromSockAddr(reinterpret_cast<sockaddr*>(nameBuffer.data()));
} }
@ -383,7 +384,7 @@ namespace Nz
{ {
int errorCode = WSAGetLastError(); int errorCode = WSAGetLastError();
if (errorCode == WSAEINVAL) if (errorCode == WSAEINVAL)
*error = SocketError_NoError; *error = SocketError::NoError;
else else
*error = TranslateWSAErrorToSocketError(errorCode); *error = TranslateWSAErrorToSocketError(errorCode);
} }
@ -392,7 +393,7 @@ namespace Nz
} }
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return IpAddressImpl::FromSockAddr(reinterpret_cast<sockaddr*>(nameBuffer.data())); return IpAddressImpl::FromSockAddr(reinterpret_cast<sockaddr*>(nameBuffer.data()));
} }
@ -411,7 +412,7 @@ namespace Nz
} }
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return code; return code;
} }
@ -436,7 +437,7 @@ namespace Nz
assert(result >= 0); assert(result >= 0);
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return static_cast<unsigned int>(result); return static_cast<unsigned int>(result);
#else #else
@ -445,7 +446,7 @@ namespace Nz
NazaraUnused(timeout); NazaraUnused(timeout);
if (error) if (error)
*error = SocketError_NotSupported; *error = SocketError::NotSupported;
return 0; return 0;
#endif #endif
@ -465,7 +466,7 @@ namespace Nz
if (error) if (error)
*error = TranslateWSAErrorToSocketError(WSAGetLastError()); *error = TranslateWSAErrorToSocketError(WSAGetLastError());
return SocketState_NotConnected; return SocketState::NotConnected;
} }
else if (ret > 0) else if (ret > 0)
{ {
@ -474,14 +475,14 @@ namespace Nz
if (error) if (error)
*error = GetLastError(handle); *error = GetLastError(handle);
return SocketState_NotConnected; return SocketState::NotConnected;
} }
else if (descriptor.revents & POLLWRNORM) else if (descriptor.revents & POLLWRNORM)
return SocketState_Connected; return SocketState::Connected;
else else
{ {
NazaraWarning("Socket " + std::to_string(handle) + " was returned by poll without POLLOUT nor error events (events: 0x" + NumberToString(descriptor.revents, 16) + ')'); NazaraWarning("Socket " + std::to_string(handle) + " was returned by poll without POLLOUT nor error events (events: 0x" + NumberToString(descriptor.revents, 16) + ')');
return SocketState_NotConnected; return SocketState::NotConnected;
} }
} }
else else
@ -490,12 +491,12 @@ namespace Nz
if (error) if (error)
{ {
if (msTimeout > 0) if (msTimeout > 0)
*error = SocketError_TimedOut; *error = SocketError::TimedOut;
else else
*error = SocketError_NoError; *error = SocketError::NoError;
} }
return SocketState_Connecting; return SocketState::Connecting;
} }
} }
@ -529,7 +530,7 @@ namespace Nz
else if (byteRead == 0) else if (byteRead == 0)
{ {
if (error) if (error)
*error = SocketError_ConnectionClosed; *error = SocketError::ConnectionClosed;
return false; //< Connection has been closed return false; //< Connection has been closed
} }
@ -538,7 +539,7 @@ namespace Nz
*read = byteRead; *read = byteRead;
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return true; return true;
} }
@ -581,7 +582,7 @@ namespace Nz
else if (byteRead == 0) else if (byteRead == 0)
{ {
if (error) if (error)
*error = SocketError_ConnectionClosed; *error = SocketError::ConnectionClosed;
return false; //< Connection closed return false; //< Connection closed
} }
@ -595,7 +596,7 @@ namespace Nz
*read = byteRead; *read = byteRead;
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return true; return true;
} }
@ -650,7 +651,7 @@ namespace Nz
if (flags & MSG_PARTIAL) if (flags & MSG_PARTIAL)
{ {
if (error) if (error)
*error = SocketError_DatagramSize; *error = SocketError::DatagramSize;
return false; return false;
} }
@ -662,7 +663,7 @@ namespace Nz
*read = byteRead; *read = byteRead;
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return true; return true;
} }
@ -698,7 +699,7 @@ namespace Nz
*sent = byteSent; *sent = byteSent;
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return true; return true;
} }
@ -744,7 +745,7 @@ namespace Nz
*sent = static_cast<int>(byteSent); *sent = static_cast<int>(byteSent);
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return true; return true;
} }
@ -783,7 +784,7 @@ namespace Nz
*sent = byteSent; *sent = byteSent;
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return true; return true;
} }
@ -802,7 +803,7 @@ namespace Nz
} }
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return true; return true;
} }
@ -821,7 +822,7 @@ namespace Nz
} }
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return true; return true;
} }
@ -841,12 +842,12 @@ namespace Nz
} }
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return true; return true;
#else #else
if (error) if (error)
*error = SocketError_NotSupported; *error = SocketError::NotSupported;
return false; return false;
#endif #endif
@ -871,7 +872,7 @@ namespace Nz
} }
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return true; return true;
} }
@ -890,7 +891,7 @@ namespace Nz
} }
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return true; return true;
} }
@ -909,7 +910,7 @@ namespace Nz
} }
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return true; return true;
} }
@ -928,7 +929,7 @@ namespace Nz
} }
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
return true; return true;
} }
@ -938,7 +939,7 @@ namespace Nz
switch (error) switch (error)
{ {
case 0: case 0:
return SocketError_NoError; return SocketError::NoError;
// Engine error // Engine error
case WSAEACCES: case WSAEACCES:
@ -953,82 +954,82 @@ namespace Nz
case WSAEISCONN: case WSAEISCONN:
case WSAEWOULDBLOCK: case WSAEWOULDBLOCK:
NazaraWarning("Internal error occurred: " + Error::GetLastSystemError(error) + " (" + NumberToString(error) + ')'); NazaraWarning("Internal error occurred: " + Error::GetLastSystemError(error) + " (" + NumberToString(error) + ')');
return SocketError_Internal; return SocketError::Internal;
case WSAEADDRNOTAVAIL: case WSAEADDRNOTAVAIL:
case WSAEADDRINUSE: case WSAEADDRINUSE:
return SocketError_AddressNotAvailable; return SocketError::AddressNotAvailable;
case WSAEAFNOSUPPORT: case WSAEAFNOSUPPORT:
case WSAEPFNOSUPPORT: case WSAEPFNOSUPPORT:
case WSAEOPNOTSUPP: case WSAEOPNOTSUPP:
case WSAEPROTONOSUPPORT: case WSAEPROTONOSUPPORT:
case WSAESOCKTNOSUPPORT: case WSAESOCKTNOSUPPORT:
return SocketError_NotSupported; return SocketError::NotSupported;
case WSAECONNREFUSED: case WSAECONNREFUSED:
return SocketError_ConnectionRefused; return SocketError::ConnectionRefused;
case WSAECONNABORTED: case WSAECONNABORTED:
case WSAECONNRESET: case WSAECONNRESET:
case WSAENOTCONN: case WSAENOTCONN:
case WSAESHUTDOWN: case WSAESHUTDOWN:
return SocketError_ConnectionClosed; return SocketError::ConnectionClosed;
case WSAEMSGSIZE: case WSAEMSGSIZE:
return SocketError_DatagramSize; return SocketError::DatagramSize;
case WSAEMFILE: case WSAEMFILE:
case WSAENOBUFS: case WSAENOBUFS:
case WSA_NOT_ENOUGH_MEMORY: case WSA_NOT_ENOUGH_MEMORY:
return SocketError_ResourceError; return SocketError::ResourceError;
case WSAEHOSTUNREACH: case WSAEHOSTUNREACH:
return SocketError_UnreachableHost; return SocketError::UnreachableHost;
case WSAENETDOWN: case WSAENETDOWN:
case WSAENETUNREACH: case WSAENETUNREACH:
return SocketError_NetworkError; return SocketError::NetworkError;
case WSANOTINITIALISED: case WSANOTINITIALISED:
return SocketError_NotInitialized; return SocketError::NotInitialized;
case WSAETIMEDOUT: case WSAETIMEDOUT:
return SocketError_TimedOut; return SocketError::TimedOut;
} }
NazaraWarning("Unhandled WinSock error: " + Error::GetLastSystemError(error) + " (" + NumberToString(error) + ')'); NazaraWarning("Unhandled WinSock error: " + Error::GetLastSystemError(error) + " (" + NumberToString(error) + ')');
return SocketError_Unknown; return SocketError::Unknown;
} }
int SocketImpl::TranslateNetProtocolToAF(NetProtocol protocol) int SocketImpl::TranslateNetProtocolToAF(NetProtocol protocol)
{ {
NazaraAssert(protocol <= NetProtocol_Max, "Protocol has value out of enum"); NazaraAssert(protocol <= NetProtocol::Max, "Protocol has value out of enum");
static int addressFamily[] = { static int addressFamily[] = {
AF_UNSPEC, //< NetProtocol_Any AF_UNSPEC, //< NetProtocol::Any
AF_INET, //< NetProtocol_IPv4 AF_INET, //< NetProtocol::IPv4
AF_INET6, //< NetProtocol_IPv6 AF_INET6, //< NetProtocol::IPv6
-1 //< NetProtocol_Unknown -1 //< NetProtocol::Unknown
}; };
static_assert(sizeof(addressFamily) / sizeof(int) == NetProtocol_Max + 1, "Address family array is incomplete"); static_assert(sizeof(addressFamily) / sizeof(int) == NetProtocolCount, "Address family array is incomplete");
return addressFamily[protocol]; return addressFamily[UnderlyingCast(protocol)];
} }
int SocketImpl::TranslateSocketTypeToSock(SocketType type) int SocketImpl::TranslateSocketTypeToSock(SocketType type)
{ {
NazaraAssert(type <= SocketType_Max, "Socket type has value out of enum"); NazaraAssert(type <= SocketType::Max, "Socket type has value out of enum");
static int socketType[] = { static int socketType[] = {
SOCK_RAW, //< SocketType_Raw SOCK_RAW, //< SocketType::Raw
SOCK_STREAM, //< SocketType_TCP SOCK_STREAM, //< SocketType::TCP
SOCK_DGRAM, //< SocketType_UDP SOCK_DGRAM, //< SocketType::UDP
-1 //< SocketType_Unknown -1 //< SocketType::Unknown
}; };
static_assert(sizeof(socketType) / sizeof(int) == SocketType_Max + 1, "Socket type array is incomplete"); static_assert(sizeof(socketType) / sizeof(int) == SocketTypeCount, "Socket type array is incomplete");
return socketType[type]; return socketType[UnderlyingCast(type)];
} }
void SocketImpl::Uninitialize() void SocketImpl::Uninitialize()

View File

@ -74,10 +74,10 @@ namespace Nz
0 0
}; };
if (eventFlags & SocketPollEvent_Read) if (eventFlags & SocketPollEvent::Read)
entry.events |= POLLRDNORM; entry.events |= POLLRDNORM;
if (eventFlags & SocketPollEvent_Write) if (eventFlags & SocketPollEvent::Write)
entry.events |= POLLWRNORM; entry.events |= POLLWRNORM;
m_allSockets[socket] = m_sockets.size(); m_allSockets[socket] = m_sockets.size();
@ -85,7 +85,7 @@ namespace Nz
#else #else
for (std::size_t i = 0; i < 2; ++i) for (std::size_t i = 0; i < 2; ++i)
{ {
if ((eventFlags & ((i == 0) ? SocketPollEvent_Read : SocketPollEvent_Write)) == 0) if ((eventFlags & ((i == 0) ? SocketPollEvent::Read : SocketPollEvent::Write)) == 0)
continue; continue;
fd_set& targetSet = (i == 0) ? m_readSockets : m_writeSockets; fd_set& targetSet = (i == 0) ? m_readSockets : m_writeSockets;
@ -202,7 +202,7 @@ namespace Nz
activeSockets = static_cast<unsigned int>(selectValue); activeSockets = static_cast<unsigned int>(selectValue);
if (error) if (error)
*error = SocketError_NoError; *error = SocketError::NoError;
#endif #endif
return activeSockets; return activeSockets;

View File

@ -51,7 +51,7 @@ namespace Nz::GL
return CreateInternal(configs[configIndex], shareContext); return CreateInternal(configs[configIndex], shareContext);
} }
bool EGLContextBase::Create(const ContextParams& params, WindowHandle window, const EGLContextBase* shareContext) bool EGLContextBase::Create(const ContextParams& /*params*/, WindowHandle /*window*/, const EGLContextBase* /*shareContext*/)
{ {
NazaraError("Unexpected context creation call"); NazaraError("Unexpected context creation call");
return false; return false;
@ -140,7 +140,7 @@ namespace Nz::GL
}; };
EGLint numConfig = 0; EGLint numConfig = 0;
if (m_loader.eglChooseConfig(m_display, configAttributes, configs, maxConfigCount, &numConfig) != GL_TRUE) if (m_loader.eglChooseConfig(m_display, configAttributes, configs, EGLint(maxConfigCount), &numConfig) != GL_TRUE)
{ {
NazaraError(std::string("failed to retrieve compatible EGL configurations: ") + EGLLoader::TranslateError(m_loader.eglGetError())); NazaraError(std::string("failed to retrieve compatible EGL configurations: ") + EGLLoader::TranslateError(m_loader.eglGetError()));
return false; return false;

View File

@ -202,7 +202,7 @@ namespace Nz::GL
} }
} }
bool EGLLoader::ImplementFallback(const std::string_view& function) bool EGLLoader::ImplementFallback(const std::string_view& /*function*/)
{ {
return false; return false;
} }

View File

@ -101,11 +101,11 @@ namespace Nz
{ {
switch (coordSys) switch (coordSys)
{ {
case CoordSys_Global: case CoordSys::Global:
cpBodyApplyForceAtWorldPoint(m_handle, cpv(force.x, force.y), cpv(point.x, point.y)); cpBodyApplyForceAtWorldPoint(m_handle, cpv(force.x, force.y), cpv(point.x, point.y));
break; break;
case CoordSys_Local: case CoordSys::Local:
cpBodyApplyForceAtLocalPoint(m_handle, cpv(force.x, force.y), cpv(point.x, point.y)); cpBodyApplyForceAtLocalPoint(m_handle, cpv(force.x, force.y), cpv(point.x, point.y));
break; break;
} }
@ -120,11 +120,11 @@ namespace Nz
{ {
switch (coordSys) switch (coordSys)
{ {
case CoordSys_Global: case CoordSys::Global:
cpBodyApplyImpulseAtWorldPoint(m_handle, cpv(impulse.x, impulse.y), cpv(point.x, point.y)); cpBodyApplyImpulseAtWorldPoint(m_handle, cpv(impulse.x, impulse.y), cpv(point.x, point.y));
break; break;
case CoordSys_Local: case CoordSys::Local:
cpBodyApplyImpulseAtLocalPoint(m_handle, cpv(impulse.x, impulse.y), cpv(point.x, point.y)); cpBodyApplyImpulseAtLocalPoint(m_handle, cpv(impulse.x, impulse.y), cpv(point.x, point.y));
break; break;
} }
@ -254,11 +254,11 @@ namespace Nz
switch (coordSys) switch (coordSys)
{ {
case CoordSys_Global: case CoordSys::Global:
massCenter = cpBodyLocalToWorld(m_handle, massCenter); massCenter = cpBodyLocalToWorld(m_handle, massCenter);
break; break;
case CoordSys_Local: case CoordSys::Local:
break; // Nothing to do break; // Nothing to do
} }
@ -456,11 +456,11 @@ namespace Nz
switch (coordSys) switch (coordSys)
{ {
case CoordSys_Global: case CoordSys::Global:
massCenter = cpBodyWorldToLocal(m_handle, massCenter); massCenter = cpBodyWorldToLocal(m_handle, massCenter);
break; break;
case CoordSys_Local: case CoordSys::Local:
break; // Nothing to do break; // Nothing to do
} }

View File

@ -16,21 +16,21 @@ namespace Nz
{ {
switch (primitive.type) switch (primitive.type)
{ {
case PrimitiveType_Box: case PrimitiveType::Box:
return std::make_shared<BoxCollider3D>(primitive.box.lengths, primitive.matrix); return std::make_shared<BoxCollider3D>(primitive.box.lengths, primitive.matrix);
case PrimitiveType_Cone: case PrimitiveType::Cone:
return std::make_shared<ConeCollider3D>(primitive.cone.length, primitive.cone.radius, primitive.matrix); return std::make_shared<ConeCollider3D>(primitive.cone.length, primitive.cone.radius, primitive.matrix);
case PrimitiveType_Plane: case PrimitiveType::Plane:
return std::make_shared<BoxCollider3D>(Vector3f(primitive.plane.size.x, 0.01f, primitive.plane.size.y), primitive.matrix); return std::make_shared<BoxCollider3D>(Vector3f(primitive.plane.size.x, 0.01f, primitive.plane.size.y), primitive.matrix);
///TODO: PlaneGeom? ///TODO: PlaneGeom?
case PrimitiveType_Sphere: case PrimitiveType::Sphere:
return std::make_shared<SphereCollider3D>(primitive.sphere.size, primitive.matrix.GetTranslation()); return std::make_shared<SphereCollider3D>(primitive.sphere.size, primitive.matrix.GetTranslation());
} }
NazaraError("Primitive type not handled (0x" + NumberToString(primitive.type, 16) + ')'); NazaraError("Primitive type not handled (0x" + NumberToString(UnderlyingCast(primitive.type), 16) + ')');
return std::shared_ptr<Collider3D>(); return std::shared_ptr<Collider3D>();
} }
} }

View File

@ -84,11 +84,11 @@ namespace Nz
{ {
switch (coordSys) switch (coordSys)
{ {
case CoordSys_Global: case CoordSys::Global:
m_forceAccumulator += force; m_forceAccumulator += force;
break; break;
case CoordSys_Local: case CoordSys::Local:
m_forceAccumulator += GetRotation() * force; m_forceAccumulator += GetRotation() * force;
break; break;
} }
@ -101,13 +101,13 @@ namespace Nz
{ {
switch (coordSys) switch (coordSys)
{ {
case CoordSys_Global: case CoordSys::Global:
m_forceAccumulator += force; m_forceAccumulator += force;
m_torqueAccumulator += Vector3f::CrossProduct(point - GetMassCenter(CoordSys_Global), force); m_torqueAccumulator += Vector3f::CrossProduct(point - GetMassCenter(CoordSys::Global), force);
break; break;
case CoordSys_Local: case CoordSys::Local:
return AddForce(m_matrix.Transform(force, 0.f), m_matrix.Transform(point), CoordSys_Global); return AddForce(m_matrix.Transform(force, 0.f), m_matrix.Transform(point), CoordSys::Global);
} }
// On réveille le corps pour que le callback soit appelé et que les forces soient appliquées // On réveille le corps pour que le callback soit appelé et que les forces soient appliquées
@ -118,11 +118,11 @@ namespace Nz
{ {
switch (coordSys) switch (coordSys)
{ {
case CoordSys_Global: case CoordSys::Global:
m_torqueAccumulator += torque; m_torqueAccumulator += torque;
break; break;
case CoordSys_Local: case CoordSys::Local:
m_torqueAccumulator += m_matrix.Transform(torque, 0.f); m_torqueAccumulator += m_matrix.Transform(torque, 0.f);
break; break;
} }
@ -205,11 +205,11 @@ namespace Nz
switch (coordSys) switch (coordSys)
{ {
case CoordSys_Global: case CoordSys::Global:
center = m_matrix.Transform(center); center = m_matrix.Transform(center);
break; break;
case CoordSys_Local: case CoordSys::Local:
break; // Aucune opération à effectuer sur le centre de rotation break; // Aucune opération à effectuer sur le centre de rotation
} }

View File

@ -13,13 +13,13 @@ namespace Nz
Cursor::Cursor(const Image& cursor, const Vector2i& hotSpot, SystemCursor placeholder) Cursor::Cursor(const Image& cursor, const Vector2i& hotSpot, SystemCursor placeholder)
{ {
ErrorFlags flags(ErrorFlag_ThrowException, true); ErrorFlags flags(ErrorMode::ThrowException, true);
Create(cursor, hotSpot, placeholder); Create(cursor, hotSpot, placeholder);
} }
Cursor::Cursor(SystemCursor systemCursor) Cursor::Cursor(SystemCursor systemCursor)
{ {
ErrorFlags flags(ErrorFlag_ThrowException, true); ErrorFlags flags(ErrorMode::ThrowException, true);
Create(systemCursor); Create(systemCursor);
} }

View File

@ -12,7 +12,7 @@ namespace Nz
Icon::Icon(const Image& icon) Icon::Icon(const Image& icon)
{ {
ErrorFlags flags(ErrorFlag_ThrowException, true); ErrorFlags flags(ErrorMode::ThrowException, true);
Create(icon); Create(icon);
} }

View File

@ -39,7 +39,7 @@ namespace Nz
CursorImpl::CursorImpl(const Image& cursor, const Vector2i& hotSpot) CursorImpl::CursorImpl(const Image& cursor, const Vector2i& hotSpot)
{ {
ErrorFlags errFlags(ErrorFlag_ThrowException); ErrorFlags errFlags(ErrorMode::ThrowException);
m_cursorImage = cursor; m_cursorImage = cursor;
if (!m_cursorImage.Convert(PixelFormat::BGRA8)) if (!m_cursorImage.Convert(PixelFormat::BGRA8))
@ -69,7 +69,7 @@ namespace Nz
CursorImpl::CursorImpl(SystemCursor cursor) CursorImpl::CursorImpl(SystemCursor cursor)
{ {
ErrorFlags errFlags(ErrorFlag_ThrowException); ErrorFlags errFlags(ErrorMode::ThrowException);
if (cursor != SystemCursor::None) if (cursor != SystemCursor::None)
{ {

View File

@ -12,7 +12,7 @@ namespace Nz
{ {
IconImpl::IconImpl(const Image& icon) IconImpl::IconImpl(const Image& icon)
{ {
ErrorFlags errFlags(ErrorFlag_ThrowException); ErrorFlags errFlags(ErrorMode::ThrowException);
m_iconImage = icon; m_iconImage = icon;
if (!m_iconImage.Convert(PixelFormat::BGRA8)) if (!m_iconImage.Convert(PixelFormat::BGRA8))

View File

@ -198,7 +198,7 @@ namespace Nz
if (SDL_GetWindowWMInfo(m_handle, &wmInfo) != SDL_TRUE) if (SDL_GetWindowWMInfo(m_handle, &wmInfo) != SDL_TRUE)
{ {
ErrorFlags flags(ErrorFlag_ThrowException, true); ErrorFlags flags(ErrorMode::ThrowException, true);
NazaraError(std::string("failed to retrieve window manager info: ") + SDL_GetError()); NazaraError(std::string("failed to retrieve window manager info: ") + SDL_GetError());
} }
@ -235,7 +235,7 @@ namespace Nz
#endif #endif
default: default:
{ {
ErrorFlags flags(ErrorFlag_ThrowException, true); ErrorFlags flags(ErrorMode::ThrowException, true);
NazaraError("unhandled window subsystem"); NazaraError("unhandled window subsystem");
} }
} }

View File

@ -14,7 +14,7 @@ namespace Nz
std::shared_ptr<ShaderModule> RenderDevice::InstantiateShaderModule(ShaderStageTypeFlags shaderStages, ShaderLanguage lang, const std::filesystem::path& sourcePath, const ShaderWriter::States& states) std::shared_ptr<ShaderModule> RenderDevice::InstantiateShaderModule(ShaderStageTypeFlags shaderStages, ShaderLanguage lang, const std::filesystem::path& sourcePath, const ShaderWriter::States& states)
{ {
File file(sourcePath); File file(sourcePath);
if (!file.Open(OpenMode_ReadOnly | OpenMode_Text)) if (!file.Open(OpenMode::ReadOnly | OpenMode::Text))
{ {
NazaraError("Failed to open \"" + sourcePath.generic_u8string() + '"'); NazaraError("Failed to open \"" + sourcePath.generic_u8string() + '"');
return {}; return {};

View File

@ -753,7 +753,7 @@ namespace Nz::ShaderAst
ByteArray SerializeShader(StatementPtr& shader) ByteArray SerializeShader(StatementPtr& shader)
{ {
ByteArray byteArray; ByteArray byteArray;
ByteStream stream(&byteArray, OpenModeFlags(OpenMode_WriteOnly)); ByteStream stream(&byteArray, OpenModeFlags(OpenMode::WriteOnly));
ShaderAstSerializer serializer(stream); ShaderAstSerializer serializer(stream);
serializer.Serialize(shader); serializer.Serialize(shader);

View File

@ -1016,7 +1016,7 @@ namespace Nz::ShaderLang
ShaderAst::StatementPtr Parse(const std::filesystem::path& sourcePath) ShaderAst::StatementPtr Parse(const std::filesystem::path& sourcePath)
{ {
File file(sourcePath); File file(sourcePath);
if (!file.Open(OpenMode_ReadOnly | OpenMode_Text)) if (!file.Open(OpenMode::ReadOnly | OpenMode::Text))
{ {
NazaraError("Failed to open \"" + sourcePath.generic_u8string() + '"'); NazaraError("Failed to open \"" + sourcePath.generic_u8string() + '"');
return {}; return {};

View File

@ -25,7 +25,7 @@ namespace Nz
Buffer::Buffer(BufferType type, UInt32 size, DataStorage storage, BufferUsageFlags usage) : Buffer::Buffer(BufferType type, UInt32 size, DataStorage storage, BufferUsageFlags usage) :
Buffer(type) Buffer(type)
{ {
ErrorFlags flags(ErrorFlag_ThrowException, true); ErrorFlags flags(ErrorMode::ThrowException, true);
Create(size, storage, usage); Create(size, storage, usage);
} }

View File

@ -30,7 +30,7 @@ namespace Nz
return Ternary::False; return Ternary::False;
ByteStream byteStream(&stream); ByteStream byteStream(&stream);
byteStream.SetDataEndianness(Endianness_LittleEndian); byteStream.SetDataEndianness(Endianness::LittleEndian);
UInt32 magic; UInt32 magic;
byteStream >> magic; byteStream >> magic;
@ -43,7 +43,7 @@ namespace Nz
NazaraUnused(parameters); NazaraUnused(parameters);
ByteStream byteStream(&stream); ByteStream byteStream(&stream);
byteStream.SetDataEndianness(Endianness_LittleEndian); byteStream.SetDataEndianness(Endianness::LittleEndian);
UInt32 magic; UInt32 magic;
byteStream >> magic; byteStream >> magic;

View File

@ -324,7 +324,7 @@ namespace Nz
bool SetFile(const std::filesystem::path& filePath) bool SetFile(const std::filesystem::path& filePath)
{ {
std::unique_ptr<File> file = std::make_unique<File>(); std::unique_ptr<File> file = std::make_unique<File>();
if (!file->Open(filePath, OpenMode_ReadOnly)) if (!file->Open(filePath, OpenMode::ReadOnly))
{ {
NazaraError("Failed to open stream from file: " + Error::GetLastError()); NazaraError("Failed to open stream from file: " + Error::GetLastError());
return false; return false;

View File

@ -25,7 +25,7 @@ namespace Nz
MD5AnimParser::~MD5AnimParser() MD5AnimParser::~MD5AnimParser()
{ {
// Reset stream flags // Reset stream flags
if ((m_streamFlags & StreamOption_Text) == 0) if ((m_streamFlags & StreamOption::Text) == 0)
m_stream.EnableTextMode(false); m_stream.EnableTextMode(false);
} }

View File

@ -25,7 +25,7 @@ namespace Nz
MD5MeshParser::~MD5MeshParser() MD5MeshParser::~MD5MeshParser()
{ {
// Reset stream flags // Reset stream flags
if ((m_streamFlags & StreamOption_Text) == 0) if ((m_streamFlags & StreamOption::Text) == 0)
m_stream.EnableTextMode(false); m_stream.EnableTextMode(false);
} }

View File

@ -35,7 +35,7 @@ namespace Nz
// Force stream in text mode, reset it at the end // Force stream in text mode, reset it at the end
Nz::CallOnExit resetTextMode; Nz::CallOnExit resetTextMode;
if ((stream.GetStreamOptions() & StreamOption_Text) == 0) if ((stream.GetStreamOptions() & StreamOption::Text) == 0)
{ {
stream.EnableTextMode(true); stream.EnableTextMode(true);
@ -490,7 +490,7 @@ namespace Nz
// Force stream in text mode, reset it at the end // Force stream in text mode, reset it at the end
Nz::CallOnExit resetTextMode; Nz::CallOnExit resetTextMode;
if ((stream.GetStreamOptions() & StreamOption_Text) == 0) if ((stream.GetStreamOptions() & StreamOption::Text) == 0)
{ {
stream.EnableTextMode(true); stream.EnableTextMode(true);

View File

@ -45,7 +45,7 @@ namespace Nz
bool ParseMTL(Mesh& mesh, const std::filesystem::path& filePath, const std::string* materials, const OBJParser::Mesh* meshes, std::size_t meshCount) bool ParseMTL(Mesh& mesh, const std::filesystem::path& filePath, const std::string* materials, const OBJParser::Mesh* meshes, std::size_t meshCount)
{ {
File file(filePath); File file(filePath);
if (!file.Open(OpenMode_ReadOnly | OpenMode_Text)) if (!file.Open(OpenMode::ReadOnly | OpenMode::Text))
{ {
NazaraError("Failed to open MTL file (" + file.GetPath().generic_u8string() + ')'); NazaraError("Failed to open MTL file (" + file.GetPath().generic_u8string() + ')');
return false; return false;
@ -344,7 +344,7 @@ namespace Nz
std::filesystem::path mtlLib = parser.GetMtlLib(); std::filesystem::path mtlLib = parser.GetMtlLib();
if (!mtlLib.empty()) if (!mtlLib.empty())
{ {
ErrorFlags flags(ErrorFlag_ThrowExceptionDisabled); ErrorFlags flags(ErrorMode::ThrowExceptionDisabled);
ParseMTL(*mesh, stream.GetDirectory() / mtlLib, materials, meshes, meshCount); ParseMTL(*mesh, stream.GetDirectory() / mtlLib, materials, meshes, meshCount);
} }

View File

@ -23,7 +23,7 @@ namespace Nz
// Force stream in text mode, reset it at the end // Force stream in text mode, reset it at the end
Nz::CallOnExit resetTextMode; Nz::CallOnExit resetTextMode;
if ((stream.GetStreamOptions() & StreamOption_Text) == 0) if ((stream.GetStreamOptions() & StreamOption::Text) == 0)
{ {
stream.EnableTextMode(true); stream.EnableTextMode(true);
@ -95,7 +95,7 @@ namespace Nz
// Force stream in text mode, reset it at the end // Force stream in text mode, reset it at the end
Nz::CallOnExit resetTextMode; Nz::CallOnExit resetTextMode;
if ((stream.GetStreamOptions() & StreamOption_Text) == 0) if ((stream.GetStreamOptions() & StreamOption::Text) == 0)
{ {
stream.EnableTextMode(true); stream.EnableTextMode(true);
@ -493,7 +493,7 @@ namespace Nz
// Force stream in text mode, reset it at the end // Force stream in text mode, reset it at the end
Nz::CallOnExit resetTextMode; Nz::CallOnExit resetTextMode;
if ((stream.GetStreamOptions() & StreamOption_Text) == 0) if ((stream.GetStreamOptions() & StreamOption::Text) == 0)
{ {
stream.EnableTextMode(true); stream.EnableTextMode(true);

View File

@ -190,7 +190,7 @@ namespace Nz
if (!mtlPath.empty()) if (!mtlPath.empty())
{ {
File mtlFile(mtlPath, OpenMode_WriteOnly | OpenMode_Truncate); File mtlFile(mtlPath, OpenMode::WriteOnly | OpenMode::Truncate);
if (mtlFile.IsOpen()) if (mtlFile.IsOpen())
mtlFormat.Save(mtlFile); mtlFormat.Save(mtlFile);
} }

View File

@ -47,7 +47,7 @@ namespace Nz
Image::Image(ImageType type, PixelFormat format, unsigned int width, unsigned int height, unsigned int depth, UInt8 levelCount) : Image::Image(ImageType type, PixelFormat format, unsigned int width, unsigned int height, unsigned int depth, UInt8 levelCount) :
m_sharedImage(&emptyImage) m_sharedImage(&emptyImage)
{ {
ErrorFlags flags(ErrorFlag_ThrowException); ErrorFlags flags(ErrorMode::ThrowException);
Create(type, format, width, height, depth, levelCount); Create(type, format, width, height, depth, levelCount);
} }

View File

@ -15,19 +15,19 @@ namespace Nz
{ {
IndexBuffer::IndexBuffer(bool largeIndices, std::shared_ptr<Buffer> buffer) IndexBuffer::IndexBuffer(bool largeIndices, std::shared_ptr<Buffer> buffer)
{ {
ErrorFlags(ErrorFlag_ThrowException, true); ErrorFlags(ErrorMode::ThrowException, true);
Reset(largeIndices, std::move(buffer)); Reset(largeIndices, std::move(buffer));
} }
IndexBuffer::IndexBuffer(bool largeIndices, std::shared_ptr<Buffer> buffer, std::size_t offset, std::size_t size) IndexBuffer::IndexBuffer(bool largeIndices, std::shared_ptr<Buffer> buffer, std::size_t offset, std::size_t size)
{ {
ErrorFlags(ErrorFlag_ThrowException, true); ErrorFlags(ErrorMode::ThrowException, true);
Reset(largeIndices, std::move(buffer), offset, size); Reset(largeIndices, std::move(buffer), offset, size);
} }
IndexBuffer::IndexBuffer(bool largeIndices, std::size_t length, DataStorage storage, BufferUsageFlags usage) IndexBuffer::IndexBuffer(bool largeIndices, std::size_t length, DataStorage storage, BufferUsageFlags usage)
{ {
ErrorFlags(ErrorFlag_ThrowException, true); ErrorFlags(ErrorMode::ThrowException, true);
Reset(largeIndices, length, storage, usage); Reset(largeIndices, length, storage, usage);
} }

View File

@ -106,7 +106,7 @@ namespace Nz
switch (primitive.type) switch (primitive.type)
{ {
case PrimitiveType_Box: case PrimitiveType::Box:
{ {
unsigned int indexCount; unsigned int indexCount;
unsigned int vertexCount; unsigned int vertexCount;
@ -128,7 +128,7 @@ namespace Nz
break; break;
} }
case PrimitiveType_Cone: case PrimitiveType::Cone:
{ {
unsigned int indexCount; unsigned int indexCount;
unsigned int vertexCount; unsigned int vertexCount;
@ -150,7 +150,7 @@ namespace Nz
break; break;
} }
case PrimitiveType_Plane: case PrimitiveType::Plane:
{ {
unsigned int indexCount; unsigned int indexCount;
unsigned int vertexCount; unsigned int vertexCount;
@ -172,11 +172,11 @@ namespace Nz
break; break;
} }
case PrimitiveType_Sphere: case PrimitiveType::Sphere:
{ {
switch (primitive.sphere.type) switch (primitive.sphere.type)
{ {
case SphereType_Cubic: case SphereType::Cubic:
{ {
unsigned int indexCount; unsigned int indexCount;
unsigned int vertexCount; unsigned int vertexCount;
@ -198,7 +198,7 @@ namespace Nz
break; break;
} }
case SphereType_Ico: case SphereType::Ico:
{ {
unsigned int indexCount; unsigned int indexCount;
unsigned int vertexCount; unsigned int vertexCount;
@ -220,7 +220,7 @@ namespace Nz
break; break;
} }
case SphereType_UV: case SphereType::UV:
{ {
unsigned int indexCount; unsigned int indexCount;
unsigned int vertexCount; unsigned int vertexCount;

View File

@ -3,6 +3,7 @@
// For conditions of distribution and use, see copyright notice in Config.hpp // For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Utility/Node.hpp> #include <Nazara/Utility/Node.hpp>
#include <Nazara/Core/Algorithm.hpp>
#include <Nazara/Utility/Debug.hpp> #include <Nazara/Utility/Debug.hpp>
namespace Nz namespace Nz
@ -148,17 +149,17 @@ namespace Nz
{ {
switch (coordSys) switch (coordSys)
{ {
case CoordSys_Global: case CoordSys::Global:
if (!m_derivedUpdated) if (!m_derivedUpdated)
UpdateDerived(); UpdateDerived();
return m_derivedPosition; return m_derivedPosition;
case CoordSys_Local: case CoordSys::Local:
return m_position; return m_position;
} }
NazaraError("Coordinate system out of enum (0x" + NumberToString(coordSys, 16) + ')'); NazaraError("Coordinate system out of enum (0x" + NumberToString(UnderlyingCast(coordSys), 16) + ')');
return Vector3f(); return Vector3f();
} }
@ -174,17 +175,17 @@ namespace Nz
{ {
switch (coordSys) switch (coordSys)
{ {
case CoordSys_Global: case CoordSys::Global:
if (!m_derivedUpdated) if (!m_derivedUpdated)
UpdateDerived(); UpdateDerived();
return m_derivedRotation; return m_derivedRotation;
case CoordSys_Local: case CoordSys::Local:
return m_rotation; return m_rotation;
} }
NazaraError("Coordinate system out of enum (0x" + NumberToString(coordSys, 16) + ')'); NazaraError("Coordinate system out of enum (0x" + NumberToString(UnderlyingCast(coordSys), 16) + ')');
return Quaternionf(); return Quaternionf();
} }
@ -192,17 +193,17 @@ namespace Nz
{ {
switch (coordSys) switch (coordSys)
{ {
case CoordSys_Global: case CoordSys::Global:
if (!m_derivedUpdated) if (!m_derivedUpdated)
UpdateDerived(); UpdateDerived();
return m_derivedScale; return m_derivedScale;
case CoordSys_Local: case CoordSys::Local:
return m_scale; return m_scale;
} }
NazaraError("Coordinate system out of enum (0x" + NumberToString(coordSys, 16) + ')'); NazaraError("Coordinate system out of enum (0x" + NumberToString(UnderlyingCast(coordSys), 16) + ')');
return Vector3f(); return Vector3f();
} }
@ -231,7 +232,7 @@ namespace Nz
{ {
switch (coordSys) switch (coordSys)
{ {
case CoordSys_Global: case CoordSys::Global:
if (!nodeA.m_derivedUpdated) if (!nodeA.m_derivedUpdated)
nodeA.UpdateDerived(); nodeA.UpdateDerived();
@ -243,7 +244,7 @@ namespace Nz
m_scale = ToLocalScale(Vector3f::Lerp(nodeA.m_derivedScale, nodeB.m_derivedScale, interpolation)); m_scale = ToLocalScale(Vector3f::Lerp(nodeA.m_derivedScale, nodeB.m_derivedScale, interpolation));
break; break;
case CoordSys_Local: case CoordSys::Local:
m_position = Vector3f::Lerp(nodeA.m_position, nodeB.m_position, interpolation); m_position = Vector3f::Lerp(nodeA.m_position, nodeB.m_position, interpolation);
m_rotation = Quaternionf::Slerp(nodeA.m_rotation, nodeB.m_rotation, interpolation); m_rotation = Quaternionf::Slerp(nodeA.m_rotation, nodeB.m_rotation, interpolation);
m_scale = Vector3f::Lerp(nodeA.m_scale, nodeB.m_scale, interpolation); m_scale = Vector3f::Lerp(nodeA.m_scale, nodeB.m_scale, interpolation);
@ -258,7 +259,7 @@ namespace Nz
{ {
switch (coordSys) switch (coordSys)
{ {
case CoordSys_Global: case CoordSys::Global:
{ {
if (m_parent) if (m_parent)
{ {
@ -273,7 +274,7 @@ namespace Nz
break; break;
} }
case CoordSys_Local: case CoordSys::Local:
m_position += m_rotation * movement; m_position += m_rotation * movement;
break; break;
} }
@ -295,7 +296,7 @@ namespace Nz
switch (coordSys) switch (coordSys)
{ {
case CoordSys_Global: case CoordSys::Global:
{ {
if (!m_derivedUpdated) if (!m_derivedUpdated)
UpdateDerived(); UpdateDerived();
@ -304,7 +305,7 @@ namespace Nz
break; break;
} }
case CoordSys_Local: case CoordSys::Local:
m_rotation *= q; m_rotation *= q;
break; break;
} }
@ -449,9 +450,9 @@ namespace Nz
if (m_parent) if (m_parent)
m_parent->AddChild(this); m_parent->AddChild(this);
SetRotation(m_derivedRotation, CoordSys_Global); SetRotation(m_derivedRotation, CoordSys::Global);
SetScale(m_derivedScale, CoordSys_Global); SetScale(m_derivedScale, CoordSys::Global);
SetPosition(m_derivedPosition, CoordSys_Global); SetPosition(m_derivedPosition, CoordSys::Global);
} }
else else
{ {
@ -477,7 +478,7 @@ namespace Nz
{ {
switch (coordSys) switch (coordSys)
{ {
case CoordSys_Global: case CoordSys::Global:
if (m_parent && m_inheritPosition) if (m_parent && m_inheritPosition)
{ {
if (!m_parent->m_derivedUpdated) if (!m_parent->m_derivedUpdated)
@ -489,7 +490,7 @@ namespace Nz
m_position = position - m_initialPosition; m_position = position - m_initialPosition;
break; break;
case CoordSys_Local: case CoordSys::Local:
m_position = position; m_position = position;
break; break;
} }
@ -510,7 +511,7 @@ namespace Nz
switch (coordSys) switch (coordSys)
{ {
case CoordSys_Global: case CoordSys::Global:
if (m_parent && m_inheritRotation) if (m_parent && m_inheritRotation)
{ {
Quaternionf rot(m_parent->GetRotation() * m_initialRotation); Quaternionf rot(m_parent->GetRotation() * m_initialRotation);
@ -522,7 +523,7 @@ namespace Nz
break; break;
case CoordSys_Local: case CoordSys::Local:
m_rotation = q; m_rotation = q;
break; break;
} }
@ -540,14 +541,14 @@ namespace Nz
{ {
switch (coordSys) switch (coordSys)
{ {
case CoordSys_Global: case CoordSys::Global:
if (m_parent && m_inheritScale) if (m_parent && m_inheritScale)
m_scale = scale / (m_initialScale * m_parent->GetScale()); m_scale = scale / (m_initialScale * m_parent->GetScale());
else else
m_scale = scale / m_initialScale; m_scale = scale / m_initialScale;
break; break;
case CoordSys_Local: case CoordSys::Local:
m_scale = scale; m_scale = scale;
break; break;
} }
@ -567,9 +568,9 @@ namespace Nz
void Node::SetTransformMatrix(const Matrix4f& matrix) void Node::SetTransformMatrix(const Matrix4f& matrix)
{ {
SetPosition(matrix.GetTranslation(), CoordSys_Global); SetPosition(matrix.GetTranslation(), CoordSys::Global);
SetRotation(matrix.GetRotation(), CoordSys_Global); SetRotation(matrix.GetRotation(), CoordSys::Global);
SetScale(matrix.GetScale(), CoordSys_Global); SetScale(matrix.GetScale(), CoordSys::Global);
m_transformMatrix = matrix; m_transformMatrix = matrix;
m_transformMatrixUpdated = true; m_transformMatrixUpdated = true;

View File

@ -155,7 +155,7 @@ namespace Nz
const Joint* jointsA = &skeletonA.m_impl->joints[0]; const Joint* jointsA = &skeletonA.m_impl->joints[0];
const Joint* jointsB = &skeletonB.m_impl->joints[0]; const Joint* jointsB = &skeletonB.m_impl->joints[0];
for (std::size_t i = 0; i < m_impl->joints.size(); ++i) for (std::size_t i = 0; i < m_impl->joints.size(); ++i)
m_impl->joints[i].Interpolate(jointsA[i], jointsB[i], interpolation, CoordSys_Local); m_impl->joints[i].Interpolate(jointsA[i], jointsB[i], interpolation, CoordSys::Local);
InvalidateJoints(); InvalidateJoints();
} }
@ -174,7 +174,7 @@ namespace Nz
std::size_t index = indices[i]; std::size_t index = indices[i];
NazaraAssert(index < m_impl->joints.size(), "joint index out of range"); NazaraAssert(index < m_impl->joints.size(), "joint index out of range");
m_impl->joints[index].Interpolate(jointsA[index], jointsB[index], interpolation, CoordSys_Local); m_impl->joints[index].Interpolate(jointsA[index], jointsB[index], interpolation, CoordSys::Local);
} }
InvalidateJoints(); InvalidateJoints();

View File

@ -12,19 +12,19 @@ namespace Nz
{ {
UniformBuffer::UniformBuffer(std::shared_ptr<Buffer> buffer) UniformBuffer::UniformBuffer(std::shared_ptr<Buffer> buffer)
{ {
ErrorFlags(ErrorFlag_ThrowException, true); ErrorFlags(ErrorMode::ThrowException, true);
Reset(std::move(buffer)); Reset(std::move(buffer));
} }
UniformBuffer::UniformBuffer(std::shared_ptr<Buffer> buffer, UInt32 offset, UInt32 size) UniformBuffer::UniformBuffer(std::shared_ptr<Buffer> buffer, UInt32 offset, UInt32 size)
{ {
ErrorFlags(ErrorFlag_ThrowException, true); ErrorFlags(ErrorMode::ThrowException, true);
Reset(std::move(buffer), offset, size); Reset(std::move(buffer), offset, size);
} }
UniformBuffer::UniformBuffer(UInt32 length, DataStorage storage, BufferUsageFlags usage) UniformBuffer::UniformBuffer(UInt32 length, DataStorage storage, BufferUsageFlags usage)
{ {
ErrorFlags(ErrorFlag_ThrowException, true); ErrorFlags(ErrorMode::ThrowException, true);
Reset(length, storage, usage); Reset(length, storage, usage);
} }

View File

@ -11,19 +11,19 @@ namespace Nz
{ {
VertexBuffer::VertexBuffer(std::shared_ptr<const VertexDeclaration> vertexDeclaration, std::shared_ptr<Buffer> buffer) VertexBuffer::VertexBuffer(std::shared_ptr<const VertexDeclaration> vertexDeclaration, std::shared_ptr<Buffer> buffer)
{ {
ErrorFlags(ErrorFlag_ThrowException, true); ErrorFlags(ErrorMode::ThrowException, true);
Reset(std::move(vertexDeclaration), std::move(buffer)); Reset(std::move(vertexDeclaration), std::move(buffer));
} }
VertexBuffer::VertexBuffer(std::shared_ptr<const VertexDeclaration> vertexDeclaration, std::shared_ptr<Buffer> buffer, std::size_t offset, std::size_t size) VertexBuffer::VertexBuffer(std::shared_ptr<const VertexDeclaration> vertexDeclaration, std::shared_ptr<Buffer> buffer, std::size_t offset, std::size_t size)
{ {
ErrorFlags(ErrorFlag_ThrowException, true); ErrorFlags(ErrorMode::ThrowException, true);
Reset(std::move(vertexDeclaration), std::move(buffer), offset, size); Reset(std::move(vertexDeclaration), std::move(buffer), offset, size);
} }
VertexBuffer::VertexBuffer(std::shared_ptr<const VertexDeclaration> vertexDeclaration, std::size_t length, DataStorage storage, BufferUsageFlags usage) VertexBuffer::VertexBuffer(std::shared_ptr<const VertexDeclaration> vertexDeclaration, std::size_t length, DataStorage storage, BufferUsageFlags usage)
{ {
ErrorFlags(ErrorFlag_ThrowException, true); ErrorFlags(ErrorMode::ThrowException, true);
Reset(std::move(vertexDeclaration), length, storage, usage); Reset(std::move(vertexDeclaration), length, storage, usage);
} }

View File

@ -37,7 +37,7 @@ namespace Nz
VertexDeclaration::VertexDeclaration(VertexInputRate inputRate, std::initializer_list<ComponentEntry> components) : VertexDeclaration::VertexDeclaration(VertexInputRate inputRate, std::initializer_list<ComponentEntry> components) :
m_inputRate(inputRate) m_inputRate(inputRate)
{ {
ErrorFlags errFlags(ErrorFlag_ThrowException); ErrorFlags errFlags(ErrorMode::ThrowException);
std::size_t offset = 0; std::size_t offset = 0;
m_components.reserve(components.size()); m_components.reserve(components.size());
@ -99,7 +99,7 @@ namespace Nz
{ {
try try
{ {
ErrorFlags flags(ErrorFlag_Silent | ErrorFlag_ThrowException); ErrorFlags flags(ErrorMode::Silent | ErrorMode::ThrowException);
auto NewDeclaration = [](VertexInputRate inputRate, std::initializer_list<ComponentEntry> components) auto NewDeclaration = [](VertexInputRate inputRate, std::initializer_list<ComponentEntry> components)
{ {

View File

@ -14,7 +14,7 @@ namespace Nz
{ {
VertexMapper::VertexMapper(SubMesh& subMesh, BufferAccess access) VertexMapper::VertexMapper(SubMesh& subMesh, BufferAccess access)
{ {
ErrorFlags flags(ErrorFlag_ThrowException, true); ErrorFlags flags(ErrorMode::ThrowException, true);
std::shared_ptr<VertexBuffer> buffer = nullptr; std::shared_ptr<VertexBuffer> buffer = nullptr;
switch (subMesh.GetAnimationType()) switch (subMesh.GetAnimationType())
@ -44,13 +44,13 @@ namespace Nz
VertexMapper::VertexMapper(VertexBuffer& vertexBuffer, BufferAccess access) VertexMapper::VertexMapper(VertexBuffer& vertexBuffer, BufferAccess access)
{ {
ErrorFlags flags(ErrorFlag_ThrowException, true); ErrorFlags flags(ErrorMode::ThrowException, true);
m_mapper.Map(vertexBuffer, access); m_mapper.Map(vertexBuffer, access);
} }
VertexMapper::VertexMapper(const SubMesh& subMesh, BufferAccess access) VertexMapper::VertexMapper(const SubMesh& subMesh, BufferAccess access)
{ {
ErrorFlags flags(ErrorFlag_ThrowException, true); ErrorFlags flags(ErrorMode::ThrowException, true);
std::shared_ptr<VertexBuffer> buffer = nullptr; std::shared_ptr<VertexBuffer> buffer = nullptr;
switch (subMesh.GetAnimationType()) switch (subMesh.GetAnimationType())
@ -80,7 +80,7 @@ namespace Nz
VertexMapper::VertexMapper(const VertexBuffer& vertexBuffer, BufferAccess access) VertexMapper::VertexMapper(const VertexBuffer& vertexBuffer, BufferAccess access)
{ {
ErrorFlags flags(ErrorFlag_ThrowException, true); ErrorFlags flags(ErrorMode::ThrowException, true);
m_mapper.Map(vertexBuffer, access); m_mapper.Map(vertexBuffer, access);
} }

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