Apply new clang-formatting

This commit is contained in:
Alexander Harkness 2024-11-02 21:27:47 +00:00
parent a376d7e2bb
commit cb50ec1059
917 changed files with 310633 additions and 127540 deletions

View File

@ -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]);

View File

@ -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
}

View File

@ -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; }
};

View File

@ -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;
} ;
};

View File

@ -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);

View File

@ -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;
} ;
};

View File

@ -4,7 +4,3 @@
// This file is used for precompiled header generation in MSVC environments
#include "Globals.h"

View File

@ -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>
#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 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 <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 <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);
}

View File

@ -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())

View File

@ -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; }
};

View File

@ -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
}

View File

@ -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; }
};

View File

@ -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);

View File

@ -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);
} ;
};

View File

@ -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() {}

View File

@ -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);
} ;
};

View File

@ -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[]
}

View File

@ -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);
} ;
};

View File

@ -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");

View File

@ -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);
} ;
};

View File

@ -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] : "";
}

View File

@ -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);

View File

@ -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;
} ;
};

View File

@ -4,7 +4,3 @@
// Used for precompiled header generation in MSVC
#include "Globals.h"

View File

@ -8,7 +8,3 @@
#include "../../src/Globals.h"

View File

@ -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)
);
}

View File

@ -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);
} ;
};

View File

@ -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:

View File

@ -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);
} ;
};

View File

@ -4,7 +4,3 @@
// This file is used for precompiled header generation in MSVC environments
#include "Globals.h"

View File

@ -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 <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>
#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
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);
}

View File

@ -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 }, },
} 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 }, },
{
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);

View File

@ -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:

View File

@ -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);
} ;
};

View File

@ -29,7 +29,3 @@
// Libraries:
#include "expat/expat.h"

View File

@ -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,

View File

@ -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

View File

@ -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;
}

View File

@ -1,5 +1 @@
// NoiseSpeedTest.h

View File

@ -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];
};

File diff suppressed because it is too large Load Diff

View File

@ -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,
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);
/** 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 */
/** 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);
} ;
};

View File

@ -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();

View File

@ -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; }
} ;
};

View File

@ -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 }, },
} 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 }, },
{
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);

View File

@ -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;
};

View File

@ -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;
}

View File

@ -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);
};

View File

@ -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[]
}

View File

@ -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();
};

View File

@ -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
#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
#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/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
{
};
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)
#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)
#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
#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

View File

@ -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;
}

View File

@ -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();
};

View File

@ -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();
}

View File

@ -35,7 +35,3 @@ EMCSBiome Chunk::getBiome(int a_RelX, int a_RelZ)
}
return static_cast<EMCSBiome>(m_Biomes[a_RelX + 16 * a_RelZ]);
}

View File

@ -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;

View File

@ -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));
}

View File

@ -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;
};

View File

@ -132,7 +132,3 @@ void RegionCache::queueRegionRender(int a_RegionX, int a_RegionZ, RegionPtr & a_
QThreadPool::globalInstance()->start(loader);
}

View File

@ -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);
};

View File

@ -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);
}

View File

@ -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;
};

View File

@ -4,7 +4,3 @@
// This file is used for precompiled header generation in MSVC environments
#include "Globals.h"

View File

@ -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 <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 <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

View File

@ -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;
}

View File

@ -4,7 +4,3 @@
// Used for precompiled header generation in MSVC
#include "Globals.h"

View File

@ -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 <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 <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

View File

@ -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;

View File

@ -5,7 +5,7 @@
BlockState::BlockState():
BlockState::BlockState() :
mChecksum(initializeChecksum())
{
// Nothing needed yet
@ -15,9 +15,8 @@ BlockState::BlockState():
BlockState::BlockState(const AString & aKey, const AString & aValue):
mState({{aKey, aValue}}),
mChecksum(initializeChecksum())
BlockState::BlockState(const AString & aKey, const AString & aValue) :
mState({{aKey, aValue}}), mChecksum(initializeChecksum())
{
}
@ -25,9 +24,8 @@ BlockState::BlockState(const AString & aKey, const AString & aValue):
BlockState::BlockState(std::initializer_list<std::pair<const AString, AString>> aKeysAndValues):
mState(aKeysAndValues),
mChecksum(initializeChecksum())
BlockState::BlockState(std::initializer_list<std::pair<const AString, AString>> aKeysAndValues) :
mState(aKeysAndValues), mChecksum(initializeChecksum())
{
}
@ -35,9 +33,8 @@ BlockState::BlockState(std::initializer_list<std::pair<const AString, AString>>
BlockState::BlockState(const std::map<AString, AString> & aKeysAndValues):
mState(aKeysAndValues),
mChecksum(initializeChecksum())
BlockState::BlockState(const std::map<AString, AString> & aKeysAndValues) :
mState(aKeysAndValues), mChecksum(initializeChecksum())
{
}
@ -45,9 +42,8 @@ BlockState::BlockState(const std::map<AString, AString> & aKeysAndValues):
BlockState::BlockState(std::map<AString, AString> && aKeysAndValues):
mState(std::move(aKeysAndValues)),
mChecksum(initializeChecksum())
BlockState::BlockState(std::map<AString, AString> && aKeysAndValues) :
mState(std::move(aKeysAndValues)), mChecksum(initializeChecksum())
{
}
@ -55,10 +51,13 @@ BlockState::BlockState(std::map<AString, AString> && aKeysAndValues):
BlockState::BlockState(const BlockState & aCopyFrom, std::initializer_list<std::pair<const AString, AString>> aAdditionalKeysAndValues):
BlockState::BlockState(
const BlockState & aCopyFrom,
std::initializer_list<std::pair<const AString, AString>> aAdditionalKeysAndValues
) :
mState(aCopyFrom.mState)
{
for (const auto & kav: aAdditionalKeysAndValues)
for (const auto & kav : aAdditionalKeysAndValues)
{
mState[kav.first] = kav.second;
}
@ -69,10 +68,10 @@ BlockState::BlockState(const BlockState & aCopyFrom, std::initializer_list<std::
BlockState::BlockState(const BlockState & aCopyFrom, const std::map<AString, AString> & aAdditionalKeysAndValues):
BlockState::BlockState(const BlockState & aCopyFrom, const std::map<AString, AString> & aAdditionalKeysAndValues) :
mState(aCopyFrom.mState)
{
for (const auto & kav: aAdditionalKeysAndValues)
for (const auto & kav : aAdditionalKeysAndValues)
{
mState[kav.first] = kav.second;
}
@ -83,7 +82,7 @@ BlockState::BlockState(const BlockState & aCopyFrom, const std::map<AString, ASt
bool BlockState::operator <(const BlockState & aOther) const
bool BlockState::operator<(const BlockState & aOther) const
{
// Fast-return this using checksum
if (mChecksum != aOther.mChecksum)
@ -129,7 +128,7 @@ bool BlockState::operator <(const BlockState & aOther) const
bool BlockState::operator ==(const BlockState & aOther) const
bool BlockState::operator==(const BlockState & aOther) const
{
// Fast-fail if the checksums differ or differrent counts:
if ((mChecksum != aOther.mChecksum) || (mState.size() != aOther.mState.size()))
@ -167,7 +166,7 @@ UInt32 BlockState::initializeChecksum()
// Calculate the checksum as a XOR of all mState keys' and values' checksums
// This way we don't depend on the std::map's ordering
UInt32 res = 0;
for (const auto & kv: mState)
for (const auto & kv : mState)
{
auto partial = partialChecksum(kv.first) ^ partialChecksum(kv.second);
res = res ^ partial;
@ -202,7 +201,7 @@ UInt32 BlockState::partialChecksum(const AString & aString)
{
UInt32 shift = 0;
UInt32 res = 0;
for (auto ch: aString)
for (auto ch : aString)
{
UInt32 v = static_cast<UInt8>(ch);
v = v << shift;

View File

@ -7,10 +7,10 @@
/** Represents the state of a single block (previously known as "block meta").
The state consists of a map of string -> string, plus a mechanism for fast equality checks between two BlockState instances.
Once a BlockState instance is created, it is then immutable - there's no way of changing it, only by creating a (modified) copy.
A BlockState instance can be created from hard-coded data or from dynamic data:
BlockState bs({{"key1", "value1"}, {key2", "value2"}}); // Hard-coded
The state consists of a map of string -> string, plus a mechanism for fast equality checks between two BlockState
instances. Once a BlockState instance is created, it is then immutable - there's no way of changing it, only by creating
a (modified) copy. A BlockState instance can be created from hard-coded data or from dynamic data: BlockState
bs({{"key1", "value1"}, {key2", "value2"}}); // Hard-coded
- or -
std::map<AString, AString> map({{"key1", "value1"}, {key2", "value2"}});
map["key3"] = "value3";
@ -18,8 +18,7 @@ A BlockState instance can be created from hard-coded data or from dynamic data:
*/
class BlockState
{
public:
public:
/** Creates a new instance with an empty map. */
BlockState();
@ -41,36 +40,35 @@ public:
BlockState(std::map<AString, AString> && aKeysAndValues);
/** Creates a copy of the specified BlockState with the (hard-coded) additional keys and values added to it.
Any key in aAdditionalKeysAndValues that is already present in aCopyFrom is overwritten with the aAdditionalKeysAndValues' one.
Any key with an empty value is not stored in the map.
(it's possible to erase a key from aCopyFrom by setting it to empty string in aAdditionalKeysAndValues). */
BlockState(const BlockState & aCopyFrom, std::initializer_list<std::pair<const AString, AString>> aAdditionalKeysAndValues);
Any key in aAdditionalKeysAndValues that is already present in aCopyFrom is overwritten with the
aAdditionalKeysAndValues' one. Any key with an empty value is not stored in the map. (it's possible to erase a key
from aCopyFrom by setting it to empty string in aAdditionalKeysAndValues). */
BlockState(
const BlockState & aCopyFrom,
std::initializer_list<std::pair<const AString, AString>> aAdditionalKeysAndValues
);
/** Creates a copy of the specified BlockState with the (dynamic) additional keys and values added to it.
Any key in aAdditionalKeysAndValues that is already present in aCopyFrom is overwritten with the aAdditionalKeysAndValues' one.
Any key with an empty value is not stored in the map.
(it's possible to erase a key from aCopyFrom by setting it to empty string in aAdditionalKeysAndValues). */
Any key in aAdditionalKeysAndValues that is already present in aCopyFrom is overwritten with the
aAdditionalKeysAndValues' one. Any key with an empty value is not stored in the map. (it's possible to erase a key
from aCopyFrom by setting it to empty string in aAdditionalKeysAndValues). */
BlockState(const BlockState & aCopyFrom, const std::map<AString, AString> & aAdditionalKeysAndValues);
/** Less-than comparison. */
bool operator <(const BlockState & aOther) const;
bool operator<(const BlockState & aOther) const;
/** Fast equality check. */
bool operator ==(const BlockState & aOther) const;
bool operator==(const BlockState & aOther) const;
/** Fast inequality check. */
bool operator !=(const BlockState & aOther) const
{
return !(operator ==(aOther));
}
bool operator!=(const BlockState & aOther) const { return !(operator==(aOther)); }
/** Returns the value at the specified key.
If the key is not present, returns an empty string. */
const AString & value(const AString & aKey) const;
protected:
protected:
/** The state, represented as a string->string map. */
std::map<AString, AString> mState;

View File

@ -31,7 +31,7 @@ static size_t findNextSeparator(const AString & aString, size_t aStartIdx = 0)
BlockTypePalette::BlockTypePalette():
BlockTypePalette::BlockTypePalette() :
mMaxIndex(0)
{
}
@ -59,7 +59,8 @@ UInt32 BlockTypePalette::index(const AString & aBlockTypeName, const BlockState
std::pair<UInt32, bool> BlockTypePalette::maybeIndex(const AString & aBlockTypeName, const BlockState & aBlockState) const
std::pair<UInt32, bool> BlockTypePalette::maybeIndex(const AString & aBlockTypeName, const BlockState & aBlockState)
const
{
auto itr1 = mBlockToNumber.find(aBlockTypeName);
if (itr1 == mBlockToNumber.end())
@ -104,7 +105,7 @@ const std::pair<AString, BlockState> & BlockTypePalette::entry(UInt32 aIndex) co
std::map<UInt32, UInt32> BlockTypePalette::createTransformMapAddMissing(const BlockTypePalette & aFrom)
{
std::map<UInt32, UInt32> res;
for (const auto & fromEntry: aFrom.mNumberToBlock)
for (const auto & fromEntry : aFrom.mNumberToBlock)
{
auto fromIndex = fromEntry.first;
const auto & blockTypeName = fromEntry.second.first;
@ -118,10 +119,13 @@ std::map<UInt32, UInt32> BlockTypePalette::createTransformMapAddMissing(const Bl
std::map<UInt32, UInt32> BlockTypePalette::createTransformMapWithFallback(const BlockTypePalette & aFrom, UInt32 aFallbackIndex) const
std::map<UInt32, UInt32> BlockTypePalette::createTransformMapWithFallback(
const BlockTypePalette & aFrom,
UInt32 aFallbackIndex
) const
{
std::map<UInt32, UInt32> res;
for (const auto & fromEntry: aFrom.mNumberToBlock)
for (const auto & fromEntry : aFrom.mNumberToBlock)
{
auto fromIndex = fromEntry.first;
const auto & blockTypeName = fromEntry.second.first;
@ -189,9 +193,10 @@ void BlockTypePalette::loadFromJsonString(const AString & aJsonPalette)
const auto & states = (*itr)["states"];
if (states == Json::Value())
{
throw LoadFailedException(fmt::format(FMT_STRING("Missing \"states\" for block type \"{}\""), blockTypeName));
throw LoadFailedException(fmt::format(FMT_STRING("Missing \"states\" for block type \"{}\""), blockTypeName)
);
}
for (const auto & state: states)
for (const auto & state : states)
{
auto id = static_cast<UInt32>(std::stoul(state["id"].asString()));
std::map<AString, AString> props;
@ -200,9 +205,13 @@ void BlockTypePalette::loadFromJsonString(const AString & aJsonPalette)
const auto & properties = state["properties"];
if (!properties.isObject())
{
throw LoadFailedException(fmt::format(FMT_STRING("Member \"properties\" is not a JSON object (block type \"{}\", id {})."), blockTypeName, id));
throw LoadFailedException(fmt::format(
FMT_STRING("Member \"properties\" is not a JSON object (block type \"{}\", id {})."),
blockTypeName,
id
));
}
for (const auto & key: properties.getMemberNames())
for (const auto & key : properties.getMemberNames())
{
props[key] = properties[key].asString();
}
@ -233,7 +242,7 @@ void BlockTypePalette::loadFromTsv(const AString & aTsvPalette, bool aIsUpgrade)
{
throw LoadFailedException("Unknown signature");
}
if (aTsvPalette[idx] == '\r') // CR of the CRLF pair, skip the LF:
if (aTsvPalette[idx] == '\r') // CR of the CRLF pair, skip the LF:
{
idx += 1;
}
@ -277,7 +286,9 @@ void BlockTypePalette::loadFromTsv(const AString & aTsvPalette, bool aIsUpgrade)
}
else if (version != 1)
{
throw LoadFailedException(fmt::format(FMT_STRING("Unknown FileVersion: {}. Only version 1 is supported."), version));
throw LoadFailedException(
fmt::format(FMT_STRING("Unknown FileVersion: {}. Only version 1 is supported."), version)
);
}
hasHadVersion = true;
}
@ -348,7 +359,8 @@ void BlockTypePalette::loadFromTsv(const AString & aTsvPalette, bool aIsUpgrade)
auto valueEnd = findNextSeparator(aTsvPalette, keyEnd + 1);
if (valueEnd == AString::npos)
{
throw LoadFailedException(fmt::format(FMT_STRING("Incomplete data on line {} (blockState value)"), line));
throw LoadFailedException(fmt::format(FMT_STRING("Incomplete data on line {} (blockState value)"), line)
);
}
auto key = aTsvPalette.substr(blockStateEnd + 1, keyEnd - blockStateEnd - 1);
auto value = aTsvPalette.substr(keyEnd + 1, valueEnd - keyEnd - 1);

View File

@ -35,16 +35,14 @@ If a CommonPrefix header is present, its value is pre-pended to each blockTypeNa
the file to be overall smaller). */
class BlockTypePalette
{
public:
public:
/** Exception that is thrown if requiesting an index not present in the palette. */
class NoSuchIndexException:
public std::runtime_error
class NoSuchIndexException : public std::runtime_error
{
using Super = std::runtime_error;
public:
NoSuchIndexException(UInt32 aIndex):
public:
NoSuchIndexException(UInt32 aIndex) :
Super(fmt::format(FMT_STRING("No such palette index: {}"), aIndex))
{
}
@ -52,13 +50,12 @@ public:
/** Exception that is thrown when loading the palette fails hard (bad format). */
class LoadFailedException:
public std::runtime_error
class LoadFailedException : public std::runtime_error
{
using Super = std::runtime_error;
public:
LoadFailedException(const AString & aReason):
public:
LoadFailedException(const AString & aReason) :
Super(aReason)
{
}
@ -92,7 +89,8 @@ public:
/** Returns an index-transform map from aFrom to this (this.entry(idx) == aFrom.entry(res[idx])).
Entries from aFrom that are not present in this are assigned the fallback index.
Used for protocol block type mapping. */
std::map<UInt32, UInt32> createTransformMapWithFallback(const BlockTypePalette & aFrom, UInt32 aFallbackIndex) const;
std::map<UInt32, UInt32> createTransformMapWithFallback(const BlockTypePalette & aFrom, UInt32 aFallbackIndex)
const;
/** Loads the palette from the string representation.
Throws a LoadFailedException if the loading fails hard (bad string format);
@ -103,8 +101,7 @@ public:
void loadFromString(const AString & aString);
protected:
protected:
/** The mapping from numeric to stringular representation.
mNumberToBlock[index] = {"blockTypeName", blockState}. */
std::map<UInt32, std::pair<AString, BlockState>> mNumberToBlock;

View File

@ -14,7 +14,7 @@ BlockInfo::BlockInfo(
std::shared_ptr<cBlockHandler> aHandler,
const std::map<AString, AString> & aHints,
const std::map<AString, BlockInfo::HintCallback> & aHintCallbacks
):
) :
m_PluginName(aPluginName),
m_BlockTypeName(aBlockTypeName),
m_Handler(std::move(aHandler)),
@ -27,10 +27,7 @@ BlockInfo::BlockInfo(
AString BlockInfo::hintValue(
const AString & aHintName,
const BlockState & aBlockState
)
AString BlockInfo::hintValue(const AString & aHintName, const BlockState & aBlockState)
{
// Search the hint callbacks first:
auto itrC = m_HintCallbacks.find(aHintName);
@ -64,8 +61,11 @@ void BlockInfo::setHint(const AString & aHintKey, const AString & aHintValue)
auto itrC = m_HintCallbacks.find(aHintKey);
if (itrC != m_HintCallbacks.end())
{
LOGINFO("Setting a static hint %s for block type %s, but there's already a callback for that hint. The static hint will be ignored.",
aHintKey.c_str(), m_BlockTypeName.c_str()
LOGINFO(
"Setting a static hint %s for block type %s, but there's already a callback for that hint. The static hint "
"will be ignored.",
aHintKey.c_str(),
m_BlockTypeName.c_str()
);
}
}
@ -94,9 +94,8 @@ void BlockTypeRegistry::registerBlockType(
const std::map<AString, BlockInfo::HintCallback> & aHintCallbacks
)
{
auto blockInfo = std::make_shared<BlockInfo>(
aPluginName, aBlockTypeName, std::move(aHandler), aHints, aHintCallbacks
);
auto blockInfo =
std::make_shared<BlockInfo>(aPluginName, aBlockTypeName, std::move(aHandler), aHints, aHintCallbacks);
// Check previous registrations:
cCSLock lock(m_CSRegistry);
@ -171,10 +170,7 @@ void BlockTypeRegistry::setBlockTypeHint(
void BlockTypeRegistry::removeBlockTypeHint(
const AString & aBlockTypeName,
const AString & aHintKey
)
void BlockTypeRegistry::removeBlockTypeHint(const AString & aBlockTypeName, const AString & aHintKey)
{
cCSLock lock(m_CSRegistry);
auto blockInfo = m_Registry.find(aBlockTypeName);
@ -212,7 +208,8 @@ AString BlockTypeRegistry::AlreadyRegisteredException::message(
)
{
return fmt::format(
FMT_STRING("Attempting to register BlockTypeName {} from plugin {}, while it is already registered in plugin {}"),
FMT_STRING("Attempting to register BlockTypeName {} from plugin {}, while it is already registered in plugin {}"
),
aNewRegistration->blockTypeName(),
aNewRegistration->pluginName(),
aPreviousRegistration->pluginName()
@ -230,9 +227,10 @@ BlockTypeRegistry::NotRegisteredException::NotRegisteredException(
const AString & aBlockTypeName,
const AString & aHintKey,
const AString & aHintValue
):
) :
Super(fmt::format(
FMT_STRING("Attempting to set a hint of nonexistent BlockTypeName.\n\tBlockTypeName = {}\n\tHintKey = {}\n\tHintValue = {}"),
FMT_STRING("Attempting to set a hint of nonexistent BlockTypeName.\n\tBlockTypeName = {}\n\tHintKey = "
"{}\n\tHintValue = {}"),
aBlockTypeName,
aHintKey,
aHintValue

View File

@ -23,8 +23,7 @@ class BlockState;
The BlockTypeRegistry uses this structure to store the registered information. */
class BlockInfo
{
public:
public:
/** Callback is used to query block hints dynamically, based on the current BlockState.
Useful for example for redstone lamps that can be turned on or off. */
using HintCallback = std::function<AString(const AString & aTypeName, const BlockState & aBlockState)>;
@ -44,10 +43,7 @@ public:
/** Retrieves the value associated with the specified hint for this specific BlockTypeName and BlockState.
Queries hint callbacks first, then static hints if a callback doesn't exist.
Returns an empty string if hint not found at all. */
AString hintValue(
const AString & aHintName,
const BlockState & aBlockState
);
AString hintValue(const AString & aHintName, const BlockState & aBlockState);
// Simple getters:
const AString & pluginName() const { return m_PluginName; }
@ -55,8 +51,8 @@ public:
std::shared_ptr<cBlockHandler> handler() const { return m_Handler; }
/** Sets (creates or updates) a static hint.
Hints provided by callbacks are unaffected by this - callbacks are "higher priority", they overwrite anything set here.
Logs an info message if the hint is already provided by a hint callback. */
Hints provided by callbacks are unaffected by this - callbacks are "higher priority", they overwrite anything set
here. Logs an info message if the hint is already provided by a hint callback. */
void setHint(const AString & aHintKey, const AString & aHintValue);
/** Removes a hint.
@ -64,8 +60,7 @@ public:
void removeHint(const AString & aHintKey);
private:
private:
/** The name of the plugin that registered the block. */
AString m_PluginName;
@ -76,11 +71,13 @@ private:
std::shared_ptr<cBlockHandler> m_Handler;
/** Optional static hints for any subsystem to use, such as "IsSnowable" -> "1".
Hint callbacks are of higher priority than m_Hints - if a hint is provided by a m_HintCallback, its value in m_Hints is ignored. */
Hint callbacks are of higher priority than m_Hints - if a hint is provided by a m_HintCallback, its value in m_Hints
is ignored. */
std::map<AString, AString> m_Hints;
/** The callbacks for dynamic evaluation of hints, such as "LightValue" -> function(BlockTypeName, BlockState).
Hint callbacks are of higher priority than m_Hints - if a hint is provided by a m_HintCallback, its value in m_Hints is ignored. */
Hint callbacks are of higher priority than m_Hints - if a hint is provided by a m_HintCallback, its value in m_Hints
is ignored. */
std::map<AString, HintCallback> m_HintCallbacks;
};
@ -96,7 +93,7 @@ Stores the name of the plugin that registered the type, for better plugin error
and so that we can unload and reload plugins. */
class BlockTypeRegistry
{
public:
public:
// fwd:
class AlreadyRegisteredException;
class NotRegisteredException;
@ -125,23 +122,15 @@ public:
/** Sets (adds or overwrites) a single Hint value for a BlockType.
Throws NotRegisteredException if the BlockTypeName is not registered. */
void setBlockTypeHint(
const AString & aBlockTypeName,
const AString & aHintKey,
const AString & aHintValue
);
void setBlockTypeHint(const AString & aBlockTypeName, const AString & aHintKey, const AString & aHintValue);
/** Removes a previously registered single Hint value for a BlockType.
Throws NotRegisteredException if the BlockTypeName is not registered.
Silently ignored if the Hint hasn't been previously set. */
void removeBlockTypeHint(
const AString & aBlockTypeName,
const AString & aHintKey
);
void removeBlockTypeHint(const AString & aBlockTypeName, const AString & aHintKey);
private:
private:
/** The actual block type registry.
Maps the BlockTypeName to the BlockInfo instance. */
std::map<AString, std::shared_ptr<BlockInfo>> m_Registry;
@ -154,15 +143,15 @@ private:
/** The exception thrown from BlockTypeRegistry::registerBlockType() if the same block type is being registered from a different plugin. */
class BlockTypeRegistry::AlreadyRegisteredException: public std::runtime_error
/** The exception thrown from BlockTypeRegistry::registerBlockType() if the same block type is being registered from a
* different plugin. */
class BlockTypeRegistry::AlreadyRegisteredException : public std::runtime_error
{
using Super = std::runtime_error;
public:
/** Creates a new instance of the exception that provides info on both the original registration and the newly attempted
registration that caused the failure. */
public:
/** Creates a new instance of the exception that provides info on both the original registration and the newly
attempted registration that caused the failure. */
AlreadyRegisteredException(
const std::shared_ptr<BlockInfo> & aPreviousRegistration,
const std::shared_ptr<BlockInfo> & aNewRegistration
@ -170,11 +159,10 @@ public:
// Simple getters:
std::shared_ptr<BlockInfo> previousRegistration() const { return m_PreviousRegistration; }
std::shared_ptr<BlockInfo> newRegistration() const { return m_NewRegistration; }
std::shared_ptr<BlockInfo> newRegistration() const { return m_NewRegistration; }
private:
private:
std::shared_ptr<BlockInfo> m_PreviousRegistration;
std::shared_ptr<BlockInfo> m_NewRegistration;
@ -192,25 +180,19 @@ private:
/** The exception thrown from BlockTypeRegistry::setBlockTypeHint() if the block type has not been registered before. */
class BlockTypeRegistry::NotRegisteredException: public std::runtime_error
class BlockTypeRegistry::NotRegisteredException : public std::runtime_error
{
using Super = std::runtime_error;
public:
/** Creates a new instance of the exception that provides info on both the original registration and the newly attempted
registration that caused the failure. */
NotRegisteredException(
const AString & aBlockTypeName,
const AString & aHintKey,
const AString & aHintValue
);
public:
/** Creates a new instance of the exception that provides info on both the original registration and the newly
attempted registration that caused the failure. */
NotRegisteredException(const AString & aBlockTypeName, const AString & aHintKey, const AString & aHintValue);
// Simple getters:
const AString & blockTypeName() const { return m_BlockTypeName; }
private:
private:
const AString m_BlockTypeName;
};

View File

@ -4,8 +4,8 @@
#include "DeprecatedBindings.h"
extern "C"
{
#include "lua/src/lua.h"
#include "lua/src/lauxlib.h"
#include "lua/src/lua.h"
#include "lua/src/lauxlib.h"
}
#undef TOLUA_TEMPLATE_BIND
#include "tolua++/include/tolua++.h"
@ -23,12 +23,12 @@ extern "C"
/* get function: g_BlockLightValue */
#ifndef TOLUA_DISABLE_tolua_get_AllToLua_g_BlockLightValue
static int tolua_get_AllToLua_g_BlockLightValue(lua_State* tolua_S)
static int tolua_get_AllToLua_g_BlockLightValue(lua_State * tolua_S)
{
cLuaState LuaState(tolua_S);
int BlockType = 0;
#ifndef TOLUA_RELEASE
#ifndef TOLUA_RELEASE
{
tolua_Error tolua_err;
if (!tolua_isnumber(tolua_S, 2, 0, &tolua_err))
@ -36,7 +36,7 @@ static int tolua_get_AllToLua_g_BlockLightValue(lua_State* tolua_S)
tolua_error(tolua_S, "#vinvalid type in array indexing.", &tolua_err);
}
}
#endif
#endif
LuaState.GetStackValue(2, BlockType);
if ((BlockType < 0) || (BlockType > E_BLOCK_MAX_TYPE_ID))
{
@ -53,12 +53,12 @@ static int tolua_get_AllToLua_g_BlockLightValue(lua_State* tolua_S)
/* get function: g_BlockSpreadLightFalloff */
#ifndef TOLUA_DISABLE_tolua_get_AllToLua_g_BlockSpreadLightFalloff
static int tolua_get_AllToLua_g_BlockSpreadLightFalloff(lua_State* tolua_S)
static int tolua_get_AllToLua_g_BlockSpreadLightFalloff(lua_State * tolua_S)
{
cLuaState LuaState(tolua_S);
int BlockType = 0;
#ifndef TOLUA_RELEASE
#ifndef TOLUA_RELEASE
{
tolua_Error tolua_err;
if (!tolua_isnumber(tolua_S, 2, 0, &tolua_err))
@ -66,7 +66,7 @@ static int tolua_get_AllToLua_g_BlockSpreadLightFalloff(lua_State* tolua_S)
tolua_error(tolua_S, "#vinvalid type in array indexing.", &tolua_err);
}
}
#endif
#endif
LuaState.GetStackValue(2, BlockType);
if ((BlockType < 0) || (BlockType > E_BLOCK_MAX_TYPE_ID))
{
@ -83,12 +83,12 @@ static int tolua_get_AllToLua_g_BlockSpreadLightFalloff(lua_State* tolua_S)
/* get function: g_BlockTransparent */
#ifndef TOLUA_DISABLE_tolua_get_AllToLua_g_BlockTransparent
static int tolua_get_AllToLua_g_BlockTransparent(lua_State* tolua_S)
static int tolua_get_AllToLua_g_BlockTransparent(lua_State * tolua_S)
{
cLuaState LuaState(tolua_S);
int BlockType = 0;
#ifndef TOLUA_RELEASE
#ifndef TOLUA_RELEASE
{
tolua_Error tolua_err;
if (!tolua_isnumber(tolua_S, 2, 0, &tolua_err))
@ -96,7 +96,7 @@ static int tolua_get_AllToLua_g_BlockTransparent(lua_State* tolua_S)
tolua_error(tolua_S, "#vinvalid type in array indexing.", &tolua_err);
}
}
#endif
#endif
LuaState.GetStackValue(2, BlockType);
if ((BlockType < 0) || (BlockType > E_BLOCK_MAX_TYPE_ID))
{
@ -113,12 +113,12 @@ static int tolua_get_AllToLua_g_BlockTransparent(lua_State* tolua_S)
/* get function: g_BlockOneHitDig */
#ifndef TOLUA_DISABLE_tolua_get_AllToLua_g_BlockOneHitDig
static int tolua_get_AllToLua_g_BlockOneHitDig(lua_State* tolua_S)
static int tolua_get_AllToLua_g_BlockOneHitDig(lua_State * tolua_S)
{
cLuaState LuaState(tolua_S);
int BlockType = 0;
#ifndef TOLUA_RELEASE
#ifndef TOLUA_RELEASE
{
tolua_Error tolua_err;
if (!tolua_isnumber(tolua_S, 2, 0, &tolua_err))
@ -126,7 +126,7 @@ static int tolua_get_AllToLua_g_BlockOneHitDig(lua_State* tolua_S)
tolua_error(tolua_S, "#vinvalid type in array indexing.", &tolua_err);
}
}
#endif
#endif
LuaState.GetStackValue(2, BlockType);
if ((BlockType < 0) || (BlockType > E_BLOCK_MAX_TYPE_ID))
{
@ -143,12 +143,12 @@ static int tolua_get_AllToLua_g_BlockOneHitDig(lua_State* tolua_S)
/* get function: g_BlockPistonBreakable */
#ifndef TOLUA_DISABLE_tolua_get_AllToLua_g_BlockPistonBreakable
static int tolua_get_AllToLua_g_BlockPistonBreakable(lua_State* tolua_S)
static int tolua_get_AllToLua_g_BlockPistonBreakable(lua_State * tolua_S)
{
cLuaState LuaState(tolua_S);
int BlockType = 0;
#ifndef TOLUA_RELEASE
#ifndef TOLUA_RELEASE
{
tolua_Error tolua_err;
if (!tolua_isnumber(tolua_S, 2, 0, &tolua_err))
@ -156,7 +156,7 @@ static int tolua_get_AllToLua_g_BlockPistonBreakable(lua_State* tolua_S)
tolua_error(tolua_S, "#vinvalid type in array indexing.", &tolua_err);
}
}
#endif
#endif
LuaState.GetStackValue(2, BlockType);
if ((BlockType < 0) || (BlockType > E_BLOCK_MAX_TYPE_ID))
{
@ -173,12 +173,12 @@ static int tolua_get_AllToLua_g_BlockPistonBreakable(lua_State* tolua_S)
/* get function: g_BlockIsSnowable */
#ifndef TOLUA_DISABLE_tolua_get_AllToLua_g_BlockIsSnowable
static int tolua_get_AllToLua_g_BlockIsSnowable(lua_State* tolua_S)
static int tolua_get_AllToLua_g_BlockIsSnowable(lua_State * tolua_S)
{
cLuaState LuaState(tolua_S);
int BlockType = 0;
#ifndef TOLUA_RELEASE
#ifndef TOLUA_RELEASE
{
tolua_Error tolua_err;
if (!tolua_isnumber(tolua_S, 2, 0, &tolua_err))
@ -186,7 +186,7 @@ static int tolua_get_AllToLua_g_BlockIsSnowable(lua_State* tolua_S)
tolua_error(tolua_S, "#vinvalid type in array indexing.", &tolua_err);
}
}
#endif
#endif
LuaState.GetStackValue(2, BlockType);
if ((BlockType < 0) || (BlockType > E_BLOCK_MAX_TYPE_ID))
{
@ -203,12 +203,12 @@ static int tolua_get_AllToLua_g_BlockIsSnowable(lua_State* tolua_S)
/* get function: g_BlockIsSolid */
#ifndef TOLUA_DISABLE_tolua_get_AllToLua_g_BlockIsSolid
static int tolua_get_AllToLua_g_BlockIsSolid(lua_State* tolua_S)
static int tolua_get_AllToLua_g_BlockIsSolid(lua_State * tolua_S)
{
cLuaState LuaState(tolua_S);
int BlockType = 0;
#ifndef TOLUA_RELEASE
#ifndef TOLUA_RELEASE
{
tolua_Error tolua_err;
if (!tolua_isnumber(tolua_S, 2, 0, &tolua_err))
@ -216,7 +216,7 @@ static int tolua_get_AllToLua_g_BlockIsSolid(lua_State* tolua_S)
tolua_error(tolua_S, "#vinvalid type in array indexing.", &tolua_err);
}
}
#endif
#endif
LuaState.GetStackValue(2, BlockType);
if ((BlockType < 0) || (BlockType > E_BLOCK_MAX_TYPE_ID))
{
@ -233,12 +233,12 @@ static int tolua_get_AllToLua_g_BlockIsSolid(lua_State* tolua_S)
/* get function: g_BlockFullyOccupiesVoxel */
#ifndef TOLUA_DISABLE_tolua_get_AllToLua_g_BlockFullyOccupiesVoxel
static int tolua_get_AllToLua_g_BlockFullyOccupiesVoxel(lua_State* tolua_S)
static int tolua_get_AllToLua_g_BlockFullyOccupiesVoxel(lua_State * tolua_S)
{
cLuaState LuaState(tolua_S);
int BlockType = 0;
#ifndef TOLUA_RELEASE
#ifndef TOLUA_RELEASE
{
tolua_Error tolua_err;
if (!tolua_isnumber(tolua_S, 2, 0, &tolua_err))
@ -246,7 +246,7 @@ static int tolua_get_AllToLua_g_BlockFullyOccupiesVoxel(lua_State* tolua_S)
tolua_error(tolua_S, "#vinvalid type in array indexing.", &tolua_err);
}
}
#endif
#endif
LuaState.GetStackValue(2, BlockType);
if ((BlockType < 0) || (BlockType > E_BLOCK_MAX_TYPE_ID))
{
@ -262,19 +262,16 @@ static int tolua_get_AllToLua_g_BlockFullyOccupiesVoxel(lua_State* tolua_S)
/* function: StringToMobType */
static int tolua_AllToLua_StringToMobType00(lua_State* tolua_S)
static int tolua_AllToLua_StringToMobType00(lua_State * tolua_S)
{
cLuaState LuaState(tolua_S);
#ifndef TOLUA_RELEASE
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_iscppstring(tolua_S, 1, 0, &tolua_err) ||
!tolua_isnoobj(tolua_S, 2, &tolua_err)
)
if (!tolua_iscppstring(tolua_S, 1, 0, &tolua_err) || !tolua_isnoobj(tolua_S, 2, &tolua_err))
goto tolua_lerror;
else
#endif
#endif
{
const AString a_MobString = tolua_tocppstring(LuaState, 1, nullptr);
eMonsterType MobType = cMonster::StringToMobType(a_MobString);
@ -282,15 +279,16 @@ static int tolua_AllToLua_StringToMobType00(lua_State* tolua_S)
tolua_pushcppstring(LuaState, a_MobString);
}
LOGWARNING("Warning in function call 'StringToMobType': StringToMobType() is deprecated. Please use cMonster:StringToMobType()");
LOGWARNING("Warning in function call 'StringToMobType': StringToMobType() is deprecated. Please use "
"cMonster:StringToMobType()");
LuaState.LogStackTrace(0);
return 2;
#ifndef TOLUA_RELEASE
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(LuaState, "#ferror in function 'StringToMobType'.", &tolua_err);
return 0;
#endif
#endif
}
@ -300,10 +298,7 @@ tolua_lerror:
static int tolua_cBlockInfo_GetPlaceSound(lua_State * tolua_S)
{
cLuaState L(tolua_S);
if (
!L.CheckParamStaticSelf("cBlockInfo") ||
!L.CheckParamNumber(2)
)
if (!L.CheckParamStaticSelf("cBlockInfo") || !L.CheckParamNumber(2))
{
return 0;
}
@ -347,10 +342,7 @@ static int tolua_set_cItem_m_Lore(lua_State * tolua_S)
{
// Maintain legacy m_Lore variable as Lore table split by ` (grave-accent)
cLuaState L(tolua_S);
if (
!L.CheckParamSelf("cItem") ||
!L.CheckParamString(2)
)
if (!L.CheckParamSelf("cItem") || !L.CheckParamString(2))
{
return 0;
}
@ -374,10 +366,7 @@ static int tolua_cNoteEntity_GetPitch(lua_State * tolua_S)
{
cLuaState LuaState(tolua_S);
if (
!LuaState.CheckParamUserType(1, "cNoteEntity") ||
!LuaState.CheckParamEnd(2)
)
if (!LuaState.CheckParamUserType(1, "cNoteEntity") || !LuaState.CheckParamEnd(2))
{
return 0;
}
@ -406,10 +395,7 @@ static int tolua_cNoteEntity_IncrementPitch(lua_State * tolua_S)
{
cLuaState LuaState(tolua_S);
if (
!LuaState.CheckParamUserType(1, "cNoteEntity") ||
!LuaState.CheckParamEnd(2)
)
if (!LuaState.CheckParamUserType(1, "cNoteEntity") || !LuaState.CheckParamEnd(2))
{
return 0;
}
@ -426,7 +412,9 @@ static int tolua_cNoteEntity_IncrementPitch(lua_State * tolua_S)
}
Self->IncrementNote();
LOGWARNING("Warning: 'cNoteEntity:IncrementPitch' function is deprecated. Please use 'cNoteEntity:IncrementNote' instead.");
LOGWARNING(
"Warning: 'cNoteEntity:IncrementPitch' function is deprecated. Please use 'cNoteEntity:IncrementNote' instead."
);
LuaState.LogStackTrace(0);
return 1;
}
@ -439,11 +427,7 @@ static int tolua_cNoteEntity_SetPitch(lua_State * tolua_S)
{
cLuaState LuaState(tolua_S);
if (
!LuaState.CheckParamUserType(1, "cNoteEntity") ||
!LuaState.CheckParamNumber(2) ||
!LuaState.CheckParamEnd(3)
)
if (!LuaState.CheckParamUserType(1, "cNoteEntity") || !LuaState.CheckParamNumber(2) || !LuaState.CheckParamEnd(3))
{
return 0;
}
@ -474,17 +458,12 @@ static int tolua_cWorld_SetSignLines(lua_State * tolua_S)
{
cLuaState LuaState(tolua_S);
#ifndef TOLUA_RELEASE
if (
!LuaState.CheckParamUserType(1, "cWorld") ||
!LuaState.CheckParamNumber(2, 4) ||
!LuaState.CheckParamString(5, 8) ||
!LuaState.CheckParamUserType(9, "cPlayer") ||
!LuaState.CheckParamEnd(10)
)
#ifndef TOLUA_RELEASE
if (!LuaState.CheckParamUserType(1, "cWorld") || !LuaState.CheckParamNumber(2, 4) ||
!LuaState.CheckParamString(5, 8) || !LuaState.CheckParamUserType(9, "cPlayer") || !LuaState.CheckParamEnd(10))
return 0;
else
#endif
#endif
{
cWorld * self = nullptr;
cPlayer * Player = nullptr;
@ -498,12 +477,12 @@ static int tolua_cWorld_SetSignLines(lua_State * tolua_S)
LuaState.GetStackValues(1, self, BlockX, BlockY, BlockZ, Line1, Line2, Line3, Line4, Player);
#ifndef TOLUA_RELEASE
#ifndef TOLUA_RELEASE
if (self == nullptr)
{
tolua_error(LuaState, "invalid 'self' in function 'UpdateSign'", nullptr);
}
#endif
#endif
{
bool res = self->SetSignLines({BlockX, BlockY, BlockZ}, Line1, Line2, Line3, Line4, Player);
tolua_pushboolean(LuaState, res ? 1 : 0);
@ -527,7 +506,8 @@ static int tolua_cWorld_GrowTree(lua_State * a_LuaState)
if (lua_isnumber(LuaState, 2))
{
// This is the obsolete signature, warn and translate:
LOGWARNING("Warning: cWorld:GrowTree function expects Vector3i-based coords rather than int-based coords. Emulating old-style call.");
LOGWARNING("Warning: cWorld:GrowTree function expects Vector3i-based coords rather than int-based coords. "
"Emulating old-style call.");
LuaState.LogStackTrace(0);
cWorld * Self = nullptr;
int BlockX, BlockY, BlockZ;
@ -563,7 +543,8 @@ static int tolua_cWorld_GrowTreeByBiome(lua_State * a_LuaState)
if (lua_isnumber(LuaState, 2))
{
// This is the obsolete signature, warn and translate:
LOGWARNING("Warning: cWorld:GrowTreeByBiome function expects Vector3i-based coords rather than int-based coords. Emulating old-style call.");
LOGWARNING("Warning: cWorld:GrowTreeByBiome function expects Vector3i-based coords rather than int-based "
"coords. Emulating old-style call.");
LuaState.LogStackTrace(0);
cWorld * Self = nullptr;
int BlockX, BlockY, BlockZ;
@ -599,7 +580,8 @@ static int tolua_cWorld_GrowTreeFromSapling(lua_State * a_LuaState)
if (lua_isnumber(LuaState, 2))
{
// This is the obsolete signature, warn and translate:
LOGWARNING("Warning: cWorld:GrowTreeFromSapling function expects Vector3i-based coords rather than int-based coords. Emulating old-style call.");
LOGWARNING("Warning: cWorld:GrowTreeFromSapling function expects Vector3i-based coords rather than int-based "
"coords. Emulating old-style call.");
LuaState.LogStackTrace(0);
cWorld * Self = nullptr;
int BlockX, BlockY, BlockZ;
@ -621,7 +603,9 @@ static int tolua_cWorld_GrowTreeFromSapling(lua_State * a_LuaState)
if (lua_isnumber(LuaState, 3))
{
// There's an extra parameter, the obsolete SaplingMeta
LOGWARNING("Warning: cWorld:GrowTreeFromSapling function no longer has the SaplingMeta parameter. Ignoring it now.");
LOGWARNING(
"Warning: cWorld:GrowTreeFromSapling function no longer has the SaplingMeta parameter. Ignoring it now."
);
LuaState.LogStackTrace(0);
}
LuaState.Push(Self->GrowTreeFromSapling(BlockPos));
@ -637,11 +621,7 @@ static int tolua_cWorld_SetNextBlockTick(lua_State * tolua_S)
{
cLuaState LuaState(tolua_S);
if (
!LuaState.CheckParamUserType(1, "cWorld") ||
!LuaState.CheckParamNumber(2, 4) ||
!LuaState.CheckParamEnd(5)
)
if (!LuaState.CheckParamUserType(1, "cWorld") || !LuaState.CheckParamNumber(2, 4) || !LuaState.CheckParamEnd(5))
{
return 0;
}
@ -660,7 +640,9 @@ static int tolua_cWorld_SetNextBlockTick(lua_State * tolua_S)
tolua_error(LuaState, "invalid 'self' in function 'SetNextBlockTick'", nullptr);
}
Self->SetNextBlockToTick({BlockX, BlockY, BlockZ});
LOGWARNING("Warning: 'cWorld:SetNextBlockTick' function is deprecated. Please use 'cWorld:SetNextBlockToTick' instead.");
LOGWARNING(
"Warning: 'cWorld:SetNextBlockTick' function is deprecated. Please use 'cWorld:SetNextBlockToTick' instead."
);
LuaState.LogStackTrace(0);
return 1;
}
@ -673,42 +655,38 @@ void DeprecatedBindings::Bind(lua_State * tolua_S)
{
tolua_beginmodule(tolua_S, nullptr);
tolua_array(tolua_S, "g_BlockLightValue", tolua_get_AllToLua_g_BlockLightValue, nullptr);
tolua_array(tolua_S, "g_BlockSpreadLightFalloff", tolua_get_AllToLua_g_BlockSpreadLightFalloff, nullptr);
tolua_array(tolua_S, "g_BlockTransparent", tolua_get_AllToLua_g_BlockTransparent, nullptr);
tolua_array(tolua_S, "g_BlockOneHitDig", tolua_get_AllToLua_g_BlockOneHitDig, nullptr);
tolua_array(tolua_S, "g_BlockPistonBreakable", tolua_get_AllToLua_g_BlockPistonBreakable, nullptr);
tolua_array(tolua_S, "g_BlockIsSnowable", tolua_get_AllToLua_g_BlockIsSnowable, nullptr);
tolua_array(tolua_S, "g_BlockIsSolid", tolua_get_AllToLua_g_BlockIsSolid, nullptr);
tolua_array(tolua_S, "g_BlockFullyOccupiesVoxel", tolua_get_AllToLua_g_BlockFullyOccupiesVoxel, nullptr);
tolua_array(tolua_S, "g_BlockLightValue", tolua_get_AllToLua_g_BlockLightValue, nullptr);
tolua_array(tolua_S, "g_BlockSpreadLightFalloff", tolua_get_AllToLua_g_BlockSpreadLightFalloff, nullptr);
tolua_array(tolua_S, "g_BlockTransparent", tolua_get_AllToLua_g_BlockTransparent, nullptr);
tolua_array(tolua_S, "g_BlockOneHitDig", tolua_get_AllToLua_g_BlockOneHitDig, nullptr);
tolua_array(tolua_S, "g_BlockPistonBreakable", tolua_get_AllToLua_g_BlockPistonBreakable, nullptr);
tolua_array(tolua_S, "g_BlockIsSnowable", tolua_get_AllToLua_g_BlockIsSnowable, nullptr);
tolua_array(tolua_S, "g_BlockIsSolid", tolua_get_AllToLua_g_BlockIsSolid, nullptr);
tolua_array(tolua_S, "g_BlockFullyOccupiesVoxel", tolua_get_AllToLua_g_BlockFullyOccupiesVoxel, nullptr);
tolua_function(tolua_S, "StringToMobType", tolua_AllToLua_StringToMobType00);
tolua_beginmodule(tolua_S, "cBlockInfo");
tolua_function(tolua_S, "GetPlaceSound", tolua_cBlockInfo_GetPlaceSound);
tolua_function(tolua_S, "GetPlaceSound", tolua_cBlockInfo_GetPlaceSound);
tolua_endmodule(tolua_S);
tolua_beginmodule(tolua_S, "cItem");
tolua_variable(tolua_S, "m_Lore", tolua_get_cItem_m_Lore, tolua_set_cItem_m_Lore);
tolua_variable(tolua_S, "m_Lore", tolua_get_cItem_m_Lore, tolua_set_cItem_m_Lore);
tolua_endmodule(tolua_S);
tolua_beginmodule(tolua_S, "cNoteEntity");
tolua_function(tolua_S, "GetPitch", tolua_cNoteEntity_GetPitch);
tolua_function(tolua_S, "IncrementPitch", tolua_cNoteEntity_IncrementPitch);
tolua_function(tolua_S, "SetPitch", tolua_cNoteEntity_SetPitch);
tolua_function(tolua_S, "GetPitch", tolua_cNoteEntity_GetPitch);
tolua_function(tolua_S, "IncrementPitch", tolua_cNoteEntity_IncrementPitch);
tolua_function(tolua_S, "SetPitch", tolua_cNoteEntity_SetPitch);
tolua_endmodule(tolua_S);
tolua_beginmodule(tolua_S, "cWorld");
tolua_function(tolua_S, "GrowTree", tolua_cWorld_GrowTree);
tolua_function(tolua_S, "GrowTreeByBiome", tolua_cWorld_GrowTreeByBiome);
tolua_function(tolua_S, "GrowTreeFromSapling", tolua_cWorld_GrowTreeFromSapling);
tolua_function(tolua_S, "SetNextBlockTick", tolua_cWorld_SetNextBlockTick);
tolua_function(tolua_S, "UpdateSign", tolua_cWorld_SetSignLines);
tolua_function(tolua_S, "GrowTree", tolua_cWorld_GrowTree);
tolua_function(tolua_S, "GrowTreeByBiome", tolua_cWorld_GrowTreeByBiome);
tolua_function(tolua_S, "GrowTreeFromSapling", tolua_cWorld_GrowTreeFromSapling);
tolua_function(tolua_S, "SetNextBlockTick", tolua_cWorld_SetNextBlockTick);
tolua_function(tolua_S, "UpdateSign", tolua_cWorld_SetSignLines);
tolua_endmodule(tolua_S);
tolua_endmodule(tolua_S);
}

View File

@ -3,6 +3,6 @@
struct lua_State;
class DeprecatedBindings
{
public:
static void Bind( lua_State* tolua_S);
public:
static void Bind(lua_State * tolua_S);
};

View File

@ -11,9 +11,7 @@
cLuaChunkStay::cLuaChunkStay()
{
}
cLuaChunkStay::cLuaChunkStay() {}
@ -25,12 +23,16 @@ bool cLuaChunkStay::AddChunks(const cLuaState::cStackTable & a_ChunkCoordsTable)
ASSERT(m_Chunks.empty());
// Add each set of coords:
a_ChunkCoordsTable.ForEachArrayElement([=](cLuaState & a_LuaState, int a_Index)
a_ChunkCoordsTable.ForEachArrayElement(
[=](cLuaState & a_LuaState, int a_Index)
{
if (!lua_istable(a_LuaState, -1))
{
LOGWARNING("%s: Element #%d is not a table (got %s). Ignoring the element.",
__FUNCTION__, a_Index, lua_typename(a_LuaState, -1)
LOGWARNING(
"%s: Element #%d is not a table (got %s). Ignoring the element.",
__FUNCTION__,
a_Index,
lua_typename(a_LuaState, -1)
);
a_LuaState.LogStackTrace();
lua_pop(a_LuaState, 1);
@ -63,8 +65,11 @@ void cLuaChunkStay::AddChunkCoord(cLuaState & L, int a_Index)
int NumCoords = luaL_getn(L, -1);
if (NumCoords != 2)
{
LOGWARNING("%s: Element #%d doesn't contain 2 coords (got %d). Ignoring the element.",
__FUNCTION__, a_Index, NumCoords
LOGWARNING(
"%s: Element #%d doesn't contain 2 coords (got %d). Ignoring the element.",
__FUNCTION__,
a_Index,
NumCoords
);
return;
}
@ -81,9 +86,7 @@ void cLuaChunkStay::AddChunkCoord(cLuaState & L, int a_Index)
{
if ((itr->m_ChunkX == ChunkX) && (itr->m_ChunkZ == ChunkZ))
{
LOGWARNING("%s: Element #%d is a duplicate, ignoring it.",
__FUNCTION__, a_Index
);
LOGWARNING("%s: Element #%d is a duplicate, ignoring it.", __FUNCTION__, a_Index);
return;
}
} // for itr - m_Chunks[]
@ -95,7 +98,11 @@ void cLuaChunkStay::AddChunkCoord(cLuaState & L, int a_Index)
void cLuaChunkStay::Enable(cChunkMap & a_ChunkMap, cLuaState::cCallbackPtr a_OnChunkAvailable, cLuaState::cCallbackPtr a_OnAllChunksAvailable)
void cLuaChunkStay::Enable(
cChunkMap & a_ChunkMap,
cLuaState::cCallbackPtr a_OnChunkAvailable,
cLuaState::cCallbackPtr a_OnAllChunksAvailable
)
{
m_OnChunkAvailable = std::move(a_OnChunkAvailable);
m_OnAllChunksAvailable = std::move(a_OnAllChunksAvailable);
@ -145,7 +152,3 @@ void cLuaChunkStay::OnDisabled(void)
// This object is no longer needed, delete it
delete this;
}

View File

@ -23,15 +23,14 @@ class cChunkMap;
class cLuaChunkStay:
public cChunkStay
class cLuaChunkStay : public cChunkStay
{
using Super = cChunkStay;
public:
public:
cLuaChunkStay();
virtual ~cLuaChunkStay() override { }
virtual ~cLuaChunkStay() override {}
/** Adds chunks in the specified Lua table.
Can be called only once.
@ -39,9 +38,13 @@ public:
bool AddChunks(const cLuaState::cStackTable & a_ChunkCoords);
/** Enables the ChunkStay for the specified chunkmap, with the specified Lua callbacks. */
void Enable(cChunkMap & a_ChunkMap, cLuaState::cCallbackPtr a_OnChunkAvailable, cLuaState::cCallbackPtr a_OnAllChunksAvailable);
void Enable(
cChunkMap & a_ChunkMap,
cLuaState::cCallbackPtr a_OnChunkAvailable,
cLuaState::cCallbackPtr a_OnAllChunksAvailable
);
protected:
protected:
/** The Lua function to call in OnChunkAvailable. Only valid when enabled. */
cLuaState::cCallbackPtr m_OnChunkAvailable;
@ -60,9 +63,4 @@ protected:
If the coords are already present, gives a warning and ignores the pair.
The a_Index parameter is only for the error messages. */
void AddChunkCoord(cLuaState & a_LuaState, int a_Index);
} ;
};

View File

@ -26,37 +26,35 @@ static Json::Value JsonSerializeValue(cLuaState & a_LuaState);
/** Exception thrown when the input cannot be serialized.
Keeps track of the error message and the problematic value's path in the table.
*/
class CannotSerializeException:
public std::runtime_error
class CannotSerializeException : public std::runtime_error
{
using Super = std::runtime_error;
public:
public:
/** Constructs a new instance of the exception based on the provided values directly. */
explicit CannotSerializeException(const AString & a_ValueName, const char * a_ErrorMsg):
Super(a_ErrorMsg),
m_ValueName(a_ValueName)
explicit CannotSerializeException(const AString & a_ValueName, const char * a_ErrorMsg) :
Super(a_ErrorMsg), m_ValueName(a_ValueName)
{
}
/** Constructs a new instance of the exception based on the provided values directly. */
explicit CannotSerializeException(int a_ValueIndex, const char * a_ErrorMsg):
Super(a_ErrorMsg),
m_ValueName(fmt::format(FMT_STRING("{}"), a_ValueIndex))
explicit CannotSerializeException(int a_ValueIndex, const char * a_ErrorMsg) :
Super(a_ErrorMsg), m_ValueName(fmt::format(FMT_STRING("{}"), a_ValueIndex))
{
}
/** Constructs a new instance of the exception that takes the error message and value name from the parent, and prefix the value name with the specified prefix.
Used for prefixing the value name's path along the call stack that lead to the main exception. */
explicit CannotSerializeException(const CannotSerializeException & a_Parent, const AString & a_ValueNamePrefix):
Super(a_Parent.what()),
m_ValueName(a_ValueNamePrefix + "." + a_Parent.m_ValueName)
/** Constructs a new instance of the exception that takes the error message and value name from the parent, and
prefix the value name with the specified prefix. Used for prefixing the value name's path along the call stack that
lead to the main exception. */
explicit CannotSerializeException(const CannotSerializeException & a_Parent, const AString & a_ValueNamePrefix) :
Super(a_Parent.what()), m_ValueName(a_ValueNamePrefix + "." + a_Parent.m_ValueName)
{
}
/** Constructs a new instance of the exception that takes the error message and value name from the parent, and prefix the value name with the specified prefix.
Used for prefixing the value name's path along the call stack that lead to the main exception. */
explicit CannotSerializeException(const CannotSerializeException & a_Parent, int a_ValueNamePrefixIndex):
/** Constructs a new instance of the exception that takes the error message and value name from the parent, and
prefix the value name with the specified prefix. Used for prefixing the value name's path along the call stack that
lead to the main exception. */
explicit CannotSerializeException(const CannotSerializeException & a_Parent, int a_ValueNamePrefixIndex) :
Super(a_Parent.what()),
m_ValueName(fmt::format(FMT_STRING("{}"), a_ValueNamePrefixIndex) + "." + a_Parent.m_ValueName)
{
@ -64,7 +62,7 @@ public:
const AString & GetValueName() const { return m_ValueName; }
protected:
protected:
AString m_ValueName;
};
@ -81,7 +79,7 @@ static void PushJsonArray(const Json::Value & a_Value, cLuaState & a_LuaState)
// Insert each value to the appropriate index (1-based):
int idx = 1;
for (const auto & v: a_Value)
for (const auto & v : a_Value)
{
// Include Json null values in the array - it will have holes, but indices will stay the same
PushJsonValue(v, a_LuaState);
@ -104,7 +102,7 @@ static void PushJsonObject(const Json::Value & a_Value, cLuaState & a_LuaState)
// Json::Value has no means of iterating over children with their names included.
// We need to iterate over names and "find" them in the object again:
auto names = a_Value.getMemberNames();
for (const auto & n: names)
for (const auto & n : names)
{
auto v = a_Value[n];
if (v.isNull())
@ -276,11 +274,7 @@ static int tolua_cJson_Parse(lua_State * a_LuaState)
// Check the param types:
cLuaState L(a_LuaState);
if (
!L.CheckParamUserTable(1, "cJson") ||
!L.CheckParamString(2) ||
!L.CheckParamEnd(3)
)
if (!L.CheckParamUserTable(1, "cJson") || !L.CheckParamString(2) || !L.CheckParamEnd(3))
{
return 0;
}
@ -319,11 +313,7 @@ static int tolua_cJson_Serialize(lua_State * a_LuaState)
// Check the param types:
cLuaState L(a_LuaState);
if (
!L.CheckParamUserTable(1, "cJson") ||
!L.CheckParamTable(2) ||
!L.CheckParamEnd(4)
)
if (!L.CheckParamUserTable(1, "cJson") || !L.CheckParamTable(2) || !L.CheckParamEnd(4))
{
return 0;
}
@ -340,7 +330,8 @@ static int tolua_cJson_Serialize(lua_State * a_LuaState)
lua_pushnil(L);
L.Push(fmt::format(
FMT_STRING("Cannot serialize into Json, value \"{}\" caused an error \"{}\""),
exc.GetValueName(), exc.what()
exc.GetValueName(),
exc.what()
));
return 2;
}
@ -368,7 +359,7 @@ static int tolua_cJson_Serialize(lua_State * a_LuaState)
if (!builder.validate(&invalid))
{
LOGINFO("cJson:Serialize(): detected invalid settings:");
for (const auto & n: invalid.getMemberNames())
for (const auto & n : invalid.getMemberNames())
{
LOGINFO(" \"%s\" (\"%s\")", n.c_str(), invalid[n].asCString());
}
@ -391,18 +382,14 @@ void cLuaJson::Bind(cLuaState & a_LuaState)
{
tolua_beginmodule(a_LuaState, nullptr);
// Create the cJson API class:
tolua_usertype(a_LuaState, "cJson");
tolua_cclass(a_LuaState, "cJson", "cJson", "", nullptr);
// Create the cJson API class:
tolua_usertype(a_LuaState, "cJson");
tolua_cclass(a_LuaState, "cJson", "cJson", "", nullptr);
// Fill in the functions (alpha-sorted):
tolua_beginmodule(a_LuaState, "cJson");
tolua_function(a_LuaState, "Parse", tolua_cJson_Parse);
tolua_function(a_LuaState, "Serialize", tolua_cJson_Serialize);
tolua_endmodule(a_LuaState);
// Fill in the functions (alpha-sorted):
tolua_beginmodule(a_LuaState, "cJson");
tolua_function(a_LuaState, "Parse", tolua_cJson_Parse);
tolua_function(a_LuaState, "Serialize", tolua_cJson_Serialize);
tolua_endmodule(a_LuaState);
tolua_endmodule(a_LuaState);
}

View File

@ -22,11 +22,7 @@ class cLuaState;
class cLuaJson
{
public:
public:
/** Registers the Json library in the specified Lua state. */
static void Bind(cLuaState & a_LuaState);
};

View File

@ -10,9 +10,8 @@
cLuaNameLookup::cLuaNameLookup(const AString & a_Query, cLuaState::cTableRefPtr && a_Callbacks):
m_Callbacks(std::move(a_Callbacks)),
m_Query(a_Query)
cLuaNameLookup::cLuaNameLookup(const AString & a_Query, cLuaState::cTableRefPtr && a_Callbacks) :
m_Callbacks(std::move(a_Callbacks)), m_Query(a_Query)
{
}
@ -42,7 +41,3 @@ void cLuaNameLookup::OnFinished(void)
{
m_Callbacks->CallTableFn("OnFinished", m_Query);
}

View File

@ -16,15 +16,14 @@
class cLuaNameLookup:
public cNetwork::cResolveNameCallbacks
class cLuaNameLookup : public cNetwork::cResolveNameCallbacks
{
public:
public:
/** Creates a new instance of the lookup callbacks for the specified query,
using the callbacks that are in the specified table. */
cLuaNameLookup(const AString & a_Query, cLuaState::cTableRefPtr && a_Callbacks);
protected:
protected:
/** The Lua table that holds the callbacks to be invoked. */
cLuaState::cTableRefPtr m_Callbacks;
@ -37,7 +36,3 @@ protected:
virtual void OnError(int a_ErrorCode, const AString & a_ErrorMsg) override;
virtual void OnFinished(void) override;
};

View File

@ -12,9 +12,8 @@
cLuaServerHandle::cLuaServerHandle(UInt16 a_Port, cLuaState::cTableRefPtr && a_Callbacks):
m_Callbacks(std::move(a_Callbacks)),
m_Port(a_Port)
cLuaServerHandle::cLuaServerHandle(UInt16 a_Port, cLuaState::cTableRefPtr && a_Callbacks) :
m_Callbacks(std::move(a_Callbacks)), m_Port(a_Port)
{
}
@ -62,7 +61,7 @@ void cLuaServerHandle::Close(void)
cCSLock Lock(m_CSConnections);
std::swap(Connections, m_Connections);
}
for (auto & conn: Connections)
for (auto & conn : Connections)
{
conn->Close();
}
@ -127,10 +126,15 @@ cTCPLink::cCallbacksPtr cLuaServerHandle::OnIncomingConnection(const AString & a
{
// Ask the plugin for link callbacks:
cLuaState::cTableRefPtr LinkCallbacks;
if (
!m_Callbacks->CallTableFn("OnIncomingConnection", a_RemoteIPAddress, a_RemotePort, m_Port, cLuaState::Return, LinkCallbacks) ||
!LinkCallbacks->IsValid()
)
if (!m_Callbacks->CallTableFn(
"OnIncomingConnection",
a_RemoteIPAddress,
a_RemotePort,
m_Port,
cLuaState::Return,
LinkCallbacks
) ||
!LinkCallbacks->IsValid())
{
LOGINFO("cNetwork server (port %d) OnIncomingConnection callback failed. Dropping connection.", m_Port);
return nullptr;
@ -165,8 +169,3 @@ void cLuaServerHandle::OnError(int a_ErrorCode, const AString & a_ErrorMsg)
// Notify the plugin:
m_Callbacks->CallTableFn("OnError", a_ErrorCode, a_ErrorMsg);
}

View File

@ -26,10 +26,9 @@ typedef std::shared_ptr<cLuaServerHandle> cLuaServerHandlePtr;
class cLuaServerHandle:
public cNetwork::cListenCallbacks
class cLuaServerHandle : public cNetwork::cListenCallbacks
{
public:
public:
/** Creates a new instance of the server handle,
wrapping the (listen-) callbacks that are in the specified table. */
cLuaServerHandle(UInt16 a_Port, cLuaState::cTableRefPtr && a_Callbacks);
@ -53,7 +52,7 @@ public:
Releases the internal SharedPtr to self, so that the instance may be deallocated. */
void Release(void);
protected:
protected:
/** The Lua table that holds the callbacks to be invoked. */
cLuaState::cTableRefPtr m_Callbacks;
@ -76,11 +75,8 @@ protected:
// cNetwork::cListenCallbacks overrides:
virtual cTCPLink::cCallbacksPtr OnIncomingConnection(const AString & a_RemoteIPAddress, UInt16 a_RemotePort) override;
virtual cTCPLink::cCallbacksPtr OnIncomingConnection(const AString & a_RemoteIPAddress, UInt16 a_RemotePort)
override;
virtual void OnAccepted(cTCPLink & a_Link) override;
virtual void OnError(int a_ErrorCode, const AString & a_ErrorMsg) override;
};

View File

@ -8,7 +8,7 @@
extern "C"
{
#include "lua/src/lualib.h"
#include "lua/src/lualib.h"
}
#undef TOLUA_TEMPLATE_BIND
@ -27,7 +27,7 @@ extern "C"
// Hotpatching the Macro to prevent a Clang Warning (0 for pointer used)
#undef lua_tostring
#undef lua_tostring
#define lua_tostring(L, i) lua_tolstring(L, (i), nullptr)
@ -58,11 +58,12 @@ const cLuaState::cNil cLuaState::Nil = {};
// cCanonLuaStates:
/** Tracks the canon cLuaState instances for each lua_State pointer.
Used for tracked refs - the ref needs to be tracked by a single cLuaState (the canon state), despite being created from a different (attached) cLuaState.
The canon state must be available without accessing the Lua state itself (so it cannot be stored within Lua). */
Used for tracked refs - the ref needs to be tracked by a single cLuaState (the canon state), despite being created from
a different (attached) cLuaState. The canon state must be available without accessing the Lua state itself (so it cannot
be stored within Lua). */
class cCanonLuaStates
{
public:
public:
/** Returns the canon Lua state for the specified lua_State pointer. */
static cLuaState * GetCanonState(lua_State * a_LuaState)
{
@ -97,7 +98,7 @@ public:
inst.m_CanonStates.erase(itr);
}
protected:
protected:
/** The mutex protecting m_CanonStates against multithreaded access. */
cCriticalSection m_CS;
@ -137,11 +138,9 @@ void cLuaStateTracker::Del(cLuaState & a_LuaState)
cCSLock Lock(Instance.m_CSLuaStates);
Instance.m_LuaStates.erase(
std::remove_if(
Instance.m_LuaStates.begin(), Instance.m_LuaStates.end(),
[&a_LuaState](cLuaStatePtr a_StoredLuaState)
{
return (&a_LuaState == a_StoredLuaState);
}
Instance.m_LuaStates.begin(),
Instance.m_LuaStates.end(),
[&a_LuaState](cLuaStatePtr a_StoredLuaState) { return (&a_LuaState == a_StoredLuaState); }
),
Instance.m_LuaStates.end()
);
@ -157,7 +156,7 @@ AString cLuaStateTracker::GetStats()
cCSLock Lock(Instance.m_CSLuaStates);
AString res;
int Total = 0;
for (auto state: Instance.m_LuaStates)
for (auto state : Instance.m_LuaStates)
{
int Mem = 0;
if (!state->Call("collectgarbage", "count", cLuaState::Return, Mem))
@ -166,7 +165,9 @@ AString cLuaStateTracker::GetStats()
}
else
{
res.append(fmt::format(FMT_STRING("State \"{}\" is using {} KiB of memory\n"), state->GetSubsystemName(), Mem));
res.append(
fmt::format(FMT_STRING("State \"{}\" is using {} KiB of memory\n"), state->GetSubsystemName(), Mem)
);
Total += Mem;
}
}
@ -191,7 +192,7 @@ cLuaStateTracker & cLuaStateTracker::Get()
////////////////////////////////////////////////////////////////////////////////
// cLuaState::cTrackedRef:
cLuaState::cTrackedRef::cTrackedRef(void):
cLuaState::cTrackedRef::cTrackedRef(void) :
m_CS(nullptr)
{
}
@ -300,8 +301,10 @@ void cLuaState::cTrackedRef::Invalidate(void)
cCSLock Lock(*cs);
if (!m_Ref.IsValid())
{
LOGD("%s: Inconsistent callback at %p, has a CS but an invalid Ref. This should not happen",
__FUNCTION__, static_cast<void *>(this)
LOGD(
"%s: Inconsistent callback at %p, has a CS but an invalid Ref. This should not happen",
__FUNCTION__,
static_cast<void *>(this)
);
return;
}
@ -372,9 +375,8 @@ bool cLuaState::cTableRef::RefStack(cLuaState & a_LuaState, int a_StackPos)
////////////////////////////////////////////////////////////////////////////////
// cLuaState::cStackTable:
cLuaState::cStackTable::cStackTable(cLuaState & a_LuaState, int a_StackPos):
m_LuaState(a_LuaState),
m_StackPos(a_StackPos)
cLuaState::cStackTable::cStackTable(cLuaState & a_LuaState, int a_StackPos) :
m_LuaState(a_LuaState), m_StackPos(a_StackPos)
{
ASSERT(lua_istable(a_LuaState, a_StackPos));
}
@ -383,7 +385,9 @@ cLuaState::cStackTable::cStackTable(cLuaState & a_LuaState, int a_StackPos):
void cLuaState::cStackTable::ForEachArrayElement(cFunctionRef<bool(cLuaState & a_LuaState, int a_Index)> a_ElementCallback) const
void cLuaState::cStackTable::ForEachArrayElement(
cFunctionRef<bool(cLuaState & a_LuaState, int a_Index)> a_ElementCallback
) const
{
const auto numElements = luaL_getn(m_LuaState, m_StackPos);
[[maybe_unused]] const auto stackTop = lua_gettop(m_LuaState);
@ -392,7 +396,9 @@ void cLuaState::cStackTable::ForEachArrayElement(cFunctionRef<bool(cLuaState & a
// Push the idx-th element of the array onto stack top and call the callback:
lua_rawgeti(m_LuaState, m_StackPos, idx);
auto shouldAbort = a_ElementCallback(m_LuaState, idx);
ASSERT(lua_gettop(m_LuaState) == stackTop + 1); // The element callback must not change the Lua stack below the value
ASSERT(
lua_gettop(m_LuaState) == stackTop + 1
); // The element callback must not change the Lua stack below the value
lua_pop(m_LuaState, 1);
if (shouldAbort)
{
@ -410,11 +416,13 @@ void cLuaState::cStackTable::ForEachElement(cFunctionRef<bool(cLuaState & a_LuaS
{
[[maybe_unused]] const auto stackTop = lua_gettop(m_LuaState);
lua_pushvalue(m_LuaState, m_StackPos); // Stk: <table>
lua_pushnil(m_LuaState); // Stk: <table> nil
while (lua_next(m_LuaState, -2)) // Stk: <table> <key> <val>
lua_pushnil(m_LuaState); // Stk: <table> nil
while (lua_next(m_LuaState, -2)) // Stk: <table> <key> <val>
{
auto shouldAbort = a_ElementCallback(m_LuaState);
ASSERT(lua_gettop(m_LuaState) == stackTop + 3); // The element callback must not change the Lua stack below the value
ASSERT(
lua_gettop(m_LuaState) == stackTop + 3
); // The element callback must not change the Lua stack below the value
lua_pop(m_LuaState, 1); // Stk: <table> <key>
if (shouldAbort)
{
@ -435,10 +443,7 @@ void cLuaState::cStackTable::ForEachElement(cFunctionRef<bool(cLuaState & a_LuaS
// cLuaState:
cLuaState::cLuaState(const AString & a_SubsystemName) :
m_LuaState(nullptr),
m_IsOwned(false),
m_SubsystemName(a_SubsystemName),
m_NumCurrentFunctionArgs(-1)
m_LuaState(nullptr), m_IsOwned(false), m_SubsystemName(a_SubsystemName), m_NumCurrentFunctionArgs(-1)
{
}
@ -447,10 +452,7 @@ cLuaState::cLuaState(const AString & a_SubsystemName) :
cLuaState::cLuaState(lua_State * a_AttachState) :
m_LuaState(a_AttachState),
m_IsOwned(false),
m_SubsystemName("<attached>"),
m_NumCurrentFunctionArgs(-1)
m_LuaState(a_AttachState), m_IsOwned(false), m_SubsystemName("<attached>"), m_NumCurrentFunctionArgs(-1)
{
}
@ -537,7 +539,8 @@ void cLuaState::Close(void)
{
LOGWARNING(
"%s: Detected mis-use, calling Close() on an attached state (0x%p). Detaching instead.",
__FUNCTION__, static_cast<void *>(m_LuaState)
__FUNCTION__,
static_cast<void *>(m_LuaState)
);
Detach();
return;
@ -546,7 +549,7 @@ void cLuaState::Close(void)
// Invalidate all tracked refs:
{
cCSLock Lock(m_CSTrackedRefs);
for (auto & r: m_TrackedRefs)
for (auto & r : m_TrackedRefs)
{
r->Invalidate();
}
@ -568,7 +571,11 @@ void cLuaState::Attach(lua_State * a_State)
{
if (m_LuaState != nullptr)
{
LOGINFO("%s: Already contains a LuaState (0x%p), will be closed / detached.", __FUNCTION__, static_cast<void *>(m_LuaState));
LOGINFO(
"%s: Already contains a LuaState (0x%p), will be closed / detached.",
__FUNCTION__,
static_cast<void *>(m_LuaState)
);
if (m_IsOwned)
{
Close();
@ -596,7 +603,8 @@ void cLuaState::Detach(void)
{
LOGWARNING(
"%s: Detected a mis-use, calling Detach() when the state is owned. Closing the owned state (0x%p).",
__FUNCTION__, static_cast<void *>(m_LuaState)
__FUNCTION__,
static_cast<void *>(m_LuaState)
);
Close();
return;
@ -613,8 +621,8 @@ void cLuaState::AddPackagePath(const AString & a_PathVariable, const AString & a
ASSERT_LUA_STACK_BALANCE(m_LuaState);
// Get the current path:
lua_getfield(m_LuaState, LUA_GLOBALSINDEX, "package"); // Stk: <package>
lua_getfield(m_LuaState, -1, a_PathVariable.c_str()); // Stk: <package> <package.path>
lua_getfield(m_LuaState, LUA_GLOBALSINDEX, "package"); // Stk: <package>
lua_getfield(m_LuaState, -1, a_PathVariable.c_str()); // Stk: <package> <package.path>
size_t len = 0;
const char * PackagePath = lua_tolstring(m_LuaState, -1, &len);
@ -624,10 +632,10 @@ void cLuaState::AddPackagePath(const AString & a_PathVariable, const AString & a
NewPackagePath.append(a_Path);
// Set the new path to the environment:
lua_pop(m_LuaState, 1); // Stk: <package>
lua_pushlstring(m_LuaState, NewPackagePath.c_str(), NewPackagePath.length()); // Stk: <package> <NewPackagePath>
lua_setfield(m_LuaState, -2, a_PathVariable.c_str()); // Stk: <package>
lua_pop(m_LuaState, 1); // Stk: -
lua_pop(m_LuaState, 1); // Stk: <package>
lua_pushlstring(m_LuaState, NewPackagePath.c_str(), NewPackagePath.length()); // Stk: <package> <NewPackagePath>
lua_setfield(m_LuaState, -2, a_PathVariable.c_str()); // Stk: <package>
lua_pop(m_LuaState, 1); // Stk: -
}
@ -645,7 +653,13 @@ bool cLuaState::LoadFile(const AString & a_FileName, bool a_LogWarnings)
{
if (a_LogWarnings)
{
LOGWARNING("Can't load %s because of a load error in file %s: %d (%s)", m_SubsystemName.c_str(), a_FileName.c_str(), s, lua_tostring(m_LuaState, -1));
LOGWARNING(
"Can't load %s because of a load error in file %s: %d (%s)",
m_SubsystemName.c_str(),
a_FileName.c_str(),
s,
lua_tostring(m_LuaState, -1)
);
}
lua_pop(m_LuaState, 1);
return false;
@ -657,7 +671,13 @@ bool cLuaState::LoadFile(const AString & a_FileName, bool a_LogWarnings)
{
if (a_LogWarnings)
{
LOGWARNING("Can't load %s because of an initialization error in file %s: %d (%s)", m_SubsystemName.c_str(), a_FileName.c_str(), s, lua_tostring(m_LuaState, -1));
LOGWARNING(
"Can't load %s because of an initialization error in file %s: %d (%s)",
m_SubsystemName.c_str(),
a_FileName.c_str(),
s,
lua_tostring(m_LuaState, -1)
);
}
lua_pop(m_LuaState, 1);
return false;
@ -681,7 +701,13 @@ bool cLuaState::LoadString(const AString & a_StringToLoad, const AString & a_Fil
{
if (a_LogWarnings)
{
LOGWARNING("Can't load %s because of a load error in string from \"%s\": %d (%s)", m_SubsystemName.c_str(), a_FileName.c_str(), s, lua_tostring(m_LuaState, -1));
LOGWARNING(
"Can't load %s because of a load error in string from \"%s\": %d (%s)",
m_SubsystemName.c_str(),
a_FileName.c_str(),
s,
lua_tostring(m_LuaState, -1)
);
}
lua_pop(m_LuaState, 1);
return false;
@ -693,7 +719,13 @@ bool cLuaState::LoadString(const AString & a_StringToLoad, const AString & a_Fil
{
if (a_LogWarnings)
{
LOGWARNING("Can't load %s because of an initialization error in string from \"%s\": %d (%s)", m_SubsystemName.c_str(), a_FileName.c_str(), s, lua_tostring(m_LuaState, -1));
LOGWARNING(
"Can't load %s because of an initialization error in string from \"%s\": %d (%s)",
m_SubsystemName.c_str(),
a_FileName.c_str(),
s,
lua_tostring(m_LuaState, -1)
);
}
lua_pop(m_LuaState, 1);
return false;
@ -835,9 +867,9 @@ void cLuaState::Push(const AStringMap & a_Dictionary)
lua_createtable(m_LuaState, 0, static_cast<int>(a_Dictionary.size()));
int newTable = lua_gettop(m_LuaState);
for (const auto & item: a_Dictionary)
for (const auto & item : a_Dictionary)
{
Push(item.first); // key
Push(item.first); // key
Push(item.second); // value
lua_rawset(m_LuaState, newTable);
}
@ -956,7 +988,7 @@ void cLuaState::Push(bool a_Value)
void cLuaState::Push(const cEntity * a_Entity)
{
// Once we can make Lua understand constness, this function shall receive a corresponding function body
Push(const_cast<cEntity * >(a_Entity));
Push(const_cast<cEntity *>(a_Entity));
}
@ -974,41 +1006,41 @@ void cLuaState::Push(cEntity * a_Entity)
else
{
const char * ClassName = [&]
{
switch (a_Entity->GetEntityType())
{
switch (a_Entity->GetEntityType())
case cEntity::etBoat: return "cBoat";
case cEntity::etExpOrb: return "cExpOrb";
case cEntity::etFallingBlock: return "cFallingBlock";
case cEntity::etFloater: return "cFloater";
case cEntity::etItemFrame: return "cItemFrame";
case cEntity::etLeashKnot: return "cLeashKnot";
case cEntity::etPainting: return "cPainting";
case cEntity::etPickup: return "cPickup";
case cEntity::etPlayer: return "cPlayer";
case cEntity::etTNT: return "cTNTEntity";
case cEntity::etMonster:
{
case cEntity::etBoat: return "cBoat";
case cEntity::etExpOrb: return "cExpOrb";
case cEntity::etFallingBlock: return "cFallingBlock";
case cEntity::etFloater: return "cFloater";
case cEntity::etItemFrame: return "cItemFrame";
case cEntity::etLeashKnot: return "cLeashKnot";
case cEntity::etPainting: return "cPainting";
case cEntity::etPickup: return "cPickup";
case cEntity::etPlayer: return "cPlayer";
case cEntity::etTNT: return "cTNTEntity";
// Don't push specific mob types, as those are not exported in the API:
return "cMonster";
}
case cEntity::etProjectile:
{
// Push the specific projectile type:
return a_Entity->GetClass();
}
case cEntity::etMonster:
{
// Don't push specific mob types, as those are not exported in the API:
return "cMonster";
}
case cEntity::etProjectile:
{
// Push the specific projectile type:
return a_Entity->GetClass();
}
case cEntity::etEntity:
case cEntity::etEnderCrystal:
case cEntity::etMinecart:
{
// Push the generic entity class type:
return "cEntity";
}
} // switch (EntityType)
UNREACHABLE("Unsupported entity type");
}();
case cEntity::etEntity:
case cEntity::etEnderCrystal:
case cEntity::etMinecart:
{
// Push the generic entity class type:
return "cEntity";
}
} // switch (EntityType)
UNREACHABLE("Unsupported entity type");
}();
tolua_pushusertype(m_LuaState, a_Entity, ClassName);
}
}
@ -1141,7 +1173,8 @@ bool cLuaState::GetStackValue(int a_StackPos, AStringMap & a_Value)
}
cStackTable tbl(*this, a_StackPos);
bool isValid = true;
tbl.ForEachElement([&isValid, &a_Value](cLuaState & a_LuaState)
tbl.ForEachElement(
[&isValid, &a_Value](cLuaState & a_LuaState)
{
AString key, val;
if (a_LuaState.GetStackValues(-2, key, val))
@ -1172,7 +1205,8 @@ bool cLuaState::GetStackValue(int a_StackPos, AStringVector & a_Value)
}
cStackTable tbl(*this, a_StackPos);
bool isValid = true;
tbl.ForEachArrayElement([&](cLuaState & a_LuaState, int a_Index)
tbl.ForEachArrayElement(
[&](cLuaState & a_LuaState, int a_Index)
{
AString tempStr;
if (a_LuaState.GetStackValue(-1, tempStr))
@ -1265,7 +1299,9 @@ bool cLuaState::GetStackValue(int a_StackPos, cPluginManager::CommandResult & a_
{
if (lua_isnumber(m_LuaState, a_StackPos))
{
a_Result = static_cast<cPluginManager::CommandResult>(static_cast<int>((tolua_tonumber(m_LuaState, a_StackPos, a_Result))));
a_Result = static_cast<cPluginManager::CommandResult>(
static_cast<int>((tolua_tonumber(m_LuaState, a_StackPos, a_Result)))
);
return true;
}
return false;
@ -1379,7 +1415,9 @@ bool cLuaState::GetStackValue(int a_StackPos, CustomStatistic & a_Value)
{
if (lua_isnumber(m_LuaState, a_StackPos))
{
a_Value = static_cast<CustomStatistic>(static_cast<std::underlying_type_t<CustomStatistic>>(lua_tonumber(m_LuaState, a_StackPos)));
a_Value = static_cast<CustomStatistic>(
static_cast<std::underlying_type_t<CustomStatistic>>(lua_tonumber(m_LuaState, a_StackPos))
);
return true;
}
@ -1412,8 +1450,9 @@ bool cLuaState::GetStackValue(int a_StackPos, eBlockFace & a_ReturnedVal)
}
a_ReturnedVal = static_cast<eBlockFace>(Clamp(
static_cast<int>(tolua_tonumber(m_LuaState, a_StackPos, a_ReturnedVal)),
static_cast<int>(BLOCK_FACE_MIN), static_cast<int>(BLOCK_FACE_MAX))
);
static_cast<int>(BLOCK_FACE_MIN),
static_cast<int>(BLOCK_FACE_MAX)
));
return true;
}
@ -1429,8 +1468,9 @@ bool cLuaState::GetStackValue(int a_StackPos, eWeather & a_ReturnedVal)
}
a_ReturnedVal = static_cast<eWeather>(Clamp(
static_cast<int>(tolua_tonumber(m_LuaState, a_StackPos, a_ReturnedVal)),
static_cast<int>(wSunny), static_cast<int>(wThunderstorm))
);
static_cast<int>(wSunny),
static_cast<int>(wThunderstorm)
));
return true;
}
@ -1492,7 +1532,7 @@ bool cLuaState::GetStackValue(int a_StackPos, std::string_view & a_Value)
const char * const Value = lua_tolstring(m_LuaState, a_StackPos, &Length);
if (Value != nullptr)
{
a_Value = { Value, Length };
a_Value = {Value, Length};
return true;
}
return false;
@ -1502,8 +1542,7 @@ bool cLuaState::GetStackValue(int a_StackPos, std::string_view & a_Value)
template <typename T>
bool cLuaState::GetStackValue(int a_StackPos, Vector3<T> & a_ReturnedVal)
template <typename T> bool cLuaState::GetStackValue(int a_StackPos, Vector3<T> & a_ReturnedVal)
{
tolua_Error err;
if (lua_isnil(m_LuaState, a_StackPos))
@ -1561,7 +1600,7 @@ cLuaState::cStackValue cLuaState::WalkToValue(const AString & a_Name)
// Iterate over path and replace the top of the stack with the walked element
lua_pushvalue(m_LuaState, -1); // Copy the stack value into the "working area"
auto path = StringSplit(a_Name, ".");
for (const auto & elem: path)
for (const auto & elem : path)
{
// If the value is not a table, bail out (error):
if (!lua_istable(m_LuaState, -1))
@ -1593,7 +1632,7 @@ cLuaState::cStackValue cLuaState::WalkToNamedGlobal(const AString & a_Name)
// Iterate over path and replace the top of the stack with the walked element
lua_getglobal(m_LuaState, "_G");
auto path = StringSplit(a_Name, ".");
for (const auto & elem: path)
for (const auto & elem : path)
{
// If the value is not a table, bail out (error):
if (!lua_istable(m_LuaState, -1))
@ -1622,7 +1661,7 @@ cLuaState::cStackValue cLuaState::WalkToNamedGlobal(const AString & a_Name)
bool cLuaState::CallFunction(int a_NumResults)
{
ASSERT (m_NumCurrentFunctionArgs >= 0); // A function must be pushed to stack first
ASSERT(m_NumCurrentFunctionArgs >= 0); // A function must be pushed to stack first
ASSERT(lua_isfunction(m_LuaState, -m_NumCurrentFunctionArgs - 1)); // The function to call
ASSERT(lua_isfunction(m_LuaState, -m_NumCurrentFunctionArgs - 2)); // The error handler
@ -1643,7 +1682,14 @@ bool cLuaState::CallFunction(int a_NumResults)
auto top = lua_gettop(m_LuaState);
if (top < 2)
{
LogStackValues(fmt::format(FMT_STRING("The Lua stack is in an unexpected state, expected at least two values there, but got {}"), top).c_str());
LogStackValues(
fmt::format(
FMT_STRING("The Lua stack is in an unexpected state, expected at least two values there, but got {}"
),
top
)
.c_str()
);
}
lua_pop(m_LuaState, std::min(2, top));
return false;
@ -1676,9 +1722,10 @@ bool cLuaState::CheckParamUserTable(int a_StartParam, const char * a_UserTable,
}
// Not the correct parameter
lua_Debug entry;
VERIFY(lua_getstack(m_LuaState, 0, &entry));
VERIFY(lua_getinfo (m_LuaState, "n", &entry));
AString ErrMsg = fmt::format(FMT_STRING("#ferror in function '{}'."), (entry.name != nullptr) ? entry.name : "?");
VERIFY(lua_getstack(m_LuaState, 0, &entry));
VERIFY(lua_getinfo(m_LuaState, "n", &entry));
AString ErrMsg =
fmt::format(FMT_STRING("#ferror in function '{}'."), (entry.name != nullptr) ? entry.name : "?");
tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err);
return false;
} // for i - Param
@ -1709,9 +1756,10 @@ bool cLuaState::CheckParamUserType(int a_StartParam, const char * a_UserType, in
}
// Not the correct parameter
lua_Debug entry;
VERIFY(lua_getstack(m_LuaState, 0, &entry));
VERIFY(lua_getinfo (m_LuaState, "n", &entry));
AString ErrMsg = fmt::format(FMT_STRING("#ferror in function '{}'."), (entry.name != nullptr) ? entry.name : "?");
VERIFY(lua_getstack(m_LuaState, 0, &entry));
VERIFY(lua_getinfo(m_LuaState, "n", &entry));
AString ErrMsg =
fmt::format(FMT_STRING("#ferror in function '{}'."), (entry.name != nullptr) ? entry.name : "?");
tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err);
return false;
} // for i - Param
@ -1742,9 +1790,10 @@ bool cLuaState::CheckParamTable(int a_StartParam, int a_EndParam)
}
// Not the correct parameter
lua_Debug entry;
VERIFY(lua_getstack(m_LuaState, 0, &entry));
VERIFY(lua_getinfo (m_LuaState, "n", &entry));
AString ErrMsg = fmt::format(FMT_STRING("#ferror in function '{}'."), (entry.name != nullptr) ? entry.name : "?");
VERIFY(lua_getstack(m_LuaState, 0, &entry));
VERIFY(lua_getinfo(m_LuaState, "n", &entry));
AString ErrMsg =
fmt::format(FMT_STRING("#ferror in function '{}'."), (entry.name != nullptr) ? entry.name : "?");
BreakIntoDebugger(m_LuaState);
@ -1778,9 +1827,10 @@ bool cLuaState::CheckParamNumber(int a_StartParam, int a_EndParam)
}
// Not the correct parameter
lua_Debug entry;
VERIFY(lua_getstack(m_LuaState, 0, &entry));
VERIFY(lua_getinfo (m_LuaState, "n", &entry));
AString ErrMsg = fmt::format(FMT_STRING("#ferror in function '{}'."), (entry.name != nullptr) ? entry.name : "?");
VERIFY(lua_getstack(m_LuaState, 0, &entry));
VERIFY(lua_getinfo(m_LuaState, "n", &entry));
AString ErrMsg =
fmt::format(FMT_STRING("#ferror in function '{}'."), (entry.name != nullptr) ? entry.name : "?");
tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err);
return false;
} // for i - Param
@ -1811,9 +1861,10 @@ bool cLuaState::CheckParamBool(int a_StartParam, int a_EndParam)
}
// Not the correct parameter
lua_Debug entry;
VERIFY(lua_getstack(m_LuaState, 0, &entry));
VERIFY(lua_getinfo (m_LuaState, "n", &entry));
AString ErrMsg = fmt::format(FMT_STRING("#ferror in function '{}'."), (entry.name != nullptr) ? entry.name : "?");
VERIFY(lua_getstack(m_LuaState, 0, &entry));
VERIFY(lua_getinfo(m_LuaState, "n", &entry));
AString ErrMsg =
fmt::format(FMT_STRING("#ferror in function '{}'."), (entry.name != nullptr) ? entry.name : "?");
tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err);
return false;
} // for i - Param
@ -1844,12 +1895,13 @@ bool cLuaState::CheckParamString(int a_StartParam, int a_EndParam)
}
// Not the correct parameter
lua_Debug entry;
VERIFY(lua_getstack(m_LuaState, 0, &entry));
VERIFY(lua_getinfo (m_LuaState, "n", &entry));
VERIFY(lua_getstack(m_LuaState, 0, &entry));
VERIFY(lua_getinfo(m_LuaState, "n", &entry));
tolua_err.array = 0;
tolua_err.type = "string";
tolua_err.index = i;
AString ErrMsg = fmt::format(FMT_STRING("#ferror in function '{}'."), (entry.name != nullptr) ? entry.name : "?");
AString ErrMsg =
fmt::format(FMT_STRING("#ferror in function '{}'."), (entry.name != nullptr) ? entry.name : "?");
tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err);
return false;
} // for i - Param
@ -1879,10 +1931,14 @@ bool cLuaState::CheckParamFunction(int a_StartParam, int a_EndParam)
}
// Not the correct parameter
lua_Debug entry;
VERIFY(lua_getstack(m_LuaState, 0, &entry));
VERIFY(lua_getinfo (m_LuaState, "n", &entry));
luaL_error(m_LuaState, "Error in function '%s' parameter #%d. Function expected, got %s",
(entry.name != nullptr) ? entry.name : "?", i, GetTypeText(i).c_str()
VERIFY(lua_getstack(m_LuaState, 0, &entry));
VERIFY(lua_getinfo(m_LuaState, "n", &entry));
luaL_error(
m_LuaState,
"Error in function '%s' parameter #%d. Function expected, got %s",
(entry.name != nullptr) ? entry.name : "?",
i,
GetTypeText(i).c_str()
);
return false;
} // for i - Param
@ -1912,10 +1968,14 @@ bool cLuaState::CheckParamFunctionOrNil(int a_StartParam, int a_EndParam)
}
// Not the correct parameter
lua_Debug entry;
VERIFY(lua_getstack(m_LuaState, 0, &entry));
VERIFY(lua_getinfo (m_LuaState, "n", &entry));
luaL_error(m_LuaState, "Error in function '%s' parameter #%d. Function expected, got %s",
(entry.name != nullptr) ? entry.name : "?", i, GetTypeText(i).c_str()
VERIFY(lua_getstack(m_LuaState, 0, &entry));
VERIFY(lua_getinfo(m_LuaState, "n", &entry));
luaL_error(
m_LuaState,
"Error in function '%s' parameter #%d. Function expected, got %s",
(entry.name != nullptr) ? entry.name : "?",
i,
GetTypeText(i).c_str()
);
return false;
} // for i - Param
@ -1944,7 +2004,9 @@ bool cLuaState::CheckParamVector3(int a_StartParam, int a_EndParam)
continue;
}
ApiParamError(fmt::format(FMT_STRING("Failed to read parameter #{}. Vector3 expected, got {}"), i, GetTypeText(i)));
ApiParamError(
fmt::format(FMT_STRING("Failed to read parameter #{}. Vector3 expected, got {}"), i, GetTypeText(i))
);
return false;
}
return true;
@ -1976,7 +2038,9 @@ bool cLuaState::CheckParamUUID(int a_StartParam, int a_EndParam)
if (!tolua_iscppstring(m_LuaState, i, 0, &err))
{
ApiParamError(fmt::format(FMT_STRING("Failed to read parameter #{}. UUID expected, got {}"), i, GetTypeText(i)));
ApiParamError(
fmt::format(FMT_STRING("Failed to read parameter #{}. UUID expected, got {}"), i, GetTypeText(i))
);
return false;
}
@ -1984,7 +2048,11 @@ bool cLuaState::CheckParamUUID(int a_StartParam, int a_EndParam)
GetStackValue(i, tempStr);
if (!tempUUID.FromString(tempStr))
{
ApiParamError(fmt::format(FMT_STRING("Failed to read parameter #{}. UUID expected, got non-UUID string:\n\t\"{}\""), i, tempStr));
ApiParamError(fmt::format(
FMT_STRING("Failed to read parameter #{}. UUID expected, got non-UUID string:\n\t\"{}\""),
i,
tempStr
));
return false;
}
}
@ -2004,9 +2072,12 @@ bool cLuaState::CheckParamEnd(int a_Param)
}
// Not the correct parameter
lua_Debug entry;
VERIFY(lua_getstack(m_LuaState, 0, &entry));
VERIFY(lua_getinfo (m_LuaState, "n", &entry));
AString ErrMsg = fmt::format(FMT_STRING("#ferror in function '{}': Too many arguments."), (entry.name != nullptr) ? entry.name : "?");
VERIFY(lua_getstack(m_LuaState, 0, &entry));
VERIFY(lua_getinfo(m_LuaState, "n", &entry));
AString ErrMsg = fmt::format(
FMT_STRING("#ferror in function '{}': Too many arguments."),
(entry.name != nullptr) ? entry.name : "?"
);
tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err);
return false;
}
@ -2025,12 +2096,13 @@ bool cLuaState::CheckParamSelf(const char * a_SelfClassName)
// Not the correct parameter
lua_Debug entry;
VERIFY(lua_getstack(m_LuaState, 0, &entry));
VERIFY(lua_getinfo (m_LuaState, "n", &entry));
VERIFY(lua_getstack(m_LuaState, 0, &entry));
VERIFY(lua_getinfo(m_LuaState, "n", &entry));
AString ErrMsg = fmt::format(
FMT_STRING("Error in function '{}'. The 'self' parameter is not of the expected type, \"instance of {}\". " \
"Make sure you're using the correct calling convention (obj:fn() instead of obj.fn())."),
(entry.name != nullptr) ? entry.name : "<unknown>", a_SelfClassName
FMT_STRING("Error in function '{}'. The 'self' parameter is not of the expected type, \"instance of {}\". "
"Make sure you're using the correct calling convention (obj:fn() instead of obj.fn())."),
(entry.name != nullptr) ? entry.name : "<unknown>",
a_SelfClassName
);
tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err);
return false;
@ -2050,12 +2122,14 @@ bool cLuaState::CheckParamStaticSelf(const char * a_SelfClassName)
// Not the correct parameter
lua_Debug entry;
VERIFY(lua_getstack(m_LuaState, 0, &entry));
VERIFY(lua_getinfo (m_LuaState, "n", &entry));
VERIFY(lua_getstack(m_LuaState, 0, &entry));
VERIFY(lua_getinfo(m_LuaState, "n", &entry));
AString ErrMsg = fmt::format(
FMT_STRING("Error in function '{}'. The 'self' parameter is not of the expected type, \"class {}\". " \
"Make sure you're using the correct calling convention (cClassName:fn() instead of cClassName.fn() or obj:fn())."),
(entry.name != nullptr) ? entry.name : "<unknown>", a_SelfClassName
FMT_STRING("Error in function '{}'. The 'self' parameter is not of the expected type, \"class {}\". "
"Make sure you're using the correct calling convention (cClassName:fn() instead of cClassName.fn() "
"or obj:fn())."),
(entry.name != nullptr) ? entry.name : "<unknown>",
a_SelfClassName
);
tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err);
return false;
@ -2094,8 +2168,7 @@ bool cLuaState::IsParamVector3(int a_ParamIdx)
ASSERT(IsValid());
return (
IsParamUserType(a_ParamIdx, "Vector3<double>") ||
IsParamUserType(a_ParamIdx, "Vector3<float>") ||
IsParamUserType(a_ParamIdx, "Vector3<double>") || IsParamUserType(a_ParamIdx, "Vector3<float>") ||
IsParamUserType(a_ParamIdx, "Vector3<int>") ||
lua_istable(m_LuaState, a_ParamIdx) // Assume any table is good enough
);
@ -2170,7 +2243,8 @@ int cLuaState::ApiParamError(std::string_view a_Msg)
// Log everything into the console:
LOGWARNING("%s", errorMsg.c_str());
// cLuaState::LogStackTrace(a_LuaState); // Do NOT log stack trace, it is already output as part of the Lua error handling
// cLuaState::LogStackTrace(a_LuaState); // Do NOT log stack trace, it is already output as part of the Lua error
// handling
LogStackValues(m_LuaState, "Parameters on the stack");
// Raise Lua error:
@ -2283,10 +2357,10 @@ bool cLuaState::CopyTableFrom(cLuaState & a_SrcLuaState, int a_SrcStackIdx, int
[[maybe_unused]] const auto dstTop = lua_gettop(m_LuaState);
// Create the dest table:
lua_createtable(m_LuaState, 0, 0); // DST: <table>
lua_createtable(m_LuaState, 0, 0); // DST: <table>
lua_pushvalue(a_SrcLuaState, a_SrcStackIdx); // SRC: <table>
lua_pushnil(a_SrcLuaState); // SRC: <table> <key>
while (lua_next(a_SrcLuaState, -2) != 0) // SRC: <table> <key> <value>
lua_pushnil(a_SrcLuaState); // SRC: <table> <key>
while (lua_next(a_SrcLuaState, -2) != 0) // SRC: <table> <key> <value>
{
ASSERT(lua_gettop(a_SrcLuaState) == srcTop + 3);
ASSERT(lua_gettop(m_LuaState) == dstTop + 1);
@ -2306,7 +2380,7 @@ bool cLuaState::CopyTableFrom(cLuaState & a_SrcLuaState, int a_SrcStackIdx, int
// Copy the value:
if (!CopySingleValueFrom(a_SrcLuaState, -1, a_NumAllowedNestingLevels - 1)) // DST: <table> <key> <value>
{
lua_pop(m_LuaState, 2); // DST: empty
lua_pop(m_LuaState, 2); // DST: empty
lua_pop(a_SrcLuaState, 3); // SRC: empty
ASSERT(lua_gettop(a_SrcLuaState) == srcTop);
ASSERT(lua_gettop(m_LuaState) == dstTop);
@ -2371,7 +2445,7 @@ bool cLuaState::CopySingleValueFrom(cLuaState & a_SrcLuaState, int a_StackIdx, i
}
lua_rawget(a_SrcLuaState, LUA_REGISTRYINDEX); // Stack +1
type = lua_tostring(a_SrcLuaState, -1);
lua_pop(a_SrcLuaState, 1); // Stack -1
lua_pop(a_SrcLuaState, 1); // Stack -1
// Copy the value:
void * ud = tolua_touserdata(a_SrcLuaState, a_StackIdx, nullptr);
@ -2389,8 +2463,12 @@ bool cLuaState::CopySingleValueFrom(cLuaState & a_SrcLuaState, int a_StackIdx, i
}
default:
{
LOGWARNING("%s: Unsupported value: '%s' at stack position %d. Can only copy numbers, strings, bools, classes and simple tables!",
__FUNCTION__, lua_typename(a_SrcLuaState, t), a_StackIdx
LOGWARNING(
"%s: Unsupported value: '%s' at stack position %d. Can only copy numbers, strings, bools, classes and "
"simple tables!",
__FUNCTION__,
lua_typename(a_SrcLuaState, t),
a_StackIdx
);
return false;
}
@ -2435,7 +2513,7 @@ void cLuaState::LogStackValues(lua_State * a_LuaState, const char * a_Header)
int Type = lua_type(a_LuaState, i);
switch (Type)
{
case LUA_TBOOLEAN: Value.assign((lua_toboolean(a_LuaState, i) != 0) ? "true" : "false"); break;
case LUA_TBOOLEAN: Value.assign((lua_toboolean(a_LuaState, i) != 0) ? "true" : "false"); break;
case LUA_TLIGHTUSERDATA: Value = fmt::format(FMT_STRING("{}"), lua_touserdata(a_LuaState, i)); break;
case LUA_TNUMBER: Value = fmt::format(FMT_STRING("{}"), lua_tonumber(a_LuaState, i)); break;
case LUA_TSTRING:
@ -2445,11 +2523,12 @@ void cLuaState::LogStackValues(lua_State * a_LuaState, const char * a_Header)
Value.assign(txt, std::min<size_t>(len, 50)); // Only log up to 50 characters of the string
break;
}
case LUA_TTABLE: Value = fmt::format(FMT_STRING("{}"), lua_topointer(a_LuaState, i)); break;
case LUA_TFUNCTION: Value = fmt::format(FMT_STRING("{}"), lua_topointer(a_LuaState, i)); break;
case LUA_TTABLE: Value = fmt::format(FMT_STRING("{}"), lua_topointer(a_LuaState, i)); break;
case LUA_TFUNCTION: Value = fmt::format(FMT_STRING("{}"), lua_topointer(a_LuaState, i)); break;
case LUA_TUSERDATA:
{
Value = fmt::format(FMT_STRING("{} ({})"), lua_touserdata(a_LuaState, i), tolua_typename(a_LuaState, i));
Value =
fmt::format(FMT_STRING("{} ({})"), lua_touserdata(a_LuaState, i), tolua_typename(a_LuaState, i));
// tolua_typename pushes the string onto Lua stack, pop it off again:
lua_pop(a_LuaState, 1);
break;
@ -2586,8 +2665,7 @@ void cLuaState::UntrackRef(cTrackedRef & a_Ref)
// cLuaState::cRef:
cLuaState::cRef::cRef(void) :
m_LuaState(nullptr),
m_Ref(LUA_REFNIL)
m_LuaState(nullptr), m_Ref(LUA_REFNIL)
{
}
@ -2596,8 +2674,7 @@ cLuaState::cRef::cRef(void) :
cLuaState::cRef::cRef(cLuaState & a_LuaState, int a_StackPos) :
m_LuaState(nullptr),
m_Ref(LUA_REFNIL)
m_LuaState(nullptr), m_Ref(LUA_REFNIL)
{
RefStack(a_LuaState, a_StackPos);
}
@ -2606,9 +2683,8 @@ cLuaState::cRef::cRef(cLuaState & a_LuaState, int a_StackPos) :
cLuaState::cRef::cRef(cRef && a_FromRef):
m_LuaState(a_FromRef.m_LuaState),
m_Ref(a_FromRef.m_Ref)
cLuaState::cRef::cRef(cRef && a_FromRef) :
m_LuaState(a_FromRef.m_LuaState), m_Ref(a_FromRef.m_Ref)
{
a_FromRef.m_LuaState = nullptr;
a_FromRef.m_Ref = LUA_REFNIL;
@ -2657,7 +2733,3 @@ void cLuaState::cRef::UnRef(void)
m_LuaState = nullptr;
m_Ref = LUA_REFNIL;
}

View File

@ -32,7 +32,7 @@ stays valid but doesn't call into Lua code anymore, returning false for "failure
extern "C"
{
#include "lua/src/lauxlib.h"
#include "lua/src/lauxlib.h"
}
#include "../Defines.h"
@ -54,65 +54,70 @@ class cDeadlockDetect;
/** Encapsulates a Lua state and provides some syntactic sugar for common operations */
class cLuaState
{
public:
#ifndef NDEBUG
/** Asserts that the Lua stack has the same amount of entries when this object is destructed, as when it was constructed.
Used for checking functions that should preserve Lua stack balance. */
class cStackBalanceCheck
public:
#ifndef NDEBUG
/** Asserts that the Lua stack has the same amount of entries when this object is destructed, as when it was
constructed. Used for checking functions that should preserve Lua stack balance. */
class cStackBalanceCheck
{
public:
cStackBalanceCheck(
const char * a_FileName,
int a_LineNum,
lua_State * a_LuaState,
bool a_ShouldLogStack = true
) :
m_FileName(a_FileName), m_LineNum(a_LineNum), m_LuaState(a_LuaState), m_StackPos(lua_gettop(a_LuaState))
{
public:
cStackBalanceCheck(const char * a_FileName, int a_LineNum, lua_State * a_LuaState, bool a_ShouldLogStack = true):
m_FileName(a_FileName),
m_LineNum(a_LineNum),
m_LuaState(a_LuaState),
m_StackPos(lua_gettop(a_LuaState))
if (a_ShouldLogStack)
{
if (a_ShouldLogStack)
{
// DEBUG: If an unbalanced stack is reported, uncommenting the next line can help debug the imbalance
// cLuaState::LogStackValues(a_LuaState, fmt::format(FMT_STRING("Started checking Lua stack balance, currently {} items:"), m_StackPos).c_str());
// Since LogStackValues() itself uses the balance check, we must not call it recursively
}
// DEBUG: If an unbalanced stack is reported, uncommenting the next line can help debug the imbalance
// cLuaState::LogStackValues(a_LuaState, fmt::format(FMT_STRING("Started checking Lua stack balance,
// currently {} items:"), m_StackPos).c_str()); Since LogStackValues() itself uses the balance check, we
// must not call it recursively
}
}
~cStackBalanceCheck() noexcept(false)
~cStackBalanceCheck() noexcept(false)
{
auto currStackPos = lua_gettop(m_LuaState);
if (currStackPos != m_StackPos)
{
auto currStackPos = lua_gettop(m_LuaState);
if (currStackPos != m_StackPos)
{
LOGD("Lua stack not balanced. Expected %d items, found %d items. Stack watching started in %s:%d",
m_StackPos, currStackPos,
m_FileName.c_str(), m_LineNum
);
cLuaState::LogStackValues(m_LuaState);
ASSERT(!"Lua stack unbalanced"); // If this assert fires, the Lua stack is inbalanced, check the callstack / m_FileName / m_LineNum
}
LOGD(
"Lua stack not balanced. Expected %d items, found %d items. Stack watching started in %s:%d",
m_StackPos,
currStackPos,
m_FileName.c_str(),
m_LineNum
);
cLuaState::LogStackValues(m_LuaState);
ASSERT(!"Lua stack unbalanced"
); // If this assert fires, the Lua stack is inbalanced, check the callstack / m_FileName / m_LineNum
}
}
protected:
const AString m_FileName;
int m_LineNum;
lua_State * m_LuaState;
int m_StackPos;
};
protected:
const AString m_FileName;
int m_LineNum;
lua_State * m_LuaState;
int m_StackPos;
};
#define STRINGIFY2(X, Y) X##Y
#define STRINGIFY(X, Y) STRINGIFY2(X, Y)
#define ASSERT_LUA_STACK_BALANCE(...) cStackBalanceCheck STRINGIFY(Check, __COUNTER__)(__FILE__, __LINE__, __VA_ARGS__)
#else
#define ASSERT_LUA_STACK_BALANCE(...)
#endif
#define STRINGIFY2(X, Y) X##Y
#define STRINGIFY(X, Y) STRINGIFY2(X, Y)
#define ASSERT_LUA_STACK_BALANCE(...) cStackBalanceCheck STRINGIFY(Check, __COUNTER__)(__FILE__, __LINE__, __VA_ARGS__)
#else
#define ASSERT_LUA_STACK_BALANCE(...)
#endif
/** Makes sure that the Lua state's stack has the same number of elements on destruction as it had on construction of this object (RAII).
Can only remove elements, if there are less than expected, throws. */
/** Makes sure that the Lua state's stack has the same number of elements on destruction as it had on construction
of this object (RAII). Can only remove elements, if there are less than expected, throws. */
class cStackBalancePopper
{
public:
cStackBalancePopper(cLuaState & a_LuaState):
m_LuaState(a_LuaState),
m_Count(lua_gettop(a_LuaState))
public:
cStackBalancePopper(cLuaState & a_LuaState) :
m_LuaState(a_LuaState), m_Count(lua_gettop(a_LuaState))
{
}
@ -122,33 +127,49 @@ public:
if (curTop > m_Count)
{
// There are some leftover elements, adjust the stack:
m_LuaState.LogStackValues(fmt::format(FMT_STRING("Re-balancing Lua stack, expected {} values, got {}:"), m_Count, curTop).c_str());
m_LuaState.LogStackValues(
fmt::format(FMT_STRING("Re-balancing Lua stack, expected {} values, got {}:"), m_Count, curTop)
.c_str()
);
lua_pop(m_LuaState, curTop - m_Count);
}
else if (curTop < m_Count)
{
// This is an irrecoverable error, rather than letting the Lua engine crash undefinedly later on, abort now:
LOGERROR("Unable to re-balance Lua stack, there are elements missing. Expected at least %d elements, got %d.", m_Count, curTop);
throw std::runtime_error(fmt::format(FMT_STRING("Unable to re-balance Lua stack, there are elements missing. Expected at least {} elements, got {}."), m_Count, curTop));
// This is an irrecoverable error, rather than letting the Lua engine crash undefinedly later on, abort
// now:
LOGERROR(
"Unable to re-balance Lua stack, there are elements missing. Expected at least %d elements, got "
"%d.",
m_Count,
curTop
);
throw std::runtime_error(fmt::format(
FMT_STRING("Unable to re-balance Lua stack, there are elements missing. Expected at least {} "
"elements, got {}."),
m_Count,
curTop
));
}
}
protected:
protected:
cLuaState & m_LuaState;
int m_Count;
};
/** Provides a RAII-style locking for the LuaState.
Used mainly by the cPluginLua internals to provide the actual locking for interface operations, such as callbacks. */
Used mainly by the cPluginLua internals to provide the actual locking for interface operations, such as callbacks.
*/
class cLock
{
public:
cLock(cLuaState & a_LuaState):
public:
cLock(cLuaState & a_LuaState) :
m_Lock(a_LuaState.m_CS)
{
}
protected:
protected:
cCSLock m_Lock;
};
@ -158,7 +179,7 @@ public:
The reference can also be reset by calling RefStack(). */
class cRef
{
public:
public:
/** Creates an unbound reference object. */
cRef(void);
@ -179,7 +200,7 @@ public:
void UnRef(void);
/** Returns true if the reference is valid */
bool IsValid(void) const {return (m_Ref != LUA_REFNIL); }
bool IsValid(void) const { return (m_Ref != LUA_REFNIL); }
/** Allows to use this class wherever an int (i. e. ref) is to be used */
explicit operator int(void) const { return m_Ref; }
@ -188,7 +209,8 @@ public:
lua_State * GetLuaState(void) { return m_LuaState; }
/** Creates a Lua reference to the specified object instance in the specified Lua state.
This is useful to make anti-GC references for objects that were created by Lua and need to stay alive longer than Lua GC would normally guarantee. */
This is useful to make anti-GC references for objects that were created by Lua and need to stay alive longer
than Lua GC would normally guarantee. */
template <typename T> void CreateFromObject(cLuaState & a_LuaState, T && a_Object)
{
a_LuaState.Push(std::forward<T>(a_Object));
@ -196,13 +218,13 @@ public:
a_LuaState.Pop();
}
protected:
protected:
lua_State * m_LuaState;
int m_Ref;
// Remove the copy-constructor:
cRef(const cRef &) = delete;
} ;
};
/** Represents a reference to a Lua object that has a tracked lifetime -
@ -215,14 +237,12 @@ public:
class cTrackedRef
{
friend class ::cLuaState;
public:
public:
/** Creates an unbound ref instance. */
cTrackedRef(void);
~cTrackedRef()
{
Clear();
}
~cTrackedRef() { Clear(); }
/** Set the contained reference to the object at the specified Lua state's stack position.
If another reference has been previously contained, it is Clear()-ed first. */
@ -233,15 +253,17 @@ public:
void Clear(void);
/** Returns true if the contained reference is valid.
(Note that depending on this value is not thread-safe, another thread may invalidate the ref in the meantime. It is meant for quick ASSERTs only). */
(Note that depending on this value is not thread-safe, another thread may invalidate the ref in the meantime. It
is meant for quick ASSERTs only). */
bool IsValid(void);
/** Returns true if the reference resides in the specified Lua state.
Internally, compares the reference's canon Lua state.
(Note that depending on this value is not thread-safe, another thread may modify the ref in the meantime. It is meant for quick ASSERTs only). */
(Note that depending on this value is not thread-safe, another thread may modify the ref in the meantime. It is
meant for quick ASSERTs only). */
bool IsSameLuaState(cLuaState & a_LuaState);
protected:
protected:
friend class cLuaState;
/** The mutex protecting m_Ref against multithreaded access.
@ -280,20 +302,17 @@ public:
with a cCallbackPtr. Note that instances of this class are tracked in the canon LuaState instance, so that
they can be invalidated when the LuaState is unloaded; due to multithreading issues they can only be tracked
by-ptr, which has an unfortunate effect of disabling the copy and move constructors. */
class cCallback:
public cTrackedRef
class cCallback : public cTrackedRef
{
using Super = cTrackedRef;
public:
public:
cCallback(void) {}
/** Calls the Lua callback, if still available.
Returns true if callback has been called.
Returns false if the Lua state isn't valid anymore. */
template <typename... Args>
bool Call(Args &&... args)
template <typename... Args> bool Call(Args &&... args)
{
auto cs = m_CS.load();
if (cs == nullptr)
@ -313,8 +332,7 @@ public:
Returns true on success, false on failure (not a function at the specified stack pos). */
bool RefStack(cLuaState & a_LuaState, int a_StackPos);
protected:
protected:
/** This class cannot be copied, because it is tracked in the LuaState by-ptr.
Use cCallbackPtr for a copyable object. */
cCallback(const cCallback &) = delete;
@ -329,13 +347,11 @@ public:
/** Same thing as cCallback, but GetStackValue() won't fail if the callback value is nil.
Used for callbacks that are optional - they needn't be present and in such a case they won't get called. */
class cOptionalCallback:
public cCallback
class cOptionalCallback : public cCallback
{
using Super = cCallback;
public:
public:
cOptionalCallback(void) {}
/** Set the contained callback to the function in the specified Lua state's stack position.
@ -343,8 +359,7 @@ public:
Returns true on success, false on failure (not a function at the specified stack pos). */
bool RefStack(cLuaState & a_LuaState, int a_StackPos);
protected:
protected:
/** This class cannot be copied, because it is tracked in the LuaState by-ptr.
Use cCallbackPtr for a copyable object. */
cOptionalCallback(const cOptionalCallback &) = delete;
@ -364,19 +379,17 @@ public:
Note that instances of this class are tracked in the canon LuaState instance, so that they can be
invalidated when the LuaState is unloaded; due to multithreading issues they can only be tracked by-ptr,
which has an unfortunate effect of disabling the copy and move constructors. */
class cTableRef:
public cTrackedRef
class cTableRef : public cTrackedRef
{
using Super = cTrackedRef;
public:
public:
cTableRef(void) {}
/** Calls the Lua function stored under the specified name in the referenced table, if still available.
Returns true if callback has been called.
Returns false if the Lua state isn't valid anymore, or the function doesn't exist. */
template <typename... Args>
bool CallTableFn(const char * a_FnName, Args &&... args)
template <typename... Args> bool CallTableFn(const char * a_FnName, Args &&... args)
{
auto cs = m_CS.load();
if (cs == nullptr)
@ -395,8 +408,7 @@ public:
A "self" parameter is injected in front of all the given parameters and is set to the callback table.
Returns true if callback has been called.
Returns false if the Lua state isn't valid anymore, or the function doesn't exist. */
template <typename... Args>
bool CallTableFnWithSelf(const char * a_FnName, Args &&... args)
template <typename... Args> bool CallTableFnWithSelf(const char * a_FnName, Args &&... args)
{
auto cs = m_CS.load();
if (cs == nullptr)
@ -419,21 +431,21 @@ public:
typedef std::unique_ptr<cTableRef> cTableRefPtr;
/** Represents a parameter that is optional - calling a GetStackValue() with this object will not fail if the value on the Lua stack is nil.
Note that the GetStackValue() will still fail if the param is present but of a different type.
The class itself is just a marker so that the template magic will select the correct GetStackValue() overload. */
template <typename T>
class cOptionalParam
/** Represents a parameter that is optional - calling a GetStackValue() with this object will not fail if the value
on the Lua stack is nil. Note that the GetStackValue() will still fail if the param is present but of a different
type. The class itself is just a marker so that the template magic will select the correct GetStackValue() overload.
*/
template <typename T> class cOptionalParam
{
public:
explicit cOptionalParam(T & a_Dest):
public:
explicit cOptionalParam(T & a_Dest) :
m_Dest(a_Dest)
{
}
T & GetDest(void) { return m_Dest; }
protected:
protected:
T & m_Dest;
};
@ -441,7 +453,7 @@ public:
/** A dummy class that's used only to delimit function args from return values for cLuaState::Call() */
class cRet
{
} ;
};
static const cRet Return; // Use this constant to delimit function args from return values for cLuaState::Call()
@ -456,21 +468,20 @@ public:
Will pop the value off the stack in the destructor. */
class cStackValue
{
public:
cStackValue(void):
public:
cStackValue(void) :
m_LuaState(nullptr)
{
}
cStackValue(cLuaState & a_LuaState):
cStackValue(cLuaState & a_LuaState) :
m_LuaState(a_LuaState)
{
m_StackLen = lua_gettop(a_LuaState);
}
cStackValue(cStackValue && a_Src):
m_LuaState(nullptr),
m_StackLen(-1)
cStackValue(cStackValue && a_Src) :
m_LuaState(nullptr), m_StackLen(-1)
{
std::swap(m_LuaState, a_Src.m_LuaState);
std::swap(m_StackLen, a_Src.m_StackLen);
@ -491,12 +502,9 @@ public:
m_StackLen = lua_gettop(a_LuaState);
}
bool IsValid(void) const
{
return (m_LuaState != nullptr);
}
bool IsValid(void) const { return (m_LuaState != nullptr); }
protected:
protected:
lua_State * m_LuaState;
/** Used for debugging, Lua state's stack size is checked against this number to make sure
@ -514,7 +522,7 @@ public:
used for immediate queries in API bindings. */
class cStackTable
{
public:
public:
cStackTable(cLuaState & a_LuaState, int a_StackPos);
/** Iterates over all array elements in the table consecutively and calls the a_ElementCallback for each.
@ -532,7 +540,7 @@ public:
cLuaState & GetLuaState(void) const { return m_LuaState; }
protected:
protected:
/** The Lua state in which the table resides. */
cLuaState & m_LuaState;
@ -556,7 +564,7 @@ public:
~cLuaState();
/** Allows this object to be used in the same way as a lua_State *, for example in the LuaLib functions */
operator lua_State * (void) { return m_LuaState; }
operator lua_State *(void) { return m_LuaState; }
/** Creates the m_LuaState, if not created already.
This state will be automatically closed in the destructor.
@ -570,7 +578,8 @@ public:
/** Closes the m_LuaState, if not closed already */
void Close(void);
/** Attaches the specified state. Operations will be carried out on this state, but it will not be closed in the destructor */
/** Attaches the specified state. Operations will be carried out on this state, but it will not be closed in the
* destructor */
void Attach(lua_State * a_State);
/** Detaches a previously attached state. */
@ -670,7 +679,10 @@ public:
template <class T, typename = std::enable_if_t<std::is_integral_v<T>>>
bool GetStackValue(int a_StackPos, T & a_ReturnedVal)
{
if (!lua_isnumber(m_LuaState, a_StackPos)) // Also accepts strings representing a number: https://pgl.yoyo.org/luai/i/lua_isnumber
if (!lua_isnumber(
m_LuaState,
a_StackPos
)) // Also accepts strings representing a number: https://pgl.yoyo.org/luai/i/lua_isnumber
{
return false;
}
@ -688,8 +700,7 @@ public:
}
/** Retrieves an optional value on the stack - doesn't fail if the stack contains nil instead of the value. */
template <typename T>
bool GetStackValue(int a_StackPos, cOptionalParam<T> && a_ReturnedVal)
template <typename T> bool GetStackValue(int a_StackPos, cOptionalParam<T> && a_ReturnedVal)
{
if (lua_isnoneornil(m_LuaState, a_StackPos))
{
@ -699,8 +710,7 @@ public:
}
/** Retrieves any Vector3 value and coerces it into a Vector3<T>. */
template <typename T>
bool GetStackValue(int a_StackPos, Vector3<T> & a_ReturnedVal);
template <typename T> bool GetStackValue(int a_StackPos, Vector3<T> & a_ReturnedVal);
/** Pushes the named value in the table at the top of the stack.
a_Name may be a path containing multiple table levels, such as "cChatColor.Blue".
@ -710,8 +720,8 @@ public:
/** Pushes the named value in the global table to the top of the stack.
a_Name may be a path containing multiple table levels, such as "cChatColor.Blue".
If the value is found in the global table, it is pushed to the top of the stack and the returned cStackValue is valid.
If the value is not found, the stack is unchanged and the returned cStackValue is invalid. */
If the value is found in the global table, it is pushed to the top of the stack and the returned cStackValue is
valid. If the value is not found, the stack is unchanged and the returned cStackValue is invalid. */
cStackValue WalkToNamedGlobal(const AString & a_Name);
/** Retrieves the named value in the table at the top of the Lua stack.
@ -728,8 +738,8 @@ public:
return GetStackValue(-1, a_Value);
}
/** Retrieves the named global value. a_Name may be a path containing multiple table levels, such as "_G.cChatColor.Blue".
Returns true if the value was successfully retrieved, false on error. */
/** Retrieves the named global value. a_Name may be a path containing multiple table levels, such as
"_G.cChatColor.Blue". Returns true if the value was successfully retrieved, false on error. */
template <typename T> bool GetNamedGlobal(const AString & a_Name, T & a_Value)
{
// Push the globals table onto the stack and make it RAII-removed:
@ -740,15 +750,14 @@ public:
return GetNamedValue(a_Name, a_Value);
}
// Include the auto-generated Push and GetStackValue() functions:
#include "LuaState_Declaration.inc"
// Include the auto-generated Push and GetStackValue() functions:
#include "LuaState_Declaration.inc"
/** Call the specified Lua function.
Returns true if call succeeded, false if there was an error.
A special param of cRet & signifies the end of param list and the start of return values.
Example call: Call(Fn, Param1, Param2, Param3, cLuaState::Return, Ret1, Ret2) */
template <typename FnT, typename... Args>
bool Call(const FnT & a_Function, Args &&... args)
template <typename FnT, typename... Args> bool Call(const FnT & a_Function, Args &&... args)
{
cStackBalancePopper balancer(*this);
m_NumCurrentFunctionArgs = -1;
@ -772,10 +781,12 @@ public:
return GetStackValues(a_StartStackPos + 1, std::forward<Args>(args)...);
}
/** Returns true if the specified parameters on the stack are of the specified usertable type; also logs warning if not. Used for static functions */
/** Returns true if the specified parameters on the stack are of the specified usertable type; also logs warning if
* not. Used for static functions */
bool CheckParamUserTable(int a_StartParam, const char * a_UserTable, int a_EndParam = -1);
/** Returns true if the specified parameters on the stack are of the specified usertype; also logs warning if not. Used for regular functions */
/** Returns true if the specified parameters on the stack are of the specified usertype; also logs warning if not.
* Used for regular functions */
bool CheckParamUserType(int a_StartParam, const char * a_UserType, int a_EndParam = -1);
/** Returns true if the specified parameters on the stack are tables; also logs warning if not */
@ -836,9 +847,9 @@ public:
/** Logs all items in the current stack trace to the server console */
static void LogStackTrace(lua_State * a_LuaState, int a_StartingDepth = 0);
/** Prints the message, prefixed with the current function name, then logs the stack contents and raises a Lua error.
To be used for bindings when they detect bad parameters.
Doesn't return, but a dummy return type is provided so that Lua API functions may do "return ApiParamError(...)". */
/** Prints the message, prefixed with the current function name, then logs the stack contents and raises a Lua
error. To be used for bindings when they detect bad parameters. Doesn't return, but a dummy return type is provided
so that Lua API functions may do "return ApiParamError(...)". */
int ApiParamError(std::string_view a_Msg);
/** Returns the type of the item on the specified position in the stack */
@ -856,20 +867,20 @@ public:
/** Copies objects on the stack from the specified state.
Only numbers, bools, strings, API classes and simple tables containing these (recursively) are copied.
a_NumAllowedNestingLevels specifies how many table nesting levels are allowed, copying fails if there's a deeper table.
If successful, returns the number of objects copied.
If failed, returns a negative number and rewinds the stack position. */
a_NumAllowedNestingLevels specifies how many table nesting levels are allowed, copying fails if there's a deeper
table. If successful, returns the number of objects copied. If failed, returns a negative number and rewinds the
stack position. */
int CopyStackFrom(cLuaState & a_SrcLuaState, int a_SrcStart, int a_SrcEnd, int a_NumAllowedNestingLevels = 16);
/** Copies a table at the specified stack index of the source Lua state to the top of this Lua state's stack.
a_NumAllowedNestingLevels specifies how many table nesting levels are allowed, copying fails if there's a deeper table.
Returns true if successful, false on failure.
Can copy only simple values - numbers, bools, strings and recursively simple tables. */
a_NumAllowedNestingLevels specifies how many table nesting levels are allowed, copying fails if there's a deeper
table. Returns true if successful, false on failure. Can copy only simple values - numbers, bools, strings and
recursively simple tables. */
bool CopyTableFrom(cLuaState & a_SrcLuaState, int a_TableIdx, int a_NumAllowedNestingLevels);
/** Copies a single value from the specified stack index of the source Lua state to the top of this Lua state's stack.
a_NumAllowedNestingLevels specifies how many table nesting levels are allowed, copying fails if there's a deeper table.
Returns true if the value was copied, false on failure. */
/** Copies a single value from the specified stack index of the source Lua state to the top of this Lua state's
stack. a_NumAllowedNestingLevels specifies how many table nesting levels are allowed, copying fails if there's a
deeper table. Returns true if the value was copied, false on failure. */
bool CopySingleValueFrom(cLuaState & a_SrcLuaState, int a_StackIdx, int a_NumAllowedNestingLevels);
/** Reads the value at the specified stack position as a string and sets it to a_String. */
@ -881,8 +892,8 @@ public:
/** Logs all the elements' types on the API stack, with an optional header for the listing. */
static void LogStackValues(lua_State * a_LuaState, const char * a_Header = nullptr);
/** Returns the canon Lua state (the primary cLuaState instance that was used to create, rather than attach, the lua_State structure).
Returns nullptr if the canon Lua state cannot be queried. */
/** Returns the canon Lua state (the primary cLuaState instance that was used to create, rather than attach, the
lua_State structure). Returns nullptr if the canon Lua state cannot be queried. */
cLuaState * QueryCanonLuaState(void) const;
/** Outputs to log a warning about API call being unable to read its parameters from the stack,
@ -895,8 +906,7 @@ public:
/** Removes this object's CS from the DeadlockDetect's tracked CSs. */
void UntrackInDeadlockDetect(cDeadlockDetect & a_DeadlockDetect);
protected:
protected:
cCriticalSection m_CS;
lua_State * m_LuaState;
@ -927,8 +937,7 @@ protected:
Returns true if call succeeded, false if there was an error (not a table ref, function name not found).
A special param of cRet & signifies the end of param list and the start of return values.
Example call: CallTableFn(TableRef, "FnName", Param1, Param2, Param3, cLuaState::Return, Ret1, Ret2) */
template <typename... Args>
bool CallTableFn(const cRef & a_TableRef, const char * a_FnName, Args &&... args)
template <typename... Args> bool CallTableFn(const cRef & a_TableRef, const char * a_FnName, Args &&... args)
{
if (!PushFunction(a_TableRef, a_FnName))
{
@ -939,24 +948,21 @@ protected:
}
/** Variadic template terminator: If there's nothing more to push / pop, just call the function.
Note that there are no return values either, because those are prefixed by a cRet value, so the arg list is never empty. */
bool PushCallPop(void)
{
return CallFunction(0);
}
Note that there are no return values either, because those are prefixed by a cRet value, so the arg list is never
empty. */
bool PushCallPop(void) { return CallFunction(0); }
/** Variadic template recursor: More params to push. Push them and recurse. */
template <typename T, typename... Args>
inline bool PushCallPop(T && a_Param, Args &&... args)
template <typename T, typename... Args> inline bool PushCallPop(T && a_Param, Args &&... args)
{
Push(std::forward<T>(a_Param));
m_NumCurrentFunctionArgs += 1;
return PushCallPop(std::forward<Args>(args)...);
}
/** Variadic template terminator: If there's nothing more to push, but return values to collect, call the function and collect the returns. */
template <typename... Args>
bool PushCallPop(cLuaState::cRet, Args &&... args)
/** Variadic template terminator: If there's nothing more to push, but return values to collect, call the function
* and collect the returns. */
template <typename... Args> bool PushCallPop(cLuaState::cRet, Args &&... args)
{
// Calculate the number of return values (number of args left):
int NumReturns = sizeof...(args);
@ -976,12 +982,10 @@ protected:
}
/** Variadic template terminator: If there are no more values to get, bail out.
This function is not available in the public API, because it's an error to request no values directly; only internal functions can do that.
If you get a compile error saying this function is not accessible, check your calling code, you aren't reading any stack values. */
bool GetStackValues(int a_StartingStackPos)
{
return true;
}
This function is not available in the public API, because it's an error to request no values directly; only internal
functions can do that. If you get a compile error saying this function is not accessible, check your calling code,
you aren't reading any stack values. */
bool GetStackValues(int a_StartingStackPos) { return true; }
/** Pushes the function of the specified name onto the stack.
Returns true if successful. Logs a warning on failure (incl. m_SubsystemName)
@ -1038,7 +1042,7 @@ extern template bool cLuaState::GetStackValue(int a_StackPos, Vector3i & a_Retur
Can query each for the amount of currently used memory. */
class cLuaStateTracker
{
public:
public:
/** Adds the specified Lua state to the internal list of LuaStates. */
static void Add(cLuaState & a_LuaState);
@ -1048,7 +1052,7 @@ public:
/** Returns the statistics for all the registered LuaStates. */
static AString GetStats(void);
protected:
protected:
typedef cLuaState * cLuaStatePtr;
typedef std::vector<cLuaStatePtr> cLuaStatePtrs;
@ -1063,7 +1067,3 @@ protected:
/** Returns the single instance of this class. */
static cLuaStateTracker & Get(void);
};

View File

@ -13,7 +13,7 @@
cLuaTCPLink::cLuaTCPLink(cLuaState::cTableRefPtr && a_Callbacks):
cLuaTCPLink::cLuaTCPLink(cLuaState::cTableRefPtr && a_Callbacks) :
m_Callbacks(std::move(a_Callbacks))
{
}
@ -22,9 +22,8 @@ cLuaTCPLink::cLuaTCPLink(cLuaState::cTableRefPtr && a_Callbacks):
cLuaTCPLink::cLuaTCPLink(cLuaState::cTableRefPtr && a_Callbacks, cLuaServerHandleWPtr a_ServerHandle):
m_Callbacks(std::move(a_Callbacks)),
m_Server(std::move(a_ServerHandle))
cLuaTCPLink::cLuaTCPLink(cLuaState::cTableRefPtr && a_Callbacks, cLuaServerHandleWPtr a_ServerHandle) :
m_Callbacks(std::move(a_Callbacks)), m_Server(std::move(a_ServerHandle))
{
}
@ -223,19 +222,19 @@ AString cLuaTCPLink::StartTLSServer(
auto link = m_Link;
if (link != nullptr)
{
// Create the peer cert:
auto OwnCert = std::make_shared<cX509Cert>();
int res = OwnCert->Parse(a_OwnCertData.data(), a_OwnCertData.size());
if (res != 0)
{
return fmt::format(FMT_STRING("Cannot parse server certificate: -0x{:x}"), -res);
}
auto OwnPrivKey = std::make_shared<cCryptoKey>();
res = OwnPrivKey->ParsePrivate(a_OwnPrivKeyData.data(), a_OwnPrivKeyData.size(), a_OwnPrivKeyPassword);
if (res != 0)
{
return fmt::format(FMT_STRING("Cannot parse server private key: -0x{:x}"), -res);
}
// Create the peer cert:
auto OwnCert = std::make_shared<cX509Cert>();
int res = OwnCert->Parse(a_OwnCertData.data(), a_OwnCertData.size());
if (res != 0)
{
return fmt::format(FMT_STRING("Cannot parse server certificate: -0x{:x}"), -res);
}
auto OwnPrivKey = std::make_shared<cCryptoKey>();
res = OwnPrivKey->ParsePrivate(a_OwnPrivKeyData.data(), a_OwnPrivKeyData.size(), a_OwnPrivKeyPassword);
if (res != 0)
{
return fmt::format(FMT_STRING("Cannot parse server private key: -0x{:x}"), -res);
}
return link->StartTLSServer(OwnCert, OwnPrivKey, a_StartTLSData);
}
@ -263,7 +262,7 @@ void cLuaTCPLink::Terminated(void)
// If the link is still open, close it:
{
auto link= m_Link;
auto link = m_Link;
if (link != nullptr)
{
link->Close();
@ -337,8 +336,3 @@ void cLuaTCPLink::OnRemoteClosed(void)
// Terminate all processing on the link:
Terminated();
}

View File

@ -24,15 +24,15 @@ typedef std::weak_ptr<cLuaServerHandle> cLuaServerHandleWPtr;
class cLuaTCPLink:
public cNetwork::cConnectCallbacks,
public cTCPLink::cCallbacks
class cLuaTCPLink : public cNetwork::cConnectCallbacks,
public cTCPLink::cCallbacks
{
public:
public:
/** Creates a new instance of the link, wrapping the callbacks that are in the specified table. */
cLuaTCPLink(cLuaState::cTableRefPtr && a_Callbacks);
/** Creates a new instance of the link, attached to the specified plugin and wrapping the callbacks that are in the specified referenced table. */
/** Creates a new instance of the link, attached to the specified plugin and wrapping the callbacks that are in the
* specified referenced table. */
cLuaTCPLink(cLuaState::cTableRefPtr && a_Callbacks, cLuaServerHandleWPtr a_Server);
virtual ~cLuaTCPLink() override;
@ -90,8 +90,7 @@ public:
const AString & a_StartTLSData
);
protected:
protected:
/** The Lua table that holds the callbacks to be invoked. */
cLuaState::cTableRefPtr m_Callbacks;
@ -120,7 +119,3 @@ protected:
virtual void OnRemoteClosed(void) override;
// The OnError() callback is shared with cNetwork::cConnectCallbacks
};

View File

@ -10,7 +10,7 @@
cLuaUDPEndpoint::cLuaUDPEndpoint(cLuaState::cTableRefPtr && a_Callbacks):
cLuaUDPEndpoint::cLuaUDPEndpoint(cLuaState::cTableRefPtr && a_Callbacks) :
m_Callbacks(std::move(a_Callbacks))
{
}
@ -165,7 +165,12 @@ void cLuaUDPEndpoint::Terminated(void)
void cLuaUDPEndpoint::OnReceivedData(const char * a_Data, size_t a_NumBytes, const AString & a_RemotePeer, UInt16 a_RemotePort)
void cLuaUDPEndpoint::OnReceivedData(
const char * a_Data,
size_t a_NumBytes,
const AString & a_RemotePeer,
UInt16 a_RemotePort
)
{
m_Callbacks->CallTableFn("OnReceivedData", this, AString(a_Data, a_NumBytes), a_RemotePeer, a_RemotePort);
}
@ -182,7 +187,3 @@ void cLuaUDPEndpoint::OnError(int a_ErrorCode, const AString & a_ErrorMsg)
// Terminate all processing on the endpoint:
Terminated();
}

View File

@ -24,17 +24,17 @@ typedef std::shared_ptr<cLuaUDPEndpoint> cLuaUDPEndpointPtr;
class cLuaUDPEndpoint:
public cUDPEndpoint::cCallbacks
class cLuaUDPEndpoint : public cUDPEndpoint::cCallbacks
{
public:
public:
/** Creates a new instance of the endpoint, wrapping the callbacks that are in the specified table. */
cLuaUDPEndpoint(cLuaState::cTableRefPtr && a_Callbacks);
virtual ~cLuaUDPEndpoint() override;
/** Opens the endpoint so that it starts listening for incoming data on the specified port.
a_Self is the shared pointer to self that the object keeps to keep itself alive for as long as it needs (for Lua). */
a_Self is the shared pointer to self that the object keeps to keep itself alive for as long as it needs (for Lua).
*/
bool Open(UInt16 a_Port, cLuaUDPEndpointPtr a_Self);
/** Sends the data contained in the string to the specified remote peer.
@ -57,7 +57,7 @@ public:
Releases the internal SharedPtr to self, so that the instance may be deallocated. */
void Release(void);
protected:
protected:
/** The Lua table that holds the callbacks to be invoked. */
cLuaState::cTableRefPtr m_Callbacks;
@ -75,9 +75,6 @@ protected:
// cUDPEndpoint::cCallbacks overrides:
virtual void OnError(int a_ErrorCode, const AString & a_ErrorMsg) override;
virtual void OnReceivedData(const char * a_Data, size_t a_Size, const AString & a_RemotePeer, UInt16 a_RemotePort) override;
virtual void OnReceivedData(const char * a_Data, size_t a_Size, const AString & a_RemotePeer, UInt16 a_RemotePort)
override;
};

View File

@ -9,7 +9,7 @@
#include "PluginLua.h"
extern "C"
{
#include "lua/src/lauxlib.h" // Needed for LUA_REFNIL
#include "lua/src/lauxlib.h" // Needed for LUA_REFNIL
}
#include "../Root.h"
#include "../ClientHandle.h"
@ -20,12 +20,18 @@ extern "C"
////////////////////////////////////////////////////////////////////////////////
// cLuaWindow:
cLuaWindow::cLuaWindow(cLuaState & a_LuaState, cWindow::WindowType a_WindowType, int a_SlotsX, int a_SlotsY, const AString & a_Title) :
Super(a_WindowType, a_Title),
m_Contents(a_SlotsX, a_SlotsY),
m_LuaState(a_LuaState.QueryCanonLuaState())
cLuaWindow::cLuaWindow(
cLuaState & a_LuaState,
cWindow::WindowType a_WindowType,
int a_SlotsX,
int a_SlotsY,
const AString & a_Title
) :
Super(a_WindowType, a_Title), m_Contents(a_SlotsX, a_SlotsY), m_LuaState(a_LuaState.QueryCanonLuaState())
{
ASSERT(m_LuaState != nullptr); // We must have a valid Lua state; this assert fails only if there was no Canon Lua state
ASSERT(
m_LuaState != nullptr
); // We must have a valid Lua state; this assert fails only if there was no Canon Lua state
m_Contents.AddListener(*this);
m_SlotAreas.push_back(new cSlotAreaItemGrid(m_Contents, *this));
@ -57,7 +63,8 @@ cLuaWindow::~cLuaWindow()
m_Contents.RemoveListener(*this);
// Close open lua window from players, to avoid dangling pointers
cRoot::Get()->ForEachPlayer([this](cPlayer & a_Player)
cRoot::Get()->ForEachPlayer(
[this](cPlayer & a_Player)
{
if (a_Player.GetWindow() == this)
{
@ -123,7 +130,8 @@ void cLuaWindow::SetOnSlotChanged(cLuaState::cCallbackPtr && a_OnSlotChanged)
void cLuaWindow::OpenedByPlayer(cPlayer & a_Player)
{
// If the first player is opening the window, create a Lua Reference to the window object so that Lua will not GC it until the last player closes the window:
// If the first player is opening the window, create a Lua Reference to the window object so that Lua will not GC it
// until the last player closes the window:
if (m_PlayerCount == 0)
{
m_LuaRef.CreateFromObject(*m_LuaState, this);
@ -143,9 +151,8 @@ bool cLuaWindow::ClosedByPlayer(cPlayer & a_Player, bool a_CanRefuse)
if (m_OnClosing != nullptr)
{
bool res;
if (
m_OnClosing->Call(this, &a_Player, a_CanRefuse, cLuaState::Return, res) && // The callback succeeded
res // The callback says not to close the window
if (m_OnClosing->Call(this, &a_Player, a_CanRefuse, cLuaState::Return, res) && // The callback succeeded
res // The callback says not to close the window
)
{
// The callback disagrees (the higher levels check the CanRefuse flag compliance)
@ -179,7 +186,13 @@ void cLuaWindow::Destroy(void)
void cLuaWindow::DistributeStack(cItem & a_ItemStack, int a_Slot, cPlayer & a_Player, cSlotArea * a_ClickedArea, bool a_ShouldApply)
void cLuaWindow::DistributeStack(
cItem & a_ItemStack,
int a_Slot,
cPlayer & a_Player,
cSlotArea * a_ClickedArea,
bool a_ShouldApply
)
{
cSlotAreas Areas;
for (auto && Area : m_SlotAreas)
@ -212,7 +225,13 @@ void cLuaWindow::OnSlotChanged(cItemGrid * a_ItemGrid, int a_SlotNum)
void cLuaWindow::Clicked(cPlayer & a_Player, int a_WindowID, short a_SlotNum, eClickAction a_ClickAction, const cItem & a_ClickedItem)
void cLuaWindow::Clicked(
cPlayer & a_Player,
int a_WindowID,
short a_SlotNum,
eClickAction a_ClickAction,
const cItem & a_ClickedItem
)
{
if (m_OnClicked != nullptr)
{
@ -229,7 +248,3 @@ void cLuaWindow::Clicked(cPlayer & a_Player, int a_WindowID, short a_SlotNum, eC
cWindow::Clicked(a_Player, a_WindowID, a_SlotNum, a_ClickAction, a_ClickedItem);
}

View File

@ -29,17 +29,23 @@ This object needs extra care with its lifetime management:
removes the reference when the last player closes the window.
*/
// tolua_begin
class cLuaWindow :
public cWindow
class cLuaWindow : public cWindow
// tolua_end
, public cItemGrid::cListener
,
public cItemGrid::cListener
{ // tolua_export
using Super = cWindow;
public:
public:
/** Create a window of the specified type, with a slot grid of a_SlotsX * a_SlotsY size.
Exported in ManualBindings.cpp */
cLuaWindow(cLuaState & a_LuaState, cWindow::WindowType a_WindowType, int a_SlotsX, int a_SlotsY, const AString & a_Title);
cLuaWindow(
cLuaState & a_LuaState,
cWindow::WindowType a_WindowType,
int a_SlotsX,
int a_SlotsY,
const AString & a_Title
);
// tolua_begin
virtual ~cLuaWindow() override;
@ -59,8 +65,7 @@ public:
/** Sets the Lua callback function to call when a slot is changed */
void SetOnSlotChanged(cLuaState::cCallbackPtr && a_OnSlotChanged);
protected:
protected:
/** Contents of the non-inventory part */
cItemGrid m_Contents;
@ -88,19 +93,22 @@ protected:
// cWindow overrides:
virtual void OpenedByPlayer(cPlayer & a_Player) override;
virtual void Clicked(
cPlayer & a_Player, int a_WindowID,
short a_SlotNum, eClickAction a_ClickAction,
cPlayer & a_Player,
int a_WindowID,
short a_SlotNum,
eClickAction a_ClickAction,
const cItem & a_ClickedItem
) override;
virtual bool ClosedByPlayer(cPlayer & a_Player, bool a_CanRefuse) override;
virtual void Destroy(void) override;
virtual void DistributeStack(cItem & a_ItemStack, int a_Slot, cPlayer & a_Player, cSlotArea * a_ClickedArea, bool a_ShouldApply) override;
virtual void DistributeStack(
cItem & a_ItemStack,
int a_Slot,
cPlayer & a_Player,
cSlotArea * a_ClickedArea,
bool a_ShouldApply
) override;
// cItemGrid::cListener overrides:
virtual void OnSlotChanged(cItemGrid * a_ItemGrid, int a_SlotNum) override;
} ; // tolua_export
}; // tolua_export

File diff suppressed because it is too large Load Diff

View File

@ -25,11 +25,11 @@ class cPluginLua;
/** Provides namespace for the bindings. */
class cManualBindings
{
public:
public:
/** Binds all the manually implemented functions to tolua_S. */
static void Bind(lua_State * tolua_S);
protected:
protected:
/** Binds the manually implemented cNetwork-related API to tolua_S.
Implemented in ManualBindings_Network.cpp. */
static void BindNetwork(lua_State * tolua_S);
@ -47,32 +47,24 @@ protected:
static void BindBlockArea(lua_State * tolua_S);
public:
public:
// Helper functions:
static cPluginLua * GetLuaPlugin(lua_State * L);
static int tolua_do_error(lua_State * L, const char * a_pMsg, tolua_Error * a_pToLuaError);
static int vlua_do_error(lua_State * L, const char * a_pFormat, fmt::printf_args a_ArgList);
template <typename... Args>
static int lua_do_error(lua_State * L, const char * a_Format, const Args & ... a_Args)
template <typename... Args> static int lua_do_error(lua_State * L, const char * a_Format, const Args &... a_Args)
{
return vlua_do_error(L, a_Format, fmt::make_printf_args(a_Args...));
}
/** Binds the DoWith(ItemName) functions of regular classes. */
template <
class Ty1,
class Ty2,
bool (Ty1::*DoWithFn)(const AString &, cFunctionRef<bool(Ty2 &)>)
>
template <class Ty1, class Ty2, bool (Ty1::*DoWithFn)(const AString &, cFunctionRef<bool(Ty2 &)>)>
static int DoWith(lua_State * tolua_S)
{
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamString(2) ||
!L.CheckParamFunction(3)
)
if (!L.CheckParamString(2) || !L.CheckParamFunction(3))
{
return 0;
}
@ -88,15 +80,23 @@ public:
}
if (ItemName.empty() || (ItemName[0] == 0))
{
return lua_do_error(tolua_S, "Error in function call '#funcname#': Expected a non-empty string for parameter #1");
return lua_do_error(
tolua_S,
"Error in function call '#funcname#': Expected a non-empty string for parameter #1"
);
}
if (!FnRef.IsValid())
{
return lua_do_error(tolua_S, "Error in function call '#funcname#': Expected a valid callback function for parameter #2");
return lua_do_error(
tolua_S,
"Error in function call '#funcname#': Expected a valid callback function for parameter #2"
);
}
// Call the DoWith function:
bool res = (Self->*DoWithFn)(ItemName, [&](Ty2 & a_Item)
bool res = (Self->*DoWithFn)(
ItemName,
[&](Ty2 & a_Item)
{
bool ret = false;
L.Call(FnRef, &a_Item, cLuaState::Return, ret);
@ -114,19 +114,12 @@ public:
/** Template for static functions DoWith(ItemName), on a type that has a static ::Get() function. */
template <
class Ty1,
class Ty2,
bool (Ty1::*DoWithFn)(const AString &, cFunctionRef<bool(Ty2 &)>)
>
template <class Ty1, class Ty2, bool (Ty1::*DoWithFn)(const AString &, cFunctionRef<bool(Ty2 &)>)>
static int StaticDoWith(lua_State * tolua_S)
{
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamString(2) ||
!L.CheckParamFunction(3)
)
if (!L.CheckParamString(2) || !L.CheckParamFunction(3))
{
return 0;
}
@ -137,15 +130,23 @@ public:
L.GetStackValues(2, ItemName, FnRef);
if (ItemName.empty() || (ItemName[0] == 0))
{
return lua_do_error(tolua_S, "Error in function call '#funcname#': Expected a non-empty string for parameter #1");
return lua_do_error(
tolua_S,
"Error in function call '#funcname#': Expected a non-empty string for parameter #1"
);
}
if (!FnRef.IsValid())
{
return lua_do_error(tolua_S, "Error in function call '#funcname#': Expected a valid callback function for parameter #2");
return lua_do_error(
tolua_S,
"Error in function call '#funcname#': Expected a valid callback function for parameter #2"
);
}
// Call the DoWith function:
bool res = (Ty1::Get()->*DoWithFn)(ItemName, [&](Ty2 & a_Item)
bool res = (Ty1::Get()->*DoWithFn)(
ItemName,
[&](Ty2 & a_Item)
{
bool ret = false;
L.Call(FnRef, &a_Item, cLuaState::Return, ret);
@ -162,19 +163,12 @@ public:
template <
class Ty1,
class Ty2,
bool (Ty1::*DoWithFn)(UInt32, cFunctionRef<bool(Ty2 &)>)
>
template <class Ty1, class Ty2, bool (Ty1::*DoWithFn)(UInt32, cFunctionRef<bool(Ty2 &)>)>
static int DoWithID(lua_State * tolua_S)
{
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamNumber(2) ||
!L.CheckParamFunction(3)
)
if (!L.CheckParamNumber(2) || !L.CheckParamFunction(3))
{
return 0;
}
@ -190,11 +184,16 @@ public:
}
if (!FnRef.IsValid())
{
return lua_do_error(tolua_S, "Error in function call '#funcname#': Expected a valid callback function for parameter #2");
return lua_do_error(
tolua_S,
"Error in function call '#funcname#': Expected a valid callback function for parameter #2"
);
}
// Call the DoWith function:
bool res = (Self->*DoWithFn)(ItemID, [&](Ty2 & a_Item)
bool res = (Self->*DoWithFn)(
ItemID,
[&](Ty2 & a_Item)
{
bool ret = false;
L.Call(FnRef, &a_Item, cLuaState::Return, ret);
@ -211,19 +210,12 @@ public:
template <
class Ty1,
class Ty2,
bool (Ty1::*ForEachFn)(cFunctionRef<bool(Ty2 &)>)
>
template <class Ty1, class Ty2, bool (Ty1::*ForEachFn)(cFunctionRef<bool(Ty2 &)>)>
static int ForEach(lua_State * tolua_S)
{
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamFunction(2) ||
!L.CheckParamEnd(3)
)
if (!L.CheckParamFunction(2) || !L.CheckParamEnd(3))
{
return 0;
}
@ -238,11 +230,15 @@ public:
}
if (!FnRef.IsValid())
{
return lua_do_error(tolua_S, "Error in function call '#funcname#': Expected a valid callback function for parameter #1");
return lua_do_error(
tolua_S,
"Error in function call '#funcname#': Expected a valid callback function for parameter #1"
);
}
// Call the enumeration:
bool res = (Self->*ForEachFn)([&](Ty2 & a_Item)
bool res = (Self->*ForEachFn)(
[&](Ty2 & a_Item)
{
bool ret = false; // By default continue the enumeration
L.Call(FnRef, &a_Item, cLuaState::Return, ret);
@ -260,19 +256,12 @@ public:
/** Implements bindings for ForEach() functions in a class that is static (has a ::Get() static function). */
template <
class Ty1,
class Ty2,
bool (Ty1::*ForEachFn)(cFunctionRef<bool(Ty2 &)>)
>
template <class Ty1, class Ty2, bool (Ty1::*ForEachFn)(cFunctionRef<bool(Ty2 &)>)>
static int StaticForEach(lua_State * tolua_S)
{
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamFunction(2) ||
!L.CheckParamEnd(3)
)
if (!L.CheckParamFunction(2) || !L.CheckParamEnd(3))
{
return 0;
}
@ -281,11 +270,15 @@ public:
cLuaState::cRef FnRef(L, 2);
if (!FnRef.IsValid())
{
return lua_do_error(tolua_S, "Error in function call '#funcname#': Expected a valid callback function for parameter #1");
return lua_do_error(
tolua_S,
"Error in function call '#funcname#': Expected a valid callback function for parameter #1"
);
}
// Call the enumeration:
bool res = (Ty1::Get()->*ForEachFn)([&](Ty2 & a_Item)
bool res = (Ty1::Get()->*ForEachFn)(
[&](Ty2 & a_Item)
{
bool ret = false; // By default continue the enumeration
L.Call(FnRef, &a_Item, cLuaState::Return, ret);

View File

@ -20,17 +20,12 @@ template <
class SELF,
class ITEM,
bool (SELF::*DoWithFn)(int, int, int, cFunctionRef<bool(ITEM &)>),
bool (SELF::*CoordCheckFn)(int, int, int) const
>
bool (SELF::*CoordCheckFn)(int, int, int) const>
static int DoWithXYZ(lua_State * tolua_S)
{
// Check params:
cLuaState L(tolua_S);
if (
!L.CheckParamNumber(2, 4) ||
!L.CheckParamFunction(5) ||
!L.CheckParamEnd(6)
)
if (!L.CheckParamNumber(2, 4) || !L.CheckParamFunction(5) || !L.CheckParamEnd(6))
{
return 0;
}
@ -52,13 +47,17 @@ static int DoWithXYZ(lua_State * tolua_S)
}
if (!(Self->*CoordCheckFn)(BlockX, BlockY, BlockZ))
{
return L.ApiParamError(fmt::format(FMT_STRING("The provided coordinates ({0}) are not valid"),
Vector3i{BlockX, BlockY, BlockZ}
));
return L.ApiParamError(
fmt::format(FMT_STRING("The provided coordinates ({0}) are not valid"), Vector3i {BlockX, BlockY, BlockZ})
);
}
// Call the DoWith function:
bool res = (Self->*DoWithFn)(BlockX, BlockY, BlockZ, [&](ITEM & a_Item)
bool res = (Self->*DoWithFn)(
BlockX,
BlockY,
BlockZ,
[&](ITEM & a_Item)
{
bool ret = false;
L.Call(FnRef, &a_Item, cLuaState::Return, ret);
@ -88,7 +87,15 @@ static int readCuboidOverloadParams(cLuaState & a_LuaState, int a_StartParam, cC
if (a_LuaState.IsParamNumber(a_StartParam))
{
// Assume the 6-number version:
if (!a_LuaState.GetStackValues(a_StartParam, a_Cuboid.p1.x, a_Cuboid.p2.x, a_Cuboid.p1.y, a_Cuboid.p2.y, a_Cuboid.p1.z, a_Cuboid.p2.z))
if (!a_LuaState.GetStackValues(
a_StartParam,
a_Cuboid.p1.x,
a_Cuboid.p2.x,
a_Cuboid.p1.y,
a_Cuboid.p2.y,
a_Cuboid.p1.z,
a_Cuboid.p2.z
))
{
return a_LuaState.ApiParamError("Cannot read the bounds parameters, expected 6 numbers");
}
@ -127,14 +134,21 @@ These can be:
Returns the index of the first parameter following the Vector3i spec.
Raises an Api error if the params don't specify a Vector3i.
*/
static int readVector3iOverloadParams(cLuaState & a_LuaState, int a_StartParam, Vector3i & a_Coords, const char * a_ParamName)
static int readVector3iOverloadParams(
cLuaState & a_LuaState,
int a_StartParam,
Vector3i & a_Coords,
const char * a_ParamName
)
{
if (a_LuaState.IsParamNumber(a_StartParam))
{
// Assume the 3-number version:
if (!a_LuaState.GetStackValues(a_StartParam, a_Coords.x, a_Coords.y, a_Coords.z))
{
return a_LuaState.ApiParamError(fmt::format(FMT_STRING("Cannot read the {}, expected 3 numbers"), a_ParamName));
return a_LuaState.ApiParamError(
fmt::format(FMT_STRING("Cannot read the {}, expected 3 numbers"), a_ParamName)
);
}
return a_StartParam + 3;
}
@ -143,7 +157,9 @@ static int readVector3iOverloadParams(cLuaState & a_LuaState, int a_StartParam,
// Assume the Vector3i version:
if (!a_LuaState.GetStackValues(a_StartParam, a_Coords))
{
return a_LuaState.ApiParamError(fmt::format(FMT_STRING("Cannot read the {}, expected a Vector3i instance"), a_ParamName));
return a_LuaState.ApiParamError(
fmt::format(FMT_STRING("Cannot read the {}, expected a Vector3i instance"), a_ParamName)
);
}
return a_StartParam + 1;
}
@ -177,7 +193,9 @@ static int tolua_cBlockArea_Create(lua_State * a_LuaState)
L.GetStackValue(dataTypesIdx, dataTypes);
if (!cBlockArea::IsValidDataTypeCombination(dataTypes))
{
return L.ApiParamError(fmt::format(FMT_STRING("Invalid combination of baDataTypes specified (0x{:02x})"), dataTypes));
return L.ApiParamError(
fmt::format(FMT_STRING("Invalid combination of baDataTypes specified (0x{:02x})"), dataTypes)
);
}
// Create the area:
@ -226,7 +244,7 @@ static int tolua_cBlockArea_FillRelCuboid(lua_State * a_LuaState)
bounds.p1,
bounds.p2,
Vector3i(0, 0, 0),
(self->GetSize() - Vector3i{1, 1, 1})
(self->GetSize() - Vector3i {1, 1, 1})
));
}
int dataTypes = cBlockArea::baTypes | cBlockArea::baMetas | cBlockArea::baBlockEntities;
@ -275,8 +293,11 @@ static int tolua_cBlockArea_GetBlockTypeMeta(lua_State * a_LuaState)
readVector3iOverloadParams(L, 2, coords, "coords");
if (!self->IsValidCoords(coords))
{
return L.ApiParamError(fmt::format(FMT_STRING("Coords ({0}) out of range ({1} - {2})"),
coords, self->GetOrigin(), self->GetOrigin() + self->GetSize() - Vector3i{1, 1, 1}
return L.ApiParamError(fmt::format(
FMT_STRING("Coords ({0}) out of range ({1} - {2})"),
coords,
self->GetOrigin(),
self->GetOrigin() + self->GetSize() - Vector3i {1, 1, 1}
));
}
BLOCKTYPE blockType;
@ -425,8 +446,10 @@ static int tolua_cBlockArea_GetRelBlockTypeMeta(lua_State * a_LuaState)
readVector3iOverloadParams(L, 2, coords, "coords");
if (!self->IsValidRelCoords(coords))
{
return L.ApiParamError(fmt::format(FMT_STRING("The coords ({0}) are out of range (max {1})"),
coords, (self->GetSize() - Vector3i{1, 1, 1})
return L.ApiParamError(fmt::format(
FMT_STRING("The coords ({0}) are out of range (max {1})"),
coords,
(self->GetSize() - Vector3i {1, 1, 1})
));
}
BLOCKTYPE blockType;
@ -476,11 +499,7 @@ static int tolua_cBlockArea_LoadFromSchematicFile(lua_State * a_LuaState)
// function cBlockArea::LoadFromSchematicFile
// Exported manually because function has been moved to SchematicFileSerializer.cpp
cLuaState L(a_LuaState);
if (
!L.CheckParamSelf("cBlockArea") ||
!L.CheckParamString(2) ||
!L.CheckParamEnd(3)
)
if (!L.CheckParamSelf("cBlockArea") || !L.CheckParamString(2) || !L.CheckParamEnd(3))
{
return 0;
}
@ -518,11 +537,7 @@ static int tolua_cBlockArea_LoadFromSchematicString(lua_State * a_LuaState)
// function cBlockArea::LoadFromSchematicString
// Exported manually because function has been moved to SchematicFileSerializer.cpp
cLuaState L(a_LuaState);
if (
!L.CheckParamSelf("cBlockArea") ||
!L.CheckParamString(2) ||
!L.CheckParamEnd(3)
)
if (!L.CheckParamSelf("cBlockArea") || !L.CheckParamString(2) || !L.CheckParamEnd(3))
{
return 0;
}
@ -560,10 +575,7 @@ static int tolua_cBlockArea_Read(lua_State * a_LuaState)
{
// Check the common params:
cLuaState L(a_LuaState);
if (
!L.CheckParamSelf("cBlockArea") ||
!L.CheckParamUserType(2, "cWorld")
)
if (!L.CheckParamSelf("cBlockArea") || !L.CheckParamUserType(2, "cWorld"))
{
return 0;
}
@ -593,7 +605,9 @@ static int tolua_cBlockArea_Read(lua_State * a_LuaState)
// Check the coords:
if (!cChunkDef::IsValidHeight(bounds.p1) || !cChunkDef::IsValidHeight(bounds.p2))
{
return L.ApiParamError(fmt::format(FMT_STRING("Coordinates {0} - {1} exceed world bounds"), bounds.p1, bounds.p2));
return L.ApiParamError(
fmt::format(FMT_STRING("Coordinates {0} - {1} exceed world bounds"), bounds.p1, bounds.p2)
);
}
bounds.Sort();
@ -642,7 +656,8 @@ static int tolua_cBlockArea_RelLine(lua_State * a_LuaState)
{
return L.ApiParamError(fmt::format(
FMT_STRING("Requested datatypes not present in the cBlockArea. Got only 0x{:02x}, requested 0x{:02x}"),
self->GetDataTypes(), dataTypes
self->GetDataTypes(),
dataTypes
));
}
@ -660,11 +675,7 @@ static int tolua_cBlockArea_SaveToSchematicFile(lua_State * a_LuaState)
// function cBlockArea::SaveToSchematicFile
// Exported manually because function has been moved to SchematicFileSerializer.cpp
cLuaState L(a_LuaState);
if (
!L.CheckParamSelf("cBlockArea") ||
!L.CheckParamString(2) ||
!L.CheckParamEnd(3)
)
if (!L.CheckParamSelf("cBlockArea") || !L.CheckParamString(2) || !L.CheckParamEnd(3))
{
return 0;
}
@ -702,10 +713,7 @@ static int tolua_cBlockArea_SaveToSchematicString(lua_State * a_LuaState)
// function cBlockArea::SaveToSchematicString
// Exported manually because function has been moved to SchematicFileSerializer.cpp
cLuaState L(a_LuaState);
if (
!L.CheckParamSelf("cBlockArea") ||
!L.CheckParamEnd(2)
)
if (!L.CheckParamSelf("cBlockArea") || !L.CheckParamEnd(2))
{
return 0;
}
@ -741,10 +749,7 @@ static int tolua_cBlockArea_Write(lua_State * a_LuaState)
{
// Check the common params:
cLuaState L(a_LuaState);
if (
!L.CheckParamSelf("cBlockArea") ||
!L.CheckParamUserType(2, "cWorld")
)
if (!L.CheckParamSelf("cBlockArea") || !L.CheckParamUserType(2, "cWorld"))
{
return 0;
}
@ -778,14 +783,16 @@ static int tolua_cBlockArea_Write(lua_State * a_LuaState)
{
return L.ApiParamError(fmt::format(
FMT_STRING("Requesting datatypes not present in the cBlockArea. Got only 0x{:02x}, requested 0x{:02x}"),
self->GetDataTypes(), dataTypes
self->GetDataTypes(),
dataTypes
));
}
}
// Check and adjust the coord params:
// TODO: Should we report this as a failure? Because the result is definitely not what the plugin assumed
// ... Or should we silently clone-crop-write the cBlockArea so that the API call does what would be naturally expected?
// ... Or should we silently clone-crop-write the cBlockArea so that the API call does what would be naturally
// expected?
// ... Or should we change the cBlockArea::Write() to allow out-of-range Y coords and do the cropping there?
// ... NOTE: We already support auto-crop in cBlockArea::Merge() itself
if (coords.y < 0)
@ -822,11 +829,7 @@ DataType is either BLOCKTYPE or NIBBLETYPE.
DataTypeFlag is the ba___ constant used for the datatype being queried.
Fn is the getter function.
Also supports the Vector3i overloads (TODO: document these (?)). */
template <
typename DataType,
int DataTypeFlag,
DataType (cBlockArea::*Fn)(int, int, int) const
>
template <typename DataType, int DataTypeFlag, DataType (cBlockArea::*Fn)(int, int, int) const>
static int GetBlock(lua_State * a_LuaState)
{
// Check the common params:
@ -846,7 +849,8 @@ static int GetBlock(lua_State * a_LuaState)
// Check the datatype's presence:
if ((self->GetDataTypes() & DataTypeFlag) == 0)
{
return L.ApiParamError(fmt::format(FMT_STRING("The area doesn't contain the datatype (0x{:02x})"), DataTypeFlag));
return L.ApiParamError(fmt::format(FMT_STRING("The area doesn't contain the datatype (0x{:02x})"), DataTypeFlag)
);
}
// Read the overloaded params:
@ -854,8 +858,11 @@ static int GetBlock(lua_State * a_LuaState)
readVector3iOverloadParams(L, 2, coords, "coords");
if (!self->IsValidCoords(coords))
{
return L.ApiParamError(fmt::format(FMT_STRING("The coords ({0}) are out of range ({1} - {2})"),
coords, self->GetOrigin(), self->GetOrigin() + self->GetSize() - Vector3i{1, 1, 1}
return L.ApiParamError(fmt::format(
FMT_STRING("The coords ({0}) are out of range ({1} - {2})"),
coords,
self->GetOrigin(),
self->GetOrigin() + self->GetSize() - Vector3i {1, 1, 1}
));
}
@ -873,11 +880,7 @@ DataType is either BLOCKTYPE or NIBBLETYPE.
DataTypeFlag is the ba___ constant used for the datatype being queried.
Fn is the getter function.
Also supports the Vector3i overloads (TODO: document these (?)). */
template <
typename DataType,
int DataTypeFlag,
DataType (cBlockArea::*Fn)(int, int, int) const
>
template <typename DataType, int DataTypeFlag, DataType (cBlockArea::*Fn)(int, int, int) const>
static int GetRelBlock(lua_State * a_LuaState)
{
// Check the common params:
@ -897,7 +900,8 @@ static int GetRelBlock(lua_State * a_LuaState)
// Check the datatype's presence:
if ((self->GetDataTypes() & DataTypeFlag) == 0)
{
return L.ApiParamError(fmt::format(FMT_STRING("The area doesn't contain the datatype (0x{:02x})"), DataTypeFlag));
return L.ApiParamError(fmt::format(FMT_STRING("The area doesn't contain the datatype (0x{:02x})"), DataTypeFlag)
);
}
// Read the overloaded params:
@ -905,8 +909,10 @@ static int GetRelBlock(lua_State * a_LuaState)
readVector3iOverloadParams(L, 2, coords, "coords");
if (!self->IsValidRelCoords(coords))
{
return L.ApiParamError(fmt::format(FMT_STRING("The coords ({0}) are out of range ({1})"),
coords, (self->GetSize() - Vector3i(1, 1, 1))
return L.ApiParamError(fmt::format(
FMT_STRING("The coords ({0}) are out of range ({1})"),
coords,
(self->GetSize() - Vector3i(1, 1, 1))
));
}
@ -924,11 +930,7 @@ DataType is either BLOCKTYPE or NIBBLETYPE.
DataTypeFlag is the ba___ constant used for the datatypebeing manipulated.
Fn is the setter function.
Also supports the Vector3i overloads (TODO: document these (?)). */
template <
typename DataType,
int DataTypeFlag,
void (cBlockArea::*Fn)(int, int, int, DataType)
>
template <typename DataType, int DataTypeFlag, void (cBlockArea::*Fn)(int, int, int, DataType)>
static int SetBlock(lua_State * a_LuaState)
{
// Check the common params:
@ -948,7 +950,8 @@ static int SetBlock(lua_State * a_LuaState)
// Check the datatype's presence:
if ((self->GetDataTypes() & DataTypeFlag) == 0)
{
return L.ApiParamError(fmt::format(FMT_STRING("The area doesn't contain the datatype (0x{:02x})"), DataTypeFlag));
return L.ApiParamError(fmt::format(FMT_STRING("The area doesn't contain the datatype (0x{:02x})"), DataTypeFlag)
);
}
// Read the overloaded params:
@ -956,8 +959,11 @@ static int SetBlock(lua_State * a_LuaState)
auto idx = readVector3iOverloadParams(L, 2, coords, "coords");
if (!self->IsValidCoords(coords))
{
return L.ApiParamError(fmt::format(FMT_STRING("The coords ({0}) are out of range ({1} - {2})"),
coords, self->GetOrigin(), self->GetOrigin() + self->GetSize() - Vector3i{1, 1, 1}
return L.ApiParamError(fmt::format(
FMT_STRING("The coords ({0}) are out of range ({1} - {2})"),
coords,
self->GetOrigin(),
self->GetOrigin() + self->GetSize() - Vector3i {1, 1, 1}
));
}
DataType data;
@ -977,11 +983,7 @@ DataType is either BLOCKTYPE or NIBBLETYPE.
DataTypeFlag is the ba___ constant used for the datatypebeing manipulated.
Fn is the setter function.
Also supports the Vector3i overloads (TODO: document these (?)). */
template <
typename DataType,
int DataTypeFlag,
void (cBlockArea::*Fn)(int, int, int, DataType)
>
template <typename DataType, int DataTypeFlag, void (cBlockArea::*Fn)(int, int, int, DataType)>
static int SetRelBlock(lua_State * a_LuaState)
{
// Check the common params:
@ -1001,7 +1003,8 @@ static int SetRelBlock(lua_State * a_LuaState)
// Check the datatype's presence:
if ((self->GetDataTypes() & DataTypeFlag) == 0)
{
return L.ApiParamError(fmt::format(FMT_STRING("The area doesn't contain the datatype (0x{:02x})"), DataTypeFlag));
return L.ApiParamError(fmt::format(FMT_STRING("The area doesn't contain the datatype (0x{:02x})"), DataTypeFlag)
);
}
// Read the overloaded params:
@ -1011,7 +1014,8 @@ static int SetRelBlock(lua_State * a_LuaState)
{
return L.ApiParamError(fmt::format(
FMT_STRING("The coords ({0}) are out of range ({1})"),
coords, (self->GetSize() - Vector3i(1, 1, 1))
coords,
(self->GetSize() - Vector3i(1, 1, 1))
));
}
DataType data;
@ -1053,8 +1057,11 @@ static int tolua_cBlockArea_SetBlockTypeMeta(lua_State * a_LuaState)
auto idx = readVector3iOverloadParams(L, 2, coords, "coords");
if (!self->IsValidCoords(coords))
{
return L.ApiParamError(fmt::format(FMT_STRING("The coords ({0}) are out of range ({1} - {2})"),
coords, self->GetOrigin(), self->GetOrigin() + self->GetSize() - Vector3i{1, 1, 1}
return L.ApiParamError(fmt::format(
FMT_STRING("The coords ({0}) are out of range ({1} - {2})"),
coords,
self->GetOrigin(),
self->GetOrigin() + self->GetSize() - Vector3i {1, 1, 1}
));
}
@ -1093,7 +1100,10 @@ static int tolua_cBlockArea_SetRelBlockTypeMeta(lua_State * a_LuaState)
// Check if block types and metas are present:
if (!self->HasBlockTypes() || !self->HasBlockMetas())
{
return L.ApiParamError(fmt::format(FMT_STRING("The area doesn't contain the baTypes or baMetas datatypes (0x{:02x})"), self->GetDataTypes()));
return L.ApiParamError(fmt::format(
FMT_STRING("The area doesn't contain the baTypes or baMetas datatypes (0x{:02x})"),
self->GetDataTypes()
));
}
// Read the overloaded params:
@ -1101,8 +1111,10 @@ static int tolua_cBlockArea_SetRelBlockTypeMeta(lua_State * a_LuaState)
auto idx = readVector3iOverloadParams(L, 2, coords, "coords");
if (!self->IsValidRelCoords(coords))
{
return L.ApiParamError(fmt::format(FMT_STRING("The coords ({0}) are out of range ({1})"),
coords, (self->GetSize() - Vector3i(1, 1, 1))
return L.ApiParamError(fmt::format(
FMT_STRING("The coords ({0}) are out of range ({1})"),
coords,
(self->GetSize() - Vector3i(1, 1, 1))
));
}
@ -1125,47 +1137,43 @@ static int tolua_cBlockArea_SetRelBlockTypeMeta(lua_State * a_LuaState)
void cManualBindings::BindBlockArea(lua_State * a_LuaState)
{
tolua_beginmodule(a_LuaState, nullptr);
tolua_beginmodule(a_LuaState, "cBlockArea");
tolua_function(a_LuaState, "Create", tolua_cBlockArea_Create);
tolua_function(a_LuaState, "DoWithBlockEntityAt", DoWithXYZ<cBlockArea, cBlockEntity, &cBlockArea::DoWithBlockEntityAt, &cBlockArea::IsValidCoords>);
tolua_function(a_LuaState, "DoWithBlockEntityRelAt", DoWithXYZ<cBlockArea, cBlockEntity, &cBlockArea::DoWithBlockEntityRelAt, &cBlockArea::IsValidRelCoords>);
tolua_function(a_LuaState, "FillRelCuboid", tolua_cBlockArea_FillRelCuboid);
tolua_function(a_LuaState, "ForEachBlockEntity", ForEach< cBlockArea, cBlockEntity, &cBlockArea::ForEachBlockEntity>);
tolua_function(a_LuaState, "GetBlockLight", GetBlock<NIBBLETYPE, cBlockArea::baLight, &cBlockArea::GetRelBlockLight>);
tolua_function(a_LuaState, "GetBlockMeta", GetBlock<NIBBLETYPE, cBlockArea::baMetas, &cBlockArea::GetRelBlockMeta>);
tolua_function(a_LuaState, "GetBlockSkyLight", GetBlock<NIBBLETYPE, cBlockArea::baSkyLight, &cBlockArea::GetRelBlockSkyLight>);
tolua_function(a_LuaState, "GetBlockType", GetBlock<BLOCKTYPE, cBlockArea::baTypes, &cBlockArea::GetRelBlockType>);
tolua_function(a_LuaState, "GetBlockTypeMeta", tolua_cBlockArea_GetBlockTypeMeta);
tolua_function(a_LuaState, "GetCoordRange", tolua_cBlockArea_GetCoordRange);
tolua_function(a_LuaState, "GetNonAirCropRelCoords", tolua_cBlockArea_GetNonAirCropRelCoords);
tolua_function(a_LuaState, "GetOrigin", tolua_cBlockArea_GetOrigin);
tolua_function(a_LuaState, "GetRelBlockLight", GetRelBlock<NIBBLETYPE, cBlockArea::baLight, &cBlockArea::GetRelBlockLight>);
tolua_function(a_LuaState, "GetRelBlockMeta", GetRelBlock<NIBBLETYPE, cBlockArea::baMetas, &cBlockArea::GetRelBlockMeta>);
tolua_function(a_LuaState, "GetRelBlockSkyLight", GetRelBlock<NIBBLETYPE, cBlockArea::baSkyLight, &cBlockArea::GetRelBlockSkyLight>);
tolua_function(a_LuaState, "GetRelBlockType", GetRelBlock<BLOCKTYPE, cBlockArea::baTypes, &cBlockArea::GetRelBlockType>);
tolua_function(a_LuaState, "GetRelBlockTypeMeta", tolua_cBlockArea_GetRelBlockTypeMeta);
tolua_function(a_LuaState, "GetSize", tolua_cBlockArea_GetSize);
tolua_function(a_LuaState, "LoadFromSchematicFile", tolua_cBlockArea_LoadFromSchematicFile);
tolua_function(a_LuaState, "LoadFromSchematicString", tolua_cBlockArea_LoadFromSchematicString);
tolua_function(a_LuaState, "Read", tolua_cBlockArea_Read);
tolua_function(a_LuaState, "RelLine", tolua_cBlockArea_RelLine);
tolua_function(a_LuaState, "SaveToSchematicFile", tolua_cBlockArea_SaveToSchematicFile);
tolua_function(a_LuaState, "SaveToSchematicString", tolua_cBlockArea_SaveToSchematicString);
tolua_function(a_LuaState, "SetBlockType", SetBlock<BLOCKTYPE, cBlockArea::baTypes, &cBlockArea::SetRelBlockType>);
tolua_function(a_LuaState, "SetBlockMeta", SetBlock<NIBBLETYPE, cBlockArea::baMetas, &cBlockArea::SetRelBlockMeta>);
tolua_function(a_LuaState, "SetBlockLight", SetBlock<NIBBLETYPE, cBlockArea::baLight, &cBlockArea::SetRelBlockLight>);
tolua_function(a_LuaState, "SetBlockSkyLight", SetBlock<NIBBLETYPE, cBlockArea::baSkyLight, &cBlockArea::SetRelBlockSkyLight>);
tolua_function(a_LuaState, "SetBlockTypeMeta", tolua_cBlockArea_SetBlockTypeMeta);
tolua_function(a_LuaState, "SetRelBlockType", SetRelBlock<BLOCKTYPE, cBlockArea::baTypes, &cBlockArea::SetRelBlockType>);
tolua_function(a_LuaState, "SetRelBlockMeta", SetRelBlock<NIBBLETYPE, cBlockArea::baMetas, &cBlockArea::SetRelBlockMeta>);
tolua_function(a_LuaState, "SetRelBlockLight", SetRelBlock<NIBBLETYPE, cBlockArea::baLight, &cBlockArea::SetRelBlockLight>);
tolua_function(a_LuaState, "SetRelBlockSkyLight", SetRelBlock<NIBBLETYPE, cBlockArea::baSkyLight, &cBlockArea::SetRelBlockSkyLight>);
tolua_function(a_LuaState, "SetRelBlockTypeMeta", tolua_cBlockArea_SetRelBlockTypeMeta);
tolua_function(a_LuaState, "Write", tolua_cBlockArea_Write);
tolua_endmodule(a_LuaState);
tolua_beginmodule(a_LuaState, "cBlockArea");
tolua_function(a_LuaState, "Create", tolua_cBlockArea_Create);
tolua_function(a_LuaState, "DoWithBlockEntityAt", DoWithXYZ<cBlockArea, cBlockEntity, &cBlockArea::DoWithBlockEntityAt, &cBlockArea::IsValidCoords>);
tolua_function(a_LuaState, "DoWithBlockEntityRelAt", DoWithXYZ<cBlockArea, cBlockEntity, &cBlockArea::DoWithBlockEntityRelAt, &cBlockArea::IsValidRelCoords>);
tolua_function(a_LuaState, "FillRelCuboid", tolua_cBlockArea_FillRelCuboid);
tolua_function(a_LuaState, "ForEachBlockEntity", ForEach<cBlockArea, cBlockEntity, &cBlockArea::ForEachBlockEntity>);
tolua_function(a_LuaState, "GetBlockLight", GetBlock<NIBBLETYPE, cBlockArea::baLight, &cBlockArea::GetRelBlockLight>);
tolua_function(a_LuaState, "GetBlockMeta", GetBlock<NIBBLETYPE, cBlockArea::baMetas, &cBlockArea::GetRelBlockMeta>);
tolua_function(a_LuaState, "GetBlockSkyLight", GetBlock<NIBBLETYPE, cBlockArea::baSkyLight, &cBlockArea::GetRelBlockSkyLight>);
tolua_function(a_LuaState, "GetBlockType", GetBlock<BLOCKTYPE, cBlockArea::baTypes, &cBlockArea::GetRelBlockType>);
tolua_function(a_LuaState, "GetBlockTypeMeta", tolua_cBlockArea_GetBlockTypeMeta);
tolua_function(a_LuaState, "GetCoordRange", tolua_cBlockArea_GetCoordRange);
tolua_function(a_LuaState, "GetNonAirCropRelCoords", tolua_cBlockArea_GetNonAirCropRelCoords);
tolua_function(a_LuaState, "GetOrigin", tolua_cBlockArea_GetOrigin);
tolua_function(a_LuaState, "GetRelBlockLight", GetRelBlock<NIBBLETYPE, cBlockArea::baLight, &cBlockArea::GetRelBlockLight>);
tolua_function(a_LuaState, "GetRelBlockMeta", GetRelBlock<NIBBLETYPE, cBlockArea::baMetas, &cBlockArea::GetRelBlockMeta>);
tolua_function(a_LuaState, "GetRelBlockSkyLight", GetRelBlock<NIBBLETYPE, cBlockArea::baSkyLight, &cBlockArea::GetRelBlockSkyLight>);
tolua_function(a_LuaState, "GetRelBlockType", GetRelBlock<BLOCKTYPE, cBlockArea::baTypes, &cBlockArea::GetRelBlockType>);
tolua_function(a_LuaState, "GetRelBlockTypeMeta", tolua_cBlockArea_GetRelBlockTypeMeta);
tolua_function(a_LuaState, "GetSize", tolua_cBlockArea_GetSize);
tolua_function(a_LuaState, "LoadFromSchematicFile", tolua_cBlockArea_LoadFromSchematicFile);
tolua_function(a_LuaState, "LoadFromSchematicString", tolua_cBlockArea_LoadFromSchematicString);
tolua_function(a_LuaState, "Read", tolua_cBlockArea_Read);
tolua_function(a_LuaState, "RelLine", tolua_cBlockArea_RelLine);
tolua_function(a_LuaState, "SaveToSchematicFile", tolua_cBlockArea_SaveToSchematicFile);
tolua_function(a_LuaState, "SaveToSchematicString", tolua_cBlockArea_SaveToSchematicString);
tolua_function(a_LuaState, "SetBlockType", SetBlock<BLOCKTYPE, cBlockArea::baTypes, &cBlockArea::SetRelBlockType>);
tolua_function(a_LuaState, "SetBlockMeta", SetBlock<NIBBLETYPE, cBlockArea::baMetas, &cBlockArea::SetRelBlockMeta>);
tolua_function(a_LuaState, "SetBlockLight", SetBlock<NIBBLETYPE, cBlockArea::baLight, &cBlockArea::SetRelBlockLight>);
tolua_function(a_LuaState, "SetBlockSkyLight", SetBlock<NIBBLETYPE, cBlockArea::baSkyLight, &cBlockArea::SetRelBlockSkyLight>);
tolua_function(a_LuaState, "SetBlockTypeMeta", tolua_cBlockArea_SetBlockTypeMeta);
tolua_function(a_LuaState, "SetRelBlockType", SetRelBlock<BLOCKTYPE, cBlockArea::baTypes, &cBlockArea::SetRelBlockType>);
tolua_function(a_LuaState, "SetRelBlockMeta", SetRelBlock<NIBBLETYPE, cBlockArea::baMetas, &cBlockArea::SetRelBlockMeta>);
tolua_function(a_LuaState, "SetRelBlockLight", SetRelBlock<NIBBLETYPE, cBlockArea::baLight, &cBlockArea::SetRelBlockLight>);
tolua_function(a_LuaState, "SetRelBlockSkyLight", SetRelBlock<NIBBLETYPE, cBlockArea::baSkyLight, &cBlockArea::SetRelBlockSkyLight>);
tolua_function(a_LuaState, "SetRelBlockTypeMeta", tolua_cBlockArea_SetRelBlockTypeMeta);
tolua_function(a_LuaState, "Write", tolua_cBlockArea_Write);
tolua_endmodule(a_LuaState);
tolua_endmodule(a_LuaState);
}

View File

@ -28,13 +28,8 @@ static int tolua_cNetwork_Connect(lua_State * L)
// cNetwork:Connect(Host, Port, Callbacks) -> bool
cLuaState S(L);
if (
!S.CheckParamStaticSelf("cNetwork") ||
!S.CheckParamString(2) ||
!S.CheckParamNumber(3) ||
!S.CheckParamTable(4) ||
!S.CheckParamEnd(5)
)
if (!S.CheckParamStaticSelf("cNetwork") || !S.CheckParamString(2) || !S.CheckParamNumber(3) ||
!S.CheckParamTable(4) || !S.CheckParamEnd(5))
{
return 0;
}
@ -76,12 +71,7 @@ static int tolua_cNetwork_CreateUDPEndpoint(lua_State * L)
// cNetwork:CreateUDPEndpoint(Port, Callbacks) -> cUDPEndpoint
cLuaState S(L);
if (
!S.CheckParamStaticSelf("cNetwork") ||
!S.CheckParamNumber(2) ||
!S.CheckParamTable(3) ||
!S.CheckParamEnd(4)
)
if (!S.CheckParamStaticSelf("cNetwork") || !S.CheckParamNumber(2) || !S.CheckParamTable(3) || !S.CheckParamEnd(4))
{
return 0;
}
@ -125,10 +115,7 @@ static int tolua_cNetwork_EnumLocalIPAddresses(lua_State * L)
// cNetwork:EnumLocalIPAddresses() -> {string, ...}
cLuaState S(L);
if (
!S.CheckParamStaticSelf("cNetwork") ||
!S.CheckParamEnd(2)
)
if (!S.CheckParamStaticSelf("cNetwork") || !S.CheckParamEnd(2))
{
return 0;
}
@ -149,12 +136,7 @@ static int tolua_cNetwork_HostnameToIP(lua_State * L)
// cNetwork:HostnameToIP(Host, Callbacks) -> bool
cLuaState S(L);
if (
!S.CheckParamStaticSelf("cNetwork") ||
!S.CheckParamString(2) ||
!S.CheckParamTable(3) ||
!S.CheckParamEnd(4)
)
if (!S.CheckParamStaticSelf("cNetwork") || !S.CheckParamString(2) || !S.CheckParamTable(3) || !S.CheckParamEnd(4))
{
return 0;
}
@ -185,12 +167,7 @@ static int tolua_cNetwork_IPToHostname(lua_State * L)
// cNetwork:IPToHostname(IP, Callbacks) -> bool
cLuaState S(L);
if (
!S.CheckParamStaticSelf("cNetwork") ||
!S.CheckParamString(2) ||
!S.CheckParamTable(3) ||
!S.CheckParamEnd(4)
)
if (!S.CheckParamStaticSelf("cNetwork") || !S.CheckParamString(2) || !S.CheckParamTable(3) || !S.CheckParamEnd(4))
{
return 0;
}
@ -221,12 +198,7 @@ static int tolua_cNetwork_Listen(lua_State * L)
// cNetwork:Listen(Port, Callbacks) -> cServerHandle
cLuaState S(L);
if (
!S.CheckParamStaticSelf("cNetwork") ||
!S.CheckParamNumber(2) ||
!S.CheckParamTable(3) ||
!S.CheckParamEnd(4)
)
if (!S.CheckParamStaticSelf("cNetwork") || !S.CheckParamNumber(2) || !S.CheckParamTable(3) || !S.CheckParamEnd(4))
{
return 0;
}
@ -289,10 +261,7 @@ static int tolua_cServerHandle_Close(lua_State * L)
// ServerInstance:Close()
cLuaState S(L);
if (
!S.CheckParamSelf("cServerHandle") ||
!S.CheckParamEnd(2)
)
if (!S.CheckParamSelf("cServerHandle") || !S.CheckParamEnd(2))
{
return 0;
}
@ -317,10 +286,7 @@ static int tolua_cServerHandle_IsListening(lua_State * L)
// ServerInstance:IsListening() -> bool
cLuaState S(L);
if (
!S.CheckParamSelf("cServerHandle") ||
!S.CheckParamEnd(2)
)
if (!S.CheckParamSelf("cServerHandle") || !S.CheckParamEnd(2))
{
return 0;
}
@ -348,10 +314,7 @@ static int tolua_cTCPLink_Close(lua_State * L)
// LinkInstance:Close()
cLuaState S(L);
if (
!S.CheckParamSelf("cTCPLink") ||
!S.CheckParamEnd(2)
)
if (!S.CheckParamSelf("cTCPLink") || !S.CheckParamEnd(2))
{
return 0;
}
@ -376,10 +339,7 @@ static int tolua_cTCPLink_GetLocalIP(lua_State * L)
// LinkInstance:GetLocalIP() -> string
cLuaState S(L);
if (
!S.CheckParamSelf("cTCPLink") ||
!S.CheckParamEnd(2)
)
if (!S.CheckParamSelf("cTCPLink") || !S.CheckParamEnd(2))
{
return 0;
}
@ -404,10 +364,7 @@ static int tolua_cTCPLink_GetLocalPort(lua_State * L)
// LinkInstance:GetLocalPort() -> number
cLuaState S(L);
if (
!S.CheckParamSelf("cTCPLink") ||
!S.CheckParamEnd(2)
)
if (!S.CheckParamSelf("cTCPLink") || !S.CheckParamEnd(2))
{
return 0;
}
@ -432,10 +389,7 @@ static int tolua_cTCPLink_GetRemoteIP(lua_State * L)
// LinkInstance:GetRemoteIP() -> string
cLuaState S(L);
if (
!S.CheckParamSelf("cTCPLink") ||
!S.CheckParamEnd(2)
)
if (!S.CheckParamSelf("cTCPLink") || !S.CheckParamEnd(2))
{
return 0;
}
@ -460,10 +414,7 @@ static int tolua_cTCPLink_GetRemotePort(lua_State * L)
// LinkInstance:GetRemotePort() -> number
cLuaState S(L);
if (
!S.CheckParamSelf("cTCPLink") ||
!S.CheckParamEnd(2)
)
if (!S.CheckParamSelf("cTCPLink") || !S.CheckParamEnd(2))
{
return 0;
}
@ -488,11 +439,7 @@ static int tolua_cTCPLink_Send(lua_State * L)
// LinkInstance:Send(DataString)
cLuaState S(L);
if (
!S.CheckParamSelf("cTCPLink") ||
!S.CheckParamString(2) ||
!S.CheckParamEnd(3)
)
if (!S.CheckParamSelf("cTCPLink") || !S.CheckParamString(2) || !S.CheckParamEnd(3))
{
return 0;
}
@ -521,10 +468,7 @@ static int tolua_cTCPLink_Shutdown(lua_State * L)
// LinkInstance:Shutdown()
cLuaState S(L);
if (
!S.CheckParamSelf("cTCPLink") ||
!S.CheckParamEnd(2)
)
if (!S.CheckParamSelf("cTCPLink") || !S.CheckParamEnd(2))
{
return 0;
}
@ -559,16 +503,27 @@ static int tolua_cTCPLink_StartTLSClient(lua_State * L)
// Read the (optional) params:
AString OwnCert, OwnPrivKey, OwnPrivKeyPassword, TrustedRootCAs;
S.GetStackValues(2, OwnCert, OwnPrivKey, OwnPrivKeyPassword, cLuaState::cOptionalParam<std::string>(TrustedRootCAs));
S.GetStackValues(
2,
OwnCert,
OwnPrivKey,
OwnPrivKeyPassword,
cLuaState::cOptionalParam<std::string>(TrustedRootCAs)
);
// Start the TLS handshake:
AString res = Link->StartTLSClient(OwnCert, OwnPrivKey, OwnPrivKeyPassword, TrustedRootCAs);
if (!res.empty())
{
S.Push(cLuaState::Nil, fmt::format(
FMT_STRING("Cannot start TLS on link to {}:{}: {}"),
Link->GetRemoteIP(), Link->GetRemotePort(), res
));
S.Push(
cLuaState::Nil,
fmt::format(
FMT_STRING("Cannot start TLS on link to {}:{}: {}"),
Link->GetRemoteIP(),
Link->GetRemotePort(),
res
)
);
return 2;
}
return 1;
@ -585,12 +540,9 @@ static int tolua_cTCPLink_StartTLSServer(lua_State * L)
// LinkInstance:StartTLSServer(OwnCert, OwnPrivKey, OwnPrivKeyPassword, StartTLSData) -> [true] or [nil, ErrMsg]
cLuaState S(L);
if (
!S.CheckParamSelf("cTCPLink") ||
!S.CheckParamString(2, 4) ||
if (!S.CheckParamSelf("cTCPLink") || !S.CheckParamString(2, 4) ||
// Param 5 is optional, don't check
!S.CheckParamEnd(6)
)
!S.CheckParamEnd(6))
{
return 0;
}
@ -607,10 +559,15 @@ static int tolua_cTCPLink_StartTLSServer(lua_State * L)
AString res = Link->StartTLSServer(OwnCert, OwnPrivKey, OwnPrivKeyPassword, StartTLSData);
if (!res.empty())
{
S.Push(cLuaState::Nil, fmt::format(
FMT_STRING("Cannot start TLS on link to {}:{}: {}"),
Link->GetRemoteIP(), Link->GetRemotePort(), res
));
S.Push(
cLuaState::Nil,
fmt::format(
FMT_STRING("Cannot start TLS on link to {}:{}: {}"),
Link->GetRemoteIP(),
Link->GetRemotePort(),
res
)
);
return 2;
}
S.Push(true);
@ -645,10 +602,7 @@ static int tolua_cUDPEndpoint_Close(lua_State * L)
// EndpointInstance:Close()
cLuaState S(L);
if (
!S.CheckParamSelf("cUDPEndpoint") ||
!S.CheckParamEnd(2)
)
if (!S.CheckParamSelf("cUDPEndpoint") || !S.CheckParamEnd(2))
{
return 0;
}
@ -673,10 +627,7 @@ static int tolua_cUDPEndpoint_EnableBroadcasts(lua_State * L)
// EndpointInstance:EnableBroadcasts()
cLuaState S(L);
if (
!S.CheckParamSelf("cUDPEndpoint") ||
!S.CheckParamEnd(2)
)
if (!S.CheckParamSelf("cUDPEndpoint") || !S.CheckParamEnd(2))
{
return 0;
}
@ -701,10 +652,7 @@ static int tolua_cUDPEndpoint_GetPort(lua_State * L)
// Endpoint:GetPort() -> number
cLuaState S(L);
if (
!S.CheckParamSelf("cUDPEndpoint") ||
!S.CheckParamEnd(2)
)
if (!S.CheckParamSelf("cUDPEndpoint") || !S.CheckParamEnd(2))
{
return 0;
}
@ -729,10 +677,7 @@ static int tolua_cUDPEndpoint_IsOpen(lua_State * L)
// Endpoint:IsOpen() -> bool
cLuaState S(L);
if (
!S.CheckParamSelf("cUDPEndpoint") ||
!S.CheckParamEnd(2)
)
if (!S.CheckParamSelf("cUDPEndpoint") || !S.CheckParamEnd(2))
{
return 0;
}
@ -757,12 +702,7 @@ static int tolua_cUDPEndpoint_Send(lua_State * L)
// Endpoint:Send(DataString)
cLuaState S(L);
if (
!S.CheckParamSelf("cUDPEndpoint") ||
!S.CheckParamString(2, 3) ||
!S.CheckParamNumber(4) ||
!S.CheckParamEnd(5)
)
if (!S.CheckParamSelf("cUDPEndpoint") || !S.CheckParamString(2, 3) || !S.CheckParamNumber(4) || !S.CheckParamEnd(5))
{
return 0;
}
@ -779,7 +719,8 @@ static int tolua_cUDPEndpoint_Send(lua_State * L)
// Check the port:
if ((remotePort < 0) || (remotePort > USHRT_MAX))
{
return S.ApiParamError(fmt::format(FMT_STRING("Port number out of range (got {}, range 0 - 65535)"), remotePort));
return S.ApiParamError(fmt::format(FMT_STRING("Port number out of range (got {}, range 0 - 65535)"), remotePort)
);
}
// Send the data:
@ -793,12 +734,11 @@ static int tolua_cUDPEndpoint_Send(lua_State * L)
/** Used when the cUrlClient Lua request wants all the callbacks.
Maps each callback onto a Lua function callback in the callback table. */
class cFullUrlClientCallbacks:
public cUrlClient::cCallbacks
class cFullUrlClientCallbacks : public cUrlClient::cCallbacks
{
public:
public:
/** Creates a new instance bound to the specified table of callbacks. */
cFullUrlClientCallbacks(cLuaState::cTableRefPtr && a_Callbacks):
cFullUrlClientCallbacks(cLuaState::cTableRefPtr && a_Callbacks) :
m_Callbacks(std::move(a_Callbacks))
{
}
@ -814,23 +754,18 @@ public:
virtual bool OnCertificateReceived() override
{
// TODO: The received cert needs proper type specification from the underlying cUrlClient framework and in the Lua engine as well
// TODO: The received cert needs proper type specification from the underlying cUrlClient framework and in the
// Lua engine as well
bool res = true;
m_Callbacks->CallTableFnWithSelf("OnCertificateReceived", cLuaState::Return, res);
return res;
}
virtual void OnTlsHandshakeCompleted() override
{
m_Callbacks->CallTableFnWithSelf("OnTlsHandshakeCompleted");
}
virtual void OnTlsHandshakeCompleted() override { m_Callbacks->CallTableFnWithSelf("OnTlsHandshakeCompleted"); }
virtual void OnRequestSent() override
{
m_Callbacks->CallTableFnWithSelf("OnRequestSent");
}
virtual void OnRequestSent() override { m_Callbacks->CallTableFnWithSelf("OnRequestSent"); }
virtual void OnStatusLine(const AString & a_HttpVersion, int a_StatusCode, const AString & a_Rest) override
@ -846,10 +781,7 @@ public:
}
virtual void OnHeadersFinished() override
{
m_Callbacks->CallTableFnWithSelf("OnHeadersFinished", m_Headers);
}
virtual void OnHeadersFinished() override { m_Callbacks->CallTableFnWithSelf("OnHeadersFinished", m_Headers); }
virtual void OnBodyData(const void * a_Data, size_t a_Size) override
@ -858,10 +790,7 @@ public:
}
virtual void OnBodyFinished() override
{
m_Callbacks->CallTableFnWithSelf("OnBodyFinished");
}
virtual void OnBodyFinished() override { m_Callbacks->CallTableFnWithSelf("OnBodyFinished"); }
virtual void OnError(const AString & a_ErrorMsg) override
@ -876,7 +805,7 @@ public:
}
protected:
protected:
/** The Lua table containing the callbacks. */
cLuaState::cTableRefPtr m_Callbacks;
@ -894,21 +823,17 @@ callback("BodyContents", {headers})
callback(nil, "ErrorMessage")
Accumulates the body contents into a single string until the body is finished.
Accumulates all HTTP headers into an AStringMap. */
class cSimpleUrlClientCallbacks:
public cUrlClient::cCallbacks
class cSimpleUrlClientCallbacks : public cUrlClient::cCallbacks
{
public:
public:
/** Creates a new instance that uses the specified callback to report when request finishes. */
cSimpleUrlClientCallbacks(cLuaState::cCallbackPtr && a_Callback):
cSimpleUrlClientCallbacks(cLuaState::cCallbackPtr && a_Callback) :
m_Callback(std::move(a_Callback))
{
}
virtual void OnHeader(const AString & a_Key, const AString & a_Value) override
{
m_Headers[a_Key] = a_Value;
}
virtual void OnHeader(const AString & a_Key, const AString & a_Value) override { m_Headers[a_Key] = a_Value; }
virtual void OnBodyData(const void * a_Data, size_t a_Size) override
@ -917,20 +842,13 @@ public:
}
virtual void OnBodyFinished() override
{
m_Callback->Call(m_ResponseBody, m_Headers);
}
virtual void OnBodyFinished() override { m_Callback->Call(m_ResponseBody, m_Headers); }
virtual void OnError(const AString & a_ErrorMsg) override
{
m_Callback->Call(cLuaState::Nil, a_ErrorMsg);
}
virtual void OnError(const AString & a_ErrorMsg) override { m_Callback->Call(cLuaState::Nil, a_ErrorMsg); }
protected:
protected:
/** The callback to call when the request finishes. */
cLuaState::cCallbackPtr m_Callback;
@ -971,7 +889,9 @@ static int tolua_cUrlClient_Request_Common(lua_State * a_LuaState, const AString
{
if (!L.GetStackValue(a_UrlStackIdx + 1, callbacks))
{
return L.ApiParamError(fmt::format(FMT_STRING("Cannot read the CallbacksTable parameter at idx {}"), a_UrlStackIdx + 1));
return L.ApiParamError(
fmt::format(FMT_STRING("Cannot read the CallbacksTable parameter at idx {}"), a_UrlStackIdx + 1)
);
}
urlClientCallbacks = std::make_unique<cFullUrlClientCallbacks>(std::move(callbacks));
}
@ -979,7 +899,9 @@ static int tolua_cUrlClient_Request_Common(lua_State * a_LuaState, const AString
{
if (!L.GetStackValue(a_UrlStackIdx + 1, onCompleteBodyCallback))
{
return L.ApiParamError(fmt::format(FMT_STRING("Cannot read the CallbackFn parameter at idx {}"), a_UrlStackIdx + 1));
return L.ApiParamError(
fmt::format(FMT_STRING("Cannot read the CallbackFn parameter at idx {}"), a_UrlStackIdx + 1)
);
}
urlClientCallbacks = std::make_unique<cSimpleUrlClientCallbacks>(std::move(onCompleteBodyCallback));
}
@ -987,19 +909,34 @@ static int tolua_cUrlClient_Request_Common(lua_State * a_LuaState, const AString
{
L.ApiParamError(fmt::format(
FMT_STRING("Invalid Callbacks parameter at {}, expected a table or function, got {}"),
a_UrlStackIdx + 1, L.GetTypeText(a_UrlStackIdx + 1)
a_UrlStackIdx + 1,
L.GetTypeText(a_UrlStackIdx + 1)
));
}
if (!L.GetStackValues(a_UrlStackIdx + 2, cLuaState::cOptionalParam<AStringMap>(headers), cLuaState::cOptionalParam<AString>(requestBody), cLuaState::cOptionalParam<AStringMap>(options)))
if (!L.GetStackValues(
a_UrlStackIdx + 2,
cLuaState::cOptionalParam<AStringMap>(headers),
cLuaState::cOptionalParam<AString>(requestBody),
cLuaState::cOptionalParam<AStringMap>(options)
))
{
L.ApiParamError(fmt::format(
FMT_STRING("Cannot read the Header, Body or Options parameter at idx {}, {}, {}."),
a_UrlStackIdx + 2, a_UrlStackIdx + 3, a_UrlStackIdx + 4
a_UrlStackIdx + 2,
a_UrlStackIdx + 3,
a_UrlStackIdx + 4
));
}
// Make the request:
auto res = cUrlClient::Request(a_Method, url, std::move(urlClientCallbacks), std::move(headers), std::move(requestBody), std::move(options));
auto res = cUrlClient::Request(
a_Method,
url,
std::move(urlClientCallbacks),
std::move(headers),
std::move(requestBody),
std::move(options)
);
if (!res.first)
{
L.Push(false);
@ -1018,8 +955,9 @@ static int tolua_cUrlClient_Request_Common(lua_State * a_LuaState, const AString
static int tolua_cUrlClient_Delete(lua_State * a_LuaState)
{
/* Function signatures:
cUrlClient:Delete(URL, {CallbacksFnTable}, [{HeadersMapTable}], [RequestBody], [{OptionsMapTable}]) -> true / false + string
cUrlClient:Delete(URL, OnCompleteBodyCallback, [{HeadersMapTable}], [RequestBody], [{OptionsMapTable}]) -> true / false + string
cUrlClient:Delete(URL, {CallbacksFnTable}, [{HeadersMapTable}], [RequestBody], [{OptionsMapTable}]) -> true / false
+ string cUrlClient:Delete(URL, OnCompleteBodyCallback, [{HeadersMapTable}], [RequestBody], [{OptionsMapTable}]) ->
true / false + string
*/
return tolua_cUrlClient_Request_Common(a_LuaState, "DELETE", 2);
@ -1033,8 +971,9 @@ static int tolua_cUrlClient_Delete(lua_State * a_LuaState)
static int tolua_cUrlClient_Get(lua_State * a_LuaState)
{
/* Function signatures:
cUrlClient:Get(URL, {CallbacksFnTable}, [{HeadersMapTable}], [RequestBody], [{OptionsMapTable}]) -> true / false + string
cUrlClient:Get(URL, OnCompleteBodyCallback, [{HeadersMapTable}], [RequestBody], [{OptionsMapTable}]) -> true / false + string
cUrlClient:Get(URL, {CallbacksFnTable}, [{HeadersMapTable}], [RequestBody], [{OptionsMapTable}]) -> true / false +
string cUrlClient:Get(URL, OnCompleteBodyCallback, [{HeadersMapTable}], [RequestBody], [{OptionsMapTable}]) -> true
/ false + string
*/
return tolua_cUrlClient_Request_Common(a_LuaState, "GET", 2);
@ -1048,8 +987,9 @@ static int tolua_cUrlClient_Get(lua_State * a_LuaState)
static int tolua_cUrlClient_Post(lua_State * a_LuaState)
{
/* Function signatures:
cUrlClient:Post(URL, {CallbacksFnTable}, [{HeadersMapTable}], [RequestBody], [{OptionsMapTable}]) -> true / false + string
cUrlClient:Post(URL, OnCompleteBodyCallback, [{HeadersMapTable}], [RequestBody], [{OptionsMapTable}]) -> true / false + string
cUrlClient:Post(URL, {CallbacksFnTable}, [{HeadersMapTable}], [RequestBody], [{OptionsMapTable}]) -> true / false +
string cUrlClient:Post(URL, OnCompleteBodyCallback, [{HeadersMapTable}], [RequestBody], [{OptionsMapTable}]) -> true
/ false + string
*/
return tolua_cUrlClient_Request_Common(a_LuaState, "POST", 2);
@ -1063,8 +1003,9 @@ static int tolua_cUrlClient_Post(lua_State * a_LuaState)
static int tolua_cUrlClient_Put(lua_State * a_LuaState)
{
/* Function signatures:
cUrlClient:Put(URL, {CallbacksFnTable}, [{HeadersMapTable}], [RequestBody], [{OptionsMapTable}]) -> true / false + string
cUrlClient:Put(URL, OnCompleteBodyCallback, [{HeadersMapTable}], [RequestBody], [{OptionsMapTable}]) -> true / false + string
cUrlClient:Put(URL, {CallbacksFnTable}, [{HeadersMapTable}], [RequestBody], [{OptionsMapTable}]) -> true / false +
string cUrlClient:Put(URL, OnCompleteBodyCallback, [{HeadersMapTable}], [RequestBody], [{OptionsMapTable}]) -> true
/ false + string
*/
return tolua_cUrlClient_Request_Common(a_LuaState, "PUT", 2);
@ -1078,15 +1019,14 @@ static int tolua_cUrlClient_Put(lua_State * a_LuaState)
static int tolua_cUrlClient_Request(lua_State * a_LuaState)
{
/* Function signatures:
cUrlClient:Request(Method, URL, {CallbacksFnTable}, [{HeadersMapTable}], [RequestBody], [{OptionsMapTable}]) -> true / false + string
cUrlClient:Request(Method, URL, OnCompleteBodyCallback, [{HeadersMapTable}], [RequestBody], [{OptionsMapTable}]) -> true / false + string
cUrlClient:Request(Method, URL, {CallbacksFnTable}, [{HeadersMapTable}], [RequestBody], [{OptionsMapTable}]) -> true
/ false + string cUrlClient:Request(Method, URL, OnCompleteBodyCallback, [{HeadersMapTable}], [RequestBody],
[{OptionsMapTable}]) -> true / false + string
*/
// Check that the Method param is a string:
cLuaState L(a_LuaState);
if (
!L.CheckParamStaticSelf("cUrlClient") ||
!L.CheckParamString(2))
if (!L.CheckParamStaticSelf("cUrlClient") || !L.CheckParamString(2))
{
return 0;
}
@ -1115,56 +1055,52 @@ void cManualBindings::BindNetwork(lua_State * tolua_S)
tolua_usertype(tolua_S, "cTCPLink");
tolua_usertype(tolua_S, "cUDPEndpoint");
tolua_usertype(tolua_S, "cUrlClient");
tolua_cclass(tolua_S, "cNetwork", "cNetwork", "", nullptr);
tolua_cclass(tolua_S, "cNetwork", "cNetwork", "", nullptr);
tolua_cclass(tolua_S, "cServerHandle", "cServerHandle", "", tolua_collect_cServerHandle);
tolua_cclass(tolua_S, "cTCPLink", "cTCPLink", "", nullptr);
tolua_cclass(tolua_S, "cUDPEndpoint", "cUDPEndpoint", "", tolua_collect_cUDPEndpoint);
tolua_cclass(tolua_S, "cUrlClient", "cUrlClient", "", nullptr);
tolua_cclass(tolua_S, "cTCPLink", "cTCPLink", "", nullptr);
tolua_cclass(tolua_S, "cUDPEndpoint", "cUDPEndpoint", "", tolua_collect_cUDPEndpoint);
tolua_cclass(tolua_S, "cUrlClient", "cUrlClient", "", nullptr);
// Fill in the functions (alpha-sorted):
tolua_beginmodule(tolua_S, "cNetwork");
tolua_function(tolua_S, "Connect", tolua_cNetwork_Connect);
tolua_function(tolua_S, "CreateUDPEndpoint", tolua_cNetwork_CreateUDPEndpoint);
tolua_function(tolua_S, "EnumLocalIPAddresses", tolua_cNetwork_EnumLocalIPAddresses);
tolua_function(tolua_S, "HostnameToIP", tolua_cNetwork_HostnameToIP);
tolua_function(tolua_S, "IPToHostname", tolua_cNetwork_IPToHostname);
tolua_function(tolua_S, "Listen", tolua_cNetwork_Listen);
tolua_function(tolua_S, "Connect", tolua_cNetwork_Connect);
tolua_function(tolua_S, "CreateUDPEndpoint", tolua_cNetwork_CreateUDPEndpoint);
tolua_function(tolua_S, "EnumLocalIPAddresses", tolua_cNetwork_EnumLocalIPAddresses);
tolua_function(tolua_S, "HostnameToIP", tolua_cNetwork_HostnameToIP);
tolua_function(tolua_S, "IPToHostname", tolua_cNetwork_IPToHostname);
tolua_function(tolua_S, "Listen", tolua_cNetwork_Listen);
tolua_endmodule(tolua_S);
tolua_beginmodule(tolua_S, "cServerHandle");
tolua_function(tolua_S, "Close", tolua_cServerHandle_Close);
tolua_function(tolua_S, "IsListening", tolua_cServerHandle_IsListening);
tolua_function(tolua_S, "Close", tolua_cServerHandle_Close);
tolua_function(tolua_S, "IsListening", tolua_cServerHandle_IsListening);
tolua_endmodule(tolua_S);
tolua_beginmodule(tolua_S, "cTCPLink");
tolua_function(tolua_S, "Close", tolua_cTCPLink_Close);
tolua_function(tolua_S, "GetLocalIP", tolua_cTCPLink_GetLocalIP);
tolua_function(tolua_S, "GetLocalPort", tolua_cTCPLink_GetLocalPort);
tolua_function(tolua_S, "GetRemoteIP", tolua_cTCPLink_GetRemoteIP);
tolua_function(tolua_S, "GetRemotePort", tolua_cTCPLink_GetRemotePort);
tolua_function(tolua_S, "Send", tolua_cTCPLink_Send);
tolua_function(tolua_S, "Shutdown", tolua_cTCPLink_Shutdown);
tolua_function(tolua_S, "StartTLSClient", tolua_cTCPLink_StartTLSClient);
tolua_function(tolua_S, "StartTLSServer", tolua_cTCPLink_StartTLSServer);
tolua_function(tolua_S, "Close", tolua_cTCPLink_Close);
tolua_function(tolua_S, "GetLocalIP", tolua_cTCPLink_GetLocalIP);
tolua_function(tolua_S, "GetLocalPort", tolua_cTCPLink_GetLocalPort);
tolua_function(tolua_S, "GetRemoteIP", tolua_cTCPLink_GetRemoteIP);
tolua_function(tolua_S, "GetRemotePort", tolua_cTCPLink_GetRemotePort);
tolua_function(tolua_S, "Send", tolua_cTCPLink_Send);
tolua_function(tolua_S, "Shutdown", tolua_cTCPLink_Shutdown);
tolua_function(tolua_S, "StartTLSClient", tolua_cTCPLink_StartTLSClient);
tolua_function(tolua_S, "StartTLSServer", tolua_cTCPLink_StartTLSServer);
tolua_endmodule(tolua_S);
tolua_beginmodule(tolua_S, "cUDPEndpoint");
tolua_function(tolua_S, "Close", tolua_cUDPEndpoint_Close);
tolua_function(tolua_S, "EnableBroadcasts", tolua_cUDPEndpoint_EnableBroadcasts);
tolua_function(tolua_S, "GetPort", tolua_cUDPEndpoint_GetPort);
tolua_function(tolua_S, "IsOpen", tolua_cUDPEndpoint_IsOpen);
tolua_function(tolua_S, "Send", tolua_cUDPEndpoint_Send);
tolua_function(tolua_S, "Close", tolua_cUDPEndpoint_Close);
tolua_function(tolua_S, "EnableBroadcasts", tolua_cUDPEndpoint_EnableBroadcasts);
tolua_function(tolua_S, "GetPort", tolua_cUDPEndpoint_GetPort);
tolua_function(tolua_S, "IsOpen", tolua_cUDPEndpoint_IsOpen);
tolua_function(tolua_S, "Send", tolua_cUDPEndpoint_Send);
tolua_endmodule(tolua_S);
tolua_beginmodule(tolua_S, "cUrlClient");
tolua_function(tolua_S, "Delete", tolua_cUrlClient_Delete);
tolua_function(tolua_S, "Get", tolua_cUrlClient_Get);
tolua_function(tolua_S, "Post", tolua_cUrlClient_Post);
tolua_function(tolua_S, "Put", tolua_cUrlClient_Put);
tolua_function(tolua_S, "Request", tolua_cUrlClient_Request);
tolua_function(tolua_S, "Delete", tolua_cUrlClient_Delete);
tolua_function(tolua_S, "Get", tolua_cUrlClient_Get);
tolua_function(tolua_S, "Post", tolua_cUrlClient_Post);
tolua_function(tolua_S, "Put", tolua_cUrlClient_Put);
tolua_function(tolua_S, "Request", tolua_cUrlClient_Request);
tolua_endmodule(tolua_S);
}

View File

@ -21,11 +21,7 @@ static int tolua_cRankManager_AddGroup(lua_State * L)
// cRankManager:AddGroup(GroupName)
cLuaState S(L);
if (
!S.CheckParamUserTable(1, "cRankManager") ||
!S.CheckParamString(2) ||
!S.CheckParamEnd(3)
)
if (!S.CheckParamUserTable(1, "cRankManager") || !S.CheckParamString(2) || !S.CheckParamEnd(3))
{
return 0;
}
@ -50,11 +46,7 @@ static int tolua_cRankManager_AddGroupToRank(lua_State * L)
// cRankManager:AddGroupToRank(GroupName, RankName) -> bool
cLuaState S(L);
if (
!S.CheckParamUserTable(1, "cRankManager") ||
!S.CheckParamString(2, 3) ||
!S.CheckParamEnd(4)
)
if (!S.CheckParamUserTable(1, "cRankManager") || !S.CheckParamString(2, 3) || !S.CheckParamEnd(4))
{
return 0;
}
@ -79,11 +71,7 @@ static int tolua_cRankManager_AddPermissionToGroup(lua_State * L)
// cRankManager:AddPermissionToGroup(Permission, GroupName) -> bool
cLuaState S(L);
if (
!S.CheckParamUserTable(1, "cRankManager") ||
!S.CheckParamString(2, 3) ||
!S.CheckParamEnd(4)
)
if (!S.CheckParamUserTable(1, "cRankManager") || !S.CheckParamString(2, 3) || !S.CheckParamEnd(4))
{
return 0;
}
@ -108,11 +96,7 @@ static int tolua_cRankManager_AddRank(lua_State * L)
// cRankManager:AddRank(RankName)
cLuaState S(L);
if (
!S.CheckParamUserTable(1, "cRankManager") ||
!S.CheckParamString(2, 5) ||
!S.CheckParamEnd(6)
)
if (!S.CheckParamUserTable(1, "cRankManager") || !S.CheckParamString(2, 5) || !S.CheckParamEnd(6))
{
return 0;
}
@ -137,11 +121,7 @@ static int tolua_cRankManager_AddRestrictionToGroup(lua_State * L)
// cRankManager:AddRestrictionToGroup(Restriction, GroupName) -> bool
cLuaState S(L);
if (
!S.CheckParamUserTable(1, "cRankManager") ||
!S.CheckParamString(2, 3) ||
!S.CheckParamEnd(4)
)
if (!S.CheckParamUserTable(1, "cRankManager") || !S.CheckParamString(2, 3) || !S.CheckParamEnd(4))
{
return 0;
}
@ -163,10 +143,7 @@ static int tolua_cRankManager_AddRestrictionToGroup(lua_State * L)
static int tolua_cRankManager_ClearPlayerRanks(lua_State * L)
{
cLuaState S(L);
if (
!S.CheckParamUserTable(1, "cRankManager") ||
!S.CheckParamEnd(2)
)
if (!S.CheckParamUserTable(1, "cRankManager") || !S.CheckParamEnd(2))
{
return 0;
}
@ -187,10 +164,7 @@ static int tolua_cRankManager_GetAllGroups(lua_State * L)
// cRankManager:GetAllGroups() -> arraytable of GroupNames
cLuaState S(L);
if (
!S.CheckParamUserTable(1, "cRankManager") ||
!S.CheckParamEnd(2)
)
if (!S.CheckParamUserTable(1, "cRankManager") || !S.CheckParamEnd(2))
{
return 0;
}
@ -214,10 +188,7 @@ static int tolua_cRankManager_GetAllPermissions(lua_State * L)
// cRankManager:GetAllPermissions() -> arraytable of Permissions
cLuaState S(L);
if (
!S.CheckParamUserTable(1, "cRankManager") ||
!S.CheckParamEnd(2)
)
if (!S.CheckParamUserTable(1, "cRankManager") || !S.CheckParamEnd(2))
{
return 0;
}
@ -241,10 +212,7 @@ static int tolua_cRankManager_GetAllPermissionsRestrictions(lua_State * L)
// cRankManager:GetAllPermissionsRestrictions() -> arraytable of Permissions and Restrictions together
cLuaState S(L);
if (
!S.CheckParamUserTable(1, "cRankManager") ||
!S.CheckParamEnd(2)
)
if (!S.CheckParamUserTable(1, "cRankManager") || !S.CheckParamEnd(2))
{
return 0;
}
@ -266,10 +234,7 @@ static int tolua_cRankManager_GetAllPlayerUUIDs(lua_State * L)
// cRankManager:GetAllPlayerUUIDs() -> arraytable of Player UUID's
cLuaState S(L);
if (
!S.CheckParamStaticSelf("cRankManager") ||
!S.CheckParamEnd(2)
)
if (!S.CheckParamStaticSelf("cRankManager") || !S.CheckParamEnd(2))
{
return 0;
}
@ -301,10 +266,7 @@ static int tolua_cRankManager_GetAllRanks(lua_State * L)
// cRankManager:GetAllRanks() -> arraytable of RankNames
cLuaState S(L);
if (
!S.CheckParamUserTable(1, "cRankManager") ||
!S.CheckParamEnd(2)
)
if (!S.CheckParamUserTable(1, "cRankManager") || !S.CheckParamEnd(2))
{
return 0;
}
@ -325,10 +287,7 @@ static int tolua_cRankManager_GetAllRestrictions(lua_State * L)
// cRankManager:GetAllRestrictions() -> arraytable of Restrictions
cLuaState S(L);
if (
!S.CheckParamUserTable(1, "cRankManager") ||
!S.CheckParamEnd(2)
)
if (!S.CheckParamUserTable(1, "cRankManager") || !S.CheckParamEnd(2))
{
return 0;
}
@ -350,10 +309,7 @@ static int tolua_cRankManager_GetDefaultRank(lua_State * L)
// cRankManager:GetDefaultRank() -> string
cLuaState S(L);
if (
!S.CheckParamUserTable(1, "cRankManager") ||
!S.CheckParamEnd(2)
)
if (!S.CheckParamUserTable(1, "cRankManager") || !S.CheckParamEnd(2))
{
return 0;
}
@ -374,11 +330,7 @@ static int tolua_cRankManager_GetGroupPermissions(lua_State * L)
// cRankManager:GetGroupPermissions(GroupName) -> arraytable of permissions
cLuaState S(L);
if (
!S.CheckParamUserTable(1, "cRankManager") ||
!S.CheckParamString(2) ||
!S.CheckParamEnd(3)
)
if (!S.CheckParamUserTable(1, "cRankManager") || !S.CheckParamString(2) || !S.CheckParamEnd(3))
{
return 0;
}
@ -406,11 +358,7 @@ static int tolua_cRankManager_GetGroupRestrictions(lua_State * L)
// cRankManager:GetGroupRestrictions(GroupName) -> arraytable of restrictions
cLuaState S(L);
if (
!S.CheckParamUserTable(1, "cRankManager") ||
!S.CheckParamString(2) ||
!S.CheckParamEnd(3)
)
if (!S.CheckParamUserTable(1, "cRankManager") || !S.CheckParamString(2) || !S.CheckParamEnd(3))
{
return 0;
}
@ -438,11 +386,7 @@ static int tolua_cRankManager_GetPlayerGroups(lua_State * L)
// cRankManager:GetPlayerGroups(PlayerUUID) -> arraytable of GroupNames
cLuaState S(L);
if (
!S.CheckParamStaticSelf("cRankManager") ||
!S.CheckParamUUID(2) ||
!S.CheckParamEnd(3)
)
if (!S.CheckParamStaticSelf("cRankManager") || !S.CheckParamUUID(2) || !S.CheckParamEnd(3))
{
return 0;
}
@ -470,11 +414,7 @@ static int tolua_cRankManager_GetPlayerMsgVisuals(lua_State * L)
// cRankManager:GetPlayerMsgVisuals(PlayerUUID) -> string, string, string
cLuaState S(L);
if (
!S.CheckParamStaticSelf("cRankManager") ||
!S.CheckParamUUID(2) ||
!S.CheckParamEnd(3)
)
if (!S.CheckParamStaticSelf("cRankManager") || !S.CheckParamUUID(2) || !S.CheckParamEnd(3))
{
return 0;
}
@ -506,11 +446,7 @@ static int tolua_cRankManager_GetPlayerPermissions(lua_State * L)
// cRankManager:GetPlayerPermissions(PlayerUUID) -> arraytable of permissions
cLuaState S(L);
if (
!S.CheckParamStaticSelf("cRankManager") ||
!S.CheckParamUUID(2) ||
!S.CheckParamEnd(3)
)
if (!S.CheckParamStaticSelf("cRankManager") || !S.CheckParamUUID(2) || !S.CheckParamEnd(3))
{
return 0;
}
@ -538,11 +474,7 @@ static int tolua_cRankManager_GetPlayerRestrictions(lua_State * L)
// cRankManager:GetPlayerRestrictions(PlayerUUID) -> arraytable of restrictions
cLuaState S(L);
if (
!S.CheckParamStaticSelf("cRankManager") ||
!S.CheckParamUUID(2) ||
!S.CheckParamEnd(3)
)
if (!S.CheckParamStaticSelf("cRankManager") || !S.CheckParamUUID(2) || !S.CheckParamEnd(3))
{
return 0;
}
@ -570,11 +502,7 @@ static int tolua_cRankManager_GetPlayerRankName(lua_State * L)
// cRankManager:GetPlayerRankName(PlayerUUID) -> string
cLuaState S(L);
if (
!S.CheckParamStaticSelf("cRankManager") ||
!S.CheckParamUUID(2) ||
!S.CheckParamEnd(3)
)
if (!S.CheckParamStaticSelf("cRankManager") || !S.CheckParamUUID(2) || !S.CheckParamEnd(3))
{
return 0;
}
@ -602,11 +530,7 @@ static int tolua_cRankManager_GetPlayerName(lua_State * L)
// cRankManager:GetPlayerName(PlayerUUID) -> string
cLuaState S(L);
if (
!S.CheckParamStaticSelf("cRankManager") ||
!S.CheckParamUUID(2) ||
!S.CheckParamEnd(3)
)
if (!S.CheckParamStaticSelf("cRankManager") || !S.CheckParamUUID(2) || !S.CheckParamEnd(3))
{
return 0;
}
@ -634,11 +558,7 @@ static int tolua_cRankManager_GetRankGroups(lua_State * L)
// cRankManager:GetRankGroups(RankName) -> arraytable of groupnames
cLuaState S(L);
if (
!S.CheckParamUserTable(1, "cRankManager") ||
!S.CheckParamString(2) ||
!S.CheckParamEnd(3)
)
if (!S.CheckParamUserTable(1, "cRankManager") || !S.CheckParamString(2) || !S.CheckParamEnd(3))
{
return 0;
}
@ -666,11 +586,7 @@ static int tolua_cRankManager_GetRankPermissions(lua_State * L)
// cRankManager:GetRankPermissions(RankName) -> arraytable of permissions
cLuaState S(L);
if (
!S.CheckParamUserTable(1, "cRankManager") ||
!S.CheckParamString(2) ||
!S.CheckParamEnd(3)
)
if (!S.CheckParamUserTable(1, "cRankManager") || !S.CheckParamString(2) || !S.CheckParamEnd(3))
{
return 0;
}
@ -698,11 +614,7 @@ static int tolua_cRankManager_GetRankRestrictions(lua_State * L)
// cRankManager:GetRankRestrictions(RankName) -> arraytable of restrictions
cLuaState S(L);
if (
!S.CheckParamUserTable(1, "cRankManager") ||
!S.CheckParamString(2) ||
!S.CheckParamEnd(3)
)
if (!S.CheckParamUserTable(1, "cRankManager") || !S.CheckParamString(2) || !S.CheckParamEnd(3))
{
return 0;
}
@ -730,11 +642,7 @@ static int tolua_cRankManager_GetRankVisuals(lua_State * L)
// cRankManager:GetRankVisuals(RankName) -> MsgPrefix, MsgSuffix, MsgNameColorCode
cLuaState S(L);
if (
!S.CheckParamUserTable(1, "cRankManager") ||
!S.CheckParamString(2) ||
!S.CheckParamEnd(3)
)
if (!S.CheckParamUserTable(1, "cRankManager") || !S.CheckParamString(2) || !S.CheckParamEnd(3))
{
return 0;
}
@ -767,11 +675,7 @@ static int tolua_cRankManager_GroupExists(lua_State * L)
// cRankManager:GroupExists(GroupName) -> bool
cLuaState S(L);
if (
!S.CheckParamUserTable(1, "cRankManager") ||
!S.CheckParamString(2) ||
!S.CheckParamEnd(3)
)
if (!S.CheckParamUserTable(1, "cRankManager") || !S.CheckParamString(2) || !S.CheckParamEnd(3))
{
return 0;
}
@ -799,11 +703,7 @@ static int tolua_cRankManager_IsGroupInRank(lua_State * L)
// cRankManager:IsGroupInRank(GroupName, RankName) -> bool
cLuaState S(L);
if (
!S.CheckParamUserTable(1, "cRankManager") ||
!S.CheckParamString(2, 3) ||
!S.CheckParamEnd(4)
)
if (!S.CheckParamUserTable(1, "cRankManager") || !S.CheckParamString(2, 3) || !S.CheckParamEnd(4))
{
return 0;
}
@ -831,11 +731,7 @@ static int tolua_cRankManager_IsPermissionInGroup(lua_State * L)
// cRankManager:IsPermissionInGroup(Permission, GroupName) -> bool
cLuaState S(L);
if (
!S.CheckParamUserTable(1, "cRankManager") ||
!S.CheckParamString(2, 3) ||
!S.CheckParamEnd(4)
)
if (!S.CheckParamUserTable(1, "cRankManager") || !S.CheckParamString(2, 3) || !S.CheckParamEnd(4))
{
return 0;
}
@ -863,11 +759,7 @@ static int tolua_cRankManager_IsRestrictionInGroup(lua_State * L)
// cRankManager:IsRestrictionInGroup(Restriction, GroupName) -> bool
cLuaState S(L);
if (
!S.CheckParamUserTable(1, "cRankManager") ||
!S.CheckParamString(2, 3) ||
!S.CheckParamEnd(4)
)
if (!S.CheckParamUserTable(1, "cRankManager") || !S.CheckParamString(2, 3) || !S.CheckParamEnd(4))
{
return 0;
}
@ -895,11 +787,7 @@ static int tolua_cRankManager_IsPlayerRankSet(lua_State * L)
// cRankManager:IsPlayerRankSet(PlayerUUID) -> bool
cLuaState S(L);
if (
!S.CheckParamStaticSelf("cRankManager") ||
!S.CheckParamUUID(2) ||
!S.CheckParamEnd(3)
)
if (!S.CheckParamStaticSelf("cRankManager") || !S.CheckParamUUID(2) || !S.CheckParamEnd(3))
{
return 0;
}
@ -927,11 +815,7 @@ static int tolua_cRankManager_RankExists(lua_State * L)
// cRankManager:RankExists(RankName) -> bool
cLuaState S(L);
if (
!S.CheckParamUserTable(1, "cRankManager") ||
!S.CheckParamString(2) ||
!S.CheckParamEnd(3)
)
if (!S.CheckParamUserTable(1, "cRankManager") || !S.CheckParamString(2) || !S.CheckParamEnd(3))
{
return 0;
}
@ -959,11 +843,7 @@ static int tolua_cRankManager_RemoveGroup(lua_State * L)
// cRankManager:RemoveGroup(GroupName)
cLuaState S(L);
if (
!S.CheckParamUserTable(1, "cRankManager") ||
!S.CheckParamString(2) ||
!S.CheckParamEnd(3)
)
if (!S.CheckParamUserTable(1, "cRankManager") || !S.CheckParamString(2) || !S.CheckParamEnd(3))
{
return 0;
}
@ -988,11 +868,7 @@ static int tolua_cRankManager_RemoveGroupFromRank(lua_State * L)
// cRankManager:RemoveGroupFromRank(GroupName, RankName)
cLuaState S(L);
if (
!S.CheckParamUserTable(1, "cRankManager") ||
!S.CheckParamString(2, 3) ||
!S.CheckParamEnd(4)
)
if (!S.CheckParamUserTable(1, "cRankManager") || !S.CheckParamString(2, 3) || !S.CheckParamEnd(4))
{
return 0;
}
@ -1017,11 +893,7 @@ static int tolua_cRankManager_RemovePermissionFromGroup(lua_State * L)
// cRankManager:RemovePermissionFromGroup(Permission, GroupName)
cLuaState S(L);
if (
!S.CheckParamUserTable(1, "cRankManager") ||
!S.CheckParamString(2, 3) ||
!S.CheckParamEnd(4)
)
if (!S.CheckParamUserTable(1, "cRankManager") || !S.CheckParamString(2, 3) || !S.CheckParamEnd(4))
{
return 0;
}
@ -1046,11 +918,7 @@ static int tolua_cRankManager_RemoveRestrictionFromGroup(lua_State * L)
// cRankManager:RemoveRestrictionFromGroup(Restriction, GroupName)
cLuaState S(L);
if (
!S.CheckParamUserTable(1, "cRankManager") ||
!S.CheckParamString(2, 3) ||
!S.CheckParamEnd(4)
)
if (!S.CheckParamUserTable(1, "cRankManager") || !S.CheckParamString(2, 3) || !S.CheckParamEnd(4))
{
return 0;
}
@ -1075,11 +943,7 @@ static int tolua_cRankManager_RemovePlayerRank(lua_State * L)
// cRankManager:RemovePlayerRank(PlayerUUID)
cLuaState S(L);
if (
!S.CheckParamStaticSelf("cRankManager") ||
!S.CheckParamUUID(2) ||
!S.CheckParamEnd(3)
)
if (!S.CheckParamStaticSelf("cRankManager") || !S.CheckParamUUID(2) || !S.CheckParamEnd(3))
{
return 0;
}
@ -1104,12 +968,9 @@ static int tolua_cRankManager_RemoveRank(lua_State * L)
// cRankManager:RemoveRank(RankName, [ReplacementRankName])
cLuaState S(L);
if (
!S.CheckParamUserTable(1, "cRankManager") ||
!S.CheckParamString(2) ||
if (!S.CheckParamUserTable(1, "cRankManager") || !S.CheckParamString(2) ||
// Param 3 is otpional, defaults to nil -> empty string
!S.CheckParamEnd(4)
)
!S.CheckParamEnd(4))
{
return 0;
}
@ -1134,11 +995,7 @@ static int tolua_cRankManager_RenameGroup(lua_State * L)
// cRankManager:RenameGroup(OldName, NewName)
cLuaState S(L);
if (
!S.CheckParamUserTable(1, "cRankManager") ||
!S.CheckParamString(2, 3) ||
!S.CheckParamEnd(4)
)
if (!S.CheckParamUserTable(1, "cRankManager") || !S.CheckParamString(2, 3) || !S.CheckParamEnd(4))
{
return 0;
}
@ -1166,11 +1023,7 @@ static int tolua_cRankManager_RenameRank(lua_State * L)
// cRankManager:RenameRank(OldName, NewName)
cLuaState S(L);
if (
!S.CheckParamUserTable(1, "cRankManager") ||
!S.CheckParamString(2, 3) ||
!S.CheckParamEnd(4)
)
if (!S.CheckParamUserTable(1, "cRankManager") || !S.CheckParamString(2, 3) || !S.CheckParamEnd(4))
{
return 0;
}
@ -1198,11 +1051,7 @@ static int tolua_cRankManager_SetDefaultRank(lua_State * L)
// cRankManager:SetDefaultRank(RankName) -> bool
cLuaState S(L);
if (
!S.CheckParamUserTable(1, "cRankManager") ||
!S.CheckParamString(2) ||
!S.CheckParamEnd(3)
)
if (!S.CheckParamUserTable(1, "cRankManager") || !S.CheckParamString(2) || !S.CheckParamEnd(3))
{
return 0;
}
@ -1227,12 +1076,8 @@ static int tolua_cRankManager_SetPlayerRank(lua_State * L)
// cRankManager:SetPlayerRank(PlayerUUID, PlayerName, RankName)
cLuaState S(L);
if (
!S.CheckParamStaticSelf("cRankManager") ||
!S.CheckParamUUID(2) ||
!S.CheckParamString(3, 4) ||
!S.CheckParamEnd(5)
)
if (!S.CheckParamStaticSelf("cRankManager") || !S.CheckParamUUID(2) || !S.CheckParamString(3, 4) ||
!S.CheckParamEnd(5))
{
return 0;
}
@ -1258,11 +1103,7 @@ static int tolua_cRankManager_SetRankVisuals(lua_State * L)
// cRankManager:SetRankVisuals(RankName, MsgPrefix, MsgSuffix, MsgNameColorCode)
cLuaState S(L);
if (
!S.CheckParamUserTable(1, "cRankManager") ||
!S.CheckParamString(2, 5) ||
!S.CheckParamEnd(6)
)
if (!S.CheckParamUserTable(1, "cRankManager") || !S.CheckParamString(2, 5) || !S.CheckParamEnd(6))
{
return 0;
}
@ -1288,51 +1129,47 @@ void cManualBindings::BindRankManager(lua_State * tolua_S)
// Fill in the functions (alpha-sorted):
tolua_beginmodule(tolua_S, "cRankManager");
tolua_function(tolua_S, "AddGroup", tolua_cRankManager_AddGroup);
tolua_function(tolua_S, "AddGroupToRank", tolua_cRankManager_AddGroupToRank);
tolua_function(tolua_S, "AddPermissionToGroup", tolua_cRankManager_AddPermissionToGroup);
tolua_function(tolua_S, "AddRestrictionToGroup", tolua_cRankManager_AddRestrictionToGroup);
tolua_function(tolua_S, "AddRank", tolua_cRankManager_AddRank);
tolua_function(tolua_S, "ClearPlayerRanks", tolua_cRankManager_ClearPlayerRanks);
tolua_function(tolua_S, "GetAllGroups", tolua_cRankManager_GetAllGroups);
tolua_function(tolua_S, "GetAllPermissions", tolua_cRankManager_GetAllPermissions);
tolua_function(tolua_S, "GetAllRestrictions", tolua_cRankManager_GetAllRestrictions);
tolua_function(tolua_S, "GetAllPermissionsRestrictions", tolua_cRankManager_GetAllPermissionsRestrictions);
tolua_function(tolua_S, "GetAllPlayerUUIDs", tolua_cRankManager_GetAllPlayerUUIDs);
tolua_function(tolua_S, "GetAllRanks", tolua_cRankManager_GetAllRanks);
tolua_function(tolua_S, "GetDefaultRank", tolua_cRankManager_GetDefaultRank);
tolua_function(tolua_S, "GetGroupPermissions", tolua_cRankManager_GetGroupPermissions);
tolua_function(tolua_S, "GetGroupRestrictions", tolua_cRankManager_GetGroupRestrictions);
tolua_function(tolua_S, "GetPlayerGroups", tolua_cRankManager_GetPlayerGroups);
tolua_function(tolua_S, "GetPlayerMsgVisuals", tolua_cRankManager_GetPlayerMsgVisuals);
tolua_function(tolua_S, "GetPlayerPermissions", tolua_cRankManager_GetPlayerPermissions);
tolua_function(tolua_S, "GetPlayerPermissions", tolua_cRankManager_GetPlayerRestrictions);
tolua_function(tolua_S, "GetPlayerRankName", tolua_cRankManager_GetPlayerRankName);
tolua_function(tolua_S, "GetPlayerName", tolua_cRankManager_GetPlayerName);
tolua_function(tolua_S, "GetRankGroups", tolua_cRankManager_GetRankGroups);
tolua_function(tolua_S, "GetRankPermissions", tolua_cRankManager_GetRankPermissions);
tolua_function(tolua_S, "GetRankRestrictions", tolua_cRankManager_GetRankRestrictions);
tolua_function(tolua_S, "GetRankVisuals", tolua_cRankManager_GetRankVisuals);
tolua_function(tolua_S, "GroupExists", tolua_cRankManager_GroupExists);
tolua_function(tolua_S, "IsGroupInRank", tolua_cRankManager_IsGroupInRank);
tolua_function(tolua_S, "IsPermissionInGroup", tolua_cRankManager_IsPermissionInGroup);
tolua_function(tolua_S, "IsRestrictionInGroup", tolua_cRankManager_IsRestrictionInGroup);
tolua_function(tolua_S, "IsPlayerRankSet", tolua_cRankManager_IsPlayerRankSet);
tolua_function(tolua_S, "RankExists", tolua_cRankManager_RankExists);
tolua_function(tolua_S, "RemoveGroup", tolua_cRankManager_RemoveGroup);
tolua_function(tolua_S, "RemoveGroupFromRank", tolua_cRankManager_RemoveGroupFromRank);
tolua_function(tolua_S, "RemovePermissionFromGroup", tolua_cRankManager_RemovePermissionFromGroup);
tolua_function(tolua_S, "RemoveRestrictionFromGroup", tolua_cRankManager_RemoveRestrictionFromGroup);
tolua_function(tolua_S, "RemovePlayerRank", tolua_cRankManager_RemovePlayerRank);
tolua_function(tolua_S, "RemoveRank", tolua_cRankManager_RemoveRank);
tolua_function(tolua_S, "RenameGroup", tolua_cRankManager_RenameGroup);
tolua_function(tolua_S, "RenameRank", tolua_cRankManager_RenameRank);
tolua_function(tolua_S, "SetDefaultRank", tolua_cRankManager_SetDefaultRank);
tolua_function(tolua_S, "SetPlayerRank", tolua_cRankManager_SetPlayerRank);
tolua_function(tolua_S, "SetRankVisuals", tolua_cRankManager_SetRankVisuals);
tolua_function(tolua_S, "AddGroup", tolua_cRankManager_AddGroup);
tolua_function(tolua_S, "AddGroupToRank", tolua_cRankManager_AddGroupToRank);
tolua_function(tolua_S, "AddPermissionToGroup", tolua_cRankManager_AddPermissionToGroup);
tolua_function(tolua_S, "AddRestrictionToGroup", tolua_cRankManager_AddRestrictionToGroup);
tolua_function(tolua_S, "AddRank", tolua_cRankManager_AddRank);
tolua_function(tolua_S, "ClearPlayerRanks", tolua_cRankManager_ClearPlayerRanks);
tolua_function(tolua_S, "GetAllGroups", tolua_cRankManager_GetAllGroups);
tolua_function(tolua_S, "GetAllPermissions", tolua_cRankManager_GetAllPermissions);
tolua_function(tolua_S, "GetAllRestrictions", tolua_cRankManager_GetAllRestrictions);
tolua_function(tolua_S, "GetAllPermissionsRestrictions", tolua_cRankManager_GetAllPermissionsRestrictions);
tolua_function(tolua_S, "GetAllPlayerUUIDs", tolua_cRankManager_GetAllPlayerUUIDs);
tolua_function(tolua_S, "GetAllRanks", tolua_cRankManager_GetAllRanks);
tolua_function(tolua_S, "GetDefaultRank", tolua_cRankManager_GetDefaultRank);
tolua_function(tolua_S, "GetGroupPermissions", tolua_cRankManager_GetGroupPermissions);
tolua_function(tolua_S, "GetGroupRestrictions", tolua_cRankManager_GetGroupRestrictions);
tolua_function(tolua_S, "GetPlayerGroups", tolua_cRankManager_GetPlayerGroups);
tolua_function(tolua_S, "GetPlayerMsgVisuals", tolua_cRankManager_GetPlayerMsgVisuals);
tolua_function(tolua_S, "GetPlayerPermissions", tolua_cRankManager_GetPlayerPermissions);
tolua_function(tolua_S, "GetPlayerPermissions", tolua_cRankManager_GetPlayerRestrictions);
tolua_function(tolua_S, "GetPlayerRankName", tolua_cRankManager_GetPlayerRankName);
tolua_function(tolua_S, "GetPlayerName", tolua_cRankManager_GetPlayerName);
tolua_function(tolua_S, "GetRankGroups", tolua_cRankManager_GetRankGroups);
tolua_function(tolua_S, "GetRankPermissions", tolua_cRankManager_GetRankPermissions);
tolua_function(tolua_S, "GetRankRestrictions", tolua_cRankManager_GetRankRestrictions);
tolua_function(tolua_S, "GetRankVisuals", tolua_cRankManager_GetRankVisuals);
tolua_function(tolua_S, "GroupExists", tolua_cRankManager_GroupExists);
tolua_function(tolua_S, "IsGroupInRank", tolua_cRankManager_IsGroupInRank);
tolua_function(tolua_S, "IsPermissionInGroup", tolua_cRankManager_IsPermissionInGroup);
tolua_function(tolua_S, "IsRestrictionInGroup", tolua_cRankManager_IsRestrictionInGroup);
tolua_function(tolua_S, "IsPlayerRankSet", tolua_cRankManager_IsPlayerRankSet);
tolua_function(tolua_S, "RankExists", tolua_cRankManager_RankExists);
tolua_function(tolua_S, "RemoveGroup", tolua_cRankManager_RemoveGroup);
tolua_function(tolua_S, "RemoveGroupFromRank", tolua_cRankManager_RemoveGroupFromRank);
tolua_function(tolua_S, "RemovePermissionFromGroup", tolua_cRankManager_RemovePermissionFromGroup);
tolua_function(tolua_S, "RemoveRestrictionFromGroup", tolua_cRankManager_RemoveRestrictionFromGroup);
tolua_function(tolua_S, "RemovePlayerRank", tolua_cRankManager_RemovePlayerRank);
tolua_function(tolua_S, "RemoveRank", tolua_cRankManager_RemoveRank);
tolua_function(tolua_S, "RenameGroup", tolua_cRankManager_RenameGroup);
tolua_function(tolua_S, "RenameRank", tolua_cRankManager_RenameRank);
tolua_function(tolua_S, "SetDefaultRank", tolua_cRankManager_SetDefaultRank);
tolua_function(tolua_S, "SetPlayerRank", tolua_cRankManager_SetPlayerRank);
tolua_function(tolua_S, "SetRankVisuals", tolua_cRankManager_SetRankVisuals);
tolua_endmodule(tolua_S);
}

File diff suppressed because it is too large Load Diff

View File

@ -8,10 +8,7 @@
cPlugin::cPlugin(const AString & a_FolderName) :
m_Status(cPluginManager::psDisabled),
m_Name(a_FolderName),
m_Version(0),
m_FolderName(a_FolderName)
m_Status(cPluginManager::psDisabled), m_Name(a_FolderName), m_Version(0), m_FolderName(a_FolderName)
{
}
@ -57,7 +54,3 @@ void cPlugin::SetLoadError(const AString & a_LoadError)
m_Status = cPluginManager::psError;
m_LoadError = a_LoadError;
}

View File

@ -1,7 +1,8 @@
// Plugin.h
// Declares the cPlugin class representing an interface that a plugin implementation needs to expose, with some helping functions
// Declares the cPlugin class representing an interface that a plugin implementation needs to expose, with some helping
// functions
@ -18,7 +19,7 @@
// tolua_begin
class cPlugin
{
public:
public:
// tolua_end
/** Creates a new instance.
@ -36,93 +37,266 @@ public:
virtual bool Load(void) = 0;
/** Unloads the plugin. Sets m_Status to psDisabled.
The default implementation removes the plugin's associations with cPluginManager, descendants should call it as well. */
The default implementation removes the plugin's associations with cPluginManager, descendants should call it as
well. */
virtual void Unload(void);
// Called each tick
virtual void Tick(float a_Dt) = 0;
/** Calls the specified hook with the params given. Returns the bool that the hook callback returns. */
virtual bool OnBlockSpread (cWorld & a_World, int a_BlockX, int a_BlockY, int a_BlockZ, eSpreadSource a_Source) = 0;
virtual bool OnBlockToPickups (cWorld & a_World, Vector3i a_BlockPos, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, const cBlockEntity * a_BlockEntity, const cEntity * a_Digger, const cItem * a_Tool, cItems & a_Pickups) = 0;
virtual bool OnBrewingCompleting (cWorld & a_World, cBrewingstandEntity & a_BrewingstandEntity) = 0;
virtual bool OnBrewingCompleted (cWorld & a_World, cBrewingstandEntity & a_BrewingstandEntity) = 0;
virtual bool OnChat (cPlayer & a_Player, AString & a_Message) = 0;
virtual bool OnChunkAvailable (cWorld & a_World, int a_ChunkX, int a_ChunkZ) = 0;
virtual bool OnChunkGenerated (cWorld & a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc) = 0;
virtual bool OnChunkGenerating (cWorld & a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc) = 0;
virtual bool OnChunkUnloaded (cWorld & a_World, int a_ChunkX, int a_ChunkZ) = 0;
virtual bool OnChunkUnloading (cWorld & a_World, int a_ChunkX, int a_ChunkZ) = 0;
virtual bool OnCollectingPickup (cPlayer & a_Player, cPickup & a_Pickup) = 0;
virtual bool OnCraftingNoRecipe (cPlayer & a_Player, cCraftingGrid & a_Grid, cCraftingRecipe & a_Recipe) = 0;
virtual bool OnDisconnect (cClientHandle & a_Client, const AString & a_Reason) = 0;
virtual bool OnEntityAddEffect (cEntity & a_Entity, int a_EffectType, int a_EffectDurationTicks, int a_EffectIntensity, double a_DistanceModifier) = 0;
virtual bool OnEntityTeleport (cEntity & a_Entity, const Vector3d & a_OldPosition, const Vector3d & a_NewPosition) = 0;
virtual bool OnEntityChangingWorld (cEntity & a_Entity, cWorld & a_World) = 0;
virtual bool OnEntityChangedWorld (cEntity & a_Entity, cWorld & a_World) = 0;
virtual bool OnExecuteCommand (cPlayer * a_Player, const AStringVector & a_Split, const AString & a_EntireCommand, cPluginManager::CommandResult & a_Result) = 0;
virtual bool OnExploded (cWorld & a_World, double a_ExplosionSize, bool a_CanCauseFire, double a_X, double a_Y, double a_Z, eExplosionSource a_Source, void * a_SourceData) = 0;
virtual bool OnExploding (cWorld & a_World, double & a_ExplosionSize, bool & a_CanCauseFire, double a_X, double a_Y, double a_Z, eExplosionSource a_Source, void * a_SourceData) = 0;
virtual bool OnHandshake (cClientHandle & a_Client, const AString & a_Username) = 0;
virtual bool OnHopperPullingItem (cWorld & a_World, cHopperEntity & a_Hopper, int a_DstSlotNum, cBlockEntityWithItems & a_SrcEntity, int a_SrcSlotNum) = 0;
virtual bool OnHopperPushingItem (cWorld & a_World, cHopperEntity & a_Hopper, int a_SrcSlotNum, cBlockEntityWithItems & a_DstEntity, int a_DstSlotNum) = 0;
virtual bool OnDropSpense (cWorld & a_World, cDropSpenserEntity & a_DropSpenser, int a_SlotNum) = 0;
virtual bool OnKilled (cEntity & a_Victim, TakeDamageInfo & a_TDI, AString & a_DeathMessage) = 0;
virtual bool OnKilling (cEntity & a_Victim, cEntity * a_Killer, TakeDamageInfo & a_TDI) = 0;
virtual bool OnLogin (cClientHandle & a_Client, UInt32 a_ProtocolVersion, const AString & a_Username) = 0;
virtual bool OnLoginForge (cClientHandle & a_Client, const AStringMap & a_Mods) = 0;
virtual bool OnPlayerAnimation (cPlayer & a_Player, int a_Animation) = 0;
virtual bool OnPlayerBreakingBlock (cPlayer & a_Player, int a_BlockX, int a_BlockY, int a_BlockZ, eBlockFace a_BlockFace, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta) = 0;
virtual bool OnPlayerBrokenBlock (cPlayer & a_Player, int a_BlockX, int a_BlockY, int a_BlockZ, eBlockFace a_BlockFace, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta) = 0;
virtual bool OnPlayerDestroyed (cPlayer & a_Player) = 0;
virtual bool OnPlayerEating (cPlayer & a_Player) = 0;
virtual bool OnPlayerFished (cPlayer & a_Player, const cItems & a_Reward, const int ExperienceAmount) = 0;
virtual bool OnPlayerFishing (cPlayer & a_Player, cItems & a_Reward, int & ExperienceAmount) = 0;
virtual bool OnPlayerFoodLevelChange (cPlayer & a_Player, int a_NewFoodLevel) = 0;
virtual bool OnPlayerJoined (cPlayer & a_Player) = 0;
virtual bool OnPlayerLeftClick (cPlayer & a_Player, int a_BlockX, int a_BlockY, int a_BlockZ, eBlockFace a_BlockFace, char a_Status) = 0;
virtual bool OnPlayerMoving (cPlayer & a_Player, const Vector3d & a_OldPosition, const Vector3d & a_NewPosition, bool a_PreviousIsOnGround) = 0;
virtual bool OnPlayerOpeningWindow (cPlayer & a_Player, cWindow & a_Window) = 0;
virtual bool OnPlayerPlacedBlock (cPlayer & a_Player, const sSetBlock & a_BlockChange) = 0;
virtual bool OnPlayerPlacingBlock (cPlayer & a_Player, const sSetBlock & a_BlockChange) = 0;
virtual bool OnPlayerCrouched (cPlayer & a_Player) = 0;
virtual bool OnPlayerRightClick (cPlayer & a_Player, int a_BlockX, int a_BlockY, int a_BlockZ, eBlockFace a_BlockFace, int a_CursorX, int a_CursorY, int a_CursorZ) = 0;
virtual bool OnBlockSpread(cWorld & a_World, int a_BlockX, int a_BlockY, int a_BlockZ, eSpreadSource a_Source) = 0;
virtual bool OnBlockToPickups(
cWorld & a_World,
Vector3i a_BlockPos,
BLOCKTYPE a_BlockType,
NIBBLETYPE a_BlockMeta,
const cBlockEntity * a_BlockEntity,
const cEntity * a_Digger,
const cItem * a_Tool,
cItems & a_Pickups
) = 0;
virtual bool OnBrewingCompleting(cWorld & a_World, cBrewingstandEntity & a_BrewingstandEntity) = 0;
virtual bool OnBrewingCompleted(cWorld & a_World, cBrewingstandEntity & a_BrewingstandEntity) = 0;
virtual bool OnChat(cPlayer & a_Player, AString & a_Message) = 0;
virtual bool OnChunkAvailable(cWorld & a_World, int a_ChunkX, int a_ChunkZ) = 0;
virtual bool OnChunkGenerated(cWorld & a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc) = 0;
virtual bool OnChunkGenerating(cWorld & a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc) = 0;
virtual bool OnChunkUnloaded(cWorld & a_World, int a_ChunkX, int a_ChunkZ) = 0;
virtual bool OnChunkUnloading(cWorld & a_World, int a_ChunkX, int a_ChunkZ) = 0;
virtual bool OnCollectingPickup(cPlayer & a_Player, cPickup & a_Pickup) = 0;
virtual bool OnCraftingNoRecipe(cPlayer & a_Player, cCraftingGrid & a_Grid, cCraftingRecipe & a_Recipe) = 0;
virtual bool OnDisconnect(cClientHandle & a_Client, const AString & a_Reason) = 0;
virtual bool OnEntityAddEffect(
cEntity & a_Entity,
int a_EffectType,
int a_EffectDurationTicks,
int a_EffectIntensity,
double a_DistanceModifier
) = 0;
virtual bool OnEntityTeleport(
cEntity & a_Entity,
const Vector3d & a_OldPosition,
const Vector3d & a_NewPosition
) = 0;
virtual bool OnEntityChangingWorld(cEntity & a_Entity, cWorld & a_World) = 0;
virtual bool OnEntityChangedWorld(cEntity & a_Entity, cWorld & a_World) = 0;
virtual bool OnExecuteCommand(
cPlayer * a_Player,
const AStringVector & a_Split,
const AString & a_EntireCommand,
cPluginManager::CommandResult & a_Result
) = 0;
virtual bool OnExploded(
cWorld & a_World,
double a_ExplosionSize,
bool a_CanCauseFire,
double a_X,
double a_Y,
double a_Z,
eExplosionSource a_Source,
void * a_SourceData
) = 0;
virtual bool OnExploding(
cWorld & a_World,
double & a_ExplosionSize,
bool & a_CanCauseFire,
double a_X,
double a_Y,
double a_Z,
eExplosionSource a_Source,
void * a_SourceData
) = 0;
virtual bool OnHandshake(cClientHandle & a_Client, const AString & a_Username) = 0;
virtual bool OnHopperPullingItem(
cWorld & a_World,
cHopperEntity & a_Hopper,
int a_DstSlotNum,
cBlockEntityWithItems & a_SrcEntity,
int a_SrcSlotNum
) = 0;
virtual bool OnHopperPushingItem(
cWorld & a_World,
cHopperEntity & a_Hopper,
int a_SrcSlotNum,
cBlockEntityWithItems & a_DstEntity,
int a_DstSlotNum
) = 0;
virtual bool OnDropSpense(cWorld & a_World, cDropSpenserEntity & a_DropSpenser, int a_SlotNum) = 0;
virtual bool OnKilled(cEntity & a_Victim, TakeDamageInfo & a_TDI, AString & a_DeathMessage) = 0;
virtual bool OnKilling(cEntity & a_Victim, cEntity * a_Killer, TakeDamageInfo & a_TDI) = 0;
virtual bool OnLogin(cClientHandle & a_Client, UInt32 a_ProtocolVersion, const AString & a_Username) = 0;
virtual bool OnLoginForge(cClientHandle & a_Client, const AStringMap & a_Mods) = 0;
virtual bool OnPlayerAnimation(cPlayer & a_Player, int a_Animation) = 0;
virtual bool OnPlayerBreakingBlock(
cPlayer & a_Player,
int a_BlockX,
int a_BlockY,
int a_BlockZ,
eBlockFace a_BlockFace,
BLOCKTYPE a_BlockType,
NIBBLETYPE a_BlockMeta
) = 0;
virtual bool OnPlayerBrokenBlock(
cPlayer & a_Player,
int a_BlockX,
int a_BlockY,
int a_BlockZ,
eBlockFace a_BlockFace,
BLOCKTYPE a_BlockType,
NIBBLETYPE a_BlockMeta
) = 0;
virtual bool OnPlayerDestroyed(cPlayer & a_Player) = 0;
virtual bool OnPlayerEating(cPlayer & a_Player) = 0;
virtual bool OnPlayerFished(cPlayer & a_Player, const cItems & a_Reward, const int ExperienceAmount) = 0;
virtual bool OnPlayerFishing(cPlayer & a_Player, cItems & a_Reward, int & ExperienceAmount) = 0;
virtual bool OnPlayerFoodLevelChange(cPlayer & a_Player, int a_NewFoodLevel) = 0;
virtual bool OnPlayerJoined(cPlayer & a_Player) = 0;
virtual bool OnPlayerLeftClick(
cPlayer & a_Player,
int a_BlockX,
int a_BlockY,
int a_BlockZ,
eBlockFace a_BlockFace,
char a_Status
) = 0;
virtual bool OnPlayerMoving(
cPlayer & a_Player,
const Vector3d & a_OldPosition,
const Vector3d & a_NewPosition,
bool a_PreviousIsOnGround
) = 0;
virtual bool OnPlayerOpeningWindow(cPlayer & a_Player, cWindow & a_Window) = 0;
virtual bool OnPlayerPlacedBlock(cPlayer & a_Player, const sSetBlock & a_BlockChange) = 0;
virtual bool OnPlayerPlacingBlock(cPlayer & a_Player, const sSetBlock & a_BlockChange) = 0;
virtual bool OnPlayerCrouched(cPlayer & a_Player) = 0;
virtual bool OnPlayerRightClick(
cPlayer & a_Player,
int a_BlockX,
int a_BlockY,
int a_BlockZ,
eBlockFace a_BlockFace,
int a_CursorX,
int a_CursorY,
int a_CursorZ
) = 0;
virtual bool OnPlayerRightClickingEntity(cPlayer & a_Player, cEntity & a_Entity) = 0;
virtual bool OnPlayerShooting (cPlayer & a_Player) = 0;
virtual bool OnPlayerSpawned (cPlayer & a_Player) = 0;
virtual bool OnPlayerTossingItem (cPlayer & a_Player) = 0;
virtual bool OnPlayerUsedBlock (cPlayer & a_Player, int a_BlockX, int a_BlockY, int a_BlockZ, eBlockFace a_BlockFace, int a_CursorX, int a_CursorY, int a_CursorZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta) = 0;
virtual bool OnPlayerUsedItem (cPlayer & a_Player, int a_BlockX, int a_BlockY, int a_BlockZ, eBlockFace a_BlockFace, int a_CursorX, int a_CursorY, int a_CursorZ) = 0;
virtual bool OnPlayerUsingBlock (cPlayer & a_Player, int a_BlockX, int a_BlockY, int a_BlockZ, eBlockFace a_BlockFace, int a_CursorX, int a_CursorY, int a_CursorZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta) = 0;
virtual bool OnPlayerUsingItem (cPlayer & a_Player, int a_BlockX, int a_BlockY, int a_BlockZ, eBlockFace a_BlockFace, int a_CursorX, int a_CursorY, int a_CursorZ) = 0;
virtual bool OnPluginMessage (cClientHandle & a_Client, const AString & a_Channel, ContiguousByteBufferView a_Message) = 0;
virtual bool OnPluginsLoaded (void) = 0;
virtual bool OnPostCrafting (cPlayer & a_Player, cCraftingGrid & a_Grid, cCraftingRecipe & a_Recipe) = 0;
virtual bool OnPreCrafting (cPlayer & a_Player, cCraftingGrid & a_Grid, cCraftingRecipe & a_Recipe) = 0;
virtual bool OnProjectileHitBlock (cProjectileEntity & a_Projectile, int a_BlockX, int a_BlockY, int a_BlockZ, eBlockFace a_Face, const Vector3d & a_BlockHitPos) = 0;
virtual bool OnProjectileHitEntity (cProjectileEntity & a_Projectile, cEntity & a_HitEntity) = 0;
virtual bool OnServerPing (cClientHandle & a_ClientHandle, AString & a_ServerDescription, int & a_OnlinePlayersCount, int & a_MaxPlayersCount, AString & a_Favicon) = 0;
virtual bool OnSpawnedEntity (cWorld & a_World, cEntity & a_Entity) = 0;
virtual bool OnSpawnedMonster (cWorld & a_World, cMonster & a_Monster) = 0;
virtual bool OnSpawningEntity (cWorld & a_World, cEntity & a_Entity) = 0;
virtual bool OnSpawningMonster (cWorld & a_World, cMonster & a_Monster) = 0;
virtual bool OnTakeDamage (cEntity & a_Receiver, TakeDamageInfo & a_TakeDamageInfo) = 0;
virtual bool OnUpdatedSign (cWorld & a_World, int a_BlockX, int a_BlockY, int a_BlockZ, const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4, cPlayer * a_Player) = 0;
virtual bool OnUpdatingSign (cWorld & a_World, int a_BlockX, int a_BlockY, int a_BlockZ, AString & a_Line1, AString & a_Line2, AString & a_Line3, AString & a_Line4, cPlayer * a_Player) = 0;
virtual bool OnWeatherChanged (cWorld & a_World) = 0;
virtual bool OnWeatherChanging (cWorld & a_World, eWeather & a_NewWeather) = 0;
virtual bool OnWorldStarted (cWorld & a_World) = 0;
virtual bool OnWorldTick (cWorld & a_World, std::chrono::milliseconds a_Dt, std::chrono::milliseconds a_LastTickDurationMSec) = 0;
virtual bool OnPlayerShooting(cPlayer & a_Player) = 0;
virtual bool OnPlayerSpawned(cPlayer & a_Player) = 0;
virtual bool OnPlayerTossingItem(cPlayer & a_Player) = 0;
virtual bool OnPlayerUsedBlock(
cPlayer & a_Player,
int a_BlockX,
int a_BlockY,
int a_BlockZ,
eBlockFace a_BlockFace,
int a_CursorX,
int a_CursorY,
int a_CursorZ,
BLOCKTYPE a_BlockType,
NIBBLETYPE a_BlockMeta
) = 0;
virtual bool OnPlayerUsedItem(
cPlayer & a_Player,
int a_BlockX,
int a_BlockY,
int a_BlockZ,
eBlockFace a_BlockFace,
int a_CursorX,
int a_CursorY,
int a_CursorZ
) = 0;
virtual bool OnPlayerUsingBlock(
cPlayer & a_Player,
int a_BlockX,
int a_BlockY,
int a_BlockZ,
eBlockFace a_BlockFace,
int a_CursorX,
int a_CursorY,
int a_CursorZ,
BLOCKTYPE a_BlockType,
NIBBLETYPE a_BlockMeta
) = 0;
virtual bool OnPlayerUsingItem(
cPlayer & a_Player,
int a_BlockX,
int a_BlockY,
int a_BlockZ,
eBlockFace a_BlockFace,
int a_CursorX,
int a_CursorY,
int a_CursorZ
) = 0;
virtual bool OnPluginMessage(
cClientHandle & a_Client,
const AString & a_Channel,
ContiguousByteBufferView a_Message
) = 0;
virtual bool OnPluginsLoaded(void) = 0;
virtual bool OnPostCrafting(cPlayer & a_Player, cCraftingGrid & a_Grid, cCraftingRecipe & a_Recipe) = 0;
virtual bool OnPreCrafting(cPlayer & a_Player, cCraftingGrid & a_Grid, cCraftingRecipe & a_Recipe) = 0;
virtual bool OnProjectileHitBlock(
cProjectileEntity & a_Projectile,
int a_BlockX,
int a_BlockY,
int a_BlockZ,
eBlockFace a_Face,
const Vector3d & a_BlockHitPos
) = 0;
virtual bool OnProjectileHitEntity(cProjectileEntity & a_Projectile, cEntity & a_HitEntity) = 0;
virtual bool OnServerPing(
cClientHandle & a_ClientHandle,
AString & a_ServerDescription,
int & a_OnlinePlayersCount,
int & a_MaxPlayersCount,
AString & a_Favicon
) = 0;
virtual bool OnSpawnedEntity(cWorld & a_World, cEntity & a_Entity) = 0;
virtual bool OnSpawnedMonster(cWorld & a_World, cMonster & a_Monster) = 0;
virtual bool OnSpawningEntity(cWorld & a_World, cEntity & a_Entity) = 0;
virtual bool OnSpawningMonster(cWorld & a_World, cMonster & a_Monster) = 0;
virtual bool OnTakeDamage(cEntity & a_Receiver, TakeDamageInfo & a_TakeDamageInfo) = 0;
virtual bool OnUpdatedSign(
cWorld & a_World,
int a_BlockX,
int a_BlockY,
int a_BlockZ,
const AString & a_Line1,
const AString & a_Line2,
const AString & a_Line3,
const AString & a_Line4,
cPlayer * a_Player
) = 0;
virtual bool OnUpdatingSign(
cWorld & a_World,
int a_BlockX,
int a_BlockY,
int a_BlockZ,
AString & a_Line1,
AString & a_Line2,
AString & a_Line3,
AString & a_Line4,
cPlayer * a_Player
) = 0;
virtual bool OnWeatherChanged(cWorld & a_World) = 0;
virtual bool OnWeatherChanging(cWorld & a_World, eWeather & a_NewWeather) = 0;
virtual bool OnWorldStarted(cWorld & a_World) = 0;
virtual bool OnWorldTick(
cWorld & a_World,
std::chrono::milliseconds a_Dt,
std::chrono::milliseconds a_LastTickDurationMSec
) = 0;
// tolua_begin
const AString & GetName(void) const { return m_Name; }
const AString & GetName(void) const { return m_Name; }
void SetName(const AString & a_Name) { m_Name = a_Name; }
int GetVersion(void) const { return m_Version; }
int GetVersion(void) const { return m_Version; }
void SetVersion(int a_Version) { m_Version = a_Version; }
/** Returns the name of the folder (in the Plugins folder) from which the plugin is loaded. */
const AString & GetFolderName(void) const {return m_FolderName; }
const AString & GetFolderName(void) const { return m_FolderName; }
/** Returns the folder relative to the MCS Executable, from which the plugin is loaded. */
AString GetLocalFolder(void) const;
@ -138,7 +312,7 @@ public:
// Needed for ManualBindings' tolua_ForEach<>
static const char * GetClassStatic(void) { return "cPlugin"; }
protected:
protected:
friend class cPluginManager;
cPluginManager::ePluginStatus m_Status;
@ -159,7 +333,3 @@ protected:
/** Sets m_LoadError to the specified string and m_Status to psError. */
void SetLoadError(const AString & a_LoadError);
}; // tolua_export

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