diff options
Diffstat (limited to 'Tools')
68 files changed, 2466 insertions, 1834 deletions
diff --git a/Tools/AnvilStats/AnvilStats.cpp b/Tools/AnvilStats/AnvilStats.cpp index 5c3a1708a..dafeba463 100644 --- a/Tools/AnvilStats/AnvilStats.cpp +++ b/Tools/AnvilStats/AnvilStats.cpp @@ -45,12 +45,12 @@ int main(int argc, char * argv[]) cCallbackFactory * Factory = NULL; switch (atol(argv[1])) { - case 0: Factory = new cStatisticsFactory; break; - case 1: Factory = new cBiomeMapFactory; break; - case 2: Factory = new cHeightMapFactory; break; + case 0: Factory = new cStatisticsFactory; break; + case 1: Factory = new cBiomeMapFactory; break; + case 2: Factory = new cHeightMapFactory; break; case 3: Factory = new cChunkExtractFactory(WorldFolder); break; - case 4: Factory = new cSpringStatsFactory; break; - case 5: Factory = new cHeightBiomeMapFactory; break; + case 4: Factory = new cSpringStatsFactory; break; + case 5: Factory = new cHeightBiomeMapFactory; break; default: { LOG("Unknown method \"%s\", aborting.", argv[1]); diff --git a/Tools/AnvilStats/BiomeMap.cpp b/Tools/AnvilStats/BiomeMap.cpp index edb971f85..1238bf7ac 100644 --- a/Tools/AnvilStats/BiomeMap.cpp +++ b/Tools/AnvilStats/BiomeMap.cpp @@ -11,22 +11,18 @@ -static const unsigned char g_BMPHeader[] = -{ - 0x42, 0x4D, 0x36, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x36, 0x00, 0x00, 0x00, 0x28, 0x00, - 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0xfe, 0xff, 0xff, 0x01, 0x00, 0x20, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x13, 0x0B, 0x00, 0x00, 0x13, 0x0B, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 -} ; +static const unsigned char g_BMPHeader[] = {0x42, 0x4D, 0x36, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x36, + 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, + 0x00, 0xfe, 0xff, 0xff, 0x01, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x10, 0x00, 0x13, 0x0B, 0x00, 0x00, 0x13, 0x0B, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; cBiomeMap::cBiomeMap(void) : - m_CurrentRegionX(0), - m_CurrentRegionZ(0), - m_IsCurrentRegionValid(false) + m_CurrentRegionX(0), m_CurrentRegionZ(0), m_IsCurrentRegionValid(false) { } @@ -105,7 +101,7 @@ void cBiomeMap::StartNewRegion(int a_RegionX, int a_RegionZ) for (int z = 0; z < 512; z++) { int RowData[512]; - unsigned char * BiomeRow = (unsigned char *)m_Biomes + z * 512; + unsigned char * BiomeRow = (unsigned char *) m_Biomes + z * 512; for (int x = 0; x < 512; x++) { RowData[x] = g_BiomeColors[BiomeRow[x]]; @@ -131,7 +127,7 @@ cBiomeMapFactory::~cBiomeMapFactory() // Force all threads to save their last regions: for (cCallbacks::iterator itr = m_Callbacks.begin(), end = m_Callbacks.end(); itr != end; ++itr) { - ((cBiomeMap *)(*itr))->Finish(); + ((cBiomeMap *) (*itr))->Finish(); } // TODO: Join all the files into one giant image file } diff --git a/Tools/AnvilStats/BiomeMap.h b/Tools/AnvilStats/BiomeMap.h index a2eb12a41..b61d881a5 100644 --- a/Tools/AnvilStats/BiomeMap.h +++ b/Tools/AnvilStats/BiomeMap.h @@ -15,16 +15,15 @@ -class cBiomeMap : - public cCallback +class cBiomeMap : public cCallback { -public: + public: cBiomeMap(void); /** Saves the last region that it was processing */ void Finish(void); -protected: + protected: int m_CurrentChunkX; // Absolute chunk coords int m_CurrentChunkZ; int m_CurrentChunkOffX; // Chunk offset from the start of the region @@ -37,29 +36,30 @@ protected: // cCallback overrides: virtual bool OnNewChunk(int a_ChunkX, int a_ChunkZ) override; virtual bool OnHeader(int a_FileOffset, unsigned char a_NumSectors, int a_Timestamp) override { return false; } - virtual bool OnCompressedDataSizePos(int a_CompressedDataSize, int a_DataOffset, char a_CompressionMethod) override { return false; } + virtual bool OnCompressedDataSizePos(int a_CompressedDataSize, int a_DataOffset, char a_CompressionMethod) override + { + return false; + } virtual bool OnDecompressedData(const char * a_DecompressedNBT, int a_DataSize) override { return false; } virtual bool OnRealCoords(int a_ChunkX, int a_ChunkZ) override { return false; } virtual bool OnLastUpdate(Int64 a_LastUpdate) override { return false; } - virtual bool OnTerrainPopulated(bool a_Populated) override { return false; } // We don't care about "populated", the biomes are the same + virtual bool OnTerrainPopulated(bool a_Populated) override + { + return false; + } // We don't care about "populated", the biomes are the same virtual bool OnBiomes(const unsigned char * a_BiomeData) override; void StartNewRegion(int a_RegionX, int a_RegionZ); -} ; +}; -class cBiomeMapFactory : - public cCallbackFactory +class cBiomeMapFactory : public cCallbackFactory { -public: + public: virtual ~cBiomeMapFactory(); - virtual cCallback * CreateNewCallback(void) override - { - return new cBiomeMap; - } - -} ; + virtual cCallback * CreateNewCallback(void) override { return new cBiomeMap; } +}; diff --git a/Tools/AnvilStats/Callback.h b/Tools/AnvilStats/Callback.h index 9b6554a8d..3e080f65d 100644 --- a/Tools/AnvilStats/Callback.h +++ b/Tools/AnvilStats/Callback.h @@ -24,19 +24,19 @@ class cParsedNBT; The processor calls each virtual function in the order they are declared here with the specified args. If the function returns true, the processor doesn't process the data item, moves on to the next chunk and starts calling the callbacks again from start with the new chunk data. -So if a statistics collector doesn't need data decompression at all, it can stop the processor from doing so early-enough -and still get meaningful data. -A callback is guaranteed to run in a single thread and always the same thread for the same chunk. -A callback is guaranteed to run on all chunks in a region and one region is guaranteed to be handled by only callback. +So if a statistics collector doesn't need data decompression at all, it can stop the processor from doing so +early-enough and still get meaningful data. A callback is guaranteed to run in a single thread and always the same +thread for the same chunk. A callback is guaranteed to run on all chunks in a region and one region is guaranteed to be +handled by only callback. */ class cCallback abstract { -public: + public: enum { CALLBACK_CONTINUE = false, - CALLBACK_ABORT = true, - } ; + CALLBACK_ABORT = true, + }; virtual ~cCallback() {} // Force a virtual destructor in each descendant @@ -46,11 +46,16 @@ public: /** Called to inform the stats module of the chunk coords for newly processing chunk */ virtual bool OnNewChunk(int a_ChunkX, int a_ChunkZ) = 0; - /** Called to inform about the chunk's data offset in the file (chunk mini-header), the number of sectors it uses and the timestamp field value */ + /** Called to inform about the chunk's data offset in the file (chunk mini-header), the number of sectors it uses + * and the timestamp field value */ virtual bool OnHeader(int a_FileOffset, unsigned char a_NumSectors, int a_Timestamp) { return CALLBACK_ABORT; } - /** Called to inform of the compressed chunk data size and position in the file (offset from file start to the actual data) */ - virtual bool OnCompressedDataSizePos(int a_CompressedDataSize, int a_DataOffset, char a_CompressionMethod) { return CALLBACK_ABORT; } + /** Called to inform of the compressed chunk data size and position in the file (offset from file start to the + * actual data) */ + virtual bool OnCompressedDataSizePos(int a_CompressedDataSize, int a_DataOffset, char a_CompressionMethod) + { + return CALLBACK_ABORT; + } /** Just in case you wanted to process the NBT yourself ;) */ virtual bool OnDecompressedData(const char * a_DecompressedNBT, int a_DataSize) { return CALLBACK_ABORT; } @@ -71,7 +76,8 @@ public: virtual bool OnHeightMap(const int * a_HeightMapBE) { return CALLBACK_ABORT; } /** If there is data for the section, this callback is called; otherwise OnEmptySection() is called instead. - All OnSection() callbacks are called first, and only then all the remaining sections are reported in OnEmptySection(). + All OnSection() callbacks are called first, and only then all the remaining sections are reported in + OnEmptySection(). */ virtual bool OnSection( unsigned char a_Y, @@ -80,7 +86,10 @@ public: const NIBBLETYPE * a_BlockMeta, const NIBBLETYPE * a_BlockLight, const NIBBLETYPE * a_BlockSkyLight - ) { return CALLBACK_ABORT; } + ) + { + return CALLBACK_ABORT; + } /** If there is no data for a section, this callback is called; otherwise OnSection() is called instead. OnEmptySection() callbacks are called after all OnSection() callbacks. @@ -88,7 +97,7 @@ public: virtual bool OnEmptySection(unsigned char a_Y) { return CALLBACK_CONTINUE; } /** Called after all sections have been processed via either OnSection() or OnEmptySection(). - */ + */ virtual bool OnSectionsFinished(void) { return CALLBACK_ABORT; } /** Called for each entity in the chunk. @@ -98,16 +107,24 @@ public: */ virtual bool OnEntity( const AString & a_EntityType, - double a_PosX, double a_PosY, double a_PosZ, - double a_SpeedX, double a_SpeedY, double a_SpeedZ, - float a_Yaw, float a_Pitch, + double a_PosX, + double a_PosY, + double a_PosZ, + double a_SpeedX, + double a_SpeedY, + double a_SpeedZ, + float a_Yaw, + float a_Pitch, float a_FallDistance, short a_FireTicksLeft, short a_AirTicks, char a_IsOnGround, cParsedNBT & a_NBT, int a_NBTTag - ) { return CALLBACK_ABORT; } + ) + { + return CALLBACK_ABORT; + } /** Called for each tile entity in the chunk. Common parameters are parsed from the NBT. @@ -116,21 +133,26 @@ public: */ virtual bool OnTileEntity( const AString & a_EntityType, - int a_PosX, int a_PosY, int a_PosZ, + int a_PosX, + int a_PosY, + int a_PosZ, cParsedNBT & a_NBT, int a_NBTTag - ) { return CALLBACK_ABORT; } + ) + { + return CALLBACK_ABORT; + } /** Called for each tile tick in the chunk */ - virtual bool OnTileTick( - int a_BlockType, - int a_TicksLeft, - int a_PosX, int a_PosY, int a_PosZ - ) { return CALLBACK_ABORT; } + virtual bool OnTileTick(int a_BlockType, int a_TicksLeft, int a_PosX, int a_PosY, int a_PosZ) + { + return CALLBACK_ABORT; + } - /** Called after the entire region file has been processed. No more callbacks for this region will be called. No processing by default */ + /** Called after the entire region file has been processed. No more callbacks for this region will be called. No + * processing by default */ virtual void OnRegionFinished(int a_RegionX, int a_RegionZ) {} -} ; +}; typedef std::vector<cCallback *> cCallbacks; @@ -145,7 +167,7 @@ The factory keeps track of all the callbacks that it has created and deletes the */ class cCallbackFactory { -public: + public: virtual ~cCallbackFactory() { for (cCallbacks::iterator itr = m_Callbacks.begin(), end = m_Callbacks.end(); itr != end; ++itr) @@ -168,6 +190,6 @@ public: return Callback; } -protected: + protected: cCallbacks m_Callbacks; -} ; +}; diff --git a/Tools/AnvilStats/ChunkExtract.cpp b/Tools/AnvilStats/ChunkExtract.cpp index fda09dfbd..67e8b4672 100644 --- a/Tools/AnvilStats/ChunkExtract.cpp +++ b/Tools/AnvilStats/ChunkExtract.cpp @@ -1,7 +1,8 @@ // ChunkExtract.cpp -// Implements the cChunkExtract class representing a cCallback descendant that extracts raw chunk data into separate .chunk files +// Implements the cChunkExtract class representing a cCallback descendant that extracts raw chunk data into separate +// .chunk files #include "Globals.h" #include "ChunkExtract.h" @@ -47,7 +48,10 @@ bool cChunkExtract::OnCompressedDataSizePos(int a_CompressedDataSize, int a_Data AString ChunkPath = Printf("%d.%d.zchunk", mCurChunkX, mCurChunkZ); if (!ChunkFile.Open(ChunkPath, cFile::fmWrite)) { - LOG("Cannot open zchunk file \"%s\" for writing. Chunk [%d, %d] skipped.", ChunkPath.c_str(), mCurChunkX, mCurChunkZ); + LOG("Cannot open zchunk file \"%s\" for writing. Chunk [%d, %d] skipped.", + ChunkPath.c_str(), + mCurChunkX, + mCurChunkZ); return false; } @@ -56,11 +60,12 @@ bool cChunkExtract::OnCompressedDataSizePos(int a_CompressedDataSize, int a_Data for (int BytesToCopy = a_CompressedDataSize; BytesToCopy > 0;) { char Buffer[64000]; - int NumBytes = std::min(BytesToCopy, (int)sizeof(Buffer)); + int NumBytes = std::min(BytesToCopy, (int) sizeof(Buffer)); int BytesRead = mAnvilFile.Read(Buffer, NumBytes); if (BytesRead != NumBytes) { - LOG("Cannot copy chunk data, chunk [%d, %d] is probably corrupted. Skipping chunk.", mCurChunkX, mCurChunkZ); + LOG("Cannot copy chunk data, chunk [%d, %d] is probably corrupted. Skipping chunk.", mCurChunkX, mCurChunkZ + ); return false; } ChunkFile.Write(Buffer, BytesRead); @@ -80,7 +85,10 @@ bool cChunkExtract::OnDecompressedData(const char * a_DecompressedNBT, int a_Dat cGZipFile GZipChunk; if (!GZipChunk.Open(FileName, cGZipFile::fmWrite)) { - LOG("Cannot open gzchunk file \"%s\" for writing. Chunk [%d, %d] skipped.", FileName.c_str(), mCurChunkX, mCurChunkZ); + LOG("Cannot open gzchunk file \"%s\" for writing. Chunk [%d, %d] skipped.", + FileName.c_str(), + mCurChunkX, + mCurChunkZ); return true; } GZipChunk.Write(a_DecompressedNBT, a_DataSize); diff --git a/Tools/AnvilStats/ChunkExtract.h b/Tools/AnvilStats/ChunkExtract.h index a5be2bc25..777589d5e 100644 --- a/Tools/AnvilStats/ChunkExtract.h +++ b/Tools/AnvilStats/ChunkExtract.h @@ -1,7 +1,8 @@ // ChunkExtract.h -// Declares the cChunkExtract class representing a cCallback descendant that extracts raw chunk data into separate .chunk files +// Declares the cChunkExtract class representing a cCallback descendant that extracts raw chunk data into separate +// .chunk files @@ -15,19 +16,18 @@ -class cChunkExtract : - public cCallback +class cChunkExtract : public cCallback { -public: + public: cChunkExtract(const AString & iWorldFolder); -protected: + protected: AString mWorldFolder; - cFile mAnvilFile; - int mCurAnvilX; // X-coord of mAnvilFile, in Anvil-coords (1 Anvil-coord = 32 chunks) - int mCurAnvilZ; // Z-coord of mAnvilFile, -"- - int mCurChunkX; // X-coord of the chunk being processed - int mCurChunkZ; // Z-coord of the chunk being processed + cFile mAnvilFile; + int mCurAnvilX; // X-coord of mAnvilFile, in Anvil-coords (1 Anvil-coord = 32 chunks) + int mCurAnvilZ; // Z-coord of mAnvilFile, -"- + int mCurChunkX; // X-coord of the chunk being processed + int mCurChunkZ; // Z-coord of the chunk being processed /** Opens new anvil file into mAnvilFile, sets mCurAnvilX and mCurAnvilZ */ void OpenAnvilFile(int a_AnvilX, int a_AnvilZ); @@ -37,26 +37,22 @@ protected: virtual bool OnHeader(int a_FileOffset, unsigned char a_NumSectors, int a_Timestamp) override { return false; } virtual bool OnCompressedDataSizePos(int a_CompressedDataSize, int a_DataOffset, char a_CompressionMethod) override; virtual bool OnDecompressedData(const char * a_DecompressedNBT, int a_DataSize) override; -} ; +}; -class cChunkExtractFactory : - public cCallbackFactory +class cChunkExtractFactory : public cCallbackFactory { -public: + public: cChunkExtractFactory(const AString & iWorldFolder) : mWorldFolder(iWorldFolder) { } - virtual cCallback * CreateNewCallback(void) override - { - return new cChunkExtract(mWorldFolder); - } + virtual cCallback * CreateNewCallback(void) override { return new cChunkExtract(mWorldFolder); } -protected: + protected: AString mWorldFolder; -} ; +}; diff --git a/Tools/AnvilStats/Globals.cpp b/Tools/AnvilStats/Globals.cpp index 13c6ae709..680afbf75 100644 --- a/Tools/AnvilStats/Globals.cpp +++ b/Tools/AnvilStats/Globals.cpp @@ -4,7 +4,3 @@ // This file is used for precompiled header generation in MSVC environments #include "Globals.h" - - - - diff --git a/Tools/AnvilStats/Globals.h b/Tools/AnvilStats/Globals.h index 18e2ab7c4..1cb3b6912 100644 --- a/Tools/AnvilStats/Globals.h +++ b/Tools/AnvilStats/Globals.h @@ -10,22 +10,22 @@ // Compiler-dependent stuff: #if defined(_MSC_VER) - // MSVC produces warning C4481 on the override keyword usage, so disable the warning altogether - #pragma warning(disable:4481) +// MSVC produces warning C4481 on the override keyword usage, so disable the warning altogether +#pragma warning(disable : 4481) - // Disable some warnings that we don't care about: - #pragma warning(disable:4100) +// Disable some warnings that we don't care about: +#pragma warning(disable : 4100) - #define _CRT_SECURE_NO_WARNINGS +#define _CRT_SECURE_NO_WARNINGS #elif defined(__GNUC__) - // TODO: Can GCC explicitly mark classes as abstract (no instances can be created)? - #define abstract +// TODO: Can GCC explicitly mark classes as abstract (no instances can be created)? +#define abstract #else - #error "You are using an unsupported compiler, you might need to #define some stuff here for your compiler" +#error "You are using an unsupported compiler, you might need to #define some stuff here for your compiler" #endif @@ -35,12 +35,12 @@ // Integral types with predefined sizes: typedef long long Int64; -typedef int Int32; -typedef short Int16; +typedef int Int32; +typedef short Int16; typedef unsigned long long UInt64; -typedef unsigned int UInt32; -typedef unsigned short UInt16; +typedef unsigned int UInt32; +typedef unsigned short UInt16; @@ -49,48 +49,48 @@ typedef unsigned short UInt16; // A macro to disallow the copy constructor and operator= functions // This should be used in the private: declarations for any class that shouldn't allow copying itself #define DISALLOW_COPY_AND_ASSIGN(TypeName) \ - TypeName(const TypeName &); \ + TypeName(const TypeName &); \ void operator=(const TypeName &) // A macro that is used to mark unused function parameters, to avoid pedantic warnings in gcc -#define UNUSED(X) (void)(X) +#define UNUSED(X) (void) (X) // OS-dependent stuff: #ifdef _WIN32 - #define WIN32_LEAN_AND_MEAN - #include <Windows.h> - #include <winsock2.h> - - // Windows SDK defines min and max macros, messing up with our std::min and std::max usage - #undef min - #undef max - - // Windows SDK defines GetFreeSpace as a constant, probably a Win16 API remnant - #ifdef GetFreeSpace - #undef GetFreeSpace - #endif // GetFreeSpace +#define WIN32_LEAN_AND_MEAN +#include <Windows.h> +#include <winsock2.h> + +// Windows SDK defines min and max macros, messing up with our std::min and std::max usage +#undef min +#undef max + +// Windows SDK defines GetFreeSpace as a constant, probably a Win16 API remnant +#ifdef GetFreeSpace +#undef GetFreeSpace +#endif // GetFreeSpace #else - #include <sys/types.h> - #include <sys/stat.h> // for mkdir - #include <sys/time.h> - #include <sys/socket.h> - #include <netinet/in.h> - #include <arpa/inet.h> - #include <netdb.h> - #include <time.h> - #include <dirent.h> - #include <errno.h> - #include <iostream> - - #include <cstdio> - #include <cstring> - #include <pthread.h> - #include <semaphore.h> - #include <errno.h> - #include <fcntl.h> +#include <sys/types.h> +#include <sys/stat.h> // for mkdir +#include <sys/time.h> +#include <sys/socket.h> +#include <netinet/in.h> +#include <arpa/inet.h> +#include <netdb.h> +#include <time.h> +#include <dirent.h> +#include <errno.h> +#include <iostream> + +#include <cstdio> +#include <cstring> +#include <pthread.h> +#include <semaphore.h> +#include <errno.h> +#include <fcntl.h> #endif @@ -146,21 +146,21 @@ typedef unsigned short UInt16; #define ARRAYCOUNT(X) (sizeof(X) / sizeof(*(X))) /** Allows arithmetic expressions like "32 KiB" (but consider using parenthesis around it, "(32 KiB)") */ -#define KiB * 1024 +#define KiB *1024 /** Allows arithmetic expressions like "32 MiB" (but consider using parenthesis around it, "(32 MiB)") */ -#define MiB * 1024 * 1024 +#define MiB *1024 * 1024 /** Faster than (int)floorf((float)x / (float)div) */ -#define FAST_FLOOR_DIV(x, div) ((x) < 0 ? (((int)x / div) - 1) : ((int)x / div)) +#define FAST_FLOOR_DIV(x, div) ((x) < 0 ? (((int) x / div) - 1) : ((int) x / div)) #define TOLUA_TEMPLATE_BIND(...) // Own version of assert() that writes failed assertions to the log for review -#ifdef _DEBUG - #define ASSERT(x) (!!(x) || (LOGERROR("Assertion failed: %s, file %s, line %i", #x, __FILE__, __LINE__), assert(0), 0)) +#ifdef _DEBUG +#define ASSERT(x) (!!(x) || (LOGERROR("Assertion failed: %s, file %s, line %i", #x, __FILE__, __LINE__), assert(0), 0)) #else - #define ASSERT(x) ((void)0) +#define ASSERT(x) ((void) 0) #endif // Pretty much the same as ASSERT() but stays in Release builds @@ -173,8 +173,7 @@ typedef unsigned char Byte; /** Clamp value to the specified range. */ -template <typename T> -T Clamp(T a_Value, T a_Min, T a_Max) +template <typename T> T Clamp(T a_Value, T a_Min, T a_Max) { return (a_Value < a_Min) ? a_Min : ((a_Value > a_Max) ? a_Max : a_Value); } diff --git a/Tools/AnvilStats/HeightBiomeMap.cpp b/Tools/AnvilStats/HeightBiomeMap.cpp index fcbc5f4df..430a1aec1 100644 --- a/Tools/AnvilStats/HeightBiomeMap.cpp +++ b/Tools/AnvilStats/HeightBiomeMap.cpp @@ -12,11 +12,7 @@ cHeightBiomeMap::cHeightBiomeMap(void) : - super("HeBi"), - m_MinRegionX(100000), - m_MaxRegionX(-100000), - m_MinRegionZ(100000), - m_MaxRegionZ(-100000) + super("HeBi"), m_MinRegionX(100000), m_MaxRegionX(-100000), m_MinRegionZ(100000), m_MaxRegionZ(-100000) { } @@ -68,7 +64,6 @@ bool cHeightBiomeMap::OnNewChunk(int a_ChunkX, int a_ChunkZ) - bool cHeightBiomeMap::OnBiomes(const unsigned char * a_BiomeData) { memcpy(m_ChunkBiomes, a_BiomeData, sizeof(m_ChunkBiomes)); @@ -114,8 +109,7 @@ bool cHeightBiomeMap::OnSection( bool cHeightBiomeMap::OnSectionsFinished(void) { - static const int BiomePalette[] = - { + static const int BiomePalette[] = { // ARGB: 0xff0000ff, /* Ocean */ 0xff00cf3f, /* Plains */ @@ -140,7 +134,7 @@ bool cHeightBiomeMap::OnSectionsFinished(void) 0xff7f8f7f, /* Extreme Hills Edge */ 0xff004f00, /* Jungle */ 0xff003f00, /* Jungle Hills */ - } ; + }; // Remove trees and other unwanted stuff from the heightmap: for (int z = 0; z < 16; z++) @@ -185,7 +179,7 @@ cHeightBiomeMapFactory::~cHeightBiomeMapFactory() int MaxRegionZ = -100000; for (cCallbacks::iterator itr = m_Callbacks.begin(), end = m_Callbacks.end(); itr != end; ++itr) { - cHeightBiomeMap * cb = (cHeightBiomeMap *)(*itr); + cHeightBiomeMap * cb = (cHeightBiomeMap *) (*itr); if (cb->m_MinRegionX < MinRegionX) { MinRegionX = cb->m_MinRegionX; @@ -205,7 +199,8 @@ cHeightBiomeMapFactory::~cHeightBiomeMapFactory() } // If the size is small enough, write an HTML file referencing all the images in a table: - if ((MaxRegionX >= MinRegionX) && (MaxRegionZ >= MinRegionZ) && (MaxRegionX - MinRegionX < 100) && (MaxRegionZ - MinRegionZ < 100)) + if ((MaxRegionX >= MinRegionX) && (MaxRegionZ >= MinRegionZ) && (MaxRegionX - MinRegionX < 100) && + (MaxRegionZ - MinRegionZ < 100)) { cFile HTML("HeBi.html", cFile::fmWrite); if (HTML.IsOpen()) diff --git a/Tools/AnvilStats/HeightBiomeMap.h b/Tools/AnvilStats/HeightBiomeMap.h index 8a2cb9726..16d4ef308 100644 --- a/Tools/AnvilStats/HeightBiomeMap.h +++ b/Tools/AnvilStats/HeightBiomeMap.h @@ -15,40 +15,51 @@ -class cHeightBiomeMap : - public cImageComposingCallback +class cHeightBiomeMap : public cImageComposingCallback { typedef cImageComposingCallback super; -public: + public: // Minima and maxima for the regions processed through this callback int m_MinRegionX, m_MaxRegionX; int m_MinRegionZ, m_MaxRegionZ; cHeightBiomeMap(void); -protected: + protected: int m_CurrentChunkX; // Absolute chunk coords int m_CurrentChunkZ; int m_CurrentChunkRelX; // Chunk offset from the start of the region int m_CurrentChunkRelZ; /** Biome-map for the current chunk */ - char m_ChunkBiomes[16 * 16]; + char m_ChunkBiomes[16 * 16]; /** Height-map for the current chunk */ - int m_ChunkHeight[16 * 16]; + int m_ChunkHeight[16 * 16]; /** Block data for the current chunk (between OnSection() and OnSectionsFinished()) */ - BLOCKTYPE m_BlockTypes [16 * 16 * 256]; + BLOCKTYPE m_BlockTypes[16 * 16 * 256]; // cCallback overrides: virtual bool OnNewRegion(int a_RegionX, int a_RegionZ) override; virtual bool OnNewChunk(int a_ChunkX, int a_ChunkZ) override; - virtual bool OnHeader(int a_FileOffset, unsigned char a_NumSectors, int a_Timestamp) override { return CALLBACK_CONTINUE; } - virtual bool OnCompressedDataSizePos(int a_CompressedDataSize, int a_DataOffset, char a_CompressionMethod) override { return CALLBACK_CONTINUE; } - virtual bool OnDecompressedData(const char * a_DecompressedNBT, int a_DataSize) override { return CALLBACK_CONTINUE; } + virtual bool OnHeader(int a_FileOffset, unsigned char a_NumSectors, int a_Timestamp) override + { + return CALLBACK_CONTINUE; + } + virtual bool OnCompressedDataSizePos(int a_CompressedDataSize, int a_DataOffset, char a_CompressionMethod) override + { + return CALLBACK_CONTINUE; + } + virtual bool OnDecompressedData(const char * a_DecompressedNBT, int a_DataSize) override + { + return CALLBACK_CONTINUE; + } virtual bool OnRealCoords(int a_ChunkX, int a_ChunkZ) override { return CALLBACK_CONTINUE; } virtual bool OnLastUpdate(Int64 a_LastUpdate) override { return CALLBACK_CONTINUE; } - virtual bool OnTerrainPopulated(bool a_Populated) override { return a_Populated ? CALLBACK_CONTINUE : CALLBACK_ABORT; } // If not populated, we don't want it! + virtual bool OnTerrainPopulated(bool a_Populated) override + { + return a_Populated ? CALLBACK_CONTINUE : CALLBACK_ABORT; + } // If not populated, we don't want it! virtual bool OnBiomes(const unsigned char * a_BiomeData) override; virtual bool OnHeightMap(const int * a_HeightMapBE) override; virtual bool OnSection( @@ -60,21 +71,16 @@ protected: const NIBBLETYPE * a_BlockSkyLight ) override; virtual bool OnSectionsFinished(void) override; - -} ; +}; -class cHeightBiomeMapFactory : - public cCallbackFactory +class cHeightBiomeMapFactory : public cCallbackFactory { -public: + public: virtual ~cHeightBiomeMapFactory(); - virtual cCallback * CreateNewCallback(void) override - { - return new cHeightBiomeMap; - } -} ; + virtual cCallback * CreateNewCallback(void) override { return new cHeightBiomeMap; } +}; diff --git a/Tools/AnvilStats/HeightMap.cpp b/Tools/AnvilStats/HeightMap.cpp index 74ce1bf50..ee42200ac 100644 --- a/Tools/AnvilStats/HeightMap.cpp +++ b/Tools/AnvilStats/HeightMap.cpp @@ -9,22 +9,18 @@ -static const unsigned char g_BMPHeader[] = -{ - 0x42, 0x4D, 0x36, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x36, 0x00, 0x00, 0x00, 0x28, 0x00, - 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0xfe, 0xff, 0xff, 0x01, 0x00, 0x20, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x13, 0x0B, 0x00, 0x00, 0x13, 0x0B, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 -} ; +static const unsigned char g_BMPHeader[] = {0x42, 0x4D, 0x36, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x36, + 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, + 0x00, 0xfe, 0xff, 0xff, 0x01, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x10, 0x00, 0x13, 0x0B, 0x00, 0x00, 0x13, 0x0B, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; cHeightMap::cHeightMap(void) : - m_CurrentRegionX(0), - m_CurrentRegionZ(0), - m_IsCurrentRegionValid(false) + m_CurrentRegionX(0), m_CurrentRegionZ(0), m_IsCurrentRegionValid(false) { } @@ -207,7 +203,8 @@ bool cHeightMap::IsGround(BLOCKTYPE a_BlockType) case E_BLOCK_LEAVES: case E_BLOCK_LEVER: case E_BLOCK_LILY_PAD: - case E_BLOCK_LOG: // NOTE: This block is actually solid, but we don't want it because it's the thing that trees are made of, and we're getting rid of trees + case E_BLOCK_LOG: // NOTE: This block is actually solid, but we don't want it because it's the thing that trees + // are made of, and we're getting rid of trees case E_BLOCK_MELON: case E_BLOCK_MELON_STEM: case E_BLOCK_NETHER_BRICK_FENCE: @@ -261,7 +258,7 @@ cHeightMapFactory::~cHeightMapFactory() // Force all threads to save their last regions: for (cCallbacks::iterator itr = m_Callbacks.begin(), end = m_Callbacks.end(); itr != end; ++itr) { - ((cHeightMap *)(*itr))->Finish(); + ((cHeightMap *) (*itr))->Finish(); } // TODO: Join all the files into one giant image file } diff --git a/Tools/AnvilStats/HeightMap.h b/Tools/AnvilStats/HeightMap.h index 69deb5bab..9d62febfc 100644 --- a/Tools/AnvilStats/HeightMap.h +++ b/Tools/AnvilStats/HeightMap.h @@ -15,17 +15,16 @@ -class cHeightMap : - public cCallback +class cHeightMap : public cCallback { -public: + public: cHeightMap(void); void Finish(void); static bool IsGround(BLOCKTYPE a_BlockType); -protected: + protected: int m_CurrentChunkX; // Absolute chunk coords int m_CurrentChunkZ; int m_CurrentChunkOffX; // Chunk offset from the start of the region @@ -34,18 +33,24 @@ protected: int m_CurrentRegionZ; bool m_IsCurrentRegionValid; /** Height-map of the entire current region [x + 16 * 32 * z] */ - int m_Height[16 * 32 * 16 * 32]; + int m_Height[16 * 32 * 16 * 32]; /** Block data of the currently processed chunk (between OnSection() and OnSectionsFinished()) */ BLOCKTYPE m_BlockTypes[16 * 16 * 256]; // cCallback overrides: virtual bool OnNewChunk(int a_ChunkX, int a_ChunkZ) override; virtual bool OnHeader(int a_FileOffset, unsigned char a_NumSectors, int a_Timestamp) override { return false; } - virtual bool OnCompressedDataSizePos(int a_CompressedDataSize, int a_DataOffset, char a_CompressionMethod) override { return false; } + virtual bool OnCompressedDataSizePos(int a_CompressedDataSize, int a_DataOffset, char a_CompressionMethod) override + { + return false; + } virtual bool OnDecompressedData(const char * a_DecompressedNBT, int a_DataSize) override { return false; } virtual bool OnRealCoords(int a_ChunkX, int a_ChunkZ) override { return false; } virtual bool OnLastUpdate(Int64 a_LastUpdate) override { return false; } - virtual bool OnTerrainPopulated(bool a_Populated) override { return !a_Populated; } // If not populated, we don't want it! + virtual bool OnTerrainPopulated(bool a_Populated) override + { + return !a_Populated; + } // If not populated, we don't want it! virtual bool OnBiomes(const unsigned char * a_BiomeData) { return false; } virtual bool OnHeightMap(const int * a_HeightMapBE) override; virtual bool OnSection( @@ -59,21 +64,16 @@ protected: virtual bool OnSectionsFinished(void) override; void StartNewRegion(int a_RegionX, int a_RegionZ); -} ; +}; -class cHeightMapFactory : - public cCallbackFactory +class cHeightMapFactory : public cCallbackFactory { -public: + public: virtual ~cHeightMapFactory(); - virtual cCallback * CreateNewCallback(void) override - { - return new cHeightMap; - } - -} ; + virtual cCallback * CreateNewCallback(void) override { return new cHeightMap; } +}; diff --git a/Tools/AnvilStats/ImageComposingCallback.cpp b/Tools/AnvilStats/ImageComposingCallback.cpp index cc200b9a4..0bf11a815 100644 --- a/Tools/AnvilStats/ImageComposingCallback.cpp +++ b/Tools/AnvilStats/ImageComposingCallback.cpp @@ -145,7 +145,6 @@ int cImageComposingCallback::GetPixel(int a_RelU, int a_RelV) - void cImageComposingCallback::SetPixelURow(int a_RelUStart, int a_RelV, int a_CountU, int * a_Pixels) { ASSERT((a_RelUStart >= 0) && (a_RelUStart + a_CountU <= IMAGE_WIDTH)); @@ -202,13 +201,11 @@ void cImageComposingCallback::SaveImage(const AString & a_FileName) } // Header for BMP files (is the same for the same-size files) - static const unsigned char BMPHeader[] = - { - 0x42, 0x4D, 0x36, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x36, 0x00, 0x00, 0x00, 0x28, 0x00, - 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0xfe, 0xff, 0xff, 0x01, 0x00, 0x20, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x13, 0x0B, 0x00, 0x00, 0x13, 0x0B, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 - } ; + static const unsigned char BMPHeader[] = {0x42, 0x4D, 0x36, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x36, + 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, + 0x00, 0xfe, 0xff, 0xff, 0x01, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x10, 0x00, 0x13, 0x0B, 0x00, 0x00, 0x13, 0x0B, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; f.Write(BMPHeader, sizeof(BMPHeader)); f.Write(m_ImageData, PIXEL_COUNT * 4); diff --git a/Tools/AnvilStats/ImageComposingCallback.h b/Tools/AnvilStats/ImageComposingCallback.h index 916e61d92..6a1288fef 100644 --- a/Tools/AnvilStats/ImageComposingCallback.h +++ b/Tools/AnvilStats/ImageComposingCallback.h @@ -21,17 +21,16 @@ SetPixel() or SetPixelURow() functions. For the purpose of this class the image data is indexed U (horz) * V (vert), to avoid confusion with other coords. The image is a 32bpp raw imagedata, written into a BMP file. */ -class cImageComposingCallback : - public cCallback +class cImageComposingCallback : public cCallback { -public: + public: enum { INVALID_REGION_COORD = 99999, ///< Used for un-assigned region coords IMAGE_WIDTH = 32 * 16, IMAGE_HEIGHT = 32 * 16, PIXEL_COUNT = IMAGE_WIDTH * IMAGE_HEIGHT, ///< Total pixel count of the image data - } ; + }; cImageComposingCallback(const AString & a_FileNamePrefix); virtual ~cImageComposingCallback(); @@ -59,7 +58,8 @@ public: /** Erases the entire image with the specified color */ void EraseImage(int a_Color); - /** Erases the specified chunk's portion of the image with the specified color. Note that chunk coords are relative to the current region */ + /** Erases the specified chunk's portion of the image with the specified color. Note that chunk coords are relative + * to the current region */ void EraseChunk(int a_Color, int a_RelChunkX, int a_RelChunkZ); /** Returns the current region X coord */ @@ -74,7 +74,8 @@ public: /** Returns the color of the pixel at the specified UV coords; -1 if outside */ int GetPixel(int a_RelU, int a_RelV); - /** Sets a row of pixels. a_Pixels is expected to be a_CountU pixels wide. a_RelUStart + a_CountU is assumed less than image width */ + /** Sets a row of pixels. a_Pixels is expected to be a_CountU pixels wide. a_RelUStart + a_CountU is assumed less + * than image width */ void SetPixelURow(int a_RelUStart, int a_RelV, int a_CountU, int * a_Pixels); /** "Shades" the given color based on the shade amount given @@ -87,7 +88,7 @@ public: /** Mixes the two colors in the specified ratio; a_Ratio is between 0 and 256, 0 returning a_Src */ static int MixColor(int a_Src, int a_Dest, int a_Ratio); -protected: + protected: /** Prefix for the filenames, when generated by the default GetFileName() function */ AString m_FileNamePrefix; @@ -98,4 +99,4 @@ protected: int * m_ImageData; void SaveImage(const AString & a_FileName); -} ; +}; diff --git a/Tools/AnvilStats/Processor.cpp b/Tools/AnvilStats/Processor.cpp index d0bdad0ca..7a1227d25 100644 --- a/Tools/AnvilStats/Processor.cpp +++ b/Tools/AnvilStats/Processor.cpp @@ -24,9 +24,7 @@ const int CHUNK_INFLATE_MAX = 1 MiB; // cProcessor::cThread: cProcessor::cThread::cThread(cCallback & a_Callback, cProcessor & a_ParentProcessor) : - super("cProcessor::cThread"), - m_Callback(a_Callback), - m_ParentProcessor(a_ParentProcessor) + super("cProcessor::cThread"), m_Callback(a_Callback), m_ParentProcessor(a_ParentProcessor) { LOG("Created a new thread: %p", this); super::Start(); @@ -119,7 +117,7 @@ void cProcessor::cThread::ProcessFile(const AString & a_FileName) void cProcessor::cThread::ProcessFileData(const char * a_FileData, size_t a_Size, int a_ChunkBaseX, int a_ChunkBaseZ) { int Header[2048]; - int * HeaderPtr = (int *)a_FileData; + int * HeaderPtr = (int *) a_FileData; for (int i = 0; i < ARRAYCOUNT(Header); i++) { Header[i] = ntohl(HeaderPtr[i]); @@ -129,11 +127,10 @@ void cProcessor::cThread::ProcessFileData(const char * a_FileData, size_t a_Size { unsigned Location = Header[i]; unsigned Timestamp = Header[i + 1024]; - if ( - ((Location == 0) && (Timestamp == 0)) || // Official docs' "not present" - (Location >> 8 < 2) || // Logical - no chunk can start inside the header - ((Location & 0xff) == 0) || // Logical - no chunk can be zero bytes - ((Location >> 8) * 4096 > a_Size) // Logical - no chunk can start at beyond the file end + if (((Location == 0) && (Timestamp == 0)) || // Official docs' "not present" + (Location >> 8 < 2) || // Logical - no chunk can start inside the header + ((Location & 0xff) == 0) || // Logical - no chunk can be zero bytes + ((Location >> 8) * 4096 > a_Size) // Logical - no chunk can start at beyond the file end ) { // Chunk not present in the file @@ -153,7 +150,14 @@ void cProcessor::cThread::ProcessFileData(const char * a_FileData, size_t a_Size -void cProcessor::cThread::ProcessChunk(const char * a_FileData, int a_ChunkX, int a_ChunkZ, unsigned a_SectorStart, unsigned a_SectorSize, unsigned a_TimeStamp) +void cProcessor::cThread::ProcessChunk( + const char * a_FileData, + int a_ChunkX, + int a_ChunkZ, + unsigned a_SectorStart, + unsigned a_SectorSize, + unsigned a_TimeStamp +) { if (m_Callback.OnHeader(a_SectorStart * 4096, a_SectorSize, a_TimeStamp)) { @@ -161,7 +165,7 @@ void cProcessor::cThread::ProcessChunk(const char * a_FileData, int a_ChunkX, in } const char * ChunkStart = a_FileData + a_SectorStart * 4096; - int ByteSize = ntohl(*(int *)ChunkStart); + int ByteSize = ntohl(*(int *) ChunkStart); char CompressionMethod = ChunkStart[4]; if (m_Callback.OnCompressedDataSizePos(ByteSize, a_SectorStart * 4096 + 5, CompressionMethod)) @@ -176,18 +180,23 @@ void cProcessor::cThread::ProcessChunk(const char * a_FileData, int a_ChunkX, in -void cProcessor::cThread::ProcessCompressedChunkData(int a_ChunkX, int a_ChunkZ, const char * a_CompressedData, int a_CompressedSize) +void cProcessor::cThread::ProcessCompressedChunkData( + int a_ChunkX, + int a_ChunkZ, + const char * a_CompressedData, + int a_CompressedSize +) { char Decompressed[CHUNK_INFLATE_MAX]; z_stream strm; - strm.zalloc = (alloc_func)NULL; - strm.zfree = (free_func)NULL; + strm.zalloc = (alloc_func) NULL; + strm.zfree = (free_func) NULL; strm.opaque = NULL; inflateInit(&strm); - strm.next_out = (Bytef *)Decompressed; + strm.next_out = (Bytef *) Decompressed; strm.avail_out = sizeof(Decompressed); - strm.next_in = (Bytef *)a_CompressedData; - strm.avail_in = a_CompressedSize; + strm.next_in = (Bytef *) a_CompressedData; + strm.avail_in = a_CompressedSize; int res = inflate(&strm, Z_FINISH); inflateEnd(&strm); if (res != Z_STREAM_END) @@ -255,7 +264,7 @@ void cProcessor::cThread::ProcessParsedChunkData(int a_ChunkX, int a_ChunkZ, cPa int BiomesTag = a_NBT.FindChildByName(LevelTag, "Biomes"); if (BiomesTag > 0) { - if (m_Callback.OnBiomes((const unsigned char *)(a_NBT.GetData(BiomesTag)))) + if (m_Callback.OnBiomes((const unsigned char *) (a_NBT.GetData(BiomesTag)))) { return; } @@ -264,7 +273,7 @@ void cProcessor::cThread::ProcessParsedChunkData(int a_ChunkX, int a_ChunkZ, cPa int HeightMapTag = a_NBT.FindChildByName(LevelTag, "HeightMap"); if (HeightMapTag > 0) { - if (m_Callback.OnHeightMap((const int *)(a_NBT.GetData(HeightMapTag)))) + if (m_Callback.OnHeightMap((const int *) (a_NBT.GetData(HeightMapTag)))) { return; } @@ -307,12 +316,12 @@ bool cProcessor::cThread::ProcessChunkSections(int a_ChunkX, int a_ChunkZ, cPars memset(SectionProcessed, 0, sizeof(SectionProcessed)); for (int Tag = a_NBT.GetFirstChild(Sections); Tag > 0; Tag = a_NBT.GetNextSibling(Tag)) { - int YTag = a_NBT.FindChildByName(Tag, "Y"); - int BlocksTag = a_NBT.FindChildByName(Tag, "Blocks"); - int AddTag = a_NBT.FindChildByName(Tag, "Add"); - int DataTag = a_NBT.FindChildByName(Tag, "Data"); + int YTag = a_NBT.FindChildByName(Tag, "Y"); + int BlocksTag = a_NBT.FindChildByName(Tag, "Blocks"); + int AddTag = a_NBT.FindChildByName(Tag, "Add"); + int DataTag = a_NBT.FindChildByName(Tag, "Data"); int BlockLightTag = a_NBT.FindChildByName(Tag, "BlockLightTag"); - int SkyLightTag = a_NBT.FindChildByName(Tag, "SkyLight"); + int SkyLightTag = a_NBT.FindChildByName(Tag, "SkyLight"); if ((YTag < 0) || (BlocksTag < 0) || (DataTag < 0)) { @@ -326,13 +335,13 @@ bool cProcessor::cThread::ProcessChunkSections(int a_ChunkX, int a_ChunkZ, cPars continue; } if (m_Callback.OnSection( - SectionY, - (const BLOCKTYPE *) (a_NBT.GetData(BlocksTag)), - (AddTag > 0) ? (const NIBBLETYPE *)(a_NBT.GetData(AddTag)) : NULL, - (const NIBBLETYPE *)(a_NBT.GetData(DataTag)), - (BlockLightTag > 0) ? (const NIBBLETYPE *)(a_NBT.GetData(BlockLightTag)) : NULL, - (BlockLightTag > 0) ? (const NIBBLETYPE *)(a_NBT.GetData(BlockLightTag)) : NULL - )) + SectionY, + (const BLOCKTYPE *) (a_NBT.GetData(BlocksTag)), + (AddTag > 0) ? (const NIBBLETYPE *) (a_NBT.GetData(AddTag)) : NULL, + (const NIBBLETYPE *) (a_NBT.GetData(DataTag)), + (BlockLightTag > 0) ? (const NIBBLETYPE *) (a_NBT.GetData(BlockLightTag)) : NULL, + (BlockLightTag > 0) ? (const NIBBLETYPE *) (a_NBT.GetData(BlockLightTag)) : NULL + )) { return true; } @@ -405,16 +414,22 @@ bool cProcessor::cThread::ProcessChunkEntities(int a_ChunkX, int a_ChunkZ, cPars } if (m_Callback.OnEntity( - a_NBT.GetString(a_NBT.FindChildByName(EntityTag, "id")), - Pos[0], Pos[1], Pos[2], - Speed[0], Speed[1], Speed[2], - Rot[0], Rot[1], - a_NBT.GetFloat(a_NBT.FindChildByName(EntityTag, "FallDistance")), - a_NBT.GetShort(a_NBT.FindChildByName(EntityTag, "Fire")), - a_NBT.GetShort(a_NBT.FindChildByName(EntityTag, "Air")), - a_NBT.GetByte(a_NBT.FindChildByName(EntityTag, "OnGround")), - a_NBT, EntityTag - )) + a_NBT.GetString(a_NBT.FindChildByName(EntityTag, "id")), + Pos[0], + Pos[1], + Pos[2], + Speed[0], + Speed[1], + Speed[2], + Rot[0], + Rot[1], + a_NBT.GetFloat(a_NBT.FindChildByName(EntityTag, "FallDistance")), + a_NBT.GetShort(a_NBT.FindChildByName(EntityTag, "Fire")), + a_NBT.GetShort(a_NBT.FindChildByName(EntityTag, "Air")), + a_NBT.GetByte(a_NBT.FindChildByName(EntityTag, "OnGround")), + a_NBT, + EntityTag + )) { return true; } @@ -434,15 +449,17 @@ bool cProcessor::cThread::ProcessChunkTileEntities(int a_ChunkX, int a_ChunkZ, c return false; } - for (int TileEntityTag = a_NBT.GetFirstChild(TileEntitiesTag); TileEntityTag > 0; TileEntityTag = a_NBT.GetNextSibling(TileEntityTag)) + for (int TileEntityTag = a_NBT.GetFirstChild(TileEntitiesTag); TileEntityTag > 0; + TileEntityTag = a_NBT.GetNextSibling(TileEntityTag)) { if (m_Callback.OnTileEntity( - a_NBT.GetString(a_NBT.FindChildByName(TileEntityTag, "id")), - a_NBT.GetInt(a_NBT.FindChildByName(TileEntityTag, "x")), - a_NBT.GetInt(a_NBT.FindChildByName(TileEntityTag, "y")), - a_NBT.GetInt(a_NBT.FindChildByName(TileEntityTag, "z")), - a_NBT, TileEntityTag - )) + a_NBT.GetString(a_NBT.FindChildByName(TileEntityTag, "id")), + a_NBT.GetInt(a_NBT.FindChildByName(TileEntityTag, "x")), + a_NBT.GetInt(a_NBT.FindChildByName(TileEntityTag, "y")), + a_NBT.GetInt(a_NBT.FindChildByName(TileEntityTag, "z")), + a_NBT, + TileEntityTag + )) { return true; } @@ -462,7 +479,8 @@ bool cProcessor::cThread::ProcessChunkTileTicks(int a_ChunkX, int a_ChunkZ, cPar return false; } - for (int TileTickTag = a_NBT.GetFirstChild(TileTicksTag); TileTickTag > 0; TileTickTag = a_NBT.GetNextSibling(TileTickTag)) + for (int TileTickTag = a_NBT.GetFirstChild(TileTicksTag); TileTickTag > 0; + TileTickTag = a_NBT.GetNextSibling(TileTickTag)) { int iTag = a_NBT.FindChildByName(TileTicksTag, "i"); int tTag = a_NBT.FindChildByName(TileTicksTag, "t"); @@ -474,12 +492,12 @@ bool cProcessor::cThread::ProcessChunkTileTicks(int a_ChunkX, int a_ChunkZ, cPar continue; } if (m_Callback.OnTileTick( - a_NBT.GetInt(iTag), - a_NBT.GetInt(iTag), - a_NBT.GetInt(iTag), - a_NBT.GetInt(iTag), - a_NBT.GetInt(iTag) - )) + a_NBT.GetInt(iTag), + a_NBT.GetInt(iTag), + a_NBT.GetInt(iTag), + a_NBT.GetInt(iTag), + a_NBT.GetInt(iTag) + )) { return true; } @@ -503,9 +521,7 @@ cProcessor::cProcessor(void) : -cProcessor::~cProcessor() -{ -} +cProcessor::~cProcessor() {} diff --git a/Tools/AnvilStats/Processor.h b/Tools/AnvilStats/Processor.h index 30f160404..426e67d91 100644 --- a/Tools/AnvilStats/Processor.h +++ b/Tools/AnvilStats/Processor.h @@ -1,7 +1,8 @@ // Processor.h -// Interfaces to the cProcessor class representing the overall processor engine that manages threads, calls callbacks etc. +// Interfaces to the cProcessor class representing the overall processor engine that manages threads, calls callbacks +// etc. @@ -23,12 +24,11 @@ class cParsedNBT; class cProcessor { - class cThread : - public cIsThread + class cThread : public cIsThread { typedef cIsThread super; - cCallback & m_Callback; + cCallback & m_Callback; cProcessor & m_ParentProcessor; cEvent m_HasStarted; @@ -37,36 +37,49 @@ class cProcessor void ProcessFile(const AString & a_FileName); void ProcessFileData(const char * a_FileData, size_t a_Size, int a_ChunkBaseX, int a_ChunkBaseZ); - void ProcessChunk(const char * a_FileData, int a_ChunkX, int a_ChunkZ, unsigned a_SectorStart, unsigned a_SectorSize, unsigned a_TimeStamp); - void ProcessCompressedChunkData(int a_ChunkX, int a_ChunkZ, const char * a_CompressedData, int a_CompressedSize); + void ProcessChunk( + const char * a_FileData, + int a_ChunkX, + int a_ChunkZ, + unsigned a_SectorStart, + unsigned a_SectorSize, + unsigned a_TimeStamp + ); + void ProcessCompressedChunkData( + int a_ChunkX, + int a_ChunkZ, + const char * a_CompressedData, + int a_CompressedSize + ); void ProcessParsedChunkData(int a_ChunkX, int a_ChunkZ, cParsedNBT & a_NBT); - // The following processing parts return true if they were interrupted by the callback, causing the processing of current chunk to abort + // The following processing parts return true if they were interrupted by the callback, causing the processing + // of current chunk to abort bool ProcessChunkSections(int a_ChunkX, int a_ChunkZ, cParsedNBT & a_NBT, int a_LevelTag); bool ProcessChunkEntities(int a_ChunkX, int a_ChunkZ, cParsedNBT & a_NBT, int a_LevelTag); bool ProcessChunkTileEntities(int a_ChunkX, int a_ChunkZ, cParsedNBT & a_NBT, int a_LevelTag); bool ProcessChunkTileTicks(int a_ChunkX, int a_ChunkZ, cParsedNBT & a_NBT, int a_LevelTag); - public: + public: cThread(cCallback & a_Callback, cProcessor & a_ParentProcessor); /** Waits until the thread starts processing the callback code. */ void WaitForStart(void); - } ; + }; typedef std::vector<cThread *> cThreads; -public: + public: cProcessor(void); ~cProcessor(); void ProcessWorld(const AString & a_WorldFolder, cCallbackFactory & a_CallbackFactory); -protected: + protected: bool m_IsShuttingDown; // If true, the threads should stop ASAP cCriticalSection m_CS; - AStringList m_FileQueue; + AStringList m_FileQueue; cThreads m_Threads; @@ -76,4 +89,4 @@ protected: /** Returns one filename from m_FileQueue, and removes the name from the queue. */ AString GetOneFileName(void); -} ; +}; diff --git a/Tools/AnvilStats/SpringStats.cpp b/Tools/AnvilStats/SpringStats.cpp index ccc0c8e45..1a3777c61 100644 --- a/Tools/AnvilStats/SpringStats.cpp +++ b/Tools/AnvilStats/SpringStats.cpp @@ -1,7 +1,8 @@ // SpringStats.cpp -// Implements the cSpringStats class representing a cCallback descendant that collects statistics on lava and water springs +// Implements the cSpringStats class representing a cCallback descendant that collects statistics on lava and water +// springs #include "Globals.h" #include "SpringStats.h" @@ -16,7 +17,7 @@ cSpringStats::cStats::cStats(void) : m_TotalChunks(0) { - memset(m_LavaSprings, 0, sizeof(m_LavaSprings)); + memset(m_LavaSprings, 0, sizeof(m_LavaSprings)); memset(m_WaterSprings, 0, sizeof(m_WaterSprings)); } @@ -31,7 +32,7 @@ void cSpringStats::cStats::Add(const cSpringStats::cStats & a_Other) { for (int Height = 0; Height < 256; Height++) { - m_LavaSprings[Biome][Height] += a_Other.m_LavaSprings[Biome][Height]; + m_LavaSprings[Biome][Height] += a_Other.m_LavaSprings[Biome][Height]; m_WaterSprings[Biome][Height] += a_Other.m_WaterSprings[Biome][Height]; } } @@ -84,8 +85,8 @@ bool cSpringStats::OnSection( const NIBBLETYPE * a_BlockSkyLight ) { - memcpy(m_BlockTypes + ((int)a_Y) * 16 * 16 * 16, a_BlockTypes, 16 * 16 * 16); - memcpy(m_BlockMetas + ((int)a_Y) * 16 * 16 * 16 / 2, a_BlockMeta, 16 * 16 * 16 / 2); + memcpy(m_BlockTypes + ((int) a_Y) * 16 * 16 * 16, a_BlockTypes, 16 * 16 * 16); + memcpy(m_BlockMetas + ((int) a_Y) * 16 * 16 * 16 / 2, a_BlockMeta, 16 * 16 * 16 / 2); return false; } @@ -145,15 +146,14 @@ void cSpringStats::TestSpring(int a_RelX, int a_RelY, int a_RelZ, cSpringStats:: static const struct { int x, y, z; - } Coords[] = - { - {-1, 0, 0}, - { 1, 0, 0}, - { 0, -1, 0}, - { 0, 1, 0}, - { 0, 0, -1}, - { 0, 0, 1}, - } ; + } Coords[] = { + {-1, 0, 0}, + {1, 0, 0}, + {0, -1, 0}, + {0, 1, 0}, + {0, 0, -1}, + {0, 0, 1}, + }; bool HasFluidNextToIt = false; for (int i = 0; i < ARRAYCOUNT(Coords); i++) { @@ -164,7 +164,12 @@ void cSpringStats::TestSpring(int a_RelX, int a_RelY, int a_RelZ, cSpringStats:: case E_BLOCK_LAVA: case E_BLOCK_STATIONARY_LAVA: { - if (cChunkDef::GetNibble(m_BlockMetas, a_RelX + Coords[i].x, a_RelY + Coords[i].y, a_RelZ + Coords[i].z) == 0) + if (cChunkDef::GetNibble( + m_BlockMetas, + a_RelX + Coords[i].x, + a_RelY + Coords[i].y, + a_RelZ + Coords[i].z + ) == 0) { // There is another source block next to this, so this is not a spring return; @@ -182,7 +187,7 @@ void cSpringStats::TestSpring(int a_RelX, int a_RelY, int a_RelZ, cSpringStats:: } // No source blocks next to the specified block, so it is a spring. Add it to stats: - a_Stats[a_RelY][((unsigned char *)m_Biomes)[a_RelX + 16 * a_RelZ]] += 1; + a_Stats[a_RelY][((unsigned char *) m_Biomes)[a_RelX + 16 * a_RelZ]] += 1; } @@ -217,7 +222,7 @@ void cSpringStatsFactory::JoinResults(void) { for (cCallbacks::iterator itr = m_Callbacks.begin(), end = m_Callbacks.end(); itr != end; ++itr) { - m_CombinedStats.Add(((cSpringStats *)(*itr))->GetStats()); + m_CombinedStats.Add(((cSpringStats *) (*itr))->GetStats()); } // for itr - m_Callbacks[] } diff --git a/Tools/AnvilStats/SpringStats.h b/Tools/AnvilStats/SpringStats.h index 83651b7e6..d40259ae5 100644 --- a/Tools/AnvilStats/SpringStats.h +++ b/Tools/AnvilStats/SpringStats.h @@ -1,7 +1,8 @@ // SpringStats.h -// Declares the cSpringStats class representing a cCallback descendant that collects statistics on lava and water springs +// Declares the cSpringStats class representing a cCallback descendant that collects statistics on lava and water +// springs @@ -15,13 +16,12 @@ -class cSpringStats : - public cCallback +class cSpringStats : public cCallback { -public: + public: class cStats { - public: + public: /** Per-height, per-biome frequencies of springs */ typedef UInt64 SpringStats[256][256]; @@ -33,29 +33,34 @@ public: cStats(void); void Add(const cStats & a_Other); - } ; + }; cSpringStats(void); const cStats & GetStats(void) const { return m_Stats; } -protected: - - BLOCKTYPE m_BlockTypes[16 * 16 * 256]; + protected: + BLOCKTYPE m_BlockTypes[16 * 16 * 256]; NIBBLETYPE m_BlockMetas[16 * 16 * 256 / 2]; - char m_Biomes[16 * 16]; - bool m_AreBiomesValid; + char m_Biomes[16 * 16]; + bool m_AreBiomesValid; cStats m_Stats; // cCallback overrides: virtual bool OnNewChunk(int a_ChunkX, int a_ChunkZ) override; virtual bool OnHeader(int a_FileOffset, unsigned char a_NumSectors, int a_Timestamp) override { return false; } - virtual bool OnCompressedDataSizePos(int a_CompressedDataSize, int a_DataOffset, char a_CompressionMethod) override { return false; } + virtual bool OnCompressedDataSizePos(int a_CompressedDataSize, int a_DataOffset, char a_CompressionMethod) override + { + return false; + } virtual bool OnDecompressedData(const char * a_DecompressedNBT, int a_DataSize) override { return false; } virtual bool OnRealCoords(int a_ChunkX, int a_ChunkZ) override { return false; } virtual bool OnLastUpdate(Int64 a_LastUpdate) override { return false; } - virtual bool OnTerrainPopulated(bool a_Populated) override { return !a_Populated; } // If not populated, we don't want it! + virtual bool OnTerrainPopulated(bool a_Populated) override + { + return !a_Populated; + } // If not populated, we don't want it! virtual bool OnBiomes(const unsigned char * a_BiomeData) override; virtual bool OnHeightMap(const int * a_HeightMap) override { return false; } virtual bool OnSection( @@ -70,22 +75,18 @@ protected: /** Tests the specified block, if it appears to be a spring, it is added to a_Stats */ void TestSpring(int a_RelX, int a_RelY, int a_RelZ, cStats::SpringStats & a_Stats); -} ; +}; -class cSpringStatsFactory : - public cCallbackFactory +class cSpringStatsFactory : public cCallbackFactory { -public: + public: virtual ~cSpringStatsFactory(); - virtual cCallback * CreateNewCallback(void) override - { - return new cSpringStats; - } + virtual cCallback * CreateNewCallback(void) override { return new cSpringStats; } cSpringStats::cStats m_CombinedStats; @@ -96,4 +97,4 @@ public: /** Saves complete per-height, per-biome statistics for the springs to the file */ void SaveStatistics(const cSpringStats::cStats::SpringStats & a_Stats, const AString & a_FileName); -} ; +}; diff --git a/Tools/AnvilStats/Statistics.cpp b/Tools/AnvilStats/Statistics.cpp index d5ad360f3..c719fbeee 100644 --- a/Tools/AnvilStats/Statistics.cpp +++ b/Tools/AnvilStats/Statistics.cpp @@ -26,11 +26,11 @@ cStatistics::cStats::cStats(void) : m_MinChunkZ(0x7fffffff), m_MaxChunkZ(0x80000000) { - memset(m_BiomeCounts, 0, sizeof(m_BiomeCounts)); - memset(m_BlockCounts, 0, sizeof(m_BlockCounts)); + memset(m_BiomeCounts, 0, sizeof(m_BiomeCounts)); + memset(m_BlockCounts, 0, sizeof(m_BlockCounts)); memset(m_PerHeightBlockCounts, 0, sizeof(m_PerHeightBlockCounts)); - memset(m_PerHeightSpawners, 0, sizeof(m_PerHeightSpawners)); - memset(m_SpawnerEntity, 0, sizeof(m_SpawnerEntity)); + memset(m_PerHeightSpawners, 0, sizeof(m_PerHeightSpawners)); + memset(m_SpawnerEntity, 0, sizeof(m_SpawnerEntity)); } @@ -100,9 +100,7 @@ void cStatistics::cStats::UpdateCoordsRange(int a_ChunkX, int a_ChunkZ) //////////////////////////////////////////////////////////////////////////////// // cStatistics: -cStatistics::cStatistics(void) -{ -} +cStatistics::cStatistics(void) {} @@ -137,9 +135,7 @@ bool cStatistics::OnBiomes(const unsigned char * a_BiomeData) - -bool cStatistics::OnSection -( +bool cStatistics::OnSection( unsigned char a_Y, const BLOCKTYPE * a_BlockTypes, const NIBBLETYPE * a_BlockAdditional, @@ -156,7 +152,7 @@ bool cStatistics::OnSection for (int y = 0; y < 16; y++) { - int Height = (int)a_Y * 16 + y; + int Height = (int) a_Y * 16 + y; for (int z = 0; z < 16; z++) { for (int x = 0; x < 16; x++) @@ -209,9 +205,14 @@ bool cStatistics::OnEmptySection(unsigned char a_Y) bool cStatistics::OnEntity( const AString & a_EntityType, - double a_PosX, double a_PosY, double a_PosZ, - double a_SpeedX, double a_SpeedY, double a_SpeedZ, - float a_Yaw, float a_Pitch, + double a_PosX, + double a_PosY, + double a_PosZ, + double a_SpeedX, + double a_SpeedY, + double a_SpeedZ, + float a_Yaw, + float a_Pitch, float a_FallDistance, short a_FireTicksLeft, short a_AirTicks, @@ -233,7 +234,9 @@ bool cStatistics::OnEntity( bool cStatistics::OnTileEntity( const AString & a_EntityType, - int a_PosX, int a_PosY, int a_PosZ, + int a_PosX, + int a_PosY, + int a_PosZ, cParsedNBT & a_NBT, int a_NBTTag ) @@ -252,11 +255,7 @@ bool cStatistics::OnTileEntity( -bool cStatistics::OnTileTick( - int a_BlockType, - int a_TicksLeft, - int a_PosX, int a_PosY, int a_PosZ -) +bool cStatistics::OnTileTick(int a_BlockType, int a_TicksLeft, int a_PosX, int a_PosY, int a_PosZ) { m_Stats.m_NumTileTicks += 1; return false; @@ -326,7 +325,11 @@ cStatisticsFactory::~cStatisticsFactory() } } UInt64 ExpTotalBlocks = m_CombinedStats.m_BlockNumChunks * 16LL * 16LL * 256LL; - LOG(" BlockIDs processed for %llu chunks, %llu blocks (exp %llu; %s)", m_CombinedStats.m_BlockNumChunks, TotalBlocks, ExpTotalBlocks, (TotalBlocks == ExpTotalBlocks) ? "match" : "failed"); + LOG(" BlockIDs processed for %llu chunks, %llu blocks (exp %llu; %s)", + m_CombinedStats.m_BlockNumChunks, + TotalBlocks, + ExpTotalBlocks, + (TotalBlocks == ExpTotalBlocks) ? "match" : "failed"); // Save statistics: LOG(" Saving statistics into files:"); @@ -354,7 +357,7 @@ void cStatisticsFactory::JoinResults(void) { for (cCallbacks::iterator itr = m_Callbacks.begin(), end = m_Callbacks.end(); itr != end; ++itr) { - m_CombinedStats.Add(((cStatistics *)(*itr))->GetStats()); + m_CombinedStats.Add(((cStatistics *) (*itr))->GetStats()); } // for itr - m_Callbacks[] } @@ -370,7 +373,8 @@ void cStatisticsFactory::SaveBiomes(void) LOG("Cannot write to file Biomes.xls. Statistics not written."); return; } - double TotalColumns = (double)(m_CombinedStats.m_BiomeNumChunks) * 16 * 16 / 100; // Total number of columns processed; convert into percent + double TotalColumns = (double) (m_CombinedStats.m_BiomeNumChunks) * 16 * 16 / + 100; // Total number of columns processed; convert into percent if (TotalColumns < 1) { // Avoid division by zero @@ -379,7 +383,14 @@ void cStatisticsFactory::SaveBiomes(void) for (int i = 0; i <= 255; i++) { AString Line; - Printf(Line, "%s\t%d\t%llu\t%.05f\n", GetBiomeString(i), i, m_CombinedStats.m_BiomeCounts[i], ((double)(m_CombinedStats.m_BiomeCounts[i])) / TotalColumns); + Printf( + Line, + "%s\t%d\t%llu\t%.05f\n", + GetBiomeString(i), + i, + m_CombinedStats.m_BiomeCounts[i], + ((double) (m_CombinedStats.m_BiomeCounts[i])) / TotalColumns + ); f.Write(Line.c_str(), Line.length()); } } @@ -396,7 +407,8 @@ void cStatisticsFactory::SaveBlockTypes(void) LOG("Cannot write to file Biomes.xls. Statistics not written."); return; } - double TotalBlocks = ((double)(m_CombinedStats.m_BlockNumChunks)) * 16 * 16 * 256 / 100; // Total number of blocks processed; convert into percent + double TotalBlocks = ((double) (m_CombinedStats.m_BlockNumChunks)) * 16 * 16 * 256 / + 100; // Total number of blocks processed; convert into percent if (TotalBlocks < 1) { // Avoid division by zero @@ -410,7 +422,7 @@ void cStatisticsFactory::SaveBlockTypes(void) Count += m_CombinedStats.m_BlockCounts[Biome][i]; } AString Line; - Printf(Line, "%s\t%d\t%llu\t%.08f\n", GetBlockTypeString(i), i, Count, ((double)Count) / TotalBlocks); + Printf(Line, "%s\t%d\t%llu\t%.08f\n", GetBlockTypeString(i), i, Count, ((double) Count) / TotalBlocks); f.Write(Line.c_str(), Line.length()); } } @@ -548,7 +560,6 @@ void cStatisticsFactory::SaveBiomeBlockTypes(void) - void cStatisticsFactory::SaveStatistics(void) { cFile f; @@ -559,11 +570,20 @@ void cStatisticsFactory::SaveStatistics(void) } int Elapsed = (clock() - m_BeginTick) / CLOCKS_PER_SEC; - f.Printf("Time elapsed: %d seconds (%d hours, %d minutes and %d seconds)\n", Elapsed, Elapsed / 3600, (Elapsed / 60) % 60, Elapsed % 60); + f.Printf( + "Time elapsed: %d seconds (%d hours, %d minutes and %d seconds)\n", + Elapsed, + Elapsed / 3600, + (Elapsed / 60) % 60, + Elapsed % 60 + ); f.Printf("Total chunks processed: %llu\n", m_CombinedStats.m_TotalChunks); if (Elapsed > 0) { - f.Printf("Chunk processing speed: %.02f chunks per second\n", (double)(m_CombinedStats.m_TotalChunks) / Elapsed); + f.Printf( + "Chunk processing speed: %.02f chunks per second\n", + (double) (m_CombinedStats.m_TotalChunks) / Elapsed + ); } f.Printf("Biomes counted for %llu chunks.\n", m_CombinedStats.m_BiomeNumChunks); f.Printf("Blocktypes counted for %llu chunks.\n", m_CombinedStats.m_BlockNumChunks); @@ -593,7 +613,12 @@ void cStatisticsFactory::SaveSpawners(void) f.Printf("Entity type\tTotal count\tCount per chunk\n"); for (int i = 0; i < entMax; i++) { - f.Printf("%s\t%llu\t%0.4f\n", GetEntityTypeString((eEntityType)i), m_CombinedStats.m_SpawnerEntity[i], (double)(m_CombinedStats.m_SpawnerEntity[i]) / m_CombinedStats.m_BlockNumChunks); + f.Printf( + "%s\t%llu\t%0.4f\n", + GetEntityTypeString((eEntityType) i), + m_CombinedStats.m_SpawnerEntity[i], + (double) (m_CombinedStats.m_SpawnerEntity[i]) / m_CombinedStats.m_BlockNumChunks + ); } } @@ -614,7 +639,7 @@ void cStatisticsFactory::SavePerHeightSpawners(void) f.Printf("Height\tTotal"); for (int i = 0; i < entMax; i++) { - f.Printf("\t%s", GetEntityTypeString((eEntityType)i)); + f.Printf("\t%s", GetEntityTypeString((eEntityType) i)); } f.Printf("\n"); diff --git a/Tools/AnvilStats/Statistics.h b/Tools/AnvilStats/Statistics.h index 2c8c61685..2b21be562 100644 --- a/Tools/AnvilStats/Statistics.h +++ b/Tools/AnvilStats/Statistics.h @@ -16,13 +16,12 @@ -class cStatistics : - public cCallback +class cStatistics : public cCallback { -public: + public: class cStats { - public: + public: UInt64 m_TotalChunks; // Total number of chunks that go through this callback (OnNewChunk()) UInt64 m_BiomeCounts[256]; UInt64 m_BlockCounts[256][256]; // First dimension is the biome, second dimension is BlockType @@ -32,7 +31,8 @@ public: UInt64 m_NumTileEntities; UInt64 m_NumTileTicks; UInt64 m_PerHeightBlockCounts[256][256]; // First dimension is the height, second dimension is BlockType - UInt64 m_PerHeightSpawners[256][entMax + 1]; // First dimension is the height, second dimension is spawned entity type + UInt64 m_PerHeightSpawners[256][entMax + 1]; // First dimension is the height, second dimension is spawned + // entity type int m_MinChunkX, m_MaxChunkX; // X coords range int m_MinChunkZ, m_MaxChunkZ; // Z coords range @@ -42,27 +42,35 @@ public: cStats(void); void Add(const cStats & a_Stats); void UpdateCoordsRange(int a_ChunkX, int a_ChunkZ); - } ; + }; cStatistics(void); const cStats & GetStats(void) const { return m_Stats; } -protected: + protected: cStats m_Stats; - bool m_IsBiomesValid; // Set to true in OnBiomes(), reset to false in OnNewChunk(); if true, the m_BiomeData is valid for the current chunk - unsigned char m_BiomeData[16 * 16]; - bool m_IsFirstSectionInChunk; // True if there was no section in the chunk yet. Set by OnNewChunk(), reset by OnSection() + bool m_IsBiomesValid; // Set to true in OnBiomes(), reset to false in OnNewChunk(); if true, the m_BiomeData is + // valid for the current chunk + unsigned char m_BiomeData[16 * 16]; + bool m_IsFirstSectionInChunk; // True if there was no section in the chunk yet. Set by OnNewChunk(), reset by + // OnSection() // cCallback overrides: virtual bool OnNewChunk(int a_ChunkX, int a_ChunkZ) override; virtual bool OnHeader(int a_FileOffset, unsigned char a_NumSectors, int a_Timestamp) override { return false; } - virtual bool OnCompressedDataSizePos(int a_CompressedDataSize, int a_DataOffset, char a_CompressionMethod) override { return false; } + virtual bool OnCompressedDataSizePos(int a_CompressedDataSize, int a_DataOffset, char a_CompressionMethod) override + { + return false; + } virtual bool OnDecompressedData(const char * a_DecompressedNBT, int a_DataSize) override { return false; } virtual bool OnRealCoords(int a_ChunkX, int a_ChunkZ) override { return false; } virtual bool OnLastUpdate(Int64 a_LastUpdate) override { return false; } - virtual bool OnTerrainPopulated(bool a_Populated) override { return !a_Populated; } // If not populated, we don't want it! + virtual bool OnTerrainPopulated(bool a_Populated) override + { + return !a_Populated; + } // If not populated, we don't want it! virtual bool OnBiomes(const unsigned char * a_BiomeData) override; virtual bool OnHeightMap(const int * a_HeightMap) override { return false; } virtual bool OnSection( @@ -80,9 +88,14 @@ protected: virtual bool OnEntity( const AString & a_EntityType, - double a_PosX, double a_PosY, double a_PosZ, - double a_SpeedX, double a_SpeedY, double a_SpeedZ, - float a_Yaw, float a_Pitch, + double a_PosX, + double a_PosY, + double a_PosZ, + double a_SpeedX, + double a_SpeedY, + double a_SpeedZ, + float a_Yaw, + float a_Pitch, float a_FallDistance, short a_FireTicksLeft, short a_AirTicks, @@ -93,37 +106,31 @@ protected: virtual bool OnTileEntity( const AString & a_EntityType, - int a_PosX, int a_PosY, int a_PosZ, + int a_PosX, + int a_PosY, + int a_PosZ, cParsedNBT & a_NBT, int a_NBTTag ) override; - virtual bool OnTileTick( - int a_BlockType, - int a_TicksLeft, - int a_PosX, int a_PosY, int a_PosZ - ) override; + virtual bool OnTileTick(int a_BlockType, int a_TicksLeft, int a_PosX, int a_PosY, int a_PosZ) override; void OnSpawner(cParsedNBT & a_NBT, int a_TileEntityTag); -} ; +}; -class cStatisticsFactory : - public cCallbackFactory +class cStatisticsFactory : public cCallbackFactory { -public: + public: cStatisticsFactory(void); virtual ~cStatisticsFactory(); - virtual cCallback * CreateNewCallback(void) - { - return new cStatistics; - } + virtual cCallback * CreateNewCallback(void) { return new cStatistics; } -protected: + protected: // The results, combined, are stored here: cStatistics::cStats m_CombinedStats; @@ -137,4 +144,4 @@ protected: void SaveStatistics(void); void SaveSpawners(void); void SavePerHeightSpawners(void); -} ; +}; diff --git a/Tools/AnvilStats/Utils.cpp b/Tools/AnvilStats/Utils.cpp index a3fbedf28..6ac88f12e 100644 --- a/Tools/AnvilStats/Utils.cpp +++ b/Tools/AnvilStats/Utils.cpp @@ -12,43 +12,42 @@ struct { - eEntityType Type; + eEntityType Type; const char * String; -} g_EntityTypes[] = -{ - {entBat, "Bat"}, - {entBlaze, "Blaze"}, - {entCaveSpider, "CaveSpider"}, - {entChicken, "Chicken"}, - {entCow, "Cow"}, - {entCreeper, "Creeper"}, - {entEnderDragon, "EnderDragon"}, - {entEnderman, "Enderman"}, - {entGhast, "Ghast"}, - {entGiant, "Giant"}, - {entGuardian, "Guardian"}, - {entLavaSlime, "LavaSlime"}, - {entMushroomCow, "MushroomCow"}, - {entOzelot, "Ozelot"}, - {entPig, "Pig"}, - {entPigZombie, "PigZombie"}, - {entRabbit, "Rabbit"}, - {entSheep, "Sheep"}, - {entSilverfish, "Slverfish"}, - {entSkeleton, "Skeleton"}, - {entSlime, "Slime"}, - {entSnowMan, "SnowMan"}, - {entSpider, "Spider"}, - {entSquid, "Squid"}, - {entVillager, "Villager"}, - {entVillagerGolem, "VillagerGolem"}, - {entWitch, "Witch"}, - {entWitherBoss, "WitherBoss"}, - {entWolf, "Wolf"}, - {entZombie, "Zombie"}, +} g_EntityTypes[] = { + {entBat, "Bat"}, + {entBlaze, "Blaze"}, + {entCaveSpider, "CaveSpider"}, + {entChicken, "Chicken"}, + {entCow, "Cow"}, + {entCreeper, "Creeper"}, + {entEnderDragon, "EnderDragon"}, + {entEnderman, "Enderman"}, + {entGhast, "Ghast"}, + {entGiant, "Giant"}, + {entGuardian, "Guardian"}, + {entLavaSlime, "LavaSlime"}, + {entMushroomCow, "MushroomCow"}, + {entOzelot, "Ozelot"}, + {entPig, "Pig"}, + {entPigZombie, "PigZombie"}, + {entRabbit, "Rabbit"}, + {entSheep, "Sheep"}, + {entSilverfish, "Slverfish"}, + {entSkeleton, "Skeleton"}, + {entSlime, "Slime"}, + {entSnowMan, "SnowMan"}, + {entSpider, "Spider"}, + {entSquid, "Squid"}, + {entVillager, "Villager"}, + {entVillagerGolem, "VillagerGolem"}, + {entWitch, "Witch"}, + {entWitherBoss, "WitherBoss"}, + {entWolf, "Wolf"}, + {entZombie, "Zombie"}, {entZombieVillager, "ZombieVillager"}, - {entUnknown, "Unknown"}, -} ; + {entUnknown, "Unknown"}, +}; @@ -57,31 +56,31 @@ struct const char * GetBiomeString(unsigned char a_Biome) { static const char * BiomeNames[] = // Biome names, as equivalent to their index - { - "Ocean", - "Plains", - "Desert", - "Extreme Hills", - "Forest", - "Taiga", - "Swampland", - "River", - "Hell", - "Sky", - "Frozen Ocean", - "Frozen River", - "Ice Plains", - "Ice Mountains", - "Mushroom Island", - "Mushroom Island Shore", - "Beach", - "Desert Hills", - "Forest Hills", - "Taiga Hills", - "Extreme Hills Edge", - "Jungle", - "Jungle Hills", - } ; + { + "Ocean", + "Plains", + "Desert", + "Extreme Hills", + "Forest", + "Taiga", + "Swampland", + "River", + "Hell", + "Sky", + "Frozen Ocean", + "Frozen River", + "Ice Plains", + "Ice Mountains", + "Mushroom Island", + "Mushroom Island Shore", + "Beach", + "Desert Hills", + "Forest Hills", + "Taiga Hills", + "Extreme Hills Edge", + "Jungle", + "Jungle Hills", + }; return (a_Biome < ARRAYCOUNT(BiomeNames)) ? BiomeNames[a_Biome] : ""; } @@ -92,153 +91,153 @@ const char * GetBiomeString(unsigned char a_Biome) const char * GetBlockTypeString(unsigned char a_BlockType) { static const char * BlockTypeNames[] = // Block type names, as equivalent to their index - { - "air", - "stone", - "grass", - "dirt", - "cobblestone", - "planks", - "sapling", - "bedrock", - "water", - "stillwater", - "lava", - "stilllava", - "sand", - "gravel", - "goldore", - "ironore", - "coalore", - "log", - "leaves", - "sponge", - "glass", - "lapisore", - "lapisblock", - "dispenser", - "sandstone", - "noteblock", - "bedblock", - "poweredrail", - "detectorrail", - "stickypiston", - "cobweb", - "tallgrass", - "deadbush", - "piston", - "pistonhead", - "wool", - "pistonmovedblock", - "flower", - "rose", - "brownmushroom", - "redmushroom", - "goldblock", - "ironblock", - "doubleslab", - "slab", - "brickblock", - "tnt", - "bookcase", - "mossycobblestone", - "obsidian", - "torch", - "fire", - "mobspawner", - "woodstairs", - "chest", - "redstonedust", - "diamondore", - "diamondblock", - "workbench", - "crops", - "soil", - "furnace", - "litfurnace", - "signblock", - "wooddoorblock", - "ladder", - "tracks", - "cobblestonestairs", - "wallsign", - "lever", - "stoneplate", - "irondoorblock", - "woodplate", - "redstoneore", - "redstoneorealt", - "redstonetorchoff", - "redstonetorchon", - "button", - "snow", - "ice", - "snowblock", - "cactus", - "clayblock", - "reedblock", - "jukebox", - "fence", - "pumpkin", - "netherrack", - "soulsand", - "glowstone", - "portal", - "jack-o-lantern", - "cakeblock", - "repeateroff", - "repeateron", - "lockedchest", - "trapdoor", - "silverfishblock", - "stonebricks", - "hugebrownmushroom", - "hugeredmushroom", - "ironbars", - "glasspane", - "melon", - "pumpkinstem", - "melonstem", - "vines", - "fencegate", - "brickstairs", - "stonebrickstairs", - "mycelium", - "lilypad", - "netherbrick", - "netherbrickfence", - "netherbrickstairs", - "netherwartblock", - "enchantmenttable", - "brewingstandblock", - "cauldronblock", - "endportal", - "endportalframe", - "endstone", - "dragonegg", - "redstonelampoff", - "redstonelampon", - "woodendoubleslab", - "woodenslab", - "cocoapod", - "sandstonestairs", /* 128 */ - "Emerald Ore", - "Ender Chest", - "Tripwire Hook", - "Tripwire", - "Block of Emerald", - "Spruce Wood Stairs", - "Birch Wood Stairs", - "Jungle Wood Stairs", - "Command Block", - "Beacon", - "Cobblestone Wall", - "Flower Pot", - "Carrots", - "Potatoes", - "Wooden Button", - "Head", - } ; + { + "air", + "stone", + "grass", + "dirt", + "cobblestone", + "planks", + "sapling", + "bedrock", + "water", + "stillwater", + "lava", + "stilllava", + "sand", + "gravel", + "goldore", + "ironore", + "coalore", + "log", + "leaves", + "sponge", + "glass", + "lapisore", + "lapisblock", + "dispenser", + "sandstone", + "noteblock", + "bedblock", + "poweredrail", + "detectorrail", + "stickypiston", + "cobweb", + "tallgrass", + "deadbush", + "piston", + "pistonhead", + "wool", + "pistonmovedblock", + "flower", + "rose", + "brownmushroom", + "redmushroom", + "goldblock", + "ironblock", + "doubleslab", + "slab", + "brickblock", + "tnt", + "bookcase", + "mossycobblestone", + "obsidian", + "torch", + "fire", + "mobspawner", + "woodstairs", + "chest", + "redstonedust", + "diamondore", + "diamondblock", + "workbench", + "crops", + "soil", + "furnace", + "litfurnace", + "signblock", + "wooddoorblock", + "ladder", + "tracks", + "cobblestonestairs", + "wallsign", + "lever", + "stoneplate", + "irondoorblock", + "woodplate", + "redstoneore", + "redstoneorealt", + "redstonetorchoff", + "redstonetorchon", + "button", + "snow", + "ice", + "snowblock", + "cactus", + "clayblock", + "reedblock", + "jukebox", + "fence", + "pumpkin", + "netherrack", + "soulsand", + "glowstone", + "portal", + "jack-o-lantern", + "cakeblock", + "repeateroff", + "repeateron", + "lockedchest", + "trapdoor", + "silverfishblock", + "stonebricks", + "hugebrownmushroom", + "hugeredmushroom", + "ironbars", + "glasspane", + "melon", + "pumpkinstem", + "melonstem", + "vines", + "fencegate", + "brickstairs", + "stonebrickstairs", + "mycelium", + "lilypad", + "netherbrick", + "netherbrickfence", + "netherbrickstairs", + "netherwartblock", + "enchantmenttable", + "brewingstandblock", + "cauldronblock", + "endportal", + "endportalframe", + "endstone", + "dragonegg", + "redstonelampoff", + "redstonelampon", + "woodendoubleslab", + "woodenslab", + "cocoapod", + "sandstonestairs", /* 128 */ + "Emerald Ore", + "Ender Chest", + "Tripwire Hook", + "Tripwire", + "Block of Emerald", + "Spruce Wood Stairs", + "Birch Wood Stairs", + "Jungle Wood Stairs", + "Command Block", + "Beacon", + "Cobblestone Wall", + "Flower Pot", + "Carrots", + "Potatoes", + "Wooden Button", + "Head", + }; return (a_BlockType < ARRAYCOUNT(BlockTypeNames)) ? BlockTypeNames[a_BlockType] : ""; } diff --git a/Tools/AnvilStats/Utils.h b/Tools/AnvilStats/Utils.h index f2d23f287..51f67ede2 100644 --- a/Tools/AnvilStats/Utils.h +++ b/Tools/AnvilStats/Utils.h @@ -48,7 +48,7 @@ enum eEntityType entZombieVillager, entUnknown, entMax = entUnknown, -} ; +}; @@ -59,6 +59,3 @@ extern const char * GetBlockTypeString(unsigned char a_BlockType); extern eEntityType GetEntityType(const AString & a_EntityTypeString); extern const char * GetEntityTypeString(eEntityType a_EntityType); extern int GetNumCores(void); - - - diff --git a/Tools/BlockZapper/BlockZapper.cpp b/Tools/BlockZapper/BlockZapper.cpp index 9db9e3c99..de47ccfeb 100644 --- a/Tools/BlockZapper/BlockZapper.cpp +++ b/Tools/BlockZapper/BlockZapper.cpp @@ -15,8 +15,8 @@ #ifdef _MSC_VER - // Under MSVC, link to WinSock2 (needed by FastNBT's byteswapping) - #pragma comment(lib, "ws2_32.lib") +// Under MSVC, link to WinSock2 (needed by FastNBT's byteswapping) +#pragma comment(lib, "ws2_32.lib") #endif @@ -62,13 +62,8 @@ int main(int argc, char * argv[]) } i++; } - else if ( - (strcmp(argv[i], "help") == 0) || - (strcmp(argv[i], "-?") == 0) || - (strcmp(argv[i], "/?") == 0) || - (strcmp(argv[i], "-h") == 0) || - (strcmp(argv[i], "--help") == 0) - ) + else if ((strcmp(argv[i], "help") == 0) || (strcmp(argv[i], "-?") == 0) || (strcmp(argv[i], "/?") == 0) || + (strcmp(argv[i], "-h") == 0) || (strcmp(argv[i], "--help") == 0)) { ShowHelp(argv[0]); return 0; @@ -90,4 +85,4 @@ int main(int argc, char * argv[]) LOGINFO("Done"); return 0; -} ; +}; diff --git a/Tools/BlockZapper/Globals.cpp b/Tools/BlockZapper/Globals.cpp index d73265a60..6d1b25cbc 100644 --- a/Tools/BlockZapper/Globals.cpp +++ b/Tools/BlockZapper/Globals.cpp @@ -4,7 +4,3 @@ // Used for precompiled header generation in MSVC #include "Globals.h" - - - - diff --git a/Tools/BlockZapper/Globals.h b/Tools/BlockZapper/Globals.h index 3826c72fa..9de3f032c 100644 --- a/Tools/BlockZapper/Globals.h +++ b/Tools/BlockZapper/Globals.h @@ -8,7 +8,3 @@ #include "../../src/Globals.h" - - - - diff --git a/Tools/BlockZapper/Regions.cpp b/Tools/BlockZapper/Regions.cpp index 7a205a138..ec6f98545 100644 --- a/Tools/BlockZapper/Regions.cpp +++ b/Tools/BlockZapper/Regions.cpp @@ -30,7 +30,16 @@ cRegion::cRegion(void) : -cRegion::cRegion(int a_MinX, int a_MaxX, int a_MinY, int a_MaxY, int a_MinZ, int a_MaxZ, bool a_ShouldZapBlocks, bool a_ShouldZapEntities) : +cRegion::cRegion( + int a_MinX, + int a_MaxX, + int a_MinY, + int a_MaxY, + int a_MinZ, + int a_MaxZ, + bool a_ShouldZapBlocks, + bool a_ShouldZapEntities +) : m_MinX(a_MinX), m_MaxX(a_MaxX), m_MinY(std::max(0, std::min(255, a_MinY))), @@ -52,10 +61,7 @@ bool cRegion::TouchesChunk(int a_ChunkX, int a_ChunkZ) const int ChunkEndX = a_ChunkX * 16 + 15; int ChunkBeginZ = a_ChunkZ * 16; int ChunkEndZ = a_ChunkZ * 16 + 15; - if ( - (m_MinX > ChunkEndX) || (m_MaxX < ChunkBeginX) || - (m_MinZ > ChunkEndZ) || (m_MaxZ < ChunkBeginZ) - ) + if ((m_MinX > ChunkEndX) || (m_MaxX < ChunkBeginX) || (m_MinZ > ChunkEndZ) || (m_MaxZ < ChunkBeginZ)) { return false; } @@ -159,5 +165,7 @@ void cRegions::AddRegion(const AStringVector & a_Split) } // Store the region - m_Regions.push_back(cRegion(Coords[0], Coords[1], Coords[2], Coords[3], Coords[4], Coords[5], ShouldZapBlocks, ShouldZapEntities)); + m_Regions.push_back( + cRegion(Coords[0], Coords[1], Coords[2], Coords[3], Coords[4], Coords[5], ShouldZapBlocks, ShouldZapEntities) + ); } diff --git a/Tools/BlockZapper/Regions.h b/Tools/BlockZapper/Regions.h index 2fe50a9b4..b740f62f6 100644 --- a/Tools/BlockZapper/Regions.h +++ b/Tools/BlockZapper/Regions.h @@ -25,10 +25,19 @@ struct cRegion bool m_ShouldZapEntities; cRegion(void); - cRegion(int a_MinX, int a_MaxX, int a_MinY, int a_MaxY, int a_MinZ, int a_MaxZ, bool a_ShouldZapBlocks, bool a_ShouldZapEntities); + cRegion( + int a_MinX, + int a_MaxX, + int a_MinY, + int a_MaxY, + int a_MinZ, + int a_MaxZ, + bool a_ShouldZapBlocks, + bool a_ShouldZapEntities + ); bool TouchesChunk(int a_ChunkX, int a_ChunkZ) const; -} ; +}; typedef std::vector<cRegion> cRegionVector; @@ -38,17 +47,16 @@ typedef std::vector<cRegion> cRegionVector; class cRegions { -public: + public: /** Reads the list of regions from the specified stream */ void Read(std::istream & a_Stream); /** Returns all regions in this container */ const cRegionVector & GetAll(void) const { return m_Regions; } -protected: + protected: cRegionVector m_Regions; /** Adds a new region based on the contents of the split line. The split must already be the correct size */ void AddRegion(const AStringVector & a_Split); - -} ; +}; diff --git a/Tools/BlockZapper/Zapper.cpp b/Tools/BlockZapper/Zapper.cpp index ae3916835..84a5dd3f0 100644 --- a/Tools/BlockZapper/Zapper.cpp +++ b/Tools/BlockZapper/Zapper.cpp @@ -89,7 +89,12 @@ void cZapper::ZapRegionInMCAFile(const cRegion & a_Region, int a_MCAX, int a_MCA AString FileNameOut = Printf("%s/r.%d.%d.zap", m_MCAFolder.c_str(), a_MCAX, a_MCAZ); if (!fOut.Open(FileNameOut, cFile::fmWrite)) { - fprintf(stderr, "Cannot open temporary file \"%s\" for writing, skipping file \"%s\".", FileNameOut.c_str(), FileNameIn.c_str()); + fprintf( + stderr, + "Cannot open temporary file \"%s\" for writing, skipping file \"%s\".", + FileNameOut.c_str(), + FileNameIn.c_str() + ); return; } @@ -124,16 +129,17 @@ void cZapper::ZapRegionInMCAFile(const cRegion & a_Region, int a_MCAX, int a_MCA size_t DataSize = ChunkData.size() + 1; ChunkHeader[0] = (DataSize >> 24) & 0xff; ChunkHeader[1] = (DataSize >> 16) & 0xff; - ChunkHeader[2] = (DataSize >> 8) & 0xff; + ChunkHeader[2] = (DataSize >> 8) & 0xff; ChunkHeader[3] = DataSize & 0xff; ChunkHeader[4] = 2; // zlib compression - size_t Alignment = 4096 - (ChunkData.size() + 5) % 4096; // 5 bytes of the header are appended outside of ChunkData + size_t Alignment = + 4096 - (ChunkData.size() + 5) % 4096; // 5 bytes of the header are appended outside of ChunkData if (Alignment > 0) { - ChunkData.append(Alignment, (char)0); + ChunkData.append(Alignment, (char) 0); } HeaderOut[i] = htonl(((DataOut.size() / 4096 + 2) << 8) | ((ChunkData.size() + 5) / 4096)); - DataOut.append((const char *)ChunkHeader, sizeof(ChunkHeader)); + DataOut.append((const char *) ChunkHeader, sizeof(ChunkHeader)); DataOut.append(ChunkData); } // for i - chunks in fIn for (int i = 1024; i < 2048; i++) @@ -162,13 +168,19 @@ void cZapper::LoadChunkData(cFile & a_InFile, int a_ChunkHeaderValue, AString & a_InFile.Read(ChunkHeader, sizeof(ChunkHeader)); if (ChunkHeader[4] != 2) { - fprintf(stderr, "Chunk [%d, %d] is compressed in an unknown scheme (%d), skipping", a_ChunkX, a_ChunkZ, ChunkHeader[4]); + fprintf( + stderr, + "Chunk [%d, %d] is compressed in an unknown scheme (%d), skipping", + a_ChunkX, + a_ChunkZ, + ChunkHeader[4] + ); return; } - int ActualSize = (ChunkHeader[0] << 24) | (ChunkHeader[1] << 16) | (ChunkHeader[2] << 8) | ChunkHeader[3]; + int ActualSize = (ChunkHeader[0] << 24) | (ChunkHeader[1] << 16) | (ChunkHeader[2] << 8) | ChunkHeader[3]; ActualSize -= 1; // Compression took 1 byte a_ChunkData.resize(ActualSize); - int BytesRead = a_InFile.Read((void *)(a_ChunkData.data()), ActualSize); + int BytesRead = a_InFile.Read((void *) (a_ChunkData.data()), ActualSize); if (BytesRead != ActualSize) { fprintf(stderr, "Chunk is truncated in file (%d bytes out of %d), skipping.", BytesRead, ActualSize); @@ -186,14 +198,14 @@ void cZapper::ZapRegionInRawChunkData(const cRegion & a_Region, AString & a_Chun // Decompress the data: char Uncompressed[CHUNK_INFLATE_MAX]; z_stream strm; - strm.zalloc = (alloc_func)NULL; - strm.zfree = (free_func)NULL; + strm.zalloc = (alloc_func) NULL; + strm.zfree = (free_func) NULL; strm.opaque = NULL; inflateInit(&strm); - strm.next_out = (Bytef *)Uncompressed; + strm.next_out = (Bytef *) Uncompressed; strm.avail_out = sizeof(Uncompressed); - strm.next_in = (Bytef *)a_ChunkData.data(); - strm.avail_in = a_ChunkData.size(); + strm.next_in = (Bytef *) a_ChunkData.data(); + strm.avail_in = a_ChunkData.size(); int res = inflate(&strm, Z_FINISH); inflateEnd(&strm); if (res != Z_STREAM_END) @@ -268,7 +280,13 @@ void cZapper::ZapRegionInNBTChunk(const cRegion & a_Region, cParsedNBT & a_NBT, int SectionsTag = a_NBT.FindChildByName(LevelTag, "Sections"); if (SectionsTag < 0) { - fprintf(stderr, "Cannot find the Sections tag in the Level tag in chunk [%d, %d]'s NBT. Skipping block-zapping in chunk.", a_ChunkX, a_ChunkZ); + fprintf( + stderr, + "Cannot find the Sections tag in the Level tag in chunk [%d, %d]'s NBT. Skipping block-zapping in " + "chunk.", + a_ChunkX, + a_ChunkZ + ); return; } ZapRegionBlocksInNBT(Local, a_NBT, SectionsTag); @@ -279,7 +297,13 @@ void cZapper::ZapRegionInNBTChunk(const cRegion & a_Region, cParsedNBT & a_NBT, int EntitiesTag = a_NBT.FindChildByName(LevelTag, "Entities"); if (EntitiesTag < 0) { - fprintf(stderr, "Cannot find the Entities tag in the Level tag in chunk [%d, %d]'s NBT. Skipping entity-zapping in chunk.", a_ChunkX, a_ChunkZ); + fprintf( + stderr, + "Cannot find the Entities tag in the Level tag in chunk [%d, %d]'s NBT. Skipping entity-zapping in " + "chunk.", + a_ChunkX, + a_ChunkZ + ); return; } ZapRegionEntitiesInNBT(Local, a_NBT, EntitiesTag); @@ -307,18 +331,18 @@ void cZapper::ZapRegionBlocksInNBT(const cRegion & a_Region, cParsedNBT & a_NBT, } int BlockDataTag = a_NBT.FindChildByName(Child, "Blocks"); int BlockMetaTag = a_NBT.FindChildByName(Child, "Data"); - int BlockAddTag = a_NBT.FindChildByName(Child, "Add"); + int BlockAddTag = a_NBT.FindChildByName(Child, "Add"); if (BlockDataTag > 0) { - ZapRegionInNBTSectionBytes(a_Region, y, (unsigned char *)(a_NBT.GetData(BlockDataTag))); + ZapRegionInNBTSectionBytes(a_Region, y, (unsigned char *) (a_NBT.GetData(BlockDataTag))); } if (BlockMetaTag > 0) { - ZapRegionInNBTSectionNibbles(a_Region, y, (unsigned char *)(a_NBT.GetData(BlockMetaTag))); + ZapRegionInNBTSectionNibbles(a_Region, y, (unsigned char *) (a_NBT.GetData(BlockMetaTag))); } if (BlockAddTag > 0) { - ZapRegionInNBTSectionNibbles(a_Region, y, (unsigned char *)(a_NBT.GetData(BlockAddTag))); + ZapRegionInNBTSectionNibbles(a_Region, y, (unsigned char *) (a_NBT.GetData(BlockAddTag))); } } // for Child - Level / Sections / [] } @@ -384,25 +408,28 @@ void cZapper::SerializeNBTTag(const cParsedNBT & a_NBT, int a_Tag, cFastNBTWrite { switch (a_NBT.GetType(a_Tag)) { - case TAG_Byte: a_Writer.AddByte (a_NBT.GetName(a_Tag), a_NBT.GetByte (a_Tag)); break; - case TAG_Short: a_Writer.AddShort (a_NBT.GetName(a_Tag), a_NBT.GetShort (a_Tag)); break; - case TAG_Int: a_Writer.AddInt (a_NBT.GetName(a_Tag), a_NBT.GetInt (a_Tag)); break; - case TAG_Long: a_Writer.AddLong (a_NBT.GetName(a_Tag), a_NBT.GetLong (a_Tag)); break; - case TAG_Float: a_Writer.AddFloat (a_NBT.GetName(a_Tag), a_NBT.GetFloat (a_Tag)); break; - case TAG_Double: a_Writer.AddDouble (a_NBT.GetName(a_Tag), a_NBT.GetDouble(a_Tag)); break; - case TAG_ByteArray: a_Writer.AddByteArray(a_NBT.GetName(a_Tag), a_NBT.GetData (a_Tag), a_NBT.GetDataLength(a_Tag)); break; - case TAG_String: a_Writer.AddString (a_NBT.GetName(a_Tag), a_NBT.GetString(a_Tag)); break; + case TAG_Byte: a_Writer.AddByte(a_NBT.GetName(a_Tag), a_NBT.GetByte(a_Tag)); break; + case TAG_Short: a_Writer.AddShort(a_NBT.GetName(a_Tag), a_NBT.GetShort(a_Tag)); break; + case TAG_Int: a_Writer.AddInt(a_NBT.GetName(a_Tag), a_NBT.GetInt(a_Tag)); break; + case TAG_Long: a_Writer.AddLong(a_NBT.GetName(a_Tag), a_NBT.GetLong(a_Tag)); break; + case TAG_Float: a_Writer.AddFloat(a_NBT.GetName(a_Tag), a_NBT.GetFloat(a_Tag)); break; + case TAG_Double: a_Writer.AddDouble(a_NBT.GetName(a_Tag), a_NBT.GetDouble(a_Tag)); break; + case TAG_ByteArray: + a_Writer.AddByteArray(a_NBT.GetName(a_Tag), a_NBT.GetData(a_Tag), a_NBT.GetDataLength(a_Tag)); + break; + case TAG_String: a_Writer.AddString(a_NBT.GetName(a_Tag), a_NBT.GetString(a_Tag)); break; case TAG_IntArray: { std::vector<int> Data; int NumInts = a_NBT.GetDataLength(a_Tag) / 4; Data.reserve(NumInts); - int * OrigData = (int *)(a_NBT.GetData(a_Tag)); + int * OrigData = (int *) (a_NBT.GetData(a_Tag)); for (int i = 0; i < NumInts; i++) { Data.push_back(ntohl(OrigData[i])); } - a_Writer.AddIntArray (a_NBT.GetName(a_Tag), &Data.front(), Data.size()); break; + a_Writer.AddIntArray(a_NBT.GetName(a_Tag), &Data.front(), Data.size()); + break; } case TAG_List: diff --git a/Tools/BlockZapper/Zapper.h b/Tools/BlockZapper/Zapper.h index e156848af..7daa07a59 100644 --- a/Tools/BlockZapper/Zapper.h +++ b/Tools/BlockZapper/Zapper.h @@ -25,13 +25,13 @@ class cFastNBTWriter; class cZapper { -public: + public: cZapper(const AString & a_MCAFolder); /** Zaps all the specified regions */ void ZapRegions(const cRegionVector & a_Regions); -protected: + protected: static const int BlocksPerChunkX = 16; static const int BlocksPerChunkZ = 16; static const int ChunksPerMCAX = 32; @@ -49,8 +49,8 @@ protected: void ZapRegionInMCAFile(const cRegion & a_Region, int a_MCAX, int a_MCAZ); /** Loads raw compressed chunk data from the specified file - * chunk is specified by ChunkHeaderValue, which is the int describing the chunk in file header. - */ + * chunk is specified by ChunkHeaderValue, which is the int describing the chunk in file header. + */ void LoadChunkData(cFile & a_InFile, int a_ChunkHeaderValue, AString & a_ChunkData, int a_ChunkX, int a_ChunkZ); /** Zaps the specified region in the raw (compressed) chunk data. */ @@ -73,4 +73,4 @@ protected: /** Serializes the NBT subtree into a writer */ void SerializeNBTTag(const cParsedNBT & a_NBT, int a_Tag, cFastNBTWriter & a_Writer); -} ; +}; diff --git a/Tools/GrownBiomeGenVisualiser/Globals.cpp b/Tools/GrownBiomeGenVisualiser/Globals.cpp index 13c6ae709..680afbf75 100644 --- a/Tools/GrownBiomeGenVisualiser/Globals.cpp +++ b/Tools/GrownBiomeGenVisualiser/Globals.cpp @@ -4,7 +4,3 @@ // This file is used for precompiled header generation in MSVC environments #include "Globals.h" - - - - diff --git a/Tools/GrownBiomeGenVisualiser/Globals.h b/Tools/GrownBiomeGenVisualiser/Globals.h index 2c5d090f5..cdaecdba3 100644 --- a/Tools/GrownBiomeGenVisualiser/Globals.h +++ b/Tools/GrownBiomeGenVisualiser/Globals.h @@ -10,20 +10,20 @@ // Compiler-dependent stuff: #if defined(_MSC_VER) - // MSVC produces warning C4481 on the override keyword usage, so disable the warning altogether - #pragma warning(disable:4481) +// MSVC produces warning C4481 on the override keyword usage, so disable the warning altogether +#pragma warning(disable : 4481) - // Disable some warnings that we don't care about: - #pragma warning(disable:4100) +// Disable some warnings that we don't care about: +#pragma warning(disable : 4100) #elif defined(__GNUC__) - // TODO: Can GCC explicitly mark classes as abstract (no instances can be created)? - #define abstract +// TODO: Can GCC explicitly mark classes as abstract (no instances can be created)? +#define abstract #else - #error "You are using an unsupported compiler, you might need to #define some stuff here for your compiler" +#error "You are using an unsupported compiler, you might need to #define some stuff here for your compiler" #endif @@ -32,7 +32,7 @@ #ifndef TOLUA_TEMPLATE_BIND - #define TOLUA_TEMPLATE_BIND(x) +#define TOLUA_TEMPLATE_BIND(x) #endif @@ -41,12 +41,12 @@ // Integral types with predefined sizes: typedef long long Int64; -typedef int Int32; -typedef short Int16; +typedef int Int32; +typedef short Int16; typedef unsigned long long UInt64; -typedef unsigned int UInt32; -typedef unsigned short UInt16; +typedef unsigned int UInt32; +typedef unsigned short UInt16; typedef unsigned char Byte; @@ -57,57 +57,57 @@ typedef unsigned char Byte; // A macro to disallow the copy constructor and operator= functions // This should be used in the private: declarations for any class that shouldn't allow copying itself #define DISALLOW_COPY_AND_ASSIGN(TypeName) \ - TypeName(const TypeName &); \ + TypeName(const TypeName &); \ void operator=(const TypeName &) // A macro that is used to mark unused function parameters, to avoid pedantic warnings in gcc -#define UNUSED(X) (void)(X) +#define UNUSED(X) (void) (X) // OS-dependent stuff: #ifdef _WIN32 - #define WIN32_LEAN_AND_MEAN - #include <Windows.h> - #include <winsock2.h> - #include <ws2tcpip.h> +#define WIN32_LEAN_AND_MEAN +#include <Windows.h> +#include <winsock2.h> +#include <ws2tcpip.h> - // Windows SDK defines min and max macros, messing up with our std::min and std::max usage - #undef min - #undef max +// Windows SDK defines min and max macros, messing up with our std::min and std::max usage +#undef min +#undef max - // Windows SDK defines GetFreeSpace as a constant, probably a Win16 API remnant - #ifdef GetFreeSpace - #undef GetFreeSpace - #endif // GetFreeSpace +// Windows SDK defines GetFreeSpace as a constant, probably a Win16 API remnant +#ifdef GetFreeSpace +#undef GetFreeSpace +#endif // GetFreeSpace - #define SocketError WSAGetLastError() +#define SocketError WSAGetLastError() #else - #include <sys/types.h> - #include <sys/stat.h> // for mkdir - #include <sys/time.h> - #include <sys/socket.h> - #include <netinet/in.h> - #include <arpa/inet.h> - #include <netdb.h> - #include <dirent.h> - #include <iostream> - #include <unistd.h> - - #include <cstring> - #include <pthread.h> - #include <semaphore.h> - #include <cerrno> - #include <fcntl.h> - - typedef int SOCKET; - enum - { - INVALID_SOCKET = -1, - }; - #define closesocket close - #define SocketError errno +#include <sys/types.h> +#include <sys/stat.h> // for mkdir +#include <sys/time.h> +#include <sys/socket.h> +#include <netinet/in.h> +#include <arpa/inet.h> +#include <netdb.h> +#include <dirent.h> +#include <iostream> +#include <unistd.h> + +#include <cstring> +#include <pthread.h> +#include <semaphore.h> +#include <cerrno> +#include <fcntl.h> + +typedef int SOCKET; +enum +{ + INVALID_SOCKET = -1, +}; +#define closesocket close +#define SocketError errno #endif @@ -156,17 +156,17 @@ typedef unsigned char Byte; #define ARRAYCOUNT(X) (sizeof(X) / sizeof(*(X))) /** Allows arithmetic expressions like "32 KiB" (but consider using parenthesis around it, "(32 KiB)") */ -#define KiB * 1024 -#define MiB * 1024 * 1024 +#define KiB *1024 +#define MiB *1024 * 1024 /** Faster than (int)floorf((float)x / (float)div) */ -#define FAST_FLOOR_DIV(x, div) ((x) < 0 ? (((int)x / div) - 1) : ((int)x / div)) +#define FAST_FLOOR_DIV(x, div) ((x) < 0 ? (((int) x / div) - 1) : ((int) x / div)) /** Own version of assert() that writes failed assertions to the log for review */ -#ifdef NDEBUG - #define ASSERT(x) ((void)0) +#ifdef NDEBUG +#define ASSERT(x) ((void) 0) #else - #define ASSERT assert +#define ASSERT assert #endif // Pretty much the same as ASSERT() but stays in Release builds @@ -177,16 +177,13 @@ typedef unsigned char Byte; /** Clamp X to the specified range. */ -template <typename T> -T Clamp(T a_Value, T a_Min, T a_Max) +template <typename T> T Clamp(T a_Value, T a_Min, T a_Max) { return (a_Value < a_Min) ? a_Min : ((a_Value > a_Max) ? a_Max : a_Value); } -template <typename T> -auto ToUnsigned(T a_Val) +template <typename T> auto ToUnsigned(T a_Val) { ASSERT(a_Val >= 0); return static_cast<std::make_unsigned_t<T>>(a_Val); } - diff --git a/Tools/GrownBiomeGenVisualiser/GrownBiomeGenVisualiser.cpp b/Tools/GrownBiomeGenVisualiser/GrownBiomeGenVisualiser.cpp index 5201c28bf..665016b96 100644 --- a/Tools/GrownBiomeGenVisualiser/GrownBiomeGenVisualiser.cpp +++ b/Tools/GrownBiomeGenVisualiser/GrownBiomeGenVisualiser.cpp @@ -23,9 +23,11 @@ typedef int Color[3]; // Color is an array of 3 ints // Forward declarations, needed for GCC and Clang: void outputBitmapFile( const AString & a_FileName, - unsigned a_ImageSizeX, unsigned a_ImageSizeY, + unsigned a_ImageSizeX, + unsigned a_ImageSizeY, const int * a_ColorIndices, - unsigned a_IndicesSizeX, unsigned a_IndicesSizeY, + unsigned a_IndicesSizeX, + unsigned a_IndicesSizeY, const Color * a_Colors, size_t a_NumColors ); @@ -40,8 +42,7 @@ void generateExamples(int a_Seed); /** Color palette used for algorithm examples. No relevance to biomes whatsoever. */ -static const Color spectrumColors[] = -{ +static const Color spectrumColors[] = { {0, 0, 0}, {255, 0, 0}, {0, 255, 0}, @@ -56,13 +57,12 @@ static const Color spectrumColors[] = /** Color palette used for displaying biome groups. */ -static const Color biomeGroupColors[] = -{ - /* bgOcean */ {0x00, 0x00, 0x70}, - /* bgDesert */ {0xfa, 0x94, 0x18}, - /* bgTemperate */ {0x05, 0x66, 0x21}, - /* bgMountains */ {0x60, 0x60, 0x60}, - /* bgIce */ {0xa0, 0xa0, 0xff}, +static const Color biomeGroupColors[] = { + /* bgOcean */ {0x00, 0x00, 0x70}, + /* bgDesert */ {0xfa, 0x94, 0x18}, + /* bgTemperate */ {0x05, 0x66, 0x21}, + /* bgMountains */ {0x60, 0x60, 0x60}, + /* bgIce */ {0xa0, 0xa0, 0xff}, }; @@ -81,80 +81,261 @@ static const struct { EMCSBiome biome; Color color; -} biomeColorMap[] = -{ - { biOcean, { 0x00, 0x00, 0x70 }, }, - { biPlains, { 0x8d, 0xb3, 0x60 }, }, - { biDesert, { 0xfa, 0x94, 0x18 }, }, - { biExtremeHills, { 0x60, 0x60, 0x60 }, }, - { biForest, { 0x05, 0x66, 0x21 }, }, - { biTaiga, { 0x0b, 0x66, 0x59 }, }, - { biSwampland, { 0x2f, 0xff, 0xda }, }, - { biRiver, { 0x30, 0x30, 0xaf }, }, - { biHell, { 0x7f, 0x00, 0x00 }, }, - { biSky, { 0x00, 0x7f, 0xff }, }, - { biFrozenOcean, { 0xa0, 0xa0, 0xdf }, }, - { biFrozenRiver, { 0xa0, 0xa0, 0xff }, }, - { biIcePlains, { 0xff, 0xff, 0xff }, }, - { biIceMountains, { 0xa0, 0xa0, 0xa0 }, }, - { biMushroomIsland, { 0xff, 0x00, 0xff }, }, - { biMushroomShore, { 0xa0, 0x00, 0xff }, }, - { biBeach, { 0xfa, 0xde, 0x55 }, }, - { biDesertHills, { 0xd2, 0x5f, 0x12 }, }, - { biForestHills, { 0x22, 0x55, 0x1c }, }, - { biTaigaHills, { 0x16, 0x39, 0x33 }, }, - { biExtremeHillsEdge, { 0x7f, 0x8f, 0x7f }, }, - { biJungle, { 0x53, 0x7b, 0x09 }, }, - { biJungleHills, { 0x2c, 0x42, 0x05 }, }, - - { biJungleEdge, { 0x62, 0x8b, 0x17 }, }, - { biDeepOcean, { 0x00, 0x00, 0x30 }, }, - { biStoneBeach, { 0xa2, 0xa2, 0x84 }, }, - { biColdBeach, { 0xfa, 0xf0, 0xc0 }, }, - { biBirchForest, { 0x30, 0x74, 0x44 }, }, - { biBirchForestHills, { 0x1f, 0x5f, 0x32 }, }, - { biRoofedForest, { 0x40, 0x51, 0x1a }, }, - { biColdTaiga, { 0x31, 0x55, 0x4a }, }, - { biColdTaigaHills, { 0x59, 0x7d, 0x72 }, }, - { biMegaTaiga, { 0x59, 0x66, 0x51 }, }, - { biMegaTaigaHills, { 0x59, 0x66, 0x59 }, }, - { biExtremeHillsPlus, { 0x50, 0x70, 0x50 }, }, - { biSavanna, { 0xbd, 0xb2, 0x5f }, }, - { biSavannaPlateau, { 0xa7, 0x9d, 0x64 }, }, - { biMesa, { 0xd9, 0x45, 0x15 }, }, - { biMesaPlateauF, { 0xb0, 0x97, 0x65 }, }, - { biMesaPlateau, { 0xca, 0x8c, 0x65 }, }, +} biomeColorMap[] = { + { + biOcean, + {0x00, 0x00, 0x70}, + }, + { + biPlains, + {0x8d, 0xb3, 0x60}, + }, + { + biDesert, + {0xfa, 0x94, 0x18}, + }, + { + biExtremeHills, + {0x60, 0x60, 0x60}, + }, + { + biForest, + {0x05, 0x66, 0x21}, + }, + { + biTaiga, + {0x0b, 0x66, 0x59}, + }, + { + biSwampland, + {0x2f, 0xff, 0xda}, + }, + { + biRiver, + {0x30, 0x30, 0xaf}, + }, + { + biHell, + {0x7f, 0x00, 0x00}, + }, + { + biSky, + {0x00, 0x7f, 0xff}, + }, + { + biFrozenOcean, + {0xa0, 0xa0, 0xdf}, + }, + { + biFrozenRiver, + {0xa0, 0xa0, 0xff}, + }, + { + biIcePlains, + {0xff, 0xff, 0xff}, + }, + { + biIceMountains, + {0xa0, 0xa0, 0xa0}, + }, + { + biMushroomIsland, + {0xff, 0x00, 0xff}, + }, + { + biMushroomShore, + {0xa0, 0x00, 0xff}, + }, + { + biBeach, + {0xfa, 0xde, 0x55}, + }, + { + biDesertHills, + {0xd2, 0x5f, 0x12}, + }, + { + biForestHills, + {0x22, 0x55, 0x1c}, + }, + { + biTaigaHills, + {0x16, 0x39, 0x33}, + }, + { + biExtremeHillsEdge, + {0x7f, 0x8f, 0x7f}, + }, + { + biJungle, + {0x53, 0x7b, 0x09}, + }, + { + biJungleHills, + {0x2c, 0x42, 0x05}, + }, + + { + biJungleEdge, + {0x62, 0x8b, 0x17}, + }, + { + biDeepOcean, + {0x00, 0x00, 0x30}, + }, + { + biStoneBeach, + {0xa2, 0xa2, 0x84}, + }, + { + biColdBeach, + {0xfa, 0xf0, 0xc0}, + }, + { + biBirchForest, + {0x30, 0x74, 0x44}, + }, + { + biBirchForestHills, + {0x1f, 0x5f, 0x32}, + }, + { + biRoofedForest, + {0x40, 0x51, 0x1a}, + }, + { + biColdTaiga, + {0x31, 0x55, 0x4a}, + }, + { + biColdTaigaHills, + {0x59, 0x7d, 0x72}, + }, + { + biMegaTaiga, + {0x59, 0x66, 0x51}, + }, + { + biMegaTaigaHills, + {0x59, 0x66, 0x59}, + }, + { + biExtremeHillsPlus, + {0x50, 0x70, 0x50}, + }, + { + biSavanna, + {0xbd, 0xb2, 0x5f}, + }, + { + biSavannaPlateau, + {0xa7, 0x9d, 0x64}, + }, + { + biMesa, + {0xd9, 0x45, 0x15}, + }, + { + biMesaPlateauF, + {0xb0, 0x97, 0x65}, + }, + { + biMesaPlateau, + {0xca, 0x8c, 0x65}, + }, // M variants: - { biSunflowerPlains, { 0xb5, 0xdb, 0x88 }, }, - { biDesertM, { 0xff, 0xbc, 0x40 }, }, - { biExtremeHillsM, { 0x88, 0x88, 0x88 }, }, - { biFlowerForest, { 0x2d, 0x8e, 0x49 }, }, - { biTaigaM, { 0x33, 0x8e, 0x81 }, }, - { biSwamplandM, { 0x07, 0xf9, 0xb2 }, }, - { biIcePlainsSpikes, { 0xb4, 0xdc, 0xdc }, }, - { biJungleM, { 0x7b, 0xa3, 0x31 }, }, - { biJungleEdgeM, { 0x62, 0x8b, 0x17 }, }, - { biBirchForestM, { 0x58, 0x9c, 0x6c }, }, - { biBirchForestHillsM, { 0x47, 0x87, 0x5a }, }, - { biRoofedForestM, { 0x68, 0x79, 0x42 }, }, - { biColdTaigaM, { 0x24, 0x3f, 0x36 }, }, - { biMegaSpruceTaiga, { 0x45, 0x4f, 0x3e }, }, - { biMegaSpruceTaigaHills, { 0x45, 0x4f, 0x4e }, }, - { biExtremeHillsPlusM, { 0x78, 0x98, 0x78 }, }, - { biSavannaM, { 0xe5, 0xda, 0x87 }, }, - { biSavannaPlateauM, { 0xa7, 0x9d, 0x74 }, }, - { biMesaBryce, { 0xff, 0x6d, 0x3d }, }, - { biMesaPlateauFM, { 0xd8, 0xbf, 0x8d }, }, - { biMesaPlateauM, { 0xf2, 0xb4, 0x8d }, }, + { + biSunflowerPlains, + {0xb5, 0xdb, 0x88}, + }, + { + biDesertM, + {0xff, 0xbc, 0x40}, + }, + { + biExtremeHillsM, + {0x88, 0x88, 0x88}, + }, + { + biFlowerForest, + {0x2d, 0x8e, 0x49}, + }, + { + biTaigaM, + {0x33, 0x8e, 0x81}, + }, + { + biSwamplandM, + {0x07, 0xf9, 0xb2}, + }, + { + biIcePlainsSpikes, + {0xb4, 0xdc, 0xdc}, + }, + { + biJungleM, + {0x7b, 0xa3, 0x31}, + }, + { + biJungleEdgeM, + {0x62, 0x8b, 0x17}, + }, + { + biBirchForestM, + {0x58, 0x9c, 0x6c}, + }, + { + biBirchForestHillsM, + {0x47, 0x87, 0x5a}, + }, + { + biRoofedForestM, + {0x68, 0x79, 0x42}, + }, + { + biColdTaigaM, + {0x24, 0x3f, 0x36}, + }, + { + biMegaSpruceTaiga, + {0x45, 0x4f, 0x3e}, + }, + { + biMegaSpruceTaigaHills, + {0x45, 0x4f, 0x4e}, + }, + { + biExtremeHillsPlusM, + {0x78, 0x98, 0x78}, + }, + { + biSavannaM, + {0xe5, 0xda, 0x87}, + }, + { + biSavannaPlateauM, + {0xa7, 0x9d, 0x74}, + }, + { + biMesaBryce, + {0xff, 0x6d, 0x3d}, + }, + { + biMesaPlateauFM, + {0xd8, 0xbf, 0x8d}, + }, + { + biMesaPlateauM, + {0xf2, 0xb4, 0x8d}, + }, }; -template <typename ... Args> -void log(const char * a_Fmt, const Args & ... a_Args) +template <typename... Args> void log(const char * a_Fmt, const Args &... a_Args) { fmt::printf(a_Fmt, a_Args...); putchar('\n'); @@ -167,9 +348,11 @@ void log(const char * a_Fmt, const Args & ... a_Args) void outputBitmapFile( const AString & a_FileName, - unsigned a_ImageSizeX, unsigned a_ImageSizeY, + unsigned a_ImageSizeX, + unsigned a_ImageSizeY, const int * a_ColorIndices, - unsigned a_IndicesSizeX, unsigned a_IndicesSizeY, + unsigned a_IndicesSizeX, + unsigned a_IndicesSizeY, const Color * a_Colors, size_t a_NumColors ) @@ -261,7 +444,8 @@ void generateZoomLevels(int a_Seed) int workspace[maxArrSize * maxArrSize]; // Workspace for the generated array // Chain the zoom operation as many times as the image number: - std::shared_ptr<cProtIntGen> gen = std::make_shared<cProtIntGenChoice>(a_Seed, static_cast<int>(ARRAYCOUNT(spectrumColors) + 1)); + std::shared_ptr<cProtIntGen> gen = + std::make_shared<cProtIntGenChoice>(a_Seed, static_cast<int>(ARRAYCOUNT(spectrumColors) + 1)); for (unsigned j = 1; j < i; j++) { gen = std::make_shared<cProtIntGenZoom>(a_Seed + static_cast<int>(j), gen); @@ -286,7 +470,8 @@ void generateSmoothLevels(int a_Seed) const unsigned maxArrSize = 65; ///< Size of the underlying generated array // Initialize the underlying generator: - std::shared_ptr<cProtIntGen> underlyingGen = std::make_shared<cProtIntGenChoice>(a_Seed, static_cast<int>(ARRAYCOUNT(spectrumColors) + 1)); + std::shared_ptr<cProtIntGen> underlyingGen = + std::make_shared<cProtIntGenChoice>(a_Seed, static_cast<int>(ARRAYCOUNT(spectrumColors) + 1)); for (int j = 1; j < 4; j++) { underlyingGen = std::make_shared<cProtIntGenZoom>(a_Seed + j, underlyingGen); @@ -326,42 +511,86 @@ void generateExamples(int a_Seed) const int imgSize = 256; // Create the inputs: - auto in1 = - std::make_shared<cProtIntGenZoom >(a_Seed + 1, - std::make_shared<cProtIntGenAddIslands >(a_Seed + 2000, 200, - std::make_shared<cProtIntGenSetRandomly >(a_Seed + 9, 300, bgOcean, - std::make_shared<cProtIntGenZoom >(a_Seed + 2, - std::make_shared<cProtIntGenLandOcean >(a_Seed + 1, 30 - ))))); - auto in2 = - std::make_shared<cProtIntGenZoom >(a_Seed + 1, - std::make_shared<cProtIntGenBiomeGroupEdges>(in1 - )); - auto in3 = - std::make_shared<cProtIntGenZoom >(a_Seed + 1, - std::make_shared<cProtIntGenZoom >(a_Seed + 2, - std::make_shared<cProtIntGenBiomes >(a_Seed + 3000, in2 - ))); - auto inAlt = - std::make_shared<cProtIntGenZoom >(a_Seed, - std::make_shared<cProtIntGenLandOcean >(a_Seed, 30 - )); + auto in1 = std::make_shared<cProtIntGenZoom>( + a_Seed + 1, + std::make_shared<cProtIntGenAddIslands>( + a_Seed + 2000, + 200, + std::make_shared<cProtIntGenSetRandomly>( + a_Seed + 9, + 300, + bgOcean, + std::make_shared<cProtIntGenZoom>(a_Seed + 2, std::make_shared<cProtIntGenLandOcean>(a_Seed + 1, 30)) + ) + ) + ); + auto in2 = std::make_shared<cProtIntGenZoom>(a_Seed + 1, std::make_shared<cProtIntGenBiomeGroupEdges>(in1)); + auto in3 = std::make_shared<cProtIntGenZoom>( + a_Seed + 1, + std::make_shared<cProtIntGenZoom>(a_Seed + 2, std::make_shared<cProtIntGenBiomes>(a_Seed + 3000, in2)) + ); + auto inAlt = std::make_shared<cProtIntGenZoom>(a_Seed, std::make_shared<cProtIntGenLandOcean>(a_Seed, 30)); auto inRiver = std::make_shared<cProtIntGenRiver>(a_Seed, in2); int workspace[maxArrSize * maxArrSize]; in1->GetInts(0, 0, inArrSize, inArrSize, workspace); - outputBitmapFile("grownexample_in1.ppm", imgSize, imgSize, workspace, inArrSize, inArrSize, biomeGroupColors, ARRAYCOUNT(biomeGroupColors)); + outputBitmapFile( + "grownexample_in1.ppm", + imgSize, + imgSize, + workspace, + inArrSize, + inArrSize, + biomeGroupColors, + ARRAYCOUNT(biomeGroupColors) + ); log(" Created example input 1"); in2->GetInts(0, 0, inArrSize, inArrSize, workspace); - outputBitmapFile("grownexample_in2.ppm", imgSize, imgSize, workspace, inArrSize, inArrSize, biomeGroupColors, ARRAYCOUNT(biomeGroupColors)); + outputBitmapFile( + "grownexample_in2.ppm", + imgSize, + imgSize, + workspace, + inArrSize, + inArrSize, + biomeGroupColors, + ARRAYCOUNT(biomeGroupColors) + ); log(" Created example input 2"); in3->GetInts(0, 0, inArrSize, inArrSize, workspace); - outputBitmapFile("grownexample_in3.ppm", imgSize, imgSize, workspace, inArrSize, inArrSize, biomeColors, ARRAYCOUNT(biomeColors)); + outputBitmapFile( + "grownexample_in3.ppm", + imgSize, + imgSize, + workspace, + inArrSize, + inArrSize, + biomeColors, + ARRAYCOUNT(biomeColors) + ); log(" Created example input 3"); inAlt->GetInts(0, 0, inArrSize, inArrSize, workspace); - outputBitmapFile("grownexample_in_alt.ppm", imgSize, imgSize, workspace, inArrSize, inArrSize, biomeGroupColors, ARRAYCOUNT(biomeGroupColors)); + outputBitmapFile( + "grownexample_in_alt.ppm", + imgSize, + imgSize, + workspace, + inArrSize, + inArrSize, + biomeGroupColors, + ARRAYCOUNT(biomeGroupColors) + ); log(" Created example input alt"); inRiver->GetInts(0, 0, inArrSize, inArrSize, workspace); - outputBitmapFile("grownexample_in_river.ppm", imgSize, imgSize, workspace, inArrSize, inArrSize, biomeColors, ARRAYCOUNT(biomeColors)); + outputBitmapFile( + "grownexample_in_river.ppm", + imgSize, + imgSize, + workspace, + inArrSize, + inArrSize, + biomeColors, + ARRAYCOUNT(biomeColors) + ); log(" Created example input river"); // Shortcuts for colormaps used for the outputs: @@ -370,8 +599,8 @@ void generateExamples(int a_Seed) const Color * colors; size_t count; }; - static const ColorMap cmGroups = { biomeGroupColors, ARRAYCOUNT(biomeGroupColors) }; - static const ColorMap cmBiomes = { biomeColors, ARRAYCOUNT(biomeColors) }; + static const ColorMap cmGroups = {biomeGroupColors, ARRAYCOUNT(biomeGroupColors)}; + static const ColorMap cmBiomes = {biomeColors, ARRAYCOUNT(biomeColors)}; // Create the result generators: struct @@ -381,25 +610,23 @@ void generateExamples(int a_Seed) int offset; const ColorMap & colormap; std::shared_ptr<cProtIntGen> gen; - } - gens[] = - { - {"add_islands", inArrSize, 0, cmGroups, std::make_shared<cProtIntGenAddIslands> (a_Seed, 400, in1)}, - {"alt_biomes", inArrSize, 0, cmBiomes, std::make_shared<cProtIntGenAlternateBiomes>(a_Seed, inAlt, in3)}, - {"beaches", inArrSize - 2, 1, cmBiomes, std::make_shared<cProtIntGenBeaches> (in3)}, - {"biome_edges", inArrSize - 2, 1, cmBiomes, std::make_shared<cProtIntGenBiomeEdges> (a_Seed, in3)}, - {"biomes", inArrSize, 0, cmBiomes, std::make_shared<cProtIntGenBiomes> (a_Seed, in2)}, - {"grp_edges", inArrSize - 2, 0, cmGroups, std::make_shared<cProtIntGenBiomeGroupEdges>(in1)}, - {"m_biomes", inArrSize, 0, cmBiomes, std::make_shared<cProtIntGenMBiomes> (a_Seed, inAlt, in3)}, - {"mix_river", inArrSize, 0, cmBiomes, std::make_shared<cProtIntGenMixRivers> (in3, inRiver)}, - {"river", inArrSize - 2, 1, cmBiomes, inRiver}, - {"set_rnd", inArrSize, 0, cmBiomes, std::make_shared<cProtIntGenSetRandomly> (a_Seed, 500, bgOcean, in3)}, - {"smooth", inArrSize - 2, 1, cmBiomes, std::make_shared<cProtIntGenSmooth> (a_Seed, in3)}, - {"zoom", inArrSize * 2 - 1, 0, cmBiomes, std::make_shared<cProtIntGenZoom> (a_Seed, in3)}, + } gens[] = { + {"add_islands", inArrSize, 0, cmGroups, std::make_shared<cProtIntGenAddIslands>(a_Seed, 400, in1)}, + {"alt_biomes", inArrSize, 0, cmBiomes, std::make_shared<cProtIntGenAlternateBiomes>(a_Seed, inAlt, in3)}, + {"beaches", inArrSize - 2, 1, cmBiomes, std::make_shared<cProtIntGenBeaches>(in3)}, + {"biome_edges", inArrSize - 2, 1, cmBiomes, std::make_shared<cProtIntGenBiomeEdges>(a_Seed, in3)}, + {"biomes", inArrSize, 0, cmBiomes, std::make_shared<cProtIntGenBiomes>(a_Seed, in2)}, + {"grp_edges", inArrSize - 2, 0, cmGroups, std::make_shared<cProtIntGenBiomeGroupEdges>(in1)}, + {"m_biomes", inArrSize, 0, cmBiomes, std::make_shared<cProtIntGenMBiomes>(a_Seed, inAlt, in3)}, + {"mix_river", inArrSize, 0, cmBiomes, std::make_shared<cProtIntGenMixRivers>(in3, inRiver)}, + {"river", inArrSize - 2, 1, cmBiomes, inRiver}, + {"set_rnd", inArrSize, 0, cmBiomes, std::make_shared<cProtIntGenSetRandomly>(a_Seed, 500, bgOcean, in3)}, + {"smooth", inArrSize - 2, 1, cmBiomes, std::make_shared<cProtIntGenSmooth>(a_Seed, in3)}, + {"zoom", inArrSize * 2 - 1, 0, cmBiomes, std::make_shared<cProtIntGenZoom>(a_Seed, in3)}, }; // Create the outputs: - for (const auto & gen: gens) + for (const auto & gen : gens) { gen.gen->GetInts(gen.offset, gen.offset, gen.size, gen.size, workspace); AString fnam = fmt::format(FMT_STRING("grownexample_{}.ppm"), gen.name); diff --git a/Tools/MCADefrag/MCADefrag.cpp b/Tools/MCADefrag/MCADefrag.cpp index 6573fa5ea..d6387411a 100644 --- a/Tools/MCADefrag/MCADefrag.cpp +++ b/Tools/MCADefrag/MCADefrag.cpp @@ -53,8 +53,7 @@ int main(int argc, char ** argv) // cMCADefrag: cMCADefrag::cMCADefrag(void) : - m_NumThreads(4), - m_ShouldRecompress(true) + m_NumThreads(4), m_ShouldRecompress(true) { } @@ -210,12 +209,8 @@ void cMCADefrag::cThread::ProcessFile(const AString & a_FileName) for (size_t i = 0; i < 1024; i++) { size_t idx = i * 4; - if ( - (Locations[idx] == 0) && - (Locations[idx + 1] == 0) && - (Locations[idx + 2] == 0) && - (Locations[idx + 3] == 0) - ) + if ((Locations[idx] == 0) && (Locations[idx + 1] == 0) && (Locations[idx + 2] == 0) && + (Locations[idx + 3] == 0)) { // Chunk not present continue; @@ -258,8 +253,10 @@ bool cMCADefrag::cThread::ReadChunk(cFile & a_File, const Byte * a_LocationRaw) int SizeInSectors = a_LocationRaw[3] * (4 KiB); if (a_File.Seek(SectorNum * (4 KiB)) < 0) { - LOGWARNING("Failed to seek to chunk data - file pos %llu (%d KiB, %.02f MiB)!", - static_cast<Int64>(SectorNum) * (4 KiB), SectorNum * 4, + LOGWARNING( + "Failed to seek to chunk data - file pos %llu (%d KiB, %.02f MiB)!", + static_cast<Int64>(SectorNum) * (4 KiB), + SectorNum * 4, static_cast<double>(SectorNum) / 256 ); return false; @@ -275,7 +272,11 @@ bool cMCADefrag::cThread::ReadChunk(cFile & a_File, const Byte * a_LocationRaw) m_CompressedChunkDataSize = (Buf[0] << 24) | (Buf[1] << 16) | (Buf[2] << 8) | Buf[3]; if ((m_CompressedChunkDataSize > SizeInSectors) || (m_CompressedChunkDataSize < 0)) { - LOGWARNING("Invalid chunk data - SizeInSectors (%d) smaller that RealSize (%d)", SizeInSectors, m_CompressedChunkDataSize); + LOGWARNING( + "Invalid chunk data - SizeInSectors (%d) smaller that RealSize (%d)", + SizeInSectors, + m_CompressedChunkDataSize + ); return false; } @@ -318,7 +319,9 @@ bool cMCADefrag::cThread::WriteChunk(cFile & a_File, Byte * a_LocationRaw) a_LocationRaw[0] = static_cast<Byte>(m_CurrentSectorOut >> 16); a_LocationRaw[1] = (m_CurrentSectorOut >> 8) & 0xff; a_LocationRaw[2] = m_CurrentSectorOut & 0xff; - a_LocationRaw[3] = static_cast<Byte>((m_CompressedChunkDataSize + (4 KiB) + 3) / (4 KiB)); // +3 because the m_CompressedChunkDataSize doesn't include the exact-length + a_LocationRaw[3] = static_cast<Byte>( + (m_CompressedChunkDataSize + (4 KiB) + 3) / (4 KiB) + ); // +3 because the m_CompressedChunkDataSize doesn't include the exact-length m_CurrentSectorOut += a_LocationRaw[3]; // Write the data length: @@ -334,7 +337,8 @@ bool cMCADefrag::cThread::WriteChunk(cFile & a_File, Byte * a_LocationRaw) } // Write the data: - if (a_File.Write(m_CompressedChunkData, static_cast<size_t>(m_CompressedChunkDataSize)) != m_CompressedChunkDataSize) + if (a_File.Write(m_CompressedChunkData, static_cast<size_t>(m_CompressedChunkDataSize)) != + m_CompressedChunkDataSize) { LOGWARNING("Failed to write chunk data!"); return false; @@ -389,10 +393,11 @@ bool cMCADefrag::cThread::UncompressChunkZlib(void) // Uncompress the data const auto ExtractedData = m_Extractor.ExtractZLib( - { - reinterpret_cast<const std::byte *>(m_CompressedChunkData + 1), // The first byte is the compression method, skip it - static_cast<size_t>(m_CompressedChunkDataSize - 1) - }); + {reinterpret_cast<const std::byte *>( + m_CompressedChunkData + 1 + ), // The first byte is the compression method, skip it + static_cast<size_t>(m_CompressedChunkDataSize - 1)} + ); const auto Extracted = ExtractedData.GetView(); if (Extracted.size() > MAX_RAW_CHUNK_DATA_SIZE) @@ -424,10 +429,8 @@ bool cMCADefrag::cThread::CompressChunk(void) // Compress the data (using the highest compression factor, as set in the constructor) const auto CompressedData = m_Compressor.CompressZLib( - { - reinterpret_cast<const std::byte *>(m_RawChunkData), - static_cast<size_t>(m_RawChunkDataSize) - }); + {reinterpret_cast<const std::byte *>(m_RawChunkData), static_cast<size_t>(m_RawChunkDataSize)} + ); const auto Compressed = CompressedData.GetView(); // Check that the compressed data can fit: diff --git a/Tools/MCADefrag/MCADefrag.h b/Tools/MCADefrag/MCADefrag.h index cc151d032..88ed29207 100644 --- a/Tools/MCADefrag/MCADefrag.h +++ b/Tools/MCADefrag/MCADefrag.h @@ -20,16 +20,14 @@ - class cMCADefrag { -public: - + public: enum { MAX_COMPRESSED_CHUNK_DATA_SIZE = (1 MiB), - MAX_RAW_CHUNK_DATA_SIZE = (100 MiB), - } ; + MAX_RAW_CHUNK_DATA_SIZE = (100 MiB), + }; cMCADefrag(void); @@ -40,26 +38,22 @@ public: /** Runs the entire app. */ void Run(void); -protected: - + protected: /** A single thread processing MCA files from the queue */ - class cThread : - public cIsThread + class cThread : public cIsThread { typedef cIsThread super; - public: - + public: cThread(cMCADefrag & a_Parent); - protected: - + protected: /** The compression methods, as specified by the MCA compression method byte. */ enum { COMPRESSION_GZIP = 1, COMPRESSION_ZLIB = 2, - } ; + }; cMCADefrag & m_Parent; @@ -127,7 +121,7 @@ protected: // cIsThread overrides: virtual void Execute(void) override; - } ; + }; typedef std::list<cThread *> cThreads; @@ -154,4 +148,4 @@ protected: /** Retrieves one file from the queue (and removes it from the queue). Returns an empty string when queue empty. */ AString GetNextFileName(void); -} ; +}; diff --git a/Tools/MemDumpAnalysis/Globals.h b/Tools/MemDumpAnalysis/Globals.h index d5fc2abfa..5ab0d68be 100644 --- a/Tools/MemDumpAnalysis/Globals.h +++ b/Tools/MemDumpAnalysis/Globals.h @@ -29,7 +29,3 @@ // Libraries: #include "expat/expat.h" - - - - diff --git a/Tools/MemDumpAnalysis/MemDumpAnalysis.cpp b/Tools/MemDumpAnalysis/MemDumpAnalysis.cpp index 58cb304c5..73d01c954 100644 --- a/Tools/MemDumpAnalysis/MemDumpAnalysis.cpp +++ b/Tools/MemDumpAnalysis/MemDumpAnalysis.cpp @@ -6,7 +6,7 @@ #include "Globals.h" #ifdef _WIN32 - #pragma comment(lib, "ws2_32.lib") // Needed for StringUtils' RawBEToUtf8() et al. +#pragma comment(lib, "ws2_32.lib") // Needed for StringUtils' RawBEToUtf8() et al. #endif // _WIN32 @@ -21,17 +21,16 @@ typedef std::set<AString> AStringSet; class cFunction { -public: - int m_Size; ///< Sum of memory block sizes allocated by this function or its children - int m_Count; ///< Total number of memory blocks allocated by this function or its children + public: + int m_Size; ///< Sum of memory block sizes allocated by this function or its children + int m_Count; ///< Total number of memory blocks allocated by this function or its children AStringSet m_ChildrenNames; cFunction(void) : - m_Size(0), - m_Count(0) + m_Size(0), m_Count(0) { } -} ; +}; typedef std::map<AString, cFunction> FunctionMap; @@ -50,8 +49,7 @@ AString g_PrevFunctionName; bool IsFnBlackListed(const char * a_FnName) { - static const char * BlackList[] = - { + static const char * BlackList[] = { "MyAllocHook", "_heap_alloc_dbg_impl", "_nh_malloc_dbg_impl", @@ -65,7 +63,7 @@ bool IsFnBlackListed(const char * a_FnName) "l_alloc", "luaM_realloc_", "", - } ; + }; for (int i = 0; i < ARRAYCOUNT(BlackList); i++) { @@ -101,9 +99,9 @@ void OnStartElement(void * a_Data, const char * a_Element, const char ** a_Attrs { if (strcmp(a_Element, "LEAK") == 0) { - const char * attrID = FindAttr(a_Attrs, "requestID"); + const char * attrID = FindAttr(a_Attrs, "requestID"); const char * attrSize = FindAttr(a_Attrs, "size"); - g_CurrentID = atoi((attrID == NULL) ? "-1" : attrID); + g_CurrentID = atoi((attrID == NULL) ? "-1" : attrID); g_CurrentSize = atoi((attrSize == NULL) ? "-1" : attrSize); g_PrevFunctionName.clear(); return; @@ -167,7 +165,7 @@ bool CompareFnInt(const std::pair<AString, int> & a_First, const std::pair<AStri void WriteSizeStatistics(void) { - typedef std::vector<std::pair<AString, int> > StringIntPairs; + typedef std::vector<std::pair<AString, int>> StringIntPairs; StringIntPairs FnSizes; cFile f("memdump_totals.txt", cFile::fmWrite); @@ -195,7 +193,7 @@ void WriteSizeStatistics(void) void WriteCountStatistics(void) { - typedef std::vector<std::pair<AString, int> > StringIntPairs; + typedef std::vector<std::pair<AString, int>> StringIntPairs; StringIntPairs FnCounts; cFile f("memdump_counts.txt", cFile::fmWrite); @@ -258,7 +256,8 @@ void WriteDotGraph(void) f.Printf("digraph {\n\tnode [shape=plaintext]\n\n"); for (FunctionMap::const_iterator itrF = g_FnMap.begin(), endF = g_FnMap.end(); itrF != endF; ++itrF) { - f.Printf("\t\"%s\" [label=<%s<BR/>%d bytes (%d KiB)<BR/>%d blocks>]\n", + f.Printf( + "\t\"%s\" [label=<%s<BR/>%d bytes (%d KiB)<BR/>%d blocks>]\n", itrF->first.c_str(), HTMLEscape(itrF->first).c_str(), itrF->second.m_Size, diff --git a/Tools/MemDumpAnalysis/targetver.h b/Tools/MemDumpAnalysis/targetver.h index 3fedb6a1c..66535c3f1 100644 --- a/Tools/MemDumpAnalysis/targetver.h +++ b/Tools/MemDumpAnalysis/targetver.h @@ -16,6 +16,6 @@ // Modify the following defines if you have to target a platform prior to the ones specified below. // Refer to MSDN for the latest info on corresponding values for different platforms. -#ifndef _WIN32_WINNT // Specifies that the minimum required platform is Windows Vista. -#define _WIN32_WINNT 0x0600 // Change this to the appropriate value to target other versions of Windows. +#ifndef _WIN32_WINNT // Specifies that the minimum required platform is Windows Vista. +#define _WIN32_WINNT 0x0600 // Change this to the appropriate value to target other versions of Windows. #endif diff --git a/Tools/NoiseSpeedTest/NoiseSpeedTest.cpp b/Tools/NoiseSpeedTest/NoiseSpeedTest.cpp index 90bb9499e..882e78819 100644 --- a/Tools/NoiseSpeedTest/NoiseSpeedTest.cpp +++ b/Tools/NoiseSpeedTest/NoiseSpeedTest.cpp @@ -5,10 +5,12 @@ /* This program compares the performance of the highly-optimized noise implementation in Cuberite, and the Simplex noise. Since the Simplex noise is not yet implemented in Cuberite, an own implementation is provided. -Also, the performance difference between using a float and double as datatype is measured, by using a templatized Simplex noise. +Also, the performance difference between using a float and double as datatype is measured, by using a templatized +Simplex noise. -The testing is done on a usage of the generator that is typical for the Cuberite's terrain generator: generate a 3D array of numbers with -not much variance in the coords. The exact sizes and coord ranges were adapted from the cNoise3DComposable generator. +The testing is done on a usage of the generator that is typical for the Cuberite's terrain generator: generate a 3D +array of numbers with not much variance in the coords. The exact sizes and coord ranges were adapted from the +cNoise3DComposable generator. */ #include "Globals.h" @@ -59,7 +61,7 @@ static void measureClassicNoise(int a_NumIterations) /** Calculates the specified number of iterations of the Simplex noise. a_TypeStr is a string representing the DATATYPE (for logging purposes). */ -template<typename DATATYPE> static void measureSimplexNoise(int a_NumIterations, const char * a_TypeStr) +template <typename DATATYPE> static void measureSimplexNoise(int a_NumIterations, const char * a_TypeStr) { cSimplexNoise<DATATYPE> noise(1); DATATYPE total = 0; @@ -80,7 +82,12 @@ template<typename DATATYPE> static void measureSimplexNoise(int a_NumIterations, } auto timeEnd = std::chrono::high_resolution_clock::now(); auto msec = std::chrono::duration_cast<std::chrono::milliseconds>(timeEnd - timeStart); - printf("SimplexNoise<%s> took %d milliseconds, returned total %f\n", a_TypeStr, static_cast<int>(msec.count()), total); + printf( + "SimplexNoise<%s> took %d milliseconds, returned total %f\n", + a_TypeStr, + static_cast<int>(msec.count()), + total + ); } @@ -108,10 +115,10 @@ int main(int argc, char ** argv) measureSimplexNoise<double>(numIterations, "double"); measureSimplexNoise<double>(numIterations, "double"); - // If build on Windows using MSVC, wait for a keypress before ending: - #ifdef _MSC_VER - getchar(); - #endif +// If build on Windows using MSVC, wait for a keypress before ending: +#ifdef _MSC_VER + getchar(); +#endif return 0; } diff --git a/Tools/NoiseSpeedTest/NoiseSpeedTest.h b/Tools/NoiseSpeedTest/NoiseSpeedTest.h index 74a0108e6..ac701b241 100644 --- a/Tools/NoiseSpeedTest/NoiseSpeedTest.h +++ b/Tools/NoiseSpeedTest/NoiseSpeedTest.h @@ -1,5 +1 @@ // NoiseSpeedTest.h - - - - diff --git a/Tools/NoiseSpeedTest/SimplexNoise.h b/Tools/NoiseSpeedTest/SimplexNoise.h index 6e74212ae..0c422e980 100644 --- a/Tools/NoiseSpeedTest/SimplexNoise.h +++ b/Tools/NoiseSpeedTest/SimplexNoise.h @@ -14,10 +14,9 @@ http://staffwww.itn.liu.se/~stegu/simplexnoise/simplexnoise.pdf -template<typename Datatype> -class cSimplexNoise +template <typename Datatype> class cSimplexNoise { -public: + public: cSimplexNoise(unsigned a_Seed) { // Based on the seed, initialize the permutation table, using a simple LCG and swapping @@ -77,11 +76,19 @@ public: Datatype GetValueAt3D(const Datatype a_X, const Datatype a_Y, const Datatype a_Z) { // The gradients are the midpoints of the vertices of a cube. - static const Datatype grad3[12][3] = - { - {1, 1, 0}, {-1, 1, 0}, {1, -1, 0}, {-1, -1, 0}, - {1, 0, 1}, {-1, 0, 1}, {1, 0, -1}, {-1, 0, -1}, - {0, 1, 1}, { 0, -1, 1}, {0, 1, -1}, { 0, -1, -1} + static const Datatype grad3[12][3] = { + {1, 1, 0}, + {-1, 1, 0}, + {1, -1, 0}, + {-1, -1, 0}, + {1, 0, 1}, + {-1, 0, 1}, + {1, 0, -1}, + {-1, 0, -1}, + {0, 1, 1}, + {0, -1, 1}, + {0, 1, -1}, + {0, -1, -1} }; // Skew factors: @@ -115,17 +122,32 @@ public: if (y0 >= z0) { // X Y Z order - i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 1; k2 = 0; + i1 = 1; + j1 = 0; + k1 = 0; + i2 = 1; + j2 = 1; + k2 = 0; } else if (x0 >= z0) { // X Z Y order - i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 0; k2 = 1; + i1 = 1; + j1 = 0; + k1 = 0; + i2 = 1; + j2 = 0; + k2 = 1; } else { // Z X Y order - i1 = 0; j1 = 0; k1 = 1; i2 = 1; j2 = 0; k2 = 1; + i1 = 0; + j1 = 0; + k1 = 1; + i2 = 1; + j2 = 0; + k2 = 1; } } else @@ -133,17 +155,32 @@ public: if (y0 < z0) { // Z Y X order - i1 = 0; j1 = 0; k1 = 1; i2 = 0; j2 = 1; k2 = 1; + i1 = 0; + j1 = 0; + k1 = 1; + i2 = 0; + j2 = 1; + k2 = 1; } else if (x0 < z0) { // Y Z X order - i1 = 0; j1 = 1; k1 = 0; i2 = 0; j2 = 1; k2 = 1; + i1 = 0; + j1 = 1; + k1 = 0; + i2 = 0; + j2 = 1; + k2 = 1; } else { // Y X Z order - i1 = 0; j1 = 1; k1 = 0; i2 = 1; j2 = 1; k2 = 0; + i1 = 0; + j1 = 1; + k1 = 0; + i2 = 1; + j2 = 1; + k2 = 0; } } @@ -156,7 +193,8 @@ public: Datatype x2 = x0 - i2 + static_cast<Datatype>(2) * G3; // Offsets for third corner in XYZ coords Datatype y2 = y0 - j2 + static_cast<Datatype>(2) * G3; Datatype z2 = z0 - k2 + static_cast<Datatype>(2) * G3; - Datatype x3 = x0 - static_cast<Datatype>(1) + static_cast<Datatype>(3) * G3; // Offsets for last corner in XYZ coords + Datatype x3 = + x0 - static_cast<Datatype>(1) + static_cast<Datatype>(3) * G3; // Offsets for last corner in XYZ coords Datatype y3 = y0 - static_cast<Datatype>(1) + static_cast<Datatype>(3) * G3; Datatype z3 = z0 - static_cast<Datatype>(1) + static_cast<Datatype>(3) * G3; @@ -228,10 +266,15 @@ public: a_Start and a_End are the coords of the 3D array in the noise-space. */ void Generate3D( Datatype * a_Out, - int a_SizeX, int a_SizeY, int a_SizeZ, - Datatype a_StartX, Datatype a_EndX, - Datatype a_StartY, Datatype a_EndY, - Datatype a_StartZ, Datatype a_EndZ + int a_SizeX, + int a_SizeY, + int a_SizeZ, + Datatype a_StartX, + Datatype a_EndX, + Datatype a_StartY, + Datatype a_EndY, + Datatype a_StartZ, + Datatype a_EndZ ) { Datatype * out = a_Out; @@ -251,14 +294,11 @@ public: } // for z } -protected: + protected: /** The permutation table, initialized by the seed. */ int m_Perm[512]; - /** A copy of the permutation table, with each item modulo 12, to avoid 4 modulo operations per value calculation. */ + /** A copy of the permutation table, with each item modulo 12, to avoid 4 modulo operations per value calculation. + */ int m_PermMod12[512]; }; - - - - diff --git a/Tools/ProtoProxy/Connection.cpp b/Tools/ProtoProxy/Connection.cpp index 2e8428058..6fbea29b7 100644 --- a/Tools/ProtoProxy/Connection.cpp +++ b/Tools/ProtoProxy/Connection.cpp @@ -11,9 +11,9 @@ #include "../../src/Logger.h" #ifdef _WIN32 - #include <direct.h> // For _mkdir() +#include <direct.h> // For _mkdir() #else - #include <sys/stat.h> // for mkdir +#include <sys/stat.h> // for mkdir #endif @@ -27,9 +27,9 @@ #if defined(_DEBUG) && defined(SLEEP_AFTER_PACKET) - #define DebugSleep Sleep +#define DebugSleep Sleep #else - #define DebugSleep(X) +#define DebugSleep(X) #endif // else _DEBUG @@ -37,101 +37,117 @@ #define HANDLE_CLIENT_PACKET_READ(Proc, Type, Var) \ - Type Var; \ - do { \ - if (!m_ClientBuffer.Proc(Var)) \ - { \ - return false; \ - } \ - } while (false) + Type Var; \ + do \ + { \ + if (!m_ClientBuffer.Proc(Var)) \ + { \ + return false; \ + } \ + } \ + while (false) #define HANDLE_SERVER_PACKET_READ(Proc, Type, Var) \ - Type Var; \ - do { \ - if (!m_ServerBuffer.Proc(Var)) \ - { \ - return false; \ - } \ - } while (false) + Type Var; \ + do \ + { \ + if (!m_ServerBuffer.Proc(Var)) \ + { \ + return false; \ + } \ + } \ + while (false) #define CLIENTSEND(...) SendData(m_ClientSocket, __VA_ARGS__, "Client") #define SERVERSEND(...) SendData(m_ServerSocket, __VA_ARGS__, "Server") #define CLIENTENCRYPTSEND(...) SendData(m_ClientSocket, __VA_ARGS__, "Client") // The client conn is always unencrypted #define SERVERENCRYPTSEND(...) SendEncryptedData(m_ServerSocket, m_ServerEncryptor, __VA_ARGS__, "Server") -#define COPY_TO_SERVER() \ - do { \ - ContiguousByteBuffer ToServer; \ - m_ClientBuffer.ReadAgain(ToServer); \ - switch (m_ServerState) \ - { \ - case csUnencrypted: \ - { \ - SERVERSEND(ToServer); \ - break; \ - } \ - case csEncryptedUnderstood: \ - case csEncryptedUnknown: \ - { \ - SERVERENCRYPTSEND(ToServer); \ - break; \ - } \ - case csWaitingForEncryption: \ - { \ +#define COPY_TO_SERVER() \ + do \ + { \ + ContiguousByteBuffer ToServer; \ + m_ClientBuffer.ReadAgain(ToServer); \ + switch (m_ServerState) \ + { \ + case csUnencrypted: \ + { \ + SERVERSEND(ToServer); \ + break; \ + } \ + case csEncryptedUnderstood: \ + case csEncryptedUnknown: \ + { \ + SERVERENCRYPTSEND(ToServer); \ + break; \ + } \ + case csWaitingForEncryption: \ + { \ Log("Waiting for server encryption, queued %u bytes", ToServer.size()); \ - m_ServerEncryptionBuffer += ToServer; \ - break; \ - } \ - } \ - DebugSleep(50); \ - } while (false) - -#define COPY_TO_CLIENT() \ - do { \ - ContiguousByteBuffer ToClient; \ - m_ServerBuffer.ReadAgain(ToClient); \ - switch (m_ClientState) \ - { \ - case csUnencrypted: \ - { \ - CLIENTSEND(ToClient); \ - break; \ - } \ - case csEncryptedUnderstood: \ - case csEncryptedUnknown: \ - { \ + m_ServerEncryptionBuffer += ToServer; \ + break; \ + } \ + } \ + DebugSleep(50); \ + } \ + while (false) + +#define COPY_TO_CLIENT() \ + do \ + { \ + ContiguousByteBuffer ToClient; \ + m_ServerBuffer.ReadAgain(ToClient); \ + switch (m_ClientState) \ + { \ + case csUnencrypted: \ + { \ + CLIENTSEND(ToClient); \ + break; \ + } \ + case csEncryptedUnderstood: \ + case csEncryptedUnknown: \ + { \ CLIENTENCRYPTSEND(ToClient); \ - break; \ - } \ - case csWaitingForEncryption: \ - { \ - break; \ - } \ - \ - } \ - DebugSleep(50); \ - } while (false) - -#define HANDLE_CLIENT_READ(Proc) \ - do { \ - if (!Proc) \ - { \ - ContiguousByteBuffer Leftover; \ - m_ClientBuffer.ReadAgain(Leftover); \ - DataLog(Leftover.data(), Leftover.size(), "Leftover data after client packet parsing, %d bytes:", Leftover.size()); \ - m_ClientBuffer.ResetRead(); \ - return true; \ - } \ - } while (false) - -#define HANDLE_SERVER_READ(Proc) \ - do { \ - if (!Proc) \ - { \ + break; \ + } \ + case csWaitingForEncryption: \ + { \ + break; \ + } \ + } \ + DebugSleep(50); \ + } \ + while (false) + +#define HANDLE_CLIENT_READ(Proc) \ + do \ + { \ + if (!Proc) \ + { \ + ContiguousByteBuffer Leftover; \ + m_ClientBuffer.ReadAgain(Leftover); \ + DataLog( \ + Leftover.data(), \ + Leftover.size(), \ + "Leftover data after client packet parsing, %d bytes:", \ + Leftover.size() \ + ); \ + m_ClientBuffer.ResetRead(); \ + return true; \ + } \ + } \ + while (false) + +#define HANDLE_SERVER_READ(Proc) \ + do \ + { \ + if (!Proc) \ + { \ m_ServerBuffer.ResetRead(); \ - return true; \ - } \ - } while (false) + return true; \ + } \ + } \ + while (false) @@ -153,8 +169,12 @@ AString PrintableAbsIntTriplet(int a_X, int a_Y, int a_Z, double a_Divisor) { return fmt::format( FMT_STRING("<{}, {}, {}> ~ {{{}, {}, {}}}"), - a_X, a_Y, a_Z, - static_cast<double>(a_X) / a_Divisor, static_cast<double>(a_Y) / a_Divisor, static_cast<double>(a_Z) / a_Divisor + a_X, + a_Y, + a_Z, + static_cast<double>(a_X) / a_Divisor, + static_cast<double>(a_Y) / a_Divisor, + static_cast<double>(a_Z) / a_Divisor ); } @@ -166,8 +186,11 @@ struct sCoords { int x, y, z; - sCoords(int a_X, int a_Y, int a_Z) : x(a_X), y(a_Y), z(a_Z) {} -} ; + sCoords(int a_X, int a_Y, int a_Z) : + x(a_X), y(a_Y), z(a_Z) + { + } +}; @@ -182,7 +205,7 @@ struct sChunkMeta m_ChunkX(a_ChunkX), m_ChunkZ(a_ChunkZ), m_PrimaryBitmap(a_PrimaryBitmap), m_AddBitmap(a_AddBitmap) { } -} ; +}; @@ -208,21 +231,21 @@ cConnection::cConnection(SOCKET a_ClientSocket, cServer & a_Server) : m_ClientProtocolState(-1), m_IsServerEncrypted(false) { - // Create the Logs subfolder, if not already created: - #if defined(_WIN32) - _mkdir("Logs"); - #else - mkdir("Logs", 0777); - #endif +// Create the Logs subfolder, if not already created: +#if defined(_WIN32) + _mkdir("Logs"); +#else + mkdir("Logs", 0777); +#endif m_LogNameBase = fmt::format(FMT_STRING("Logs/Log_{}_{}"), time(nullptr), a_ClientSocket); AString fnam(m_LogNameBase); fnam.append(".log"); - #ifdef _WIN32 - fopen_s(&m_LogFile, fnam.c_str(), "w"); - #else - m_LogFile = fopen(fnam.c_str(), "w"); - #endif +#ifdef _WIN32 + fopen_s(&m_LogFile, fnam.c_str(), "w"); +#else + m_LogFile = fopen(fnam.c_str(), "w"); +#endif Log("Log file created"); fmt::print(FMT_STRING("Connection is logged to file \"{}\"\n"), fnam); } @@ -292,9 +315,9 @@ void cConnection::vLog(const char * a_Format, fmt::printf_args a_ArgList) fmt::fprintf(m_LogFile, "[%5.3f] ", GetRelativeTime()); fmt::vfprintf(m_LogFile, a_Format, a_ArgList); fmt::fprintf(m_LogFile, "\n"); - #ifdef _DEBUG - fflush(m_LogFile); - #endif // _DEBUG +#ifdef _DEBUG + fflush(m_LogFile); +#endif // _DEBUG // Log to screen: // std::cout << FullMsg; @@ -359,7 +382,8 @@ bool cConnection::ConnectToServer(void) bool cConnection::RelayFromServer(void) { char Buffer[64 KiB]; - int res = static_cast<int>(recv(m_ServerSocket, Buffer, sizeof(Buffer), 0)); // recv returns int on windows, ssize_t on linux + int res = static_cast<int>(recv(m_ServerSocket, Buffer, sizeof(Buffer), 0) + ); // recv returns int on windows, ssize_t on linux if (res <= 0) { Log("Server closed the socket: %d; %d; aborting connection", res, SocketError); @@ -385,7 +409,7 @@ bool cConnection::RelayFromServer(void) { m_ServerDecryptor.ProcessData(reinterpret_cast<std::byte *>(Buffer), static_cast<size_t>(res)); DataLog(Buffer, static_cast<size_t>(res), "Decrypted %d bytes from the SERVER", res); - return CLIENTSEND({ reinterpret_cast<const std::byte *>(Buffer), static_cast<size_t>(res) }); + return CLIENTSEND({reinterpret_cast<const std::byte *>(Buffer), static_cast<size_t>(res)}); } } ASSERT(!"Unhandled server state while relaying from server"); @@ -399,7 +423,8 @@ bool cConnection::RelayFromServer(void) bool cConnection::RelayFromClient(void) { char Buffer[64 KiB]; - int res = static_cast<int>(recv(m_ClientSocket, Buffer, sizeof(Buffer), 0)); // recv returns int on Windows, ssize_t on Linux + int res = static_cast<int>(recv(m_ClientSocket, Buffer, sizeof(Buffer), 0) + ); // recv returns int on Windows, ssize_t on Linux if (res <= 0) { Log("Client closed the socket: %d; %d; aborting connection", res, SocketError); @@ -423,7 +448,7 @@ bool cConnection::RelayFromClient(void) { DataLog(Buffer, static_cast<size_t>(res), "Decrypted %d bytes from the CLIENT", res); m_ServerEncryptor.ProcessData(reinterpret_cast<std::byte *>(Buffer), static_cast<size_t>(res)); - return SERVERSEND({ reinterpret_cast<const std::byte *>(Buffer), static_cast<size_t>(res) }); + return SERVERSEND({reinterpret_cast<const std::byte *>(Buffer), static_cast<size_t>(res)}); } } ASSERT(!"Unhandled server state while relaying from client"); @@ -436,7 +461,8 @@ bool cConnection::RelayFromClient(void) double cConnection::GetRelativeTime(void) { - Int64 msec = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - m_BeginTick).count(); + Int64 msec = + std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - m_BeginTick).count(); return static_cast<double>(msec) / 1000; } @@ -448,7 +474,9 @@ bool cConnection::SendData(SOCKET a_Socket, const ContiguousByteBufferView a_Dat { DataLog(a_Data.data(), a_Data.size(), "Sending data to %s, %zu bytes", a_Peer, a_Data.size()); - int res = static_cast<int>(send(a_Socket, reinterpret_cast<const char *>(a_Data.data()), a_Data.size(), 0)); // Windows uses int for a_Size, Linux uses size_t; but Windows doesn't complain. Return type is int on Windows and ssize_t on Linux + int res = static_cast<int>(send(a_Socket, reinterpret_cast<const char *>(a_Data.data()), a_Data.size(), 0) + ); // Windows uses int for a_Size, Linux uses size_t; but Windows doesn't complain. Return type is int on Windows + // and ssize_t on Linux if (res <= 0) { Log("%s closed the socket: %d, %d; aborting connection", a_Peer, res, SocketError); @@ -473,7 +501,12 @@ bool cConnection::SendData(SOCKET a_Socket, cByteBuffer & a_Data, const char * a -bool cConnection::SendEncryptedData(SOCKET a_Socket, cAesCfb128Encryptor & a_Encryptor, ContiguousByteBuffer & a_Data, const char * a_Peer) +bool cConnection::SendEncryptedData( + SOCKET a_Socket, + cAesCfb128Encryptor & a_Encryptor, + ContiguousByteBuffer & a_Data, + const char * a_Peer +) { DataLog(a_Data.data(), a_Data.size(), "Encrypting %zu bytes to %s", a_Data.size(), a_Peer); @@ -485,7 +518,12 @@ bool cConnection::SendEncryptedData(SOCKET a_Socket, cAesCfb128Encryptor & a_Enc -bool cConnection::SendEncryptedData(SOCKET a_Socket, cAesCfb128Encryptor & a_Encryptor, cByteBuffer & a_Data, const char * a_Peer) +bool cConnection::SendEncryptedData( + SOCKET a_Socket, + cAesCfb128Encryptor & a_Encryptor, + cByteBuffer & a_Data, + const char * a_Peer +) { ContiguousByteBuffer All; a_Data.ReadAll(All); @@ -508,10 +546,7 @@ bool cConnection::DecodeClientsPackets(const char * a_Data, int a_Size) while (m_ClientBuffer.CanReadBytes(1)) { UInt32 PacketLen; - if ( - !m_ClientBuffer.ReadVarInt(PacketLen) || - !m_ClientBuffer.CanReadBytes(PacketLen) - ) + if (!m_ClientBuffer.ReadVarInt(PacketLen) || !m_ClientBuffer.CanReadBytes(PacketLen)) { // Not a complete packet yet break; @@ -521,8 +556,9 @@ bool cConnection::DecodeClientsPackets(const char * a_Data, int a_Size) VERIFY(m_ClientBuffer.ReadVarInt(PacketType)); PacketReadSoFar -= m_ClientBuffer.GetReadableSpace(); Log("Decoding client's packets, there are now %u bytes in the queue; next packet is 0x%02x, %u bytes long", - static_cast<unsigned>(m_ClientBuffer.GetReadableSpace()), PacketType, PacketLen - ); + static_cast<unsigned>(m_ClientBuffer.GetReadableSpace()), + PacketType, + PacketLen); switch (m_ClientProtocolState) { case -1: @@ -531,7 +567,9 @@ bool cConnection::DecodeClientsPackets(const char * a_Data, int a_Size) switch (PacketType) { case 0x00: HANDLE_CLIENT_READ(HandleClientHandshake()); break; - default: HANDLE_CLIENT_READ(HandleClientUnknownPacket(PacketType, PacketLen, PacketReadSoFar)); break; + default: + HANDLE_CLIENT_READ(HandleClientUnknownPacket(PacketType, PacketLen, PacketReadSoFar)); + break; } break; } // case -1 @@ -543,7 +581,9 @@ bool cConnection::DecodeClientsPackets(const char * a_Data, int a_Size) { case 0x00: HANDLE_CLIENT_READ(HandleClientStatusRequest()); break; case 0x01: HANDLE_CLIENT_READ(HandleClientStatusPing()); break; - default: HANDLE_CLIENT_READ(HandleClientUnknownPacket(PacketType, PacketLen, PacketReadSoFar)); break; + default: + HANDLE_CLIENT_READ(HandleClientUnknownPacket(PacketType, PacketLen, PacketReadSoFar)); + break; } break; } @@ -555,7 +595,9 @@ bool cConnection::DecodeClientsPackets(const char * a_Data, int a_Size) { case 0x00: HANDLE_CLIENT_READ(HandleClientLoginStart()); break; case 0x01: HANDLE_CLIENT_READ(HandleClientLoginEncryptionKeyResponse()); break; - default: HANDLE_CLIENT_READ(HandleClientUnknownPacket(PacketType, PacketLen, PacketReadSoFar)); break; + default: + HANDLE_CLIENT_READ(HandleClientUnknownPacket(PacketType, PacketLen, PacketReadSoFar)); + break; } break; } @@ -586,7 +628,9 @@ bool cConnection::DecodeClientsPackets(const char * a_Data, int a_Size) case 0x15: HANDLE_CLIENT_READ(HandleClientLocaleAndView()); break; case 0x16: HANDLE_CLIENT_READ(HandleClientClientStatuses()); break; case 0x17: HANDLE_CLIENT_READ(HandleClientPluginMessage()); break; - default: HANDLE_CLIENT_READ(HandleClientUnknownPacket(PacketType, PacketLen, PacketReadSoFar)); break; + default: + HANDLE_CLIENT_READ(HandleClientUnknownPacket(PacketType, PacketLen, PacketReadSoFar)); + break; } break; } // case 3 - Game @@ -615,10 +659,7 @@ bool cConnection::DecodeServersPackets(const char * a_Data, int a_Size) return false; } - if ( - (m_ServerState == csEncryptedUnderstood) && - (m_ClientState == csUnencrypted) - ) + if ((m_ServerState == csEncryptedUnderstood) && (m_ClientState == csUnencrypted)) { // Client hasn't finished encryption handshake yet, don't send them any data yet } @@ -626,10 +667,7 @@ bool cConnection::DecodeServersPackets(const char * a_Data, int a_Size) while (true) { UInt32 PacketLen; - if ( - !m_ServerBuffer.ReadVarInt(PacketLen) || - !m_ServerBuffer.CanReadBytes(PacketLen) - ) + if (!m_ServerBuffer.ReadVarInt(PacketLen) || !m_ServerBuffer.CanReadBytes(PacketLen)) { // Not a complete packet yet m_ServerBuffer.ResetRead(); @@ -648,7 +686,10 @@ bool cConnection::DecodeServersPackets(const char * a_Data, int a_Size) PacketReadSoFar = static_cast<UInt32>(m_ServerBuffer.GetReadableSpace()); VERIFY(m_ServerBuffer.ReadVarInt(PacketType)); PacketReadSoFar -= m_ServerBuffer.GetReadableSpace(); - Log("Decoding server's packets, there are now %d bytes in the queue; next packet is 0x%0x, %u bytes long", m_ServerBuffer.GetReadableSpace(), PacketType, PacketLen); + Log("Decoding server's packets, there are now %d bytes in the queue; next packet is 0x%0x, %u bytes long", + m_ServerBuffer.GetReadableSpace(), + PacketType, + PacketLen); LogFlush(); switch (m_ServerProtocolState) { @@ -665,8 +706,10 @@ bool cConnection::DecodeServersPackets(const char * a_Data, int a_Size) switch (PacketType) { case 0x00: HANDLE_SERVER_READ(HandleServerStatusResponse()); break; - case 0x01: HANDLE_SERVER_READ(HandleServerStatusPing()); break; - default: HANDLE_SERVER_READ(HandleServerUnknownPacket(PacketType, PacketLen, PacketReadSoFar)); break; + case 0x01: HANDLE_SERVER_READ(HandleServerStatusPing()); break; + default: + HANDLE_SERVER_READ(HandleServerUnknownPacket(PacketType, PacketLen, PacketReadSoFar)); + break; } break; } @@ -679,7 +722,9 @@ bool cConnection::DecodeServersPackets(const char * a_Data, int a_Size) case 0x00: HANDLE_SERVER_READ(HandleServerLoginDisconnect()); break; case 0x01: HANDLE_SERVER_READ(HandleServerLoginEncryptionKeyRequest()); break; case 0x02: HANDLE_SERVER_READ(HandleServerLoginSuccess()); break; - default: HANDLE_SERVER_READ(HandleServerUnknownPacket(PacketType, PacketLen, PacketReadSoFar)); break; + default: + HANDLE_SERVER_READ(HandleServerUnknownPacket(PacketType, PacketLen, PacketReadSoFar)); + break; } break; } @@ -741,7 +786,9 @@ bool cConnection::DecodeServersPackets(const char * a_Data, int a_Size) case 0x3a: HANDLE_SERVER_READ(HandleServerTabCompletion()); break; case 0x3f: HANDLE_SERVER_READ(HandleServerPluginMessage()); break; case 0x40: HANDLE_SERVER_READ(HandleServerKick()); break; - default: HANDLE_SERVER_READ(HandleServerUnknownPacket(PacketType, PacketLen, PacketReadSoFar)); break; + default: + HANDLE_SERVER_READ(HandleServerUnknownPacket(PacketType, PacketLen, PacketReadSoFar)); + break; } // switch (PacketType) break; } // case 3 - Game @@ -770,10 +817,10 @@ bool cConnection::DecodeServersPackets(const char * a_Data, int a_Size) bool cConnection::HandleClientHandshake(void) { // Read the packet from the client: - HANDLE_CLIENT_PACKET_READ(ReadVarInt, UInt32, ProtocolVersion); + HANDLE_CLIENT_PACKET_READ(ReadVarInt, UInt32, ProtocolVersion); HANDLE_CLIENT_PACKET_READ(ReadVarUTF8String, AString, ServerHost); - HANDLE_CLIENT_PACKET_READ(ReadBEUInt16, UInt16, ServerPort); - HANDLE_CLIENT_PACKET_READ(ReadVarInt, UInt32, NextState); + HANDLE_CLIENT_PACKET_READ(ReadBEUInt16, UInt16, ServerPort); + HANDLE_CLIENT_PACKET_READ(ReadVarInt, UInt32, NextState); m_ClientBuffer.CommitRead(); Log("Received an initial handshake packet from the client:"); @@ -838,7 +885,7 @@ bool cConnection::HandleClientLoginStart(void) bool cConnection::HandleClientAnimation(void) { HANDLE_CLIENT_PACKET_READ(ReadBEUInt32, UInt32, EntityID); - HANDLE_CLIENT_PACKET_READ(ReadBEInt8, Int8, Animation); + HANDLE_CLIENT_PACKET_READ(ReadBEInt8, Int8, Animation); Log("Received a PACKET_ANIMATION from the client:"); Log(" EntityID: %u", EntityID); Log(" Animation: %d", Animation); @@ -987,11 +1034,11 @@ bool cConnection::HandleClientKeepAlive(void) bool cConnection::HandleClientLocaleAndView(void) { HANDLE_CLIENT_PACKET_READ(ReadVarUTF8String, AString, Locale); - HANDLE_CLIENT_PACKET_READ(ReadBEInt8, Int8, ViewDistance); - HANDLE_CLIENT_PACKET_READ(ReadBEInt8, Int8, ChatFlags); - HANDLE_CLIENT_PACKET_READ(ReadBEInt8, Int8, Unused); - HANDLE_CLIENT_PACKET_READ(ReadBEInt8, Int8, Difficulty); - HANDLE_CLIENT_PACKET_READ(ReadBEInt8, Int8, ShowCape); + HANDLE_CLIENT_PACKET_READ(ReadBEInt8, Int8, ViewDistance); + HANDLE_CLIENT_PACKET_READ(ReadBEInt8, Int8, ChatFlags); + HANDLE_CLIENT_PACKET_READ(ReadBEInt8, Int8, Unused); + HANDLE_CLIENT_PACKET_READ(ReadBEInt8, Int8, Difficulty); + HANDLE_CLIENT_PACKET_READ(ReadBEInt8, Int8, ShowCape); Log("Received a PACKET_LOCALE_AND_VIEW from the client"); COPY_TO_SERVER(); return true; @@ -1063,7 +1110,7 @@ bool cConnection::HandleClientPlayerPosition(void) HANDLE_CLIENT_PACKET_READ(ReadBEDouble, double, PosY); HANDLE_CLIENT_PACKET_READ(ReadBEDouble, double, Stance); HANDLE_CLIENT_PACKET_READ(ReadBEDouble, double, PosZ); - HANDLE_CLIENT_PACKET_READ(ReadBEUInt8, UInt8, IsOnGround); + HANDLE_CLIENT_PACKET_READ(ReadBEUInt8, UInt8, IsOnGround); Log("Received a PACKET_PLAYER_POSITION from the client"); // TODO: list packet contents @@ -1082,9 +1129,9 @@ bool cConnection::HandleClientPlayerPositionLook(void) HANDLE_CLIENT_PACKET_READ(ReadBEDouble, double, PosY); HANDLE_CLIENT_PACKET_READ(ReadBEDouble, double, Stance); HANDLE_CLIENT_PACKET_READ(ReadBEDouble, double, PosZ); - HANDLE_CLIENT_PACKET_READ(ReadBEFloat, float, Yaw); - HANDLE_CLIENT_PACKET_READ(ReadBEFloat, float, Pitch); - HANDLE_CLIENT_PACKET_READ(ReadBEUInt8, UInt8, IsOnGround); + HANDLE_CLIENT_PACKET_READ(ReadBEFloat, float, Yaw); + HANDLE_CLIENT_PACKET_READ(ReadBEFloat, float, Pitch); + HANDLE_CLIENT_PACKET_READ(ReadBEUInt8, UInt8, IsOnGround); Log("Received a PACKET_PLAYER_POSITION_LOOK from the client"); Log(" Pos = {%.03f, %.03f, %.03f}", PosX, PosY, PosZ); Log(" Stance = %.03f", Stance); @@ -1102,7 +1149,7 @@ bool cConnection::HandleClientPlayerPositionLook(void) bool cConnection::HandleClientPluginMessage(void) { HANDLE_CLIENT_PACKET_READ(ReadVarUTF8String, AString, ChannelName); - HANDLE_CLIENT_PACKET_READ(ReadBEUInt16, UInt16, Length); + HANDLE_CLIENT_PACKET_READ(ReadBEUInt16, UInt16, Length); ContiguousByteBuffer Data; if (!m_ClientBuffer.ReadSome(Data, Length)) { @@ -1171,9 +1218,9 @@ bool cConnection::HandleClientTabCompletion(void) bool cConnection::HandleClientUpdateSign(void) { - HANDLE_CLIENT_PACKET_READ(ReadBEInt32, Int32, BlockX); - HANDLE_CLIENT_PACKET_READ(ReadBEInt16, Int16, BlockY); - HANDLE_CLIENT_PACKET_READ(ReadBEInt32, Int32, BlockZ); + HANDLE_CLIENT_PACKET_READ(ReadBEInt32, Int32, BlockX); + HANDLE_CLIENT_PACKET_READ(ReadBEInt16, Int16, BlockY); + HANDLE_CLIENT_PACKET_READ(ReadBEInt32, Int32, BlockZ); HANDLE_CLIENT_PACKET_READ(ReadVarUTF8String, AString, Line1); HANDLE_CLIENT_PACKET_READ(ReadVarUTF8String, AString, Line2); HANDLE_CLIENT_PACKET_READ(ReadVarUTF8String, AString, Line3); @@ -1192,7 +1239,7 @@ bool cConnection::HandleClientUpdateSign(void) bool cConnection::HandleClientUseEntity(void) { HANDLE_CLIENT_PACKET_READ(ReadBEUInt32, UInt32, EntityID); - HANDLE_CLIENT_PACKET_READ(ReadBEUInt8, UInt8, MouseButton); + HANDLE_CLIENT_PACKET_READ(ReadBEUInt8, UInt8, MouseButton); Log("Received a PACKET_USE_ENTITY from the client:"); Log(" EntityID = %d", EntityID); Log(" MouseButton = %u", MouseButton); @@ -1206,11 +1253,11 @@ bool cConnection::HandleClientUseEntity(void) bool cConnection::HandleClientWindowClick(void) { - HANDLE_CLIENT_PACKET_READ(ReadBEUInt8, UInt8, WindowID); + HANDLE_CLIENT_PACKET_READ(ReadBEUInt8, UInt8, WindowID); HANDLE_CLIENT_PACKET_READ(ReadBEUInt16, UInt16, SlotNum); - HANDLE_CLIENT_PACKET_READ(ReadBEUInt8, UInt8, Button); + HANDLE_CLIENT_PACKET_READ(ReadBEUInt8, UInt8, Button); HANDLE_CLIENT_PACKET_READ(ReadBEUInt16, UInt16, TransactionID); - HANDLE_CLIENT_PACKET_READ(ReadBEUInt8, UInt8, Mode); + HANDLE_CLIENT_PACKET_READ(ReadBEUInt8, UInt8, Mode); AString Item; if (!ParseSlot(m_ClientBuffer, Item)) { @@ -1250,7 +1297,12 @@ bool cConnection::HandleClientUnknownPacket(UInt32 a_PacketType, UInt32 a_Packet { return false; } - DataLog(Data.data(), Data.size(), "****************** Unknown packet 0x%x from the client; relaying and ignoring", a_PacketType); + DataLog( + Data.data(), + Data.size(), + "****************** Unknown packet 0x%x from the client; relaying and ignoring", + a_PacketType + ); COPY_TO_SERVER(); return true; } @@ -1279,7 +1331,7 @@ bool cConnection::HandleServerLoginEncryptionKeyRequest(void) { // Read the packet from the server: HANDLE_SERVER_PACKET_READ(ReadVarUTF8String, AString, ServerID); - HANDLE_SERVER_PACKET_READ(ReadBEUInt16, UInt16, PublicKeyLength); + HANDLE_SERVER_PACKET_READ(ReadBEUInt16, UInt16, PublicKeyLength); ContiguousByteBuffer PublicKey; if (!m_ServerBuffer.ReadSome(PublicKey, PublicKeyLength)) { @@ -1296,7 +1348,10 @@ bool cConnection::HandleServerLoginEncryptionKeyRequest(void) DataLog(PublicKey.data(), PublicKey.size(), " Public key (%u bytes)", static_cast<unsigned>(PublicKey.size())); // Reply to the server: - SendEncryptionKeyResponse({ reinterpret_cast<const char *>(PublicKey.data()), PublicKey.size() }, { reinterpret_cast<const char *>(Nonce.data()), Nonce.size() }); + SendEncryptionKeyResponse( + {reinterpret_cast<const char *>(PublicKey.data()), PublicKey.size()}, + {reinterpret_cast<const char *>(Nonce.data()), Nonce.size()} + ); // Do not send to client - we want the client connection open return true; @@ -1321,7 +1376,12 @@ bool cConnection::HandleServerLoginSuccess(void) { Log("Server communication is now encrypted"); m_ServerState = csEncryptedUnderstood; - DataLog(m_ServerEncryptionBuffer.data(), m_ServerEncryptionBuffer.size(), "Sending the queued data to server (%u bytes):", m_ServerEncryptionBuffer.size()); + DataLog( + m_ServerEncryptionBuffer.data(), + m_ServerEncryptionBuffer.size(), + "Sending the queued data to server (%u bytes):", + m_ServerEncryptionBuffer.size() + ); SERVERENCRYPTSEND(m_ServerEncryptionBuffer); m_ServerEncryptionBuffer.clear(); } @@ -1340,9 +1400,9 @@ bool cConnection::HandleServerLoginSuccess(void) bool cConnection::HandleServerAttachEntity(void) { - HANDLE_SERVER_PACKET_READ(ReadBEUInt32, UInt32, EntityID); - HANDLE_SERVER_PACKET_READ(ReadBEUInt32, UInt32, VehicleID); - HANDLE_SERVER_PACKET_READ(ReadBool, bool, IsOnLeash); + HANDLE_SERVER_PACKET_READ(ReadBEUInt32, UInt32, EntityID); + HANDLE_SERVER_PACKET_READ(ReadBEUInt32, UInt32, VehicleID); + HANDLE_SERVER_PACKET_READ(ReadBool, bool, IsOnLeash); Log("Received a PACKET_ATTACH_ENTITY from the server:"); Log(" EntityID = %u (0x%x)", EntityID, EntityID); Log(" VehicleID = %u (0x%x)", VehicleID, VehicleID); @@ -1357,12 +1417,12 @@ bool cConnection::HandleServerAttachEntity(void) bool cConnection::HandleServerBlockAction(void) { - HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, BlockX); - HANDLE_SERVER_PACKET_READ(ReadBEInt16, Int16, BlockY); - HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, BlockZ); - HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Byte1); - HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Byte2); - HANDLE_SERVER_PACKET_READ(ReadVarInt, UInt32, BlockID); + HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, BlockX); + HANDLE_SERVER_PACKET_READ(ReadBEInt16, Int16, BlockY); + HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, BlockZ); + HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Byte1); + HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Byte2); + HANDLE_SERVER_PACKET_READ(ReadVarInt, UInt32, BlockID); Log("Received a PACKET_BLOCK_ACTION from the server:"); Log(" Pos = {%d, %d, %d}", BlockX, BlockY, BlockZ); Log(" Bytes = (%u, %u) == (0x%x, 0x%x)", Byte1, Byte2, Byte1, Byte2); @@ -1377,11 +1437,11 @@ bool cConnection::HandleServerBlockAction(void) bool cConnection::HandleServerBlockChange(void) { - HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, BlockX); - HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, BlockY); - HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, BlockZ); - HANDLE_SERVER_PACKET_READ(ReadVarInt, UInt32, BlockType); - HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, BlockMeta); + HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, BlockX); + HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, BlockY); + HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, BlockZ); + HANDLE_SERVER_PACKET_READ(ReadVarInt, UInt32, BlockType); + HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, BlockMeta); Log("Received a PACKET_BLOCK_CHANGE from the server"); Log(" Pos = {%d, %u, %d}", BlockX, BlockY, BlockZ); Log(" BlockType = %u (0x%x", BlockType, BlockType); @@ -1396,7 +1456,7 @@ bool cConnection::HandleServerBlockChange(void) bool cConnection::HandleServerChangeGameState(void) { - HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Reason); + HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Reason); HANDLE_SERVER_PACKET_READ(ReadBEFloat, float, Data); Log("Received a PACKET_CHANGE_GAME_STATE from the server:"); Log(" Reason = %u", Reason); @@ -1506,7 +1566,7 @@ bool cConnection::HandleServerEntityEquipment(void) bool cConnection::HandleServerEntityHeadLook(void) { HANDLE_SERVER_PACKET_READ(ReadBEUInt32, UInt32, EntityID); - HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, HeadYaw); + HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, HeadYaw); Log("Received a PACKET_ENTITY_HEAD_LOOK from the server:"); Log(" EntityID = %u", EntityID); Log(" HeadYaw = %u", HeadYaw); @@ -1520,9 +1580,9 @@ bool cConnection::HandleServerEntityHeadLook(void) bool cConnection::HandleServerEntityLook(void) { - HANDLE_SERVER_PACKET_READ(ReadBEUInt32, UInt32, EntityID); - HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Yaw); - HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Pitch); + HANDLE_SERVER_PACKET_READ(ReadBEUInt32, UInt32, EntityID); + HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Yaw); + HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Pitch); Log("Received a PACKET_ENTITY_LOOK from the server:"); Log(" EntityID = %u", EntityID); Log(" Yaw = %u", Yaw); @@ -1569,15 +1629,15 @@ bool cConnection::HandleServerEntityProperties(void) for (UInt32 i = 0; i < Count; i++) { HANDLE_SERVER_PACKET_READ(ReadVarUTF8String, AString, Key); - HANDLE_SERVER_PACKET_READ(ReadBEDouble, double, Value); - HANDLE_SERVER_PACKET_READ(ReadBEUInt16, UInt16, ListLength); + HANDLE_SERVER_PACKET_READ(ReadBEDouble, double, Value); + HANDLE_SERVER_PACKET_READ(ReadBEUInt16, UInt16, ListLength); Log(" \"%s\" = %f; %u modifiers", Key.c_str(), Value, ListLength); for (UInt16 j = 0; j < ListLength; j++) { HANDLE_SERVER_PACKET_READ(ReadBEUInt64, UInt64, UUIDHi); HANDLE_SERVER_PACKET_READ(ReadBEUInt64, UInt64, UUIDLo); HANDLE_SERVER_PACKET_READ(ReadBEDouble, double, DblVal); - HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, ByteVal); + HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, ByteVal); Log(" [%d] = {0x%08llx%08llx, %f, %u}", j, UUIDHi, UUIDLo, DblVal, ByteVal); } } // for i @@ -1592,9 +1652,9 @@ bool cConnection::HandleServerEntityProperties(void) bool cConnection::HandleServerEntityRelativeMove(void) { HANDLE_SERVER_PACKET_READ(ReadBEUInt32, UInt32, EntityID); - HANDLE_SERVER_PACKET_READ(ReadBEInt8, Int8, dx); - HANDLE_SERVER_PACKET_READ(ReadBEInt8, Int8, dy); - HANDLE_SERVER_PACKET_READ(ReadBEInt8, Int8, dz); + HANDLE_SERVER_PACKET_READ(ReadBEInt8, Int8, dx); + HANDLE_SERVER_PACKET_READ(ReadBEInt8, Int8, dy); + HANDLE_SERVER_PACKET_READ(ReadBEInt8, Int8, dz); Log("Received a PACKET_ENTITY_RELATIVE_MOVE from the server:"); Log(" EntityID = %u", EntityID); Log(" RelMove = %s", PrintableAbsIntTriplet(dx, dy, dz).c_str()); @@ -1609,11 +1669,11 @@ bool cConnection::HandleServerEntityRelativeMove(void) bool cConnection::HandleServerEntityRelativeMoveLook(void) { HANDLE_SERVER_PACKET_READ(ReadBEUInt32, UInt32, EntityID); - HANDLE_SERVER_PACKET_READ(ReadBEInt8, Int8, dx); - HANDLE_SERVER_PACKET_READ(ReadBEInt8, Int8, dy); - HANDLE_SERVER_PACKET_READ(ReadBEInt8, Int8, dz); - HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Yaw); - HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Pitch); + HANDLE_SERVER_PACKET_READ(ReadBEInt8, Int8, dx); + HANDLE_SERVER_PACKET_READ(ReadBEInt8, Int8, dy); + HANDLE_SERVER_PACKET_READ(ReadBEInt8, Int8, dz); + HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Yaw); + HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Pitch); Log("Received a PACKET_ENTITY_RELATIVE_MOVE_LOOK from the server:"); Log(" EntityID = %u", EntityID); Log(" RelMove = %s", PrintableAbsIntTriplet(dx, dy, dz).c_str()); @@ -1630,7 +1690,7 @@ bool cConnection::HandleServerEntityRelativeMoveLook(void) bool cConnection::HandleServerEntityStatus(void) { HANDLE_SERVER_PACKET_READ(ReadBEUInt32, UInt32, EntityID); - HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Status); + HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Status); Log("Received a PACKET_ENTITY_STATUS from the server:"); Log(" EntityID = %u", EntityID); Log(" Status = %u (0x%02x)", Status, Status); @@ -1644,12 +1704,12 @@ bool cConnection::HandleServerEntityStatus(void) bool cConnection::HandleServerEntityTeleport(void) { - HANDLE_SERVER_PACKET_READ(ReadBEUInt32, UInt32, EntityID); - HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, AbsX); - HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, AbsY); - HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, AbsZ); - HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Yaw); - HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Pitch); + HANDLE_SERVER_PACKET_READ(ReadBEUInt32, UInt32, EntityID); + HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, AbsX); + HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, AbsY); + HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, AbsZ); + HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Yaw); + HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Pitch); Log("Received a PACKET_ENTITY_TELEPORT from the server:"); Log(" EntityID = %u", EntityID); Log(" Pos = %s", PrintableAbsIntTriplet(AbsX, AbsY, AbsZ).c_str()); @@ -1666,9 +1726,9 @@ bool cConnection::HandleServerEntityTeleport(void) bool cConnection::HandleServerEntityVelocity(void) { HANDLE_SERVER_PACKET_READ(ReadBEUInt32, UInt32, EntityID); - HANDLE_SERVER_PACKET_READ(ReadBEInt16, Int16, VelocityX); - HANDLE_SERVER_PACKET_READ(ReadBEInt16, Int16, VelocityY); - HANDLE_SERVER_PACKET_READ(ReadBEInt16, Int16, VelocityZ); + HANDLE_SERVER_PACKET_READ(ReadBEInt16, Int16, VelocityX); + HANDLE_SERVER_PACKET_READ(ReadBEInt16, Int16, VelocityY); + HANDLE_SERVER_PACKET_READ(ReadBEInt16, Int16, VelocityZ); Log("Received a PACKET_ENTITY_VELOCITY from the server:"); Log(" EntityID = %u", EntityID); Log(" Velocity = %s", PrintableAbsIntTriplet(VelocityX, VelocityY, VelocityZ, 8000).c_str()); @@ -1682,10 +1742,10 @@ bool cConnection::HandleServerEntityVelocity(void) bool cConnection::HandleServerExplosion(void) { - HANDLE_SERVER_PACKET_READ(ReadBEFloat, float, PosX); - HANDLE_SERVER_PACKET_READ(ReadBEFloat, float, PosY); - HANDLE_SERVER_PACKET_READ(ReadBEFloat, float, PosZ); - HANDLE_SERVER_PACKET_READ(ReadBEFloat, float, Force); + HANDLE_SERVER_PACKET_READ(ReadBEFloat, float, PosX); + HANDLE_SERVER_PACKET_READ(ReadBEFloat, float, PosY); + HANDLE_SERVER_PACKET_READ(ReadBEFloat, float, PosZ); + HANDLE_SERVER_PACKET_READ(ReadBEFloat, float, Force); HANDLE_SERVER_PACKET_READ(ReadBEUInt32, UInt32, NumRecords); std::vector<sCoords> Records; Records.reserve(NumRecords); @@ -1721,7 +1781,7 @@ bool cConnection::HandleServerIncrementStatistic(void) { // 0xc8 HANDLE_SERVER_PACKET_READ(ReadBEUInt32, UInt32, StatisticID); - HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, Amount); + HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, Amount); Log("Received a PACKET_INCREMENT_STATISTIC from the server:"); Log(" StatisticID = %u (0x%x)", StatisticID, StatisticID); Log(" Amount = %d", Amount); @@ -1735,18 +1795,18 @@ bool cConnection::HandleServerIncrementStatistic(void) bool cConnection::HandleServerJoinGame(void) { - HANDLE_SERVER_PACKET_READ(ReadBEUInt32, UInt32, EntityID); - HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, GameMode); - HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Dimension); - HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Difficulty); - HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, MaxPlayers); + HANDLE_SERVER_PACKET_READ(ReadBEUInt32, UInt32, EntityID); + HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, GameMode); + HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Dimension); + HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Difficulty); + HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, MaxPlayers); HANDLE_SERVER_PACKET_READ(ReadVarUTF8String, AString, LevelType); Log("Received a PACKET_LOGIN from the server:"); - Log(" EntityID = %u", EntityID); - Log(" GameMode = %u", GameMode); - Log(" Dimension = %u", Dimension); - Log(" Difficulty = %u", Difficulty); - Log(" MaxPlayers = %u", MaxPlayers); + Log(" EntityID = %u", EntityID); + Log(" GameMode = %u", GameMode); + Log(" Dimension = %u", Dimension); + Log(" Difficulty = %u", Difficulty); + Log(" MaxPlayers = %u", MaxPlayers); Log(" LevelType = \"%s\"", LevelType.c_str()); COPY_TO_CLIENT(); return true; @@ -1819,8 +1879,8 @@ bool cConnection::HandleServerKick(void) AString PacketStart("\xff"); PacketStart.push_back(static_cast<char>(ReasonBE16.size() / 256)); PacketStart.push_back(static_cast<char>(ReasonBE16.size() % 256)); - CLIENTSEND({ reinterpret_cast<const std::byte *>(PacketStart.data()), PacketStart.size() }); - CLIENTSEND({ reinterpret_cast<const std::byte *>(ReasonBE16.data()), ReasonBE16.size() * sizeof(char16_t) }); + CLIENTSEND({reinterpret_cast<const std::byte *>(PacketStart.data()), PacketStart.size()}); + CLIENTSEND({reinterpret_cast<const std::byte *>(ReasonBE16.data()), ReasonBE16.size() * sizeof(char16_t)}); return true; } else @@ -1842,9 +1902,9 @@ bool cConnection::HandleServerKick(void) bool cConnection::HandleServerMapChunk(void) { - HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, ChunkX); - HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, ChunkZ); - HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, IsContiguous); + HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, ChunkX); + HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, ChunkZ); + HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, IsContiguous); HANDLE_SERVER_PACKET_READ(ReadBEUInt16, UInt16, PrimaryBitmap); HANDLE_SERVER_PACKET_READ(ReadBEUInt16, UInt16, AdditionalBitmap); HANDLE_SERVER_PACKET_READ(ReadBEUInt32, UInt32, CompressedSize); @@ -1871,7 +1931,7 @@ bool cConnection::HandleServerMapChunkBulk(void) { HANDLE_SERVER_PACKET_READ(ReadBEUInt16, UInt16, ChunkCount); HANDLE_SERVER_PACKET_READ(ReadBEUInt32, UInt32, CompressedSize); - HANDLE_SERVER_PACKET_READ(ReadBool, bool, IsSkyLightSent); + HANDLE_SERVER_PACKET_READ(ReadBool, bool, IsSkyLightSent); ContiguousByteBuffer CompressedData; if (!m_ServerBuffer.ReadSome(CompressedData, CompressedSize)) { @@ -1902,8 +1962,11 @@ bool cConnection::HandleServerMapChunkBulk(void) for (sChunkMetas::iterator itr = ChunkMetas.begin(), end = ChunkMetas.end(); itr != end; ++itr, ++idx) { Log(" [%d]: [%d, %d], primary bitmap 0x%02x, add bitmap 0x%02x", - idx, itr->m_ChunkX, itr->m_ChunkZ, itr->m_PrimaryBitmap, itr->m_AddBitmap - ); + idx, + itr->m_ChunkX, + itr->m_ChunkZ, + itr->m_PrimaryBitmap, + itr->m_AddBitmap); } // for itr - ChunkMetas[] // TODO: Save the compressed data into a file for later analysis @@ -1918,8 +1981,8 @@ bool cConnection::HandleServerMapChunkBulk(void) bool cConnection::HandleServerMultiBlockChange(void) { - HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, ChunkX); - HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, ChunkZ); + HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, ChunkX); + HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, ChunkZ); HANDLE_SERVER_PACKET_READ(ReadBEUInt16, UInt16, NumBlocks); HANDLE_SERVER_PACKET_READ(ReadBEUInt32, UInt32, DataSize); ContiguousByteBuffer BlockChangeData; @@ -1941,11 +2004,11 @@ bool cConnection::HandleServerMultiBlockChange(void) bool cConnection::HandleServerNamedSoundEffect(void) { HANDLE_SERVER_PACKET_READ(ReadVarUTF8String, AString, SoundName); - HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, PosX); - HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, PosY); - HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, PosZ); - HANDLE_SERVER_PACKET_READ(ReadBEFloat, float, Volume); - HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Pitch); + HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, PosX); + HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, PosY); + HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, PosZ); + HANDLE_SERVER_PACKET_READ(ReadBEFloat, float, Volume); + HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Pitch); Log("Received a PACKET_NAMED_SOUND_EFFECT from the server:"); Log(" SoundName = \"%s\"", SoundName.c_str()); Log(" Pos = %s", PrintableAbsIntTriplet(PosX, PosY, PosZ, 8).c_str()); @@ -1978,8 +2041,8 @@ bool cConnection::HandleServerPlayerAbilities(void) bool cConnection::HandleServerPlayerAnimation(void) { - HANDLE_SERVER_PACKET_READ(ReadVarInt, UInt32, PlayerID); - HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, AnimationID); + HANDLE_SERVER_PACKET_READ(ReadVarInt, UInt32, PlayerID); + HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, AnimationID); Log("Received a PACKET_PLAYER_ANIMATION from the server:"); Log(" PlayerID: %u (0x%x)", PlayerID, PlayerID); Log(" Animation: %u", AnimationID); @@ -1994,8 +2057,8 @@ bool cConnection::HandleServerPlayerAnimation(void) bool cConnection::HandleServerPlayerListItem(void) { HANDLE_SERVER_PACKET_READ(ReadVarUTF8String, AString, PlayerName); - HANDLE_SERVER_PACKET_READ(ReadBool, bool, IsOnline); - HANDLE_SERVER_PACKET_READ(ReadBEUInt16, UInt16, Ping); + HANDLE_SERVER_PACKET_READ(ReadBool, bool, IsOnline); + HANDLE_SERVER_PACKET_READ(ReadBEUInt16, UInt16, Ping); Log("Received a PACKET_PLAYERLIST_ITEM from the server:"); Log(" PlayerName = \"%s\" (%s)", PlayerName.c_str(), IsOnline ? "online" : "offline"); Log(" Ping = %d", Ping); @@ -2012,9 +2075,9 @@ bool cConnection::HandleServerPlayerPositionLook(void) HANDLE_SERVER_PACKET_READ(ReadBEDouble, double, PosX); HANDLE_SERVER_PACKET_READ(ReadBEDouble, double, PosY); HANDLE_SERVER_PACKET_READ(ReadBEDouble, double, PosZ); - HANDLE_SERVER_PACKET_READ(ReadBEFloat, float, Yaw); - HANDLE_SERVER_PACKET_READ(ReadBEFloat, float, Pitch); - HANDLE_SERVER_PACKET_READ(ReadBool, bool, IsOnGround); + HANDLE_SERVER_PACKET_READ(ReadBEFloat, float, Yaw); + HANDLE_SERVER_PACKET_READ(ReadBEFloat, float, Pitch); + HANDLE_SERVER_PACKET_READ(ReadBool, bool, IsOnGround); Log("Received a PACKET_PLAYER_POSITION_LOOK from the server"); // TODO: list packet contents @@ -2030,7 +2093,7 @@ bool cConnection::HandleServerPlayerPositionLook(void) bool cConnection::HandleServerPluginMessage(void) { HANDLE_SERVER_PACKET_READ(ReadVarUTF8String, AString, ChannelName); - HANDLE_SERVER_PACKET_READ(ReadBEUInt16, UInt16, Length); + HANDLE_SERVER_PACKET_READ(ReadBEUInt16, UInt16, Length); ContiguousByteBuffer Data; if (!m_ServerBuffer.ReadSome(Data, Length)) { @@ -2049,9 +2112,9 @@ bool cConnection::HandleServerPluginMessage(void) bool cConnection::HandleServerRespawn(void) { - HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, Dimension); - HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Difficulty); - HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, GameMode); + HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, Dimension); + HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Difficulty); + HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, GameMode); HANDLE_SERVER_PACKET_READ(ReadVarUTF8String, AString, LevelType); Log("Received a respawn packet from the server:"); Log(" Dimension = %d", Dimension); @@ -2068,7 +2131,7 @@ bool cConnection::HandleServerRespawn(void) bool cConnection::HandleServerSetExperience(void) { - HANDLE_SERVER_PACKET_READ(ReadBEFloat, float, ExperienceBar); + HANDLE_SERVER_PACKET_READ(ReadBEFloat, float, ExperienceBar); HANDLE_SERVER_PACKET_READ(ReadBEUInt16, UInt16, Level); HANDLE_SERVER_PACKET_READ(ReadBEUInt16, UInt16, TotalExperience); Log("Received a PACKET_SET_EXPERIENCE from the server:"); @@ -2085,7 +2148,7 @@ bool cConnection::HandleServerSetExperience(void) bool cConnection::HandleServerSetSlot(void) { - HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, WindowID); + HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, WindowID); HANDLE_SERVER_PACKET_READ(ReadBEUInt16, UInt16, SlotNum); AString Item; if (!ParseSlot(m_ServerBuffer, Item)) @@ -2124,7 +2187,7 @@ bool cConnection::HandleServerSoundEffect(void) HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, PosY); HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, PosZ); HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, Data); - HANDLE_SERVER_PACKET_READ(ReadBool, bool, NoVolumeDecrease); + HANDLE_SERVER_PACKET_READ(ReadBool, bool, NoVolumeDecrease); Log("Received a PACKET_SOUND_EFFECT from the server:"); Log(" EffectID = %d", EffectID); Log(" Pos = {%d, %d, %d}", PosX, PosY, PosZ); @@ -2140,10 +2203,10 @@ bool cConnection::HandleServerSoundEffect(void) bool cConnection::HandleServerSpawnExperienceOrbs(void) { - HANDLE_SERVER_PACKET_READ(ReadVarInt, UInt32, EntityID); - HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, PosX); - HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, PosY); - HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, PosZ); + HANDLE_SERVER_PACKET_READ(ReadVarInt, UInt32, EntityID); + HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, PosX); + HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, PosY); + HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, PosZ); HANDLE_SERVER_PACKET_READ(ReadBEUInt16, UInt16, Count); Log("Received a SPAWN_EXPERIENCE_ORBS packet from the server:"); Log(" EntityID = %u (0x%x)", EntityID, EntityID); @@ -2159,17 +2222,17 @@ bool cConnection::HandleServerSpawnExperienceOrbs(void) bool cConnection::HandleServerSpawnMob(void) { - HANDLE_SERVER_PACKET_READ(ReadVarInt, UInt32, EntityID); - HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, MobType); - HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, PosX); - HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, PosY); - HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, PosZ); - HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Yaw); - HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Pitch); - HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, HeadYaw); - HANDLE_SERVER_PACKET_READ(ReadBEInt16, Int16, VelocityX); - HANDLE_SERVER_PACKET_READ(ReadBEInt16, Int16, VelocityY); - HANDLE_SERVER_PACKET_READ(ReadBEInt16, Int16, VelocityZ); + HANDLE_SERVER_PACKET_READ(ReadVarInt, UInt32, EntityID); + HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, MobType); + HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, PosX); + HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, PosY); + HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, PosZ); + HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Yaw); + HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Pitch); + HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, HeadYaw); + HANDLE_SERVER_PACKET_READ(ReadBEInt16, Int16, VelocityX); + HANDLE_SERVER_PACKET_READ(ReadBEInt16, Int16, VelocityY); + HANDLE_SERVER_PACKET_READ(ReadBEInt16, Int16, VelocityZ); AString Metadata; if (!ParseMetadata(m_ServerBuffer, Metadata)) { @@ -2200,9 +2263,7 @@ struct sSpawnData AString m_Value; AString m_Signature; sSpawnData(const AString & a_Name, const AString & a_Value, const AString & a_Signature) : - m_Name(a_Name), - m_Value(a_Value), - m_Signature(a_Signature) + m_Name(a_Name), m_Value(a_Value), m_Signature(a_Signature) { } }; @@ -2215,10 +2276,10 @@ typedef std::vector<sSpawnData> sSpawnDatas; bool cConnection::HandleServerSpawnNamedEntity(void) { - HANDLE_SERVER_PACKET_READ(ReadVarInt, UInt32, EntityID); + HANDLE_SERVER_PACKET_READ(ReadVarInt, UInt32, EntityID); HANDLE_SERVER_PACKET_READ(ReadVarUTF8String, AString, EntityUUID); HANDLE_SERVER_PACKET_READ(ReadVarUTF8String, AString, EntityName); - HANDLE_SERVER_PACKET_READ(ReadVarInt, UInt32, DataCount); + HANDLE_SERVER_PACKET_READ(ReadVarInt, UInt32, DataCount); sSpawnDatas Data; for (UInt32 i = 0; i < DataCount; i++) { @@ -2227,11 +2288,11 @@ bool cConnection::HandleServerSpawnNamedEntity(void) HANDLE_SERVER_PACKET_READ(ReadVarUTF8String, AString, Signature); Data.push_back(sSpawnData(Name, Value, Signature)); } - HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, PosX); - HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, PosY); - HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, PosZ); - HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Yaw); - HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Pitch); + HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, PosX); + HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, PosY); + HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, PosZ); + HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Yaw); + HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Pitch); HANDLE_SERVER_PACKET_READ(ReadBEUInt16, UInt16, SelectedItem); AString Metadata; if (!ParseMetadata(m_ServerBuffer, Metadata)) @@ -2248,8 +2309,9 @@ bool cConnection::HandleServerSpawnNamedEntity(void) for (sSpawnDatas::const_iterator itr = Data.begin(), end = Data.end(); itr != end; ++itr) { Log(" Name = \"%s\", Value = \"%s\", Signature = \"%s\"", - itr->m_Name.c_str(), itr->m_Value.c_str(), itr->m_Signature.c_str() - ); + itr->m_Name.c_str(), + itr->m_Value.c_str(), + itr->m_Signature.c_str()); } // for itr - Data[] Log(" Pos = %s", PrintableAbsIntTriplet(PosX, PosY, PosZ).c_str()); Log(" Rotation = <yaw %u, pitch %u>", Yaw, Pitch); @@ -2267,7 +2329,7 @@ bool cConnection::HandleServerSpawnNamedEntity(void) bool cConnection::HandleServerSpawnObjectVehicle(void) { - #ifdef _DEBUG +#ifdef _DEBUG // DEBUG: // This packet is still troublesome when DataIndicator != 0 ContiguousByteBuffer Buffer; @@ -2282,16 +2344,21 @@ bool cConnection::HandleServerSpawnObjectVehicle(void) // Only log up to 128 bytes Buffer.erase(128, AString::npos); } - DataLog(Buffer.data(), Buffer.size(), "Buffer while parsing the PACKET_SPAWN_OBJECT_VEHICLE packet (%u bytes):", static_cast<unsigned>(Buffer.size())); - #endif // _DEBUG - - HANDLE_SERVER_PACKET_READ(ReadVarInt, UInt32, EntityID); - HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, ObjType); - HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, PosX); - HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, PosY); - HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, PosZ); - HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Pitch); - HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Yaw); + DataLog( + Buffer.data(), + Buffer.size(), + "Buffer while parsing the PACKET_SPAWN_OBJECT_VEHICLE packet (%u bytes):", + static_cast<unsigned>(Buffer.size()) + ); +#endif // _DEBUG + + HANDLE_SERVER_PACKET_READ(ReadVarInt, UInt32, EntityID); + HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, ObjType); + HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, PosX); + HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, PosY); + HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, PosZ); + HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Pitch); + HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Yaw); HANDLE_SERVER_PACKET_READ(ReadBEUInt32, UInt32, DataIndicator); AString ExtraData; Int16 VelocityX = 0; @@ -2302,7 +2369,9 @@ bool cConnection::HandleServerSpawnObjectVehicle(void) HANDLE_SERVER_PACKET_READ(ReadBEInt16, Int16, SpeedX); HANDLE_SERVER_PACKET_READ(ReadBEInt16, Int16, SpeedY); HANDLE_SERVER_PACKET_READ(ReadBEInt16, Int16, SpeedZ); - VelocityX = SpeedX; VelocityY = SpeedY; VelocityZ = SpeedZ; // Speed vars are local to this scope, but we need them available later + VelocityX = SpeedX; + VelocityY = SpeedY; + VelocityZ = SpeedZ; // Speed vars are local to this scope, but we need them available later /* // This doesn't seem to work - for a falling block I'm getting no extra data at all int ExtraLen = 0; @@ -2347,12 +2416,12 @@ bool cConnection::HandleServerSpawnObjectVehicle(void) bool cConnection::HandleServerSpawnPainting(void) { - HANDLE_SERVER_PACKET_READ(ReadVarInt, UInt32, EntityID); + HANDLE_SERVER_PACKET_READ(ReadVarInt, UInt32, EntityID); HANDLE_SERVER_PACKET_READ(ReadVarUTF8String, AString, ImageName); - HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, PosX); - HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, PosY); - HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, PosZ); - HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, Direction); + HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, PosX); + HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, PosY); + HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, PosZ); + HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, Direction); Log("Received a PACKET_SPAWN_PAINTING from the server:"); Log(" EntityID = %u", EntityID); Log(" ImageName = \"%s\"", ImageName.c_str()); @@ -2399,7 +2468,7 @@ bool cConnection::HandleServerStatistics(void) for (UInt32 i = 0; i < NumEntries; i++) { HANDLE_SERVER_PACKET_READ(ReadVarUTF8String, AString, StatName); - HANDLE_SERVER_PACKET_READ(ReadVarInt, UInt32, StatValue); + HANDLE_SERVER_PACKET_READ(ReadVarInt, UInt32, StatValue); } COPY_TO_CLIENT(); return true; @@ -2433,7 +2502,10 @@ bool cConnection::HandleServerStatusResponse(void) size_t idx = Response.find(DescSearch); if (idx != AString::npos) { - Response.assign(Response.substr(0, idx + sizeof(DescSearch) - 1) + "ProtoProxy: " + Response.substr(idx + sizeof(DescSearch) - 1)); + Response.assign( + Response.substr(0, idx + sizeof(DescSearch) - 1) + + "ProtoProxy: " + Response.substr(idx + sizeof(DescSearch) - 1) + ); } else { @@ -2457,7 +2529,7 @@ bool cConnection::HandleServerStatusResponse(void) bool cConnection::HandleServerTabCompletion(void) { - HANDLE_SERVER_PACKET_READ(ReadVarInt, UInt32, NumResults); + HANDLE_SERVER_PACKET_READ(ReadVarInt, UInt32, NumResults); HANDLE_SERVER_PACKET_READ(ReadVarUTF8String, AString, Results); Log("Received a PACKET_TAB_COMPLETION from the server, results given:"); @@ -2513,9 +2585,9 @@ bool cConnection::HandleServerUpdateHealth(void) bool cConnection::HandleServerUpdateSign(void) { - HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, BlockX); - HANDLE_SERVER_PACKET_READ(ReadBEInt16, Int16, BlockY); - HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, BlockZ); + HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, BlockX); + HANDLE_SERVER_PACKET_READ(ReadBEInt16, Int16, BlockY); + HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, BlockZ); HANDLE_SERVER_PACKET_READ(ReadVarUTF8String, AString, Line1); HANDLE_SERVER_PACKET_READ(ReadVarUTF8String, AString, Line2); HANDLE_SERVER_PACKET_READ(ReadVarUTF8String, AString, Line3); @@ -2533,10 +2605,10 @@ bool cConnection::HandleServerUpdateSign(void) bool cConnection::HandleServerUpdateTileEntity(void) { - HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, BlockX); - HANDLE_SERVER_PACKET_READ(ReadBEInt16, Int16, BlockY); - HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, BlockZ); - HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Action); + HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, BlockX); + HANDLE_SERVER_PACKET_READ(ReadBEInt16, Int16, BlockY); + HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, BlockZ); + HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, Action); HANDLE_SERVER_PACKET_READ(ReadBEUInt16, UInt16, DataLength); ContiguousByteBuffer Data; @@ -2570,9 +2642,9 @@ bool cConnection::HandleServerUpdateTileEntity(void) bool cConnection::HandleServerUseBed(void) { HANDLE_SERVER_PACKET_READ(ReadBEUInt32, UInt32, EntityID); - HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, BedX); - HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, BedY); - HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, BedZ); + HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, BedX); + HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, BedY); + HANDLE_SERVER_PACKET_READ(ReadBEInt32, Int32, BedZ); Log("Received a use bed packet from the server:"); Log(" EntityID = %u", EntityID); Log(" Bed = {%d, %u, %d}", BedX, BedY, BedZ); @@ -2599,7 +2671,7 @@ bool cConnection::HandleServerWindowClose(void) bool cConnection::HandleServerWindowContents(void) { - HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, WindowID); + HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, WindowID); HANDLE_SERVER_PACKET_READ(ReadBEUInt16, UInt16, NumSlots); Log("Received a PACKET_WINDOW_CONTENTS from the server:"); Log(" WindowID = %u", WindowID); @@ -2625,11 +2697,11 @@ bool cConnection::HandleServerWindowContents(void) bool cConnection::HandleServerWindowOpen(void) { - HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, WindowID); - HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, WindowType); + HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, WindowID); + HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, WindowType); HANDLE_SERVER_PACKET_READ(ReadVarUTF8String, AString, Title); - HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, NumSlots); - HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, UseProvidedTitle); + HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, NumSlots); + HANDLE_SERVER_PACKET_READ(ReadBEUInt8, UInt8, UseProvidedTitle); UInt32 HorseEntityID = 0; if (WindowType == 11) // Horse / Donkey / Mule { @@ -2661,7 +2733,12 @@ bool cConnection::HandleServerUnknownPacket(UInt32 a_PacketType, UInt32 a_Packet { return false; } - DataLog(Data.data(), Data.size(), "****************** Unknown packet 0x%x from the server; relaying and ignoring", a_PacketType); + DataLog( + Data.data(), + Data.size(), + "****************** Unknown packet 0x%x from the server; relaying and ignoring", + a_PacketType + ); COPY_TO_CLIENT(); return true; } @@ -2735,7 +2812,7 @@ bool cConnection::ParseMetadata(cByteBuffer & a_Buffer, AString & a_Metadata) while (x != 0x7f) { // int Index = static_cast<unsigned>(x) & 0x1f; // Lower 5 bits = index - int Type = static_cast<unsigned>(x) >> 5; // Upper 3 bits = type + int Type = static_cast<unsigned>(x) >> 5; // Upper 3 bits = type // Get the length of the data for this item: UInt32 Length = 0; @@ -2758,7 +2835,7 @@ bool cConnection::ParseMetadata(cByteBuffer & a_Buffer, AString & a_Metadata) LenBuf.WriteVarInt32(Len); ContiguousByteBuffer VarLen; LenBuf.ReadAll(VarLen); - a_Metadata += { reinterpret_cast<const char *>(VarLen.data()), VarLen.size() }; + a_Metadata += {reinterpret_cast<const char *>(VarLen.data()), VarLen.size()}; Length = Len; break; } @@ -2791,7 +2868,7 @@ bool cConnection::ParseMetadata(cByteBuffer & a_Buffer, AString & a_Metadata) { return false; } - a_Metadata += { reinterpret_cast<const char *>(data.data()), data.size() }; + a_Metadata += {reinterpret_cast<const char *>(data.data()), data.size()}; if (!a_Buffer.ReadBEUInt8(x)) { return false; @@ -2811,8 +2888,9 @@ void cConnection::LogMetadata(const AString & a_Metadata, size_t a_IndentCount) size_t pos = 0; while (a_Metadata[pos] != 0x7f) { - unsigned Index = static_cast<unsigned>(static_cast<unsigned char>(a_Metadata[pos])) & 0x1f; // Lower 5 bits = index - unsigned Type = static_cast<unsigned>(static_cast<unsigned char>(a_Metadata[pos])) >> 5; // Upper 3 bits = type + unsigned Index = + static_cast<unsigned>(static_cast<unsigned char>(a_Metadata[pos])) & 0x1f; // Lower 5 bits = index + unsigned Type = static_cast<unsigned>(static_cast<unsigned char>(a_Metadata[pos])) >> 5; // Upper 3 bits = type // int Length = 0; switch (Type) { @@ -2830,13 +2908,21 @@ void cConnection::LogMetadata(const AString & a_Metadata, size_t a_IndentCount) } case 2: { - Log("%sint[%u] = %d", Indent.c_str(), Index, (a_Metadata[pos + 1] << 24) | (a_Metadata[pos + 2] << 16) | (a_Metadata[pos + 3] << 8) | a_Metadata[pos + 4]); + Log("%sint[%u] = %d", + Indent.c_str(), + Index, + (a_Metadata[pos + 1] << 24) | (a_Metadata[pos + 2] << 16) | (a_Metadata[pos + 3] << 8) | + a_Metadata[pos + 4]); pos += 4; break; } case 3: { - Log("%sfloat[%u] = 0x%x", Indent.c_str(), Index, (a_Metadata[pos + 1] << 24) | (a_Metadata[pos + 2] << 16) | (a_Metadata[pos + 3] << 8) | a_Metadata[pos + 4]); + Log("%sfloat[%u] = 0x%x", + Indent.c_str(), + Index, + (a_Metadata[pos + 1] << 24) | (a_Metadata[pos + 2] << 16) | (a_Metadata[pos + 3] << 8) | + a_Metadata[pos + 4]); pos += 4; break; } @@ -2853,7 +2939,8 @@ void cConnection::LogMetadata(const AString & a_Metadata, size_t a_IndentCount) size_t rs = bb.GetReadableSpace(); if (!bb.ReadVarInt(Length)) { - Log("Invalid metadata value, was supposed to be a varint-prefixed string, but cannot read the varint"); + Log("Invalid metadata value, was supposed to be a varint-prefixed string, but cannot read the " + "varint"); break; } rs = rs - bb.GetReadableSpace(); @@ -2875,17 +2962,25 @@ void cConnection::LogMetadata(const AString & a_Metadata, size_t a_IndentCount) // size_t After = bb.GetReadableSpace(); size_t BytesConsumed = BytesLeft - bb.GetReadableSpace(); - Log("%sslot[%u] = %s (%u bytes)", Indent.c_str(), Index, ItemDesc.c_str(), static_cast<unsigned>(BytesConsumed)); + Log("%sslot[%u] = %s (%u bytes)", + Indent.c_str(), + Index, + ItemDesc.c_str(), + static_cast<unsigned>(BytesConsumed)); pos += BytesConsumed; break; } case 6: { - Log("%spos[%u] = <%d, %d, %d>", Indent.c_str(), Index, - (a_Metadata[pos + 1] << 24) | (a_Metadata[pos + 2] << 16) | (a_Metadata[pos + 3] << 8) | a_Metadata[pos + 4], - (a_Metadata[pos + 5] << 24) | (a_Metadata[pos + 6] << 16) | (a_Metadata[pos + 7] << 8) | a_Metadata[pos + 8], - (a_Metadata[pos + 9] << 24) | (a_Metadata[pos + 10] << 16) | (a_Metadata[pos + 11] << 8) | a_Metadata[pos + 12] - ); + Log("%spos[%u] = <%d, %d, %d>", + Indent.c_str(), + Index, + (a_Metadata[pos + 1] << 24) | (a_Metadata[pos + 2] << 16) | (a_Metadata[pos + 3] << 8) | + a_Metadata[pos + 4], + (a_Metadata[pos + 5] << 24) | (a_Metadata[pos + 6] << 16) | (a_Metadata[pos + 7] << 8) | + a_Metadata[pos + 8], + (a_Metadata[pos + 9] << 24) | (a_Metadata[pos + 10] << 16) | (a_Metadata[pos + 11] << 8) | + a_Metadata[pos + 12]); pos += 12; break; } @@ -2922,7 +3017,12 @@ void cConnection::SendEncryptionKeyResponse(const AString & a_ServerPublicKey, c // Encrypt the nonce: Byte EncryptedNonce[128]; - res = PubKey.Encrypt(reinterpret_cast<const Byte *>(a_Nonce.data()), a_Nonce.size(), EncryptedNonce, sizeof(EncryptedNonce)); + res = PubKey.Encrypt( + reinterpret_cast<const Byte *>(a_Nonce.data()), + a_Nonce.size(), + EncryptedNonce, + sizeof(EncryptedNonce) + ); if (res < 0) { Log("Nonce encryption failed: %d (0x%x)", res, res); @@ -2937,8 +3037,18 @@ void cConnection::SendEncryptionKeyResponse(const AString & a_ServerPublicKey, c ToServer.WriteBuf(EncryptedSecret, sizeof(EncryptedSecret)); ToServer.WriteBEUInt16(static_cast<UInt16>(sizeof(EncryptedNonce))); ToServer.WriteBuf(EncryptedNonce, sizeof(EncryptedNonce)); - DataLog(EncryptedSecret, sizeof(EncryptedSecret), "Encrypted secret (%u bytes)", static_cast<unsigned>(sizeof(EncryptedSecret))); - DataLog(EncryptedNonce, sizeof(EncryptedNonce), "Encrypted nonce (%u bytes)", static_cast<unsigned>(sizeof(EncryptedNonce))); + DataLog( + EncryptedSecret, + sizeof(EncryptedSecret), + "Encrypted secret (%u bytes)", + static_cast<unsigned>(sizeof(EncryptedSecret)) + ); + DataLog( + EncryptedNonce, + sizeof(EncryptedNonce), + "Encrypted nonce (%u bytes)", + static_cast<unsigned>(sizeof(EncryptedNonce)) + ); cByteBuffer Len(5); Len.WriteVarInt32(static_cast<UInt32>(ToServer.GetReadableSpace())); SERVERSEND(Len); diff --git a/Tools/ProtoProxy/Connection.h b/Tools/ProtoProxy/Connection.h index b5e1b4ce0..a0ec4ccce 100644 --- a/Tools/ProtoProxy/Connection.h +++ b/Tools/ProtoProxy/Connection.h @@ -14,7 +14,7 @@ #include "mbedTLS++/AesCfb128Encryptor.h" #ifndef _WIN32 - typedef int SOCKET; +typedef int SOCKET; #endif @@ -42,13 +42,17 @@ class cConnection SOCKET m_ClientSocket; SOCKET m_ServerSocket; - std::chrono::steady_clock::time_point m_BeginTick; // Tick when the relative time was first retrieved (used for GetRelativeTime()) + std::chrono::steady_clock::time_point + m_BeginTick; // Tick when the relative time was first retrieved (used for GetRelativeTime()) enum eConnectionState { - csUnencrypted, // The connection is not encrypted. Packets must be decoded in order to be able to start decryption. - csEncryptedUnderstood, // The communication is encrypted and so far all packets have been understood, so they can be still decoded - csEncryptedUnknown, // The communication is encrypted, but an unknown packet has been received, so packets cannot be decoded anymore + csUnencrypted, // The connection is not encrypted. Packets must be decoded in order to be able to start + // decryption. + csEncryptedUnderstood, // The communication is encrypted and so far all packets have been understood, so they + // can be still decoded + csEncryptedUnknown, // The communication is encrypted, but an unknown packet has been received, so packets + // cannot be decoded anymore csWaitingForEncryption, // The communication is waiting for the other line to establish encryption }; @@ -57,7 +61,7 @@ class cConnection int m_Nonce; -public: + public: cConnection(SOCKET a_ClientSocket, cServer & a_Server); ~cConnection(); @@ -65,8 +69,7 @@ public: void vLog(const char * a_Format, fmt::printf_args a_ArgList); - template <typename... Args> - void Log(const char * a_Format, const Args & ... a_Args) + template <typename... Args> void Log(const char * a_Format, const Args &... a_Args) { vLog(a_Format, fmt::make_printf_args(a_Args...)); } @@ -74,22 +77,22 @@ public: void vDataLog(const void * a_Data, size_t a_Size, const char * a_Format, fmt::printf_args a_ArgList); template <typename... Args> - void DataLog(const void * a_Data, size_t a_Size, const char * a_Format, const Args & ... a_Args) + void DataLog(const void * a_Data, size_t a_Size, const char * a_Format, const Args &... a_Args) { vDataLog(a_Data, a_Size, a_Format, fmt::make_printf_args(a_Args...)); } void LogFlush(void); -protected: - + protected: cByteBuffer m_ClientBuffer; cByteBuffer m_ServerBuffer; cAesCfb128Decryptor m_ServerDecryptor; cAesCfb128Encryptor m_ServerEncryptor; - ContiguousByteBuffer m_ServerEncryptionBuffer; // Buffer for the data to be sent to the server once encryption is established + ContiguousByteBuffer + m_ServerEncryptionBuffer; // Buffer for the data to be sent to the server once encryption is established /** Set to true when PACKET_PING is received from the client; will cause special parsing for server kick */ bool m_HasClientPinged; @@ -101,10 +104,12 @@ protected: 2: login 3: game */ - /** State the to-server protocol is in (as defined by the initial handshake / login), -1 if no initial handshake received yet */ + /** State the to-server protocol is in (as defined by the initial handshake / login), -1 if no initial handshake + * received yet */ int m_ServerProtocolState; - /** State the to-client protocol is in (as defined by the initial handshake / login), -1 if no initial handshake received yet */ + /** State the to-client protocol is in (as defined by the initial handshake / login), -1 if no initial handshake + * received yet */ int m_ClientProtocolState; /** True if the server connection has provided encryption keys */ @@ -128,16 +133,30 @@ protected: /** Sends data to the specified socket. If sending fails, prints a fail message using a_Peer and returns false. */ bool SendData(SOCKET a_Socket, cByteBuffer & a_Data, const char * a_Peer); - /** Sends data to the specfied socket, after encrypting it using a_Encryptor. If sending fails, prints a fail message using a_Peer and returns false */ - bool SendEncryptedData(SOCKET a_Socket, cAesCfb128Encryptor & a_Encryptor, ContiguousByteBuffer & a_Data, const char * a_Peer); - - /** Sends data to the specfied socket, after encrypting it using a_Encryptor. If sending fails, prints a fail message using a_Peer and returns false */ - bool SendEncryptedData(SOCKET a_Socket, cAesCfb128Encryptor & a_Encryptor, cByteBuffer & a_Data, const char * a_Peer); - - /** Decodes packets coming from the client, sends appropriate counterparts to the server; returns false if the connection is to be dropped */ + /** Sends data to the specfied socket, after encrypting it using a_Encryptor. If sending fails, prints a fail + * message using a_Peer and returns false */ + bool SendEncryptedData( + SOCKET a_Socket, + cAesCfb128Encryptor & a_Encryptor, + ContiguousByteBuffer & a_Data, + const char * a_Peer + ); + + /** Sends data to the specfied socket, after encrypting it using a_Encryptor. If sending fails, prints a fail + * message using a_Peer and returns false */ + bool SendEncryptedData( + SOCKET a_Socket, + cAesCfb128Encryptor & a_Encryptor, + cByteBuffer & a_Data, + const char * a_Peer + ); + + /** Decodes packets coming from the client, sends appropriate counterparts to the server; returns false if the + * connection is to be dropped */ bool DecodeClientsPackets(const char * a_Data, int a_Size); - /** Decodes packets coming from the server, sends appropriate counterparts to the client; returns false if the connection is to be dropped */ + /** Decodes packets coming from the server, sends appropriate counterparts to the client; returns false if the + * connection is to be dropped */ bool DecodeServersPackets(const char * a_Data, int a_Size); // Packet handling, client-side, initial: @@ -247,10 +266,12 @@ protected: /** Parses the slot data in a_Buffer into item description; returns true if successful, false if not enough data */ bool ParseSlot(cByteBuffer & a_Buffer, AString & a_ItemDesc); - /** Parses the metadata in a_Buffer into raw metadata in an AString; returns true if successful, false if not enough data */ + /** Parses the metadata in a_Buffer into raw metadata in an AString; returns true if successful, false if not enough + * data */ bool ParseMetadata(cByteBuffer & a_Buffer, AString & a_Metadata); - /** Logs the contents of the metadata in the AString, using Log(). Assumes a_Metadata is valid (parsed by ParseMetadata()). The log is indented by a_IndentCount spaces */ + /** Logs the contents of the metadata in the AString, using Log(). Assumes a_Metadata is valid (parsed by + * ParseMetadata()). The log is indented by a_IndentCount spaces */ void LogMetadata(const AString & a_Metadata, size_t a_IndentCount); /** Send EKResp to the server: */ @@ -258,4 +279,4 @@ protected: /** Starts client encryption based on the parameters received */ void StartClientEncryption(const AString & a_EncryptedSecret, const AString & a_EncryptedNonce); -} ; +}; diff --git a/Tools/ProtoProxy/Server.cpp b/Tools/ProtoProxy/Server.cpp index 2db67e960..0155175de 100644 --- a/Tools/ProtoProxy/Server.cpp +++ b/Tools/ProtoProxy/Server.cpp @@ -12,9 +12,7 @@ -cServer::cServer(void) -{ -} +cServer::cServer(void) {} @@ -24,24 +22,24 @@ int cServer::Init(UInt16 a_ListenPort, UInt16 a_ConnectPort) { m_ConnectPort = a_ConnectPort; - #ifdef _WIN32 - WSAData wsa; - int res = WSAStartup(0x0202, &wsa); - if (res != 0) - { - LOGERROR("Cannot initialize WinSock: %d", res); - return res; - } - #endif // _WIN32 +#ifdef _WIN32 + WSAData wsa; + int res = WSAStartup(0x0202, &wsa); + if (res != 0) + { + LOGERROR("Cannot initialize WinSock: %d", res); + return res; + } +#endif // _WIN32 m_ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (m_ListenSocket < 0) { - #ifdef _WIN32 - int err = WSAGetLastError(); - #else - int err = errno; - #endif +#ifdef _WIN32 + int err = WSAGetLastError(); +#else + int err = errno; +#endif LOGERROR("Failed to create listener socket: %d", err); return err; } @@ -52,25 +50,29 @@ int cServer::Init(UInt16 a_ListenPort, UInt16 a_ConnectPort) local.sin_port = htons(a_ListenPort); if (bind(m_ListenSocket, reinterpret_cast<const sockaddr *>(&local), sizeof(local)) != 0) { - #ifdef _WIN32 - int err = WSAGetLastError(); - #else - int err = errno; - #endif +#ifdef _WIN32 + int err = WSAGetLastError(); +#else + int err = errno; +#endif LOGERROR("Failed to bind listener socket: %d", err); return err; } if (listen(m_ListenSocket, 1) != 0) { - #ifdef _WIN32 - int err = WSAGetLastError(); - #else - int err = errno; - #endif +#ifdef _WIN32 + int err = WSAGetLastError(); +#else + int err = errno; +#endif printf("Failed to listen on socket: %d\n", err); return err; } - LOGINFO("Listening for client connections on port %d, connecting to server at localhost:%d", a_ListenPort, a_ConnectPort); + LOGINFO( + "Listening for client connections on port %d, connecting to server at localhost:%d", + a_ListenPort, + a_ConnectPort + ); LOGINFO("Generating protocol encryption keypair..."); m_PrivateKey.Generate(); diff --git a/Tools/ProtoProxy/Server.h b/Tools/ProtoProxy/Server.h index e8db7f1c7..f636d679d 100644 --- a/Tools/ProtoProxy/Server.h +++ b/Tools/ProtoProxy/Server.h @@ -13,15 +13,15 @@ #include "mbedTLS++/RsaPrivateKey.h" #ifdef _WIN32 - #define SocketError WSAGetLastError() +#define SocketError WSAGetLastError() #else - typedef int SOCKET; - enum - { - INVALID_SOCKET = -1, - }; - #define closesocket close - #define SocketError errno +typedef int SOCKET; +enum +{ + INVALID_SOCKET = -1, +}; +#define closesocket close +#define SocketError errno #endif @@ -35,14 +35,14 @@ class cServer ContiguousByteBuffer m_PublicKeyDER; UInt16 m_ConnectPort; -public: + public: cServer(void); - int Init(UInt16 a_ListenPort, UInt16 a_ConnectPort); + int Init(UInt16 a_ListenPort, UInt16 a_ConnectPort); void Run(void); cRsaPrivateKey & GetPrivateKey(void) { return m_PrivateKey; } - ContiguousByteBufferView GetPublicKeyDER (void) { return m_PublicKeyDER; } + ContiguousByteBufferView GetPublicKeyDER(void) { return m_PublicKeyDER; } UInt16 GetConnectPort(void) const { return m_ConnectPort; } -} ; +}; diff --git a/Tools/QtBiomeVisualiser/BiomeView.cpp b/Tools/QtBiomeVisualiser/BiomeView.cpp index 472d1b5ad..8dd79d619 100644 --- a/Tools/QtBiomeVisualiser/BiomeView.cpp +++ b/Tools/QtBiomeVisualiser/BiomeView.cpp @@ -22,73 +22,255 @@ static struct { EMCSBiome m_Biome; uchar m_Color[3]; -} biomeColors[] = -{ - { biOcean, { 0x00, 0x00, 0x70 }, }, - { biPlains, { 0x8d, 0xb3, 0x60 }, }, - { biDesert, { 0xfa, 0x94, 0x18 }, }, - { biExtremeHills, { 0x60, 0x60, 0x60 }, }, - { biForest, { 0x05, 0x66, 0x21 }, }, - { biTaiga, { 0x0b, 0x66, 0x59 }, }, - { biSwampland, { 0x2f, 0xff, 0xda }, }, - { biRiver, { 0x30, 0x30, 0xaf }, }, - { biHell, { 0x7f, 0x00, 0x00 }, }, - { biSky, { 0x00, 0x7f, 0xff }, }, - { biFrozenOcean, { 0xa0, 0xa0, 0xdf }, }, - { biFrozenRiver, { 0xa0, 0xa0, 0xff }, }, - { biIcePlains, { 0xff, 0xff, 0xff }, }, - { biIceMountains, { 0xa0, 0xa0, 0xa0 }, }, - { biMushroomIsland, { 0xff, 0x00, 0xff }, }, - { biMushroomShore, { 0xa0, 0x00, 0xff }, }, - { biBeach, { 0xfa, 0xde, 0x55 }, }, - { biDesertHills, { 0xd2, 0x5f, 0x12 }, }, - { biForestHills, { 0x22, 0x55, 0x1c }, }, - { biTaigaHills, { 0x16, 0x39, 0x33 }, }, - { biExtremeHillsEdge, { 0x7f, 0x8f, 0x7f }, }, - { biJungle, { 0x53, 0x7b, 0x09 }, }, - { biJungleHills, { 0x2c, 0x42, 0x05 }, }, - - { biJungleEdge, { 0x62, 0x8b, 0x17 }, }, - { biDeepOcean, { 0x00, 0x00, 0x30 }, }, - { biStoneBeach, { 0xa2, 0xa2, 0x84 }, }, - { biColdBeach, { 0xfa, 0xf0, 0xc0 }, }, - { biBirchForest, { 0x30, 0x74, 0x44 }, }, - { biBirchForestHills, { 0x1f, 0x5f, 0x32 }, }, - { biRoofedForest, { 0x40, 0x51, 0x1a }, }, - { biColdTaiga, { 0x31, 0x55, 0x4a }, }, - { biColdTaigaHills, { 0x59, 0x7d, 0x72 }, }, - { biMegaTaiga, { 0x59, 0x66, 0x51 }, }, - { biMegaTaigaHills, { 0x59, 0x66, 0x59 }, }, - { biExtremeHillsPlus, { 0x50, 0x70, 0x50 }, }, - { biSavanna, { 0xbd, 0xb2, 0x5f }, }, - { biSavannaPlateau, { 0xa7, 0x9d, 0x64 }, }, - { biMesa, { 0xd9, 0x45, 0x15 }, }, - { biMesaPlateauF, { 0xb0, 0x97, 0x65 }, }, - { biMesaPlateau, { 0xca, 0x8c, 0x65 }, }, +} biomeColors[] = { + { + biOcean, + {0x00, 0x00, 0x70}, + }, + { + biPlains, + {0x8d, 0xb3, 0x60}, + }, + { + biDesert, + {0xfa, 0x94, 0x18}, + }, + { + biExtremeHills, + {0x60, 0x60, 0x60}, + }, + { + biForest, + {0x05, 0x66, 0x21}, + }, + { + biTaiga, + {0x0b, 0x66, 0x59}, + }, + { + biSwampland, + {0x2f, 0xff, 0xda}, + }, + { + biRiver, + {0x30, 0x30, 0xaf}, + }, + { + biHell, + {0x7f, 0x00, 0x00}, + }, + { + biSky, + {0x00, 0x7f, 0xff}, + }, + { + biFrozenOcean, + {0xa0, 0xa0, 0xdf}, + }, + { + biFrozenRiver, + {0xa0, 0xa0, 0xff}, + }, + { + biIcePlains, + {0xff, 0xff, 0xff}, + }, + { + biIceMountains, + {0xa0, 0xa0, 0xa0}, + }, + { + biMushroomIsland, + {0xff, 0x00, 0xff}, + }, + { + biMushroomShore, + {0xa0, 0x00, 0xff}, + }, + { + biBeach, + {0xfa, 0xde, 0x55}, + }, + { + biDesertHills, + {0xd2, 0x5f, 0x12}, + }, + { + biForestHills, + {0x22, 0x55, 0x1c}, + }, + { + biTaigaHills, + {0x16, 0x39, 0x33}, + }, + { + biExtremeHillsEdge, + {0x7f, 0x8f, 0x7f}, + }, + { + biJungle, + {0x53, 0x7b, 0x09}, + }, + { + biJungleHills, + {0x2c, 0x42, 0x05}, + }, + + { + biJungleEdge, + {0x62, 0x8b, 0x17}, + }, + { + biDeepOcean, + {0x00, 0x00, 0x30}, + }, + { + biStoneBeach, + {0xa2, 0xa2, 0x84}, + }, + { + biColdBeach, + {0xfa, 0xf0, 0xc0}, + }, + { + biBirchForest, + {0x30, 0x74, 0x44}, + }, + { + biBirchForestHills, + {0x1f, 0x5f, 0x32}, + }, + { + biRoofedForest, + {0x40, 0x51, 0x1a}, + }, + { + biColdTaiga, + {0x31, 0x55, 0x4a}, + }, + { + biColdTaigaHills, + {0x59, 0x7d, 0x72}, + }, + { + biMegaTaiga, + {0x59, 0x66, 0x51}, + }, + { + biMegaTaigaHills, + {0x59, 0x66, 0x59}, + }, + { + biExtremeHillsPlus, + {0x50, 0x70, 0x50}, + }, + { + biSavanna, + {0xbd, 0xb2, 0x5f}, + }, + { + biSavannaPlateau, + {0xa7, 0x9d, 0x64}, + }, + { + biMesa, + {0xd9, 0x45, 0x15}, + }, + { + biMesaPlateauF, + {0xb0, 0x97, 0x65}, + }, + { + biMesaPlateau, + {0xca, 0x8c, 0x65}, + }, // M variants: - { biSunflowerPlains, { 0xb5, 0xdb, 0x88 }, }, - { biDesertM, { 0xff, 0xbc, 0x40 }, }, - { biExtremeHillsM, { 0x88, 0x88, 0x88 }, }, - { biFlowerForest, { 0x2d, 0x8e, 0x49 }, }, - { biTaigaM, { 0x33, 0x8e, 0x81 }, }, - { biSwamplandM, { 0x07, 0xf9, 0xb2 }, }, - { biIcePlainsSpikes, { 0xb4, 0xdc, 0xdc }, }, - { biJungleM, { 0x7b, 0xa3, 0x31 }, }, - { biJungleEdgeM, { 0x62, 0x8b, 0x17 }, }, - { biBirchForestM, { 0x58, 0x9c, 0x6c }, }, - { biBirchForestHillsM, { 0x47, 0x87, 0x5a }, }, - { biRoofedForestM, { 0x68, 0x79, 0x42 }, }, - { biColdTaigaM, { 0x24, 0x3f, 0x36 }, }, - { biMegaSpruceTaiga, { 0x45, 0x4f, 0x3e }, }, - { biMegaSpruceTaigaHills, { 0x45, 0x4f, 0x4e }, }, - { biExtremeHillsPlusM, { 0x78, 0x98, 0x78 }, }, - { biSavannaM, { 0xe5, 0xda, 0x87 }, }, - { biSavannaPlateauM, { 0xa7, 0x9d, 0x74 }, }, - { biMesaBryce, { 0xff, 0x6d, 0x3d }, }, - { biMesaPlateauFM, { 0xd8, 0xbf, 0x8d }, }, - { biMesaPlateauM, { 0xf2, 0xb4, 0x8d }, }, -} ; + { + biSunflowerPlains, + {0xb5, 0xdb, 0x88}, + }, + { + biDesertM, + {0xff, 0xbc, 0x40}, + }, + { + biExtremeHillsM, + {0x88, 0x88, 0x88}, + }, + { + biFlowerForest, + {0x2d, 0x8e, 0x49}, + }, + { + biTaigaM, + {0x33, 0x8e, 0x81}, + }, + { + biSwamplandM, + {0x07, 0xf9, 0xb2}, + }, + { + biIcePlainsSpikes, + {0xb4, 0xdc, 0xdc}, + }, + { + biJungleM, + {0x7b, 0xa3, 0x31}, + }, + { + biJungleEdgeM, + {0x62, 0x8b, 0x17}, + }, + { + biBirchForestM, + {0x58, 0x9c, 0x6c}, + }, + { + biBirchForestHillsM, + {0x47, 0x87, 0x5a}, + }, + { + biRoofedForestM, + {0x68, 0x79, 0x42}, + }, + { + biColdTaigaM, + {0x24, 0x3f, 0x36}, + }, + { + biMegaSpruceTaiga, + {0x45, 0x4f, 0x3e}, + }, + { + biMegaSpruceTaigaHills, + {0x45, 0x4f, 0x4e}, + }, + { + biExtremeHillsPlusM, + {0x78, 0x98, 0x78}, + }, + { + biSavannaM, + {0xe5, 0xda, 0x87}, + }, + { + biSavannaPlateauM, + {0xa7, 0x9d, 0x74}, + }, + { + biMesaBryce, + {0xff, 0x6d, 0x3d}, + }, + { + biMesaPlateauFM, + {0xd8, 0xbf, 0x8d}, + }, + { + biMesaPlateauM, + {0xf2, 0xb4, 0x8d}, + }, +}; @@ -96,7 +278,7 @@ static struct static class BiomeColorsInitializer { -public: + public: BiomeColorsInitializer(void) { // Reset all colors to gray: @@ -125,12 +307,7 @@ public: // BiomeView: BiomeView::BiomeView(QWidget * parent) : - super(parent), - m_X(0), - m_Z(0), - m_Zoom(1), - m_IsMouseDragging(false), - m_MouseWheelDelta(0) + super(parent), m_X(0), m_Z(0), m_Zoom(1), m_IsMouseDragging(false), m_MouseWheelDelta(0) { // Create the image used for undefined chunks: int offset = 0; @@ -227,7 +404,7 @@ void BiomeView::redraw() int centerchunkx = floor(m_X / 16); int centerchunkz = floor(m_Z / 16); // and the center of the screen - int centerx = m_Image.width() / 2; + int centerx = m_Image.width() / 2; int centery = m_Image.height() / 2; // and align for panning centerx -= (m_X - centerchunkx * 16) * m_Zoom; @@ -236,7 +413,7 @@ void BiomeView::redraw() int startx = centerchunkx - centerx / chunksize - 1; int startz = centerchunkz - centery / chunksize - 1; // and the dimensions of the screen in blocks - int blockswide = m_Image.width() / chunksize + 3; + int blockswide = m_Image.width() / chunksize + 3; int blockstall = m_Image.height() / chunksize + 3; for (int z = startz; z < startz + blockstall; z++) @@ -302,7 +479,7 @@ void BiomeView::drawChunk(int a_ChunkX, int a_ChunkZ) int centerchunkx = floor(m_X / 16); int centerchunkz = floor(m_Z / 16); // and the center chunk screen coordinates - int centerx = m_Image.width() / 2; + int centerx = m_Image.width() / 2; int centery = m_Image.height() / 2; // which need to be shifted to account for panning inside that chunk centerx -= (m_X - centerchunkx * 16) * m_Zoom; @@ -360,23 +537,23 @@ void BiomeView::drawChunk(int a_ChunkX, int a_ChunkZ) // Scale-blit the image: for (int z = skipy; z < blockheight; z++, imgoffset += imgstride) { - size_t srcoffset = static_cast<size_t>(std::floor((double)z / m_Zoom)) * 16; + size_t srcoffset = static_cast<size_t>(std::floor((double) z / m_Zoom)) * 16; int imgxoffset = imgoffset; for (int x = skipx; x < blockwidth; x++) { - short biome = src[srcoffset + static_cast<size_t>(std::floor((double)x / m_Zoom))]; + short biome = src[srcoffset + static_cast<size_t>(std::floor((double) x / m_Zoom))]; const uchar * color; if (biome < 0) { - static const uchar emptyBiome1[] = { 0x44, 0x44, 0x44, 0xff }; - static const uchar emptyBiome2[] = { 0x88, 0x88, 0x88, 0xff }; + static const uchar emptyBiome1[] = {0x44, 0x44, 0x44, 0xff}; + static const uchar emptyBiome2[] = {0x88, 0x88, 0x88, 0xff}; color = ((x & 8) ^ (z & 8)) ? emptyBiome1 : emptyBiome2; } else { if (biome * 4 >= ARRAYCOUNT(biomeToColor)) { - static const uchar errorImage[] = { 0xff, 0x00, 0x00, 0xff }; + static const uchar errorImage[] = {0xff, 0x00, 0x00, 0xff}; color = errorImage; } else @@ -384,7 +561,7 @@ void BiomeView::drawChunk(int a_ChunkX, int a_ChunkZ) color = biomeToColor + biome * 4; } } - bits[imgxoffset] = color[0]; + bits[imgxoffset] = color[0]; bits[imgxoffset + 1] = color[1]; bits[imgxoffset + 2] = color[2]; bits[imgxoffset + 3] = color[3]; @@ -456,7 +633,7 @@ void BiomeView::mouseMoveEvent(QMouseEvent * a_Event) } // Update the status bar info text: - int blockX = floor((a_Event->x() - width() / 2) / m_Zoom + m_X); + int blockX = floor((a_Event->x() - width() / 2) / m_Zoom + m_X); int blockZ = floor((a_Event->y() - height() / 2) / m_Zoom + m_Z); int regionX, regionZ; Region::blockToRegion(blockX, blockZ, regionX, regionZ); diff --git a/Tools/QtBiomeVisualiser/BiomeView.h b/Tools/QtBiomeVisualiser/BiomeView.h index cd9c7ead9..4d8b3d528 100644 --- a/Tools/QtBiomeVisualiser/BiomeView.h +++ b/Tools/QtBiomeVisualiser/BiomeView.h @@ -9,13 +9,12 @@ -class BiomeView : - public QWidget +class BiomeView : public QWidget { typedef QWidget super; Q_OBJECT -public: + public: explicit BiomeView(QWidget * parent = NULL); QSize minimumSizeHint() const; @@ -31,7 +30,7 @@ public: /** Sets the zoom level to the specified value and redraws the view. */ void setZoomLevel(double a_ZoomLevel); -signals: + signals: /** Signalled when the user uses the wheel to scroll upwards. */ void wheelUp(); @@ -47,7 +46,7 @@ signals: /** Emitted when the user moves the mouse, to reflect the current block under the cursor. */ void hoverChanged(int a_BlockX, int a_BlockZ, int a_Biome); -public slots: + public slots: /** Redraw the entire widget area. */ void redraw(); @@ -57,7 +56,7 @@ public slots: /** Reloads the current chunk source and redraws the entire workspace. */ void reload(); -protected: + protected: double m_X, m_Z; double m_Zoom; @@ -110,8 +109,3 @@ protected: /** Called when the user presses a key. */ virtual void keyPressEvent(QKeyEvent * a_Event) override; }; - - - - - diff --git a/Tools/QtBiomeVisualiser/ChunkSource.cpp b/Tools/QtBiomeVisualiser/ChunkSource.cpp index ea3346f04..6b622b2bc 100644 --- a/Tools/QtBiomeVisualiser/ChunkSource.cpp +++ b/Tools/QtBiomeVisualiser/ChunkSource.cpp @@ -14,8 +14,7 @@ // BioGenSource: BioGenSource::BioGenSource(cIniFilePtr a_IniFile) : - m_IniFile(a_IniFile), - m_Mtx(QMutex::Recursive) + m_IniFile(a_IniFile), m_Mtx(QMutex::Recursive) { reload(); } @@ -98,7 +97,7 @@ void BioGenSource::releaseBiomeGen(cBiomeGenPtr && a_BiomeGen, int a_Tag) class AnvilSource::AnvilFile { -public: + public: /** Coordinates of the region file. */ int m_RegionX, m_RegionZ; @@ -109,9 +108,7 @@ public: /** Creates a new instance with the specified region coords. Reads the file header. */ AnvilFile(int a_RegionX, int a_RegionZ, const AString & a_WorldPath) : - m_RegionX(a_RegionX), - m_RegionZ(a_RegionZ), - m_IsValid(false) + m_RegionX(a_RegionX), m_RegionZ(a_RegionZ), m_IsValid(false) { readFile(Printf("%s/r.%d.%d.mca", a_WorldPath.c_str(), a_RegionX, a_RegionZ)); } @@ -162,7 +159,7 @@ public: return m_FileData.substr(chunkOffset * 4096 + 5, chunkSize); } -protected: + protected: AString m_FileData; UInt32 m_Header[2048]; @@ -241,7 +238,7 @@ void AnvilSource::getChunkBiomes(int a_ChunkX, int a_ChunkZ, Chunk & a_DestChunk const char * beBiomes = nbt.GetData(mcsBiomes); for (size_t i = 0; i < ARRAYCOUNT(biomeMap); i++) { - biomeMap[i] = (EMCSBiome)GetBEInt(beBiomes + 4 * i); + biomeMap[i] = (EMCSBiome) GetBEInt(beBiomes + 4 * i); } a_DestChunk.setBiomes(biomeMap); return; @@ -320,8 +317,3 @@ AnvilSource::AnvilFilePtr AnvilSource::getAnvilFile(int a_ChunkX, int a_ChunkZ) m_Files.push_front(file); return file; } - - - - - diff --git a/Tools/QtBiomeVisualiser/ChunkSource.h b/Tools/QtBiomeVisualiser/ChunkSource.h index 62f9b5626..62e3f87b9 100644 --- a/Tools/QtBiomeVisualiser/ChunkSource.h +++ b/Tools/QtBiomeVisualiser/ChunkSource.h @@ -21,14 +21,15 @@ typedef std::shared_ptr<cIniFile> cIniFilePtr; /** Abstract interface for getting biome data for chunks. */ class ChunkSource { -public: + public: virtual ~ChunkSource() {} /** Fills the a_DestChunk with the biomes for the specified coords. It is expected to be thread-safe and re-entrant. Usually QThread::idealThreadCount() threads are used. */ virtual void getChunkBiomes(int a_ChunkX, int a_ChunkZ, Chunk & a_DestChunk) = 0; - /** Forces a fresh reload of the source. Useful mainly for the generator, whose underlying definition file may have been changed. */ + /** Forces a fresh reload of the source. Useful mainly for the generator, whose underlying definition file may have + * been changed. */ virtual void reload() = 0; }; @@ -36,11 +37,9 @@ public: - -class BioGenSource : - public ChunkSource +class BioGenSource : public ChunkSource { -public: + public: /** Constructs a new BioGenSource based on the biome generator that is defined in the specified world.ini file. */ BioGenSource(cIniFilePtr a_IniFile); @@ -48,7 +47,7 @@ public: virtual void getChunkBiomes(int a_ChunkX, int a_ChunkZ, Chunk & a_DestChunk) override; virtual void reload(void) override; -protected: + protected: /** The world.ini contents from which the generator is created and re-created on reload(). */ cIniFilePtr m_IniFile; @@ -82,10 +81,9 @@ protected: -class AnvilSource : - public ChunkSource +class AnvilSource : public ChunkSource { -public: + public: /** Constructs a new AnvilSource based on the world path. */ AnvilSource(QString a_WorldRegionFolder); @@ -93,7 +91,7 @@ public: virtual void getChunkBiomes(int a_ChunkX, int a_ChunkZ, Chunk & a_DestChunk) override; virtual void reload() override; -protected: + protected: class AnvilFile; typedef std::shared_ptr<AnvilFile> AnvilFilePtr; @@ -119,9 +117,4 @@ protected: /** Returns the file object that contains the specified chunk. The file is taken from the cache if available there, otherwise it is created anew. */ AnvilFilePtr getAnvilFile(int a_ChunkX, int a_ChunkZ); - }; - - - - diff --git a/Tools/QtBiomeVisualiser/GeneratorSetup.cpp b/Tools/QtBiomeVisualiser/GeneratorSetup.cpp index 54b7ef36e..bdee0bb50 100644 --- a/Tools/QtBiomeVisualiser/GeneratorSetup.cpp +++ b/Tools/QtBiomeVisualiser/GeneratorSetup.cpp @@ -9,8 +9,7 @@ -static const QString s_GeneratorNames[] = -{ +static const QString s_GeneratorNames[] = { QString("Checkerboard"), QString("Constant"), QString("DistortedVoronoi"), @@ -26,8 +25,7 @@ static const QString s_GeneratorNames[] = GeneratorSetup::GeneratorSetup(const AString & a_IniFileName, QWidget * a_Parent) : - super(a_Parent), - m_IniFile(new cIniFile()) + super(a_Parent), m_IniFile(new cIniFile()) { // The seed and generator name is in a separate form layout at the top, always present: m_eSeed = new QLineEdit(); @@ -67,7 +65,7 @@ GeneratorSetup::GeneratorSetup(const AString & a_IniFileName, QWidget * a_Parent // Connect the change events only after the data has been loaded: connect(m_cbGenerator, SIGNAL(currentIndexChanged(QString)), this, SLOT(generatorChanged(QString))); - connect(m_eSeed, SIGNAL(textChanged(QString)), this, SLOT(editChanged(QString))); + connect(m_eSeed, SIGNAL(textChanged(QString)), this, SLOT(editChanged(QString))); } @@ -109,7 +107,7 @@ void GeneratorSetup::generatorChanged(const QString & a_NewName) void GeneratorSetup::editChanged(const QString & a_NewValue) { QString sectionName = sender()->property("INI.SectionName").toString(); - QString itemName = sender()->property("INI.ItemName").toString(); + QString itemName = sender()->property("INI.ItemName").toString(); m_IniFile->SetValue(sectionName.toStdString(), itemName.toStdString(), a_NewValue.toStdString()); emit generatorUpdated(); } @@ -139,7 +137,7 @@ void GeneratorSetup::updateFromIni() int numItems = m_IniFile->GetNumValues(keyID); for (int i = 0; i < numItems; i++) { - AString itemName = m_IniFile->GetValueName(keyID, i); + AString itemName = m_IniFile->GetValueName(keyID, i); if ((itemName == "Generator") || (itemName == "BiomeGen")) { // These special cases are not to be added @@ -162,7 +160,3 @@ void GeneratorSetup::updateFromIni() m_FormLayout->addRow(new QLabel(QString::fromStdString(itemName)), edit); } // for i - INI values[] } - - - - diff --git a/Tools/QtBiomeVisualiser/GeneratorSetup.h b/Tools/QtBiomeVisualiser/GeneratorSetup.h index e72d3abbc..168ee3758 100644 --- a/Tools/QtBiomeVisualiser/GeneratorSetup.h +++ b/Tools/QtBiomeVisualiser/GeneratorSetup.h @@ -17,34 +17,33 @@ typedef std::shared_ptr<cIniFile> cIniFilePtr; -class GeneratorSetup : - public QWidget +class GeneratorSetup : public QWidget { typedef QWidget super; Q_OBJECT -public: + public: /** Creates the widget and loads the contents of the INI file, if not empty. */ explicit GeneratorSetup(const std::string & a_IniFileName, QWidget * parent = nullptr); /** Returns the cIniFile instance that is being edited by this widget. */ cIniFilePtr getIniFile() { return m_IniFile; } -signals: + signals: /** Emitted when the generator parameters have changed. */ void generatorUpdated(); -public slots: + public slots: /** Called when the user selects a different generator from the top combobox. Re-creates m_IniFile and updates the form layout. */ void generatorChanged(const QString & a_NewName); -protected slots: + protected slots: /** Called when any of the edit widgets are changed. */ void editChanged(const QString & a_NewValue); -protected: + protected: QComboBox * m_cbGenerator; QLineEdit * m_eSeed; QVBoxLayout * m_MainLayout; @@ -58,7 +57,3 @@ protected: /** Updates the form layout with the values from m_IniFile. */ void updateFromIni(); }; - - - - diff --git a/Tools/QtBiomeVisualiser/Globals.h b/Tools/QtBiomeVisualiser/Globals.h index fe037c2ad..52182c3b6 100644 --- a/Tools/QtBiomeVisualiser/Globals.h +++ b/Tools/QtBiomeVisualiser/Globals.h @@ -6,44 +6,45 @@ // Compiler-dependent stuff: #if defined(_MSC_VER) - // MSVC produces warning C4481 on the override keyword usage, so disable the warning altogether - #pragma warning(disable:4481) +// MSVC produces warning C4481 on the override keyword usage, so disable the warning altogether +#pragma warning(disable : 4481) - // Disable some warnings that we don't care about: - #pragma warning(disable:4100) // Unreferenced formal parameter +// Disable some warnings that we don't care about: +#pragma warning(disable : 4100) // Unreferenced formal parameter - // Useful warnings from warning level 4: - #pragma warning(3 : 4127) // Conditional expression is constant - #pragma warning(3 : 4189) // Local variable is initialized but not referenced - #pragma warning(3 : 4245) // Conversion from 'type1' to 'type2', signed / unsigned mismatch - #pragma warning(3 : 4310) // Cast truncates constant value - #pragma warning(3 : 4389) // Signed / unsigned mismatch - #pragma warning(3 : 4505) // Unreferenced local function has been removed - #pragma warning(3 : 4701) // Potentially unitialized local variable used - #pragma warning(3 : 4702) // Unreachable code - #pragma warning(3 : 4706) // Assignment within conditional expression +// Useful warnings from warning level 4: +#pragma warning(3 : 4127) // Conditional expression is constant +#pragma warning(3 : 4189) // Local variable is initialized but not referenced +#pragma warning(3 : 4245) // Conversion from 'type1' to 'type2', signed / unsigned mismatch +#pragma warning(3 : 4310) // Cast truncates constant value +#pragma warning(3 : 4389) // Signed / unsigned mismatch +#pragma warning(3 : 4505) // Unreferenced local function has been removed +#pragma warning(3 : 4701) // Potentially unitialized local variable used +#pragma warning(3 : 4702) // Unreachable code +#pragma warning(3 : 4706) // Assignment within conditional expression - // Disabling this warning, because we know what we're doing when we're doing this: - #pragma warning(disable: 4355) // 'this' used in initializer list +// Disabling this warning, because we know what we're doing when we're doing this: +#pragma warning(disable : 4355) // 'this' used in initializer list - // Disabled because it's useless: - #pragma warning(disable: 4512) // 'class': assignment operator could not be generated - reported for each class that has a reference-type member +// Disabled because it's useless: +#pragma warning(disable : 4512 \ +) // 'class': assignment operator could not be generated - reported for each class that has a reference-type member - // 2014_01_06 xoft: Disabled this warning because MSVC is stupid and reports it in obviously wrong places - // #pragma warning(3 : 4244) // Conversion from 'type1' to 'type2', possible loss of data +// 2014_01_06 xoft: Disabled this warning because MSVC is stupid and reports it in obviously wrong places +// #pragma warning(3 : 4244) // Conversion from 'type1' to 'type2', possible loss of data - #define FORMATSTRING(formatIndex, va_argsIndex) +#define FORMATSTRING(formatIndex, va_argsIndex) #elif defined(__GNUC__) - // TODO: Can GCC explicitly mark classes as abstract (no instances can be created)? - #define abstract +// TODO: Can GCC explicitly mark classes as abstract (no instances can be created)? +#define abstract - #define FORMATSTRING(formatIndex, va_argsIndex) __attribute__((format (printf, formatIndex, va_argsIndex))) +#define FORMATSTRING(formatIndex, va_argsIndex) __attribute__((format(printf, formatIndex, va_argsIndex))) #else - #error "You are using an unsupported compiler, you might need to #define some stuff here for your compiler" +#error "You are using an unsupported compiler, you might need to #define some stuff here for your compiler" #endif @@ -53,22 +54,20 @@ // Integral types with predefined sizes: typedef long long Int64; -typedef int Int32; -typedef short Int16; +typedef int Int32; +typedef short Int16; typedef unsigned long long UInt64; -typedef unsigned int UInt32; -typedef unsigned short UInt16; +typedef unsigned int UInt32; +typedef unsigned short UInt16; typedef unsigned char Byte; // If you get an error about specialization check the size of integral types -template <typename T, size_t Size, bool x = sizeof(T) == Size> -class SizeChecker; +template <typename T, size_t Size, bool x = sizeof(T) == Size> class SizeChecker; -template <typename T, size_t Size> -class SizeChecker<T, Size, true> +template <typename T, size_t Size> class SizeChecker<T, Size, true> { T v; }; @@ -84,19 +83,19 @@ template class SizeChecker<UInt16, 2>; // A macro to disallow the copy constructor and operator = functions // This should be used in the private: declarations for any class that shouldn't allow copying itself #define DISALLOW_COPY_AND_ASSIGN(TypeName) \ - TypeName(const TypeName &); \ - void operator =(const TypeName &) + TypeName(const TypeName &); \ + void operator=(const TypeName &) // A macro that is used to mark unused local variables, to avoid pedantic warnings in gcc / clang / MSVC // Note that in MSVC it requires the full type of X to be known -#define UNUSED_VAR(X) (void)(X) +#define UNUSED_VAR(X) (void) (X) // A macro that is used to mark unused function parameters, to avoid pedantic warnings in gcc // Written so that the full type of param needn't be known #ifdef _MSC_VER - #define UNUSED(X) +#define UNUSED(X) #else - #define UNUSED UNUSED_VAR +#define UNUSED UNUSED_VAR #endif @@ -104,38 +103,40 @@ template class SizeChecker<UInt16, 2>; // OS-dependent stuff: #ifdef _WIN32 - #define WIN32_LEAN_AND_MEAN - #define _WIN32_WINNT _WIN32_WINNT_WS03 // We want to target Windows XP with Service Pack 2 & Windows Server 2003 with Service Pack 1 and higher - - #include <Windows.h> - #include <winsock2.h> - #include <Ws2tcpip.h> // IPv6 stuff - - // Windows SDK defines min and max macros, messing up with our std::min and std::max usage - #undef min - #undef max - - // Windows SDK defines GetFreeSpace as a constant, probably a Win16 API remnant - #ifdef GetFreeSpace - #undef GetFreeSpace - #endif // GetFreeSpace +#define WIN32_LEAN_AND_MEAN +#define _WIN32_WINNT \ + _WIN32_WINNT_WS03 // We want to target Windows XP with Service Pack 2 & Windows Server 2003 with Service Pack 1 and + // higher + +#include <Windows.h> +#include <winsock2.h> +#include <Ws2tcpip.h> // IPv6 stuff + +// Windows SDK defines min and max macros, messing up with our std::min and std::max usage +#undef min +#undef max + +// Windows SDK defines GetFreeSpace as a constant, probably a Win16 API remnant +#ifdef GetFreeSpace +#undef GetFreeSpace +#endif // GetFreeSpace #else - #include <sys/types.h> - #include <sys/time.h> - #include <sys/socket.h> - #include <netinet/in.h> - #include <arpa/inet.h> - #include <netdb.h> - #include <time.h> - #include <dirent.h> - #include <errno.h> - #include <iostream> - #include <cstdio> - #include <cstring> - #include <pthread.h> - #include <semaphore.h> - #include <errno.h> - #include <fcntl.h> +#include <sys/types.h> +#include <sys/time.h> +#include <sys/socket.h> +#include <netinet/in.h> +#include <arpa/inet.h> +#include <netdb.h> +#include <time.h> +#include <dirent.h> +#include <errno.h> +#include <iostream> +#include <cstdio> +#include <cstring> +#include <pthread.h> +#include <semaphore.h> +#include <errno.h> +#include <fcntl.h> #endif @@ -168,15 +169,15 @@ template class SizeChecker<UInt16, 2>; #ifndef TEST_GLOBALS - // Common headers (part 1, without macros): - #include "src/StringUtils.h" - #include "src/OSSupport/CriticalSection.h" - #include "src/OSSupport/Semaphore.h" - #include "src/OSSupport/Event.h" - #include "src/OSSupport/File.h" - #include "src/Logger.h" +// Common headers (part 1, without macros): +#include "src/StringUtils.h" +#include "src/OSSupport/CriticalSection.h" +#include "src/OSSupport/Semaphore.h" +#include "src/OSSupport/Event.h" +#include "src/OSSupport/File.h" +#include "src/Logger.h" #else - // Logging functions +// Logging functions void inline LOGERROR(const char * a_Format, ...) FORMATSTRING(1, 2); void inline LOGERROR(const char * a_Format, ...) @@ -199,55 +200,86 @@ void inline LOGERROR(const char * a_Format, ...) /** Allows arithmetic expressions like "32 KiB" (but consider using parenthesis around it, "(32 KiB)") */ -#define KiB * 1024 -#define MiB * 1024 * 1024 +#define KiB *1024 +#define MiB *1024 * 1024 /** Faster than (int)floorf((float)x / (float)div) */ -#define FAST_FLOOR_DIV( x, div) (((x) - (((x) < 0) ? ((div) - 1) : 0)) / (div)) +#define FAST_FLOOR_DIV(x, div) (((x) - (((x) < 0) ? ((div) - 1) : 0)) / (div)) // Own version of assert() that writes failed assertions to the log for review #ifdef TEST_GLOBALS - class cAssertFailure - { - }; - - #ifdef _WIN32 - #if (defined(_MSC_VER) && defined(_DEBUG)) - #define DBG_BREAK _CrtDbgBreak() - #else - #define DBG_BREAK - #endif - #define REPORT_ERROR(FMT, ...) \ - { \ - AString msg = Printf(FMT, __VA_ARGS__); \ - puts(msg.c_str()); \ - fflush(stdout); \ - OutputDebugStringA(msg.c_str()); \ - DBG_BREAK; \ - } - #else - #define REPORT_ERROR(FMT, ...) \ - { \ - AString msg = Printf(FMT, __VA_ARGS__); \ - puts(msg.c_str()); \ - fflush(stdout); \ - } - #endif - #define ASSERT(x) do { if (!(x)) { throw cAssertFailure();} } while (0) - #define testassert(x) do { if (!(x)) { REPORT_ERROR("Test failure: %s, file %s, line %d\n", #x, __FILE__, __LINE__); exit(1); } } while (0) - #define CheckAsserts(x) do { try {x} catch (cAssertFailure) { break; } REPORT_ERROR("Test failure: assert didn't fire for %s, file %s, line %d\n", #x, __FILE__, __LINE__); exit(1); } while (0) +class cAssertFailure +{ +}; +#ifdef _WIN32 +#if (defined(_MSC_VER) && defined(_DEBUG)) +#define DBG_BREAK _CrtDbgBreak() #else - #ifdef _DEBUG - #define ASSERT( x) ( !!(x) || ( LOGERROR("Assertion failed: %s, file %s, line %i", #x, __FILE__, __LINE__), assert(0), 0)) - #else - #define ASSERT(x) ((void)(x)) - #endif +#define DBG_BREAK +#endif +#define REPORT_ERROR(FMT, ...) \ + { \ + AString msg = Printf(FMT, __VA_ARGS__); \ + puts(msg.c_str()); \ + fflush(stdout); \ + OutputDebugStringA(msg.c_str()); \ + DBG_BREAK; \ + } +#else +#define REPORT_ERROR(FMT, ...) \ + { \ + AString msg = Printf(FMT, __VA_ARGS__); \ + puts(msg.c_str()); \ + fflush(stdout); \ + } +#endif +#define ASSERT(x) \ + do \ + { \ + if (!(x)) \ + { \ + throw cAssertFailure(); \ + } \ + } \ + while (0) +#define testassert(x) \ + do \ + { \ + if (!(x)) \ + { \ + REPORT_ERROR("Test failure: %s, file %s, line %d\n", #x, __FILE__, __LINE__); \ + exit(1); \ + } \ + } \ + while (0) +#define CheckAsserts(x) \ + do \ + { \ + try \ + { \ + x \ + } \ + catch (cAssertFailure) \ + { \ + break; \ + } \ + REPORT_ERROR("Test failure: assert didn't fire for %s, file %s, line %d\n", #x, __FILE__, __LINE__); \ + exit(1); \ + } \ + while (0) + +#else +#ifdef _DEBUG +#define ASSERT(x) (!!(x) || (LOGERROR("Assertion failed: %s, file %s, line %i", #x, __FILE__, __LINE__), assert(0), 0)) +#else +#define ASSERT(x) ((void) (x)) +#endif #endif // Pretty much the same as ASSERT() but stays in Release builds -#define VERIFY( x) ( !!(x) || ( LOGERROR("Verification failed: %s, file %s, line %i", #x, __FILE__, __LINE__), exit(1), 0)) +#define VERIFY(x) (!!(x) || (LOGERROR("Verification failed: %s, file %s, line %i", #x, __FILE__, __LINE__), exit(1), 0)) // C++11 has std::shared_ptr in <memory>, included earlier #define SharedPtr std::shared_ptr @@ -256,8 +288,7 @@ around it, "(32 KiB)") */ /** Clamp X to the specified range. */ -template <typename T> -T Clamp(T a_Value, T a_Min, T a_Max) +template <typename T> T Clamp(T a_Value, T a_Min, T a_Max) { return (a_Value < a_Min) ? a_Min : ((a_Value > a_Max) ? a_Max : a_Value); } @@ -267,7 +298,7 @@ T Clamp(T a_Value, T a_Min, T a_Max) #ifndef TOLUA_TEMPLATE_BIND - #define TOLUA_TEMPLATE_BIND(x) +#define TOLUA_TEMPLATE_BIND(x) #endif diff --git a/Tools/QtBiomeVisualiser/MainWindow.cpp b/Tools/QtBiomeVisualiser/MainWindow.cpp index 8d5b768d8..6aa1b84a9 100644 --- a/Tools/QtBiomeVisualiser/MainWindow.cpp +++ b/Tools/QtBiomeVisualiser/MainWindow.cpp @@ -20,9 +20,17 @@ -const double MainWindow::m_ViewZooms[] = -{ - 0.0625, 0.125, 0.25, 0.5, 1, 2, 4, 8, 16, 24, +const double MainWindow::m_ViewZooms[] = { + 0.0625, + 0.125, + 0.25, + 0.5, + 1, + 2, + 4, + 8, + 16, + 24, }; @@ -30,18 +38,15 @@ const double MainWindow::m_ViewZooms[] = MainWindow::MainWindow(QWidget * parent) : - QMainWindow(parent), - m_GeneratorSetup(nullptr), - m_LineSeparator(nullptr), - m_CurrentZoomLevel(2) + QMainWindow(parent), m_GeneratorSetup(nullptr), m_LineSeparator(nullptr), m_CurrentZoomLevel(2) { initMinecraftPath(); m_BiomeView = new BiomeView(); connect(m_BiomeView, SIGNAL(increaseZoom()), this, SLOT(increaseZoom())); connect(m_BiomeView, SIGNAL(decreaseZoom()), this, SLOT(decreaseZoom())); - connect(m_BiomeView, SIGNAL(wheelUp()), this, SLOT(increaseZoom())); - connect(m_BiomeView, SIGNAL(wheelDown()), this, SLOT(decreaseZoom())); + connect(m_BiomeView, SIGNAL(wheelUp()), this, SLOT(increaseZoom())); + connect(m_BiomeView, SIGNAL(wheelDown()), this, SLOT(decreaseZoom())); m_BiomeView->setZoomLevel(m_ViewZooms[m_CurrentZoomLevel]); m_StatusBar = new QStatusBar(); @@ -225,7 +230,7 @@ void MainWindow::hoverChanged(int a_BlockX, int a_BlockZ, int a_Biome) { m_StatusBlockX->setText(tr("X: %1").arg(a_BlockX)); m_StatusBlockZ->setText(tr("Z: %1").arg(a_BlockZ)); - m_StatusBiome->setText (tr("B: %1 (%2)").arg(BiomeToString(a_Biome).c_str()).arg(a_Biome)); + m_StatusBiome->setText(tr("B: %1 (%2)").arg(BiomeToString(a_Biome).c_str()).arg(a_Biome)); } @@ -234,14 +239,14 @@ void MainWindow::hoverChanged(int a_BlockX, int a_BlockZ, int a_Biome) void MainWindow::initMinecraftPath() { - #ifdef Q_OS_MAC - m_MinecraftPath = QDir::homePath() + QDir::toNativeSeparators("/Library/Application Support/minecraft"); - #elif defined Q_OS_WIN32 - QSettings ini(QSettings::IniFormat, QSettings::UserScope, ".minecraft", "minecraft1"); - m_MinecraftPath = QFileInfo(ini.fileName()).absolutePath(); - #else - m_MinecraftPath = QDir::homePath() + QDir::toNativeSeparators("/.minecraft"); - #endif +#ifdef Q_OS_MAC + m_MinecraftPath = QDir::homePath() + QDir::toNativeSeparators("/Library/Application Support/minecraft"); +#elif defined Q_OS_WIN32 + QSettings ini(QSettings::IniFormat, QSettings::UserScope, ".minecraft", "minecraft1"); + m_MinecraftPath = QFileInfo(ini.fileName()).absolutePath(); +#else + m_MinecraftPath = QDir::homePath() + QDir::toNativeSeparators("/.minecraft"); +#endif } @@ -434,7 +439,3 @@ void MainWindow::closeGeneratorSetup() m_GeneratorSetup = nullptr; m_LineSeparator = nullptr; } - - - - diff --git a/Tools/QtBiomeVisualiser/MainWindow.h b/Tools/QtBiomeVisualiser/MainWindow.h index 27faae7a8..230e3ba38 100644 --- a/Tools/QtBiomeVisualiser/MainWindow.h +++ b/Tools/QtBiomeVisualiser/MainWindow.h @@ -18,16 +18,15 @@ class GeneratorSetup; -class MainWindow : - public QMainWindow +class MainWindow : public QMainWindow { Q_OBJECT -public: + public: MainWindow(QWidget * parent = nullptr); ~MainWindow(); -private slots: + private slots: /** Creates a generator definition from scratch, lets user modify generator params in realtime. */ void newGenerator(); @@ -55,7 +54,7 @@ private slots: /** Updates the statusbar for the specified info about the current block under the cursor. */ void hoverChanged(int a_BlockX, int a_BlockZ, int a_Biome); -protected: + protected: /** The zoom levels */ static const double m_ViewZooms[10]; @@ -119,9 +118,3 @@ protected: /** Closes and destroys the generator setup pane, if there is one. */ void closeGeneratorSetup(); }; - - - - - - diff --git a/Tools/QtBiomeVisualiser/QtBiomeVisualiser.cpp b/Tools/QtBiomeVisualiser/QtBiomeVisualiser.cpp index f41cdcfb2..4f7fe73ff 100644 --- a/Tools/QtBiomeVisualiser/QtBiomeVisualiser.cpp +++ b/Tools/QtBiomeVisualiser/QtBiomeVisualiser.cpp @@ -6,7 +6,7 @@ -int main(int argc, char *argv[]) +int main(int argc, char * argv[]) { QApplication a(argc, argv); MainWindow w; @@ -14,7 +14,3 @@ int main(int argc, char *argv[]) return a.exec(); } - - - - diff --git a/Tools/QtBiomeVisualiser/QtChunk.cpp b/Tools/QtBiomeVisualiser/QtChunk.cpp index f201ef220..c458452ab 100644 --- a/Tools/QtBiomeVisualiser/QtChunk.cpp +++ b/Tools/QtBiomeVisualiser/QtChunk.cpp @@ -35,7 +35,3 @@ EMCSBiome Chunk::getBiome(int a_RelX, int a_RelZ) } return static_cast<EMCSBiome>(m_Biomes[a_RelX + 16 * a_RelZ]); } - - - - diff --git a/Tools/QtBiomeVisualiser/QtChunk.h b/Tools/QtBiomeVisualiser/QtChunk.h index d806d18bb..b43ab748f 100644 --- a/Tools/QtBiomeVisualiser/QtChunk.h +++ b/Tools/QtBiomeVisualiser/QtChunk.h @@ -8,7 +8,7 @@ class Chunk { -public: + public: /** The type used for storing image data for a chunk. */ typedef uchar Image[16 * 16 * 4]; @@ -28,7 +28,7 @@ public: /** Returns the raw biome data for this chunk. */ const short * getBiomes(void) const { return m_Biomes; } -protected: + protected: /** Flag that specifies if the chunk data is valid - loaded or generated. */ bool m_IsValid; @@ -38,8 +38,3 @@ protected: }; typedef std::shared_ptr<Chunk> ChunkPtr; - - - - - diff --git a/Tools/QtBiomeVisualiser/Region.cpp b/Tools/QtBiomeVisualiser/Region.cpp index d8a0a2f76..b8fdc00db 100644 --- a/Tools/QtBiomeVisualiser/Region.cpp +++ b/Tools/QtBiomeVisualiser/Region.cpp @@ -6,9 +6,7 @@ -Region::Region() -{ -} +Region::Region() {} @@ -16,12 +14,12 @@ Region::Region() Chunk & Region::getRelChunk(int a_RelChunkX, int a_RelChunkZ) { - ASSERT(a_RelChunkX >= 0); - ASSERT(a_RelChunkZ >= 0); - ASSERT(a_RelChunkX < 32); - ASSERT(a_RelChunkZ < 32); + ASSERT(a_RelChunkX >= 0); + ASSERT(a_RelChunkZ >= 0); + ASSERT(a_RelChunkX < 32); + ASSERT(a_RelChunkZ < 32); - return m_Chunks[a_RelChunkX + a_RelChunkZ * 32]; + return m_Chunks[a_RelChunkX + a_RelChunkZ * 32]; } @@ -66,7 +64,3 @@ void Region::chunkToRegion(int a_ChunkX, int a_ChunkZ, int & a_RegionX, int & a_ a_RegionX = static_cast<int>(std::floor(static_cast<float>(a_ChunkX) / 32)); a_RegionZ = static_cast<int>(std::floor(static_cast<float>(a_ChunkZ) / 32)); } - - - - diff --git a/Tools/QtBiomeVisualiser/Region.h b/Tools/QtBiomeVisualiser/Region.h index 863c0ac02..1b3713aa7 100644 --- a/Tools/QtBiomeVisualiser/Region.h +++ b/Tools/QtBiomeVisualiser/Region.h @@ -8,7 +8,7 @@ class Region { -public: + public: Region(); /** Retrieves the chunk with the specified relative coords. */ @@ -29,7 +29,7 @@ public: /** Converts chunk coordinates into region coordinates. */ static void chunkToRegion(int a_ChunkX, int a_ChunkZ, int & a_RegionX, int & a_RegionZ); -protected: + protected: friend class RegionLoader; @@ -40,7 +40,3 @@ protected: be displayed. */ bool m_IsValid; }; - - - - diff --git a/Tools/QtBiomeVisualiser/RegionCache.cpp b/Tools/QtBiomeVisualiser/RegionCache.cpp index e46fd222a..f779bd42f 100644 --- a/Tools/QtBiomeVisualiser/RegionCache.cpp +++ b/Tools/QtBiomeVisualiser/RegionCache.cpp @@ -132,7 +132,3 @@ void RegionCache::queueRegionRender(int a_RegionX, int a_RegionZ, RegionPtr & a_ QThreadPool::globalInstance()->start(loader); } - - - - diff --git a/Tools/QtBiomeVisualiser/RegionCache.h b/Tools/QtBiomeVisualiser/RegionCache.h index c343e4ba9..fb76b93f0 100644 --- a/Tools/QtBiomeVisualiser/RegionCache.h +++ b/Tools/QtBiomeVisualiser/RegionCache.h @@ -20,13 +20,12 @@ class ChunkSource; /** Caches regions' chunk data for reuse */ -class RegionCache : - public QObject +class RegionCache : public QObject { typedef QObject super; Q_OBJECT -public: + public: explicit RegionCache(QObject * parent = NULL); /** Retrieves the specified region from the cache. @@ -43,13 +42,13 @@ public: /** Reloads the current chunk source. */ void reload(); -signals: + signals: void regionAvailable(int a_RegionX, int a_RegionZ); -protected slots: + protected slots: void gotRegion(int a_RegionX, int a_RegionZ); -protected: + protected: /** The cache of the chunks */ QCache<quint32, RegionPtr> m_Cache; @@ -66,8 +65,3 @@ protected: /** Queues the specified region for rendering by m_RegionSource. */ void queueRegionRender(int a_RegionX, int a_RegionZ, RegionPtr & a_Region); }; - - - - - diff --git a/Tools/QtBiomeVisualiser/RegionLoader.cpp b/Tools/QtBiomeVisualiser/RegionLoader.cpp index 2a318098b..6cd00487f 100644 --- a/Tools/QtBiomeVisualiser/RegionLoader.cpp +++ b/Tools/QtBiomeVisualiser/RegionLoader.cpp @@ -14,10 +14,7 @@ volatile bool RegionLoader::m_IsShuttingDown = false; RegionLoader::RegionLoader(int a_RegionX, int a_RegionZ, RegionPtr a_Region, ChunkSourcePtr a_ChunkSource) : - m_RegionX(a_RegionX), - m_RegionZ(a_RegionZ), - m_Region(a_Region), - m_ChunkSource(a_ChunkSource) + m_RegionX(a_RegionX), m_RegionZ(a_RegionZ), m_Region(a_Region), m_ChunkSource(a_ChunkSource) { } @@ -43,7 +40,3 @@ void RegionLoader::run() emit loaded(m_RegionX, m_RegionZ); } - - - - diff --git a/Tools/QtBiomeVisualiser/RegionLoader.h b/Tools/QtBiomeVisualiser/RegionLoader.h index 6bbb4aa60..935fbdcd9 100644 --- a/Tools/QtBiomeVisualiser/RegionLoader.h +++ b/Tools/QtBiomeVisualiser/RegionLoader.h @@ -18,26 +18,25 @@ typedef std::shared_ptr<ChunkSource> ChunkSourcePtr; -class RegionLoader : - public QObject, - public QRunnable +class RegionLoader : public QObject, + public QRunnable { Q_OBJECT -public: + public: RegionLoader(int a_RegionX, int a_RegionZ, RegionPtr a_Region, ChunkSourcePtr a_ChunkSource); virtual ~RegionLoader() {} /** Signals to all loaders that the app is shutting down and the loading should be aborted. */ static void shutdown() { m_IsShuttingDown = true; } -signals: + signals: void loaded(int a_RegionX, int a_RegionZ); -protected: + protected: virtual void run() override; -private: + private: /** Coords of the region to be loaded. */ int m_RegionX, m_RegionZ; @@ -50,7 +49,3 @@ private: /** Flag that is set upon app exit to terminate the queued loaders faster. */ static volatile bool m_IsShuttingDown; }; - - - - diff --git a/Tools/RCONClient/Globals.cpp b/Tools/RCONClient/Globals.cpp index 13c6ae709..680afbf75 100644 --- a/Tools/RCONClient/Globals.cpp +++ b/Tools/RCONClient/Globals.cpp @@ -4,7 +4,3 @@ // This file is used for precompiled header generation in MSVC environments #include "Globals.h" - - - - diff --git a/Tools/RCONClient/Globals.h b/Tools/RCONClient/Globals.h index 661918063..d19f235c7 100644 --- a/Tools/RCONClient/Globals.h +++ b/Tools/RCONClient/Globals.h @@ -10,23 +10,23 @@ // Compiler-dependent stuff: #if defined(_MSC_VER) - // MSVC produces warning C4481 on the override keyword usage, so disable the warning altogether - #pragma warning(disable:4481) +// MSVC produces warning C4481 on the override keyword usage, so disable the warning altogether +#pragma warning(disable : 4481) - // Disable some warnings that we don't care about: - #pragma warning(disable:4100) +// Disable some warnings that we don't care about: +#pragma warning(disable : 4100) - // Use non-standard defines in <cmath> - #define _USE_MATH_DEFINES +// Use non-standard defines in <cmath> +#define _USE_MATH_DEFINES #elif defined(__GNUC__) - // TODO: Can GCC explicitly mark classes as abstract (no instances can be created)? - #define abstract +// TODO: Can GCC explicitly mark classes as abstract (no instances can be created)? +#define abstract #else - #error "You are using an unsupported compiler, you might need to #define some stuff here for your compiler" +#error "You are using an unsupported compiler, you might need to #define some stuff here for your compiler" #endif @@ -36,12 +36,12 @@ // Integral types with predefined sizes: typedef long long Int64; -typedef int Int32; -typedef short Int16; +typedef int Int32; +typedef short Int16; typedef unsigned long long UInt64; -typedef unsigned int UInt32; -typedef unsigned short UInt16; +typedef unsigned int UInt32; +typedef unsigned short UInt16; typedef unsigned char Byte; @@ -52,52 +52,52 @@ typedef unsigned char Byte; // A macro to disallow the copy constructor and operator= functions // This should be used in the private: declarations for any class that shouldn't allow copying itself #define DISALLOW_COPY_AND_ASSIGN(TypeName) \ - TypeName(const TypeName &); \ + TypeName(const TypeName &); \ void operator=(const TypeName &) // A macro that is used to mark unused function parameters, to avoid pedantic warnings in gcc -#define UNUSED(X) (void)(X) +#define UNUSED(X) (void) (X) // OS-dependent stuff: #ifdef _WIN32 - #define WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN - #define _WIN32_WINNT 0x502 // We want to target WinXP SP2 and higher +#define _WIN32_WINNT 0x502 // We want to target WinXP SP2 and higher - #include <Windows.h> - #include <winsock2.h> - #include <Ws2tcpip.h> // IPv6 stuff +#include <Windows.h> +#include <winsock2.h> +#include <Ws2tcpip.h> // IPv6 stuff - // Windows SDK defines min and max macros, messing up with our std::min and std::max usage - #undef min - #undef max +// Windows SDK defines min and max macros, messing up with our std::min and std::max usage +#undef min +#undef max - // Windows SDK defines GetFreeSpace as a constant, probably a Win16 API remnant - #ifdef GetFreeSpace - #undef GetFreeSpace - #endif // GetFreeSpace +// Windows SDK defines GetFreeSpace as a constant, probably a Win16 API remnant +#ifdef GetFreeSpace +#undef GetFreeSpace +#endif // GetFreeSpace #else - #include <sys/types.h> - #include <sys/stat.h> // for mkdir - #include <sys/time.h> - #include <sys/socket.h> - #include <netinet/in.h> - #include <arpa/inet.h> - #include <netdb.h> - #include <time.h> - #include <dirent.h> - #include <errno.h> - #include <iostream> - - #include <cstdio> - #include <cstring> - #include <pthread.h> - #include <semaphore.h> - #include <errno.h> - #include <fcntl.h> +#include <sys/types.h> +#include <sys/stat.h> // for mkdir +#include <sys/time.h> +#include <sys/socket.h> +#include <netinet/in.h> +#include <arpa/inet.h> +#include <netdb.h> +#include <time.h> +#include <dirent.h> +#include <errno.h> +#include <iostream> + +#include <cstdio> +#include <cstring> +#include <pthread.h> +#include <semaphore.h> +#include <errno.h> +#include <fcntl.h> #endif @@ -146,16 +146,16 @@ typedef unsigned char Byte; #define ARRAYCOUNT(X) (sizeof(X) / sizeof(*(X))) /** Allows arithmetic expressions like "32 KiB" (but consider using parenthesis around it, "(32 KiB)") */ -#define KiB * 1024 +#define KiB *1024 /** Faster than (int)floorf((float)x / (float)div) */ -#define FAST_FLOOR_DIV(x, div) ((x) < 0 ? (((int)x / div) - 1) : ((int)x / div)) +#define FAST_FLOOR_DIV(x, div) ((x) < 0 ? (((int) x / div) - 1) : ((int) x / div)) // Own version of assert() that writes failed assertions to the log for review -#ifdef NDEBUG - #define ASSERT(x) ((void)0) +#ifdef NDEBUG +#define ASSERT(x) ((void) 0) #else - #define ASSERT assert +#define ASSERT assert #endif // Pretty much the same as ASSERT() but stays in Release builds diff --git a/Tools/RCONClient/RCONClient.cpp b/Tools/RCONClient/RCONClient.cpp index f9fd0b2e2..99f44365f 100644 --- a/Tools/RCONClient/RCONClient.cpp +++ b/Tools/RCONClient/RCONClient.cpp @@ -21,12 +21,12 @@ bool g_IsVerbose = false; /** This class can read and write RCON packets to / from a connected socket */ class cRCONPacketizer { -public: + public: enum { ptCommand = 2, ptLogin = 3, - } ; + }; cRCONPacketizer(cSocket & a_Socket); @@ -35,7 +35,7 @@ public: Dumps the reply payload to stdout. */ bool SendPacket(int a_PacketType, const AString & a_PacketPayload); -protected: + protected: /** The socket to use for reading incoming data and writing outgoing data: */ cSocket & m_Socket; @@ -51,15 +51,14 @@ protected: Assumes that the packet length has already been read from the packet If the packet is successfully parsed, increments m_RequestID */ bool ParsePacket(cByteBuffer & a_Buffer, int a_PacketLength); -} ; +}; cRCONPacketizer::cRCONPacketizer(cSocket & a_Socket) : - m_Socket(a_Socket), - m_RequestID(0) + m_Socket(a_Socket), m_RequestID(0) { } @@ -78,17 +77,23 @@ bool cRCONPacketizer::SendPacket(int a_PacketType, const AString & a_PacketPaylo AString Packet; bb.ReadAll(Packet); size_t Length = Packet.size(); - if (!m_Socket.Send((const char *)&Length, 4)) + if (!m_Socket.Send((const char *) &Length, 4)) { - fprintf(stderr, "Network error while sending packet: %d (%s). Aborting.\n", - cSocket::GetLastError(), cSocket::GetLastErrorString().c_str() + fprintf( + stderr, + "Network error while sending packet: %d (%s). Aborting.\n", + cSocket::GetLastError(), + cSocket::GetLastErrorString().c_str() ); return false; } if (!m_Socket.Send(Packet.data(), Packet.size())) { - fprintf(stderr, "Network error while sending packet: %d (%s). Aborting.\n", - cSocket::GetLastError(), cSocket::GetLastErrorString().c_str() + fprintf( + stderr, + "Network error while sending packet: %d (%s). Aborting.\n", + cSocket::GetLastError(), + cSocket::GetLastErrorString().c_str() ); return false; } @@ -115,8 +120,12 @@ bool cRCONPacketizer::ReceiveResponse(void) } if (NumReceived < 0) { - fprintf(stderr, "Network error while receiving response: %d, %d (%s). Aborting.\n", - NumReceived, cSocket::GetLastError(), cSocket::GetLastErrorString().c_str() + fprintf( + stderr, + "Network error while receiving response: %d, %d (%s). Aborting.\n", + NumReceived, + cSocket::GetLastError(), + cSocket::GetLastErrorString().c_str() ); return false; } @@ -162,7 +171,12 @@ bool cRCONPacketizer::ParsePacket(cByteBuffer & a_Buffer, int a_PacketLength) } else { - fprintf(stderr, "The server returned an invalid request ID, got %d, exp. %d. Aborting.\n", RequestID, m_RequestID); + fprintf( + stderr, + "The server returned an invalid request ID, got %d, exp. %d. Aborting.\n", + RequestID, + m_RequestID + ); return false; } } @@ -226,7 +240,9 @@ int RealMain(int argc, char * argv[]) i++; continue; } - if (((NoCaseCompare(argv[i], "-c") == 0) || (NoCaseCompare(argv[i], "--cmd") == 0) || (NoCaseCompare(argv[i], "--command") == 0)) && (i < argc - 1)) + if (((NoCaseCompare(argv[i], "-c") == 0) || (NoCaseCompare(argv[i], "--cmd") == 0) || + (NoCaseCompare(argv[i], "--command") == 0)) && + (i < argc - 1)) { Commands.push_back(argv[i + 1]); i++; @@ -258,7 +274,10 @@ int RealMain(int argc, char * argv[]) if (ServerAddress.empty() || (ServerPort < 0)) { - fprintf(stderr, "Server address or port not set. Use the --server and --port parameters to set them. Aborting."); + fprintf( + stderr, + "Server address or port not set. Use the --server and --port parameters to set them. Aborting." + ); return 1; } @@ -273,9 +292,15 @@ int RealMain(int argc, char * argv[]) fprintf(stderr, "Connecting to \"%s:%d\"...\n", ServerAddress.c_str(), ServerPort); } cSocket s = cSocket::CreateSocket(cSocket::IPv4); - if (!s.ConnectIPv4(ServerAddress, (unsigned short)ServerPort)) + if (!s.ConnectIPv4(ServerAddress, (unsigned short) ServerPort)) { - fprintf(stderr, "Cannot connect to \"%s:%d\": %s\n", ServerAddress.c_str(), ServerPort, cSocket::GetLastErrorString().c_str()); + fprintf( + stderr, + "Cannot connect to \"%s:%d\": %s\n", + ServerAddress.c_str(), + ServerPort, + cSocket::GetLastErrorString().c_str() + ); return 3; } cRCONPacketizer Packetizer(s); @@ -323,7 +348,8 @@ int RealMain(int argc, char * argv[]) int main(int argc, char * argv[]) { - // This redirection function is only so that debugging the program is easier in MSVC - when RealMain exits, it's still possible to place a breakpoint + // This redirection function is only so that debugging the program is easier in MSVC - when RealMain exits, it's + // still possible to place a breakpoint int res = RealMain(argc, argv); return res; } diff --git a/Tools/ToLuaDoxy/Globals.cpp b/Tools/ToLuaDoxy/Globals.cpp index d73265a60..6d1b25cbc 100644 --- a/Tools/ToLuaDoxy/Globals.cpp +++ b/Tools/ToLuaDoxy/Globals.cpp @@ -4,7 +4,3 @@ // Used for precompiled header generation in MSVC #include "Globals.h" - - - - diff --git a/Tools/ToLuaDoxy/Globals.h b/Tools/ToLuaDoxy/Globals.h index 9dc94892a..5e366426d 100644 --- a/Tools/ToLuaDoxy/Globals.h +++ b/Tools/ToLuaDoxy/Globals.h @@ -8,41 +8,41 @@ // OS-dependent stuff: #ifdef _WIN32 - #define WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN - #define _WIN32_WINNT 0x501 // We want to target WinXP and higher +#define _WIN32_WINNT 0x501 // We want to target WinXP and higher - #include <Windows.h> - #include <winsock2.h> - #include <Ws2tcpip.h> // IPv6 stuff +#include <Windows.h> +#include <winsock2.h> +#include <Ws2tcpip.h> // IPv6 stuff - // Windows SDK defines min and max macros, messing up with our std::min and std::max usage - #undef min - #undef max +// Windows SDK defines min and max macros, messing up with our std::min and std::max usage +#undef min +#undef max - // Windows SDK defines GetFreeSpace as a constant, probably a Win16 API remnant - #ifdef GetFreeSpace - #undef GetFreeSpace - #endif // GetFreeSpace +// Windows SDK defines GetFreeSpace as a constant, probably a Win16 API remnant +#ifdef GetFreeSpace +#undef GetFreeSpace +#endif // GetFreeSpace #else - #include <sys/types.h> - #include <sys/stat.h> // for mkdir - #include <sys/time.h> - #include <sys/socket.h> - #include <netinet/in.h> - #include <arpa/inet.h> - #include <netdb.h> - #include <time.h> - #include <dirent.h> - #include <errno.h> - #include <iostream> - - #include <cstdio> - #include <cstring> - #include <pthread.h> - #include <semaphore.h> - #include <errno.h> - #include <fcntl.h> +#include <sys/types.h> +#include <sys/stat.h> // for mkdir +#include <sys/time.h> +#include <sys/socket.h> +#include <netinet/in.h> +#include <arpa/inet.h> +#include <netdb.h> +#include <time.h> +#include <dirent.h> +#include <errno.h> +#include <iostream> + +#include <cstdio> +#include <cstring> +#include <pthread.h> +#include <semaphore.h> +#include <errno.h> +#include <fcntl.h> #endif @@ -87,7 +87,7 @@ #define ARRAYCOUNT(X) (sizeof(X) / sizeof(*(X))) /** Allows arithmetic expressions like "32 KiB" (but consider using parenthesis around it, "(32 KiB)") */ -#define KiB * 1024 -#define MiB * 1024 * 1024 +#define KiB *1024 +#define MiB *1024 * 1024 #define ASSERT assert diff --git a/Tools/ToLuaDoxy/ToLuaDoxy.cpp b/Tools/ToLuaDoxy/ToLuaDoxy.cpp index 2a54192a4..e1a864091 100644 --- a/Tools/ToLuaDoxy/ToLuaDoxy.cpp +++ b/Tools/ToLuaDoxy/ToLuaDoxy.cpp @@ -19,19 +19,14 @@ typedef std::vector<AString> AStrings; class cProcessor { -public: + public: cProcessor(const AString & a_FileOut) : - m_Out(a_FileOut.c_str(), std::ios::out), - m_IsInToLua(false), - m_IsInComment(false) + m_Out(a_FileOut.c_str(), std::ios::out), m_IsInToLua(false), m_IsInComment(false) { } - bool IsGood(void) const - { - return !m_Out.fail(); - } + bool IsGood(void) const { return !m_Out.fail(); } void ProcessFile(const AString & a_FileIn) @@ -50,11 +45,11 @@ public: } } -protected: + protected: std::ofstream m_Out; - bool m_IsInToLua; ///< Set to true if inside a tolua_begin .. tolua_end block - bool m_IsInComment; ///< Set to true if previous line has started a multiline comment; only outside tolua blocks - AString m_LastComment; ///< Accumulator for a multiline comment preceding a tolua block + bool m_IsInToLua; ///< Set to true if inside a tolua_begin .. tolua_end block + bool m_IsInComment; ///< Set to true if previous line has started a multiline comment; only outside tolua blocks + AString m_LastComment; ///< Accumulator for a multiline comment preceding a tolua block void PushLine(const AString & a_Line) @@ -129,7 +124,7 @@ protected: m_LastComment.clear(); } } -} ; +}; @@ -188,14 +183,14 @@ void ProcessCFile(const AString & a_CFileIn, const AString & a_CFileOut) int main(int argc, char * argv[]) { AString BaseDir = (argc > 1) ? argv[1] : "."; - AString OutDir = (argc > 2) ? argv[2] : "Out"; + AString OutDir = (argc > 2) ? argv[2] : "Out"; - // Create the output directory: - #ifdef _WIN32 +// Create the output directory: +#ifdef _WIN32 CreateDirectory(OutDir.c_str(), NULL); - #else +#else mkdir(OutDir.c_str(), S_IRWXU | S_IRWXG | S_IRWXO); - #endif +#endif // Parse the package file AStrings CFiles; |