use cc::gfx namespace (#2576)

This commit is contained in:
minggo
2020-06-16 18:10:41 +08:00
committed by GitHub
parent 715f43bbb6
commit e07bc0821c
238 changed files with 7262 additions and 6733 deletions
+45 -45
View File
@@ -181,47 +181,47 @@ namespace
// v2
typedef const std::map<PVR2TexturePixelFormat, GFXFormat> _pixel2_formathash;
typedef const std::map<PVR2TexturePixelFormat, gfx::GFXFormat> _pixel2_formathash;
static const _pixel2_formathash::value_type v2_pixel_formathash_value[] =
{
_pixel2_formathash::value_type(PVR2TexturePixelFormat::BGRA8888, GFXFormat::BGRA8),
_pixel2_formathash::value_type(PVR2TexturePixelFormat::RGBA8888, GFXFormat::RGBA8),
_pixel2_formathash::value_type(PVR2TexturePixelFormat::RGBA4444, GFXFormat::RGBA4),
_pixel2_formathash::value_type(PVR2TexturePixelFormat::RGBA5551, GFXFormat::RGB5A1),
_pixel2_formathash::value_type(PVR2TexturePixelFormat::RGB565, GFXFormat::R5G6B5),
_pixel2_formathash::value_type(PVR2TexturePixelFormat::RGB888, GFXFormat::RGB8),
_pixel2_formathash::value_type(PVR2TexturePixelFormat::A8, GFXFormat::A8),
_pixel2_formathash::value_type(PVR2TexturePixelFormat::I8, GFXFormat::L8),
_pixel2_formathash::value_type(PVR2TexturePixelFormat::AI88, GFXFormat::LA8),
_pixel2_formathash::value_type(PVR2TexturePixelFormat::BGRA8888, gfx::GFXFormat::BGRA8),
_pixel2_formathash::value_type(PVR2TexturePixelFormat::RGBA8888, gfx::GFXFormat::RGBA8),
_pixel2_formathash::value_type(PVR2TexturePixelFormat::RGBA4444, gfx::GFXFormat::RGBA4),
_pixel2_formathash::value_type(PVR2TexturePixelFormat::RGBA5551, gfx::GFXFormat::RGB5A1),
_pixel2_formathash::value_type(PVR2TexturePixelFormat::RGB565, gfx::GFXFormat::R5G6B5),
_pixel2_formathash::value_type(PVR2TexturePixelFormat::RGB888, gfx::GFXFormat::RGB8),
_pixel2_formathash::value_type(PVR2TexturePixelFormat::A8, gfx::GFXFormat::A8),
_pixel2_formathash::value_type(PVR2TexturePixelFormat::I8, gfx::GFXFormat::L8),
_pixel2_formathash::value_type(PVR2TexturePixelFormat::AI88, gfx::GFXFormat::LA8),
_pixel2_formathash::value_type(PVR2TexturePixelFormat::PVRTC2BPP_RGBA, GFXFormat::PVRTC_RGBA2),
_pixel2_formathash::value_type(PVR2TexturePixelFormat::PVRTC4BPP_RGBA, GFXFormat::PVRTC_RGBA4),
_pixel2_formathash::value_type(PVR2TexturePixelFormat::PVRTC2BPP_RGBA, gfx::GFXFormat::PVRTC_RGBA2),
_pixel2_formathash::value_type(PVR2TexturePixelFormat::PVRTC4BPP_RGBA, gfx::GFXFormat::PVRTC_RGBA4),
};
static const int PVR2_MAX_TABLE_ELEMENTS = sizeof(v2_pixel_formathash_value) / sizeof(v2_pixel_formathash_value[0]);
static const _pixel2_formathash v2_pixel_formathash(v2_pixel_formathash_value, v2_pixel_formathash_value + PVR2_MAX_TABLE_ELEMENTS);
// v3
typedef const std::map<PVR3TexturePixelFormat, GFXFormat> _pixel3_formathash;
typedef const std::map<PVR3TexturePixelFormat, gfx::GFXFormat> _pixel3_formathash;
static _pixel3_formathash::value_type v3_pixel_formathash_value[] =
{
_pixel3_formathash::value_type(PVR3TexturePixelFormat::BGRA8888, GFXFormat::BGRA8),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::RGBA8888, GFXFormat::RGBA8),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::RGBA4444, GFXFormat::RGBA4),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::RGBA5551, GFXFormat::RGB5A1),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::RGB565, GFXFormat::R5G6B5),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::RGB888, GFXFormat::RGB8),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::A8, GFXFormat::A8),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::L8, GFXFormat::L8),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::LA88, GFXFormat::LA8),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::BGRA8888, gfx::GFXFormat::BGRA8),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::RGBA8888, gfx::GFXFormat::RGBA8),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::RGBA4444, gfx::GFXFormat::RGBA4),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::RGBA5551, gfx::GFXFormat::RGB5A1),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::RGB565, gfx::GFXFormat::R5G6B5),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::RGB888, gfx::GFXFormat::RGB8),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::A8, gfx::GFXFormat::A8),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::L8, gfx::GFXFormat::L8),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::LA88, gfx::GFXFormat::LA8),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::PVRTC2BPP_RGB, GFXFormat::PVRTC_RGB2),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::PVRTC2BPP_RGBA, GFXFormat::PVRTC_RGBA2),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::PVRTC4BPP_RGB, GFXFormat::PVRTC_RGB4),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::PVRTC4BPP_RGBA, GFXFormat::PVRTC_RGBA4),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::PVRTC2BPP_RGB, gfx::GFXFormat::PVRTC_RGB2),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::PVRTC2BPP_RGBA, gfx::GFXFormat::PVRTC_RGBA2),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::PVRTC4BPP_RGB, gfx::GFXFormat::PVRTC_RGB4),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::PVRTC4BPP_RGBA, gfx::GFXFormat::PVRTC_RGBA4),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::ETC1, GFXFormat::ETC_RGB8),
_pixel3_formathash::value_type(PVR3TexturePixelFormat::ETC1, gfx::GFXFormat::ETC_RGB8),
};
static const int PVR3_MAX_TABLE_ELEMENTS = sizeof(v3_pixel_formathash_value) / sizeof(v3_pixel_formathash_value[0]);
@@ -303,7 +303,7 @@ namespace
//////////////////////////////////////////////////////////////////////////
bool Image::PNG_PREMULTIPLIED_ALPHA_ENABLED = false;
Image::Image(): _renderFormat(GFXFormat::UNKNOWN)
Image::Image(): _renderFormat(gfx::GFXFormat::UNKNOWN)
{
}
@@ -485,12 +485,12 @@ Image::Format Image::detectFormat(const unsigned char * data, ssize_t dataLen)
bool Image::hasAlpha() const
{
return GFX_FORMAT_INFOS[static_cast<int>(_renderFormat)].hasAlpha;
return gfx::GFX_FORMAT_INFOS[static_cast<int>(_renderFormat)].hasAlpha;
}
bool Image::isCompressed() const
{
return GFX_FORMAT_INFOS[static_cast<int>(_renderFormat)].isCompressed;
return gfx::GFX_FORMAT_INFOS[static_cast<int>(_renderFormat)].isCompressed;
}
namespace
@@ -597,10 +597,10 @@ bool Image::initWithJpgData(const unsigned char * data, ssize_t dataLen)
// we only support RGB or grayscale
if (cinfo.jpeg_color_space == JCS_GRAYSCALE)
_renderFormat = GFXFormat::L8;
_renderFormat = gfx::GFXFormat::L8;
else {
cinfo.out_color_space = JCS_RGB;
_renderFormat = GFXFormat::RGB8;
_renderFormat = gfx::GFXFormat::RGB8;
}
/* Start decompression jpeg here */
@@ -723,16 +723,16 @@ bool Image::initWithPngData(const unsigned char * data, ssize_t dataLen)
switch (color_type)
{
case PNG_COLOR_TYPE_GRAY:
_renderFormat = GFXFormat::L8;
_renderFormat = gfx::GFXFormat::L8;
break;
case PNG_COLOR_TYPE_GRAY_ALPHA:
_renderFormat = GFXFormat::LA8;
_renderFormat = gfx::GFXFormat::LA8;
break;
case PNG_COLOR_TYPE_RGB:
_renderFormat = GFXFormat::RGB8;
_renderFormat = gfx::GFXFormat::RGB8;
break;
case PNG_COLOR_TYPE_RGB_ALPHA:
_renderFormat = GFXFormat::RGBA8;
_renderFormat = gfx::GFXFormat::RGBA8;
break;
default:
break;
@@ -829,7 +829,7 @@ bool Image::initWithPVRv2Data(const unsigned char * data, ssize_t dataLen)
}
_renderFormat = it->second;
int bpp = GFX_FORMAT_INFOS[static_cast<int>(_renderFormat)].size;
int bpp = gfx::GFX_FORMAT_INFOS[static_cast<int>(_renderFormat)].size;
//Reset num of mipmaps
_numberOfMipmaps = 0;
@@ -932,7 +932,7 @@ bool Image::initWithPVRv3Data(const unsigned char * data, ssize_t dataLen)
}
_renderFormat = it->second;
int bpp = GFX_FORMAT_INFOS[static_cast<int>(_renderFormat)].size;;
int bpp = gfx::GFX_FORMAT_INFOS[static_cast<int>(_renderFormat)].size;;
// flags
int flags = CC_SWAP_INT32_LITTLE_TO_HOST(header->flags);
@@ -1037,7 +1037,7 @@ bool Image::initWithETCData(const unsigned char * data, ssize_t dataLen)
return false;
}
_renderFormat = GFXFormat::ETC_RGB8;
_renderFormat = gfx::GFXFormat::ETC_RGB8;
_dataLen = dataLen - ETC_PKM_HEADER_SIZE;
_data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
memcpy(_data, static_cast<const unsigned char*>(data) + ETC_PKM_HEADER_SIZE, _dataLen);
@@ -1064,9 +1064,9 @@ bool Image::initWithETC2Data(const unsigned char * data, ssize_t dataLen)
etc2_uint32 format = etc2_pkm_get_format(header);
if (format == ETC2_RGB_NO_MIPMAPS)
_renderFormat = GFXFormat::ETC2_RGB8;
_renderFormat = gfx::GFXFormat::ETC2_RGB8;
else
_renderFormat = GFXFormat::ETC2_RGBA8;
_renderFormat = gfx::GFXFormat::ETC2_RGBA8;
_dataLen = dataLen - ETC2_PKM_HEADER_SIZE;
_data = static_cast<unsigned char*>(malloc(_dataLen * sizeof(unsigned char)));
@@ -1093,7 +1093,7 @@ bool Image::initWithWebpData(const unsigned char * data, ssize_t dataLen)
if (config.input.width == 0 || config.input.height == 0) break;
config.output.colorspace = config.input.has_alpha?MODE_rgbA:MODE_RGB;
_renderFormat = config.input.has_alpha ? GFXFormat::RGBA8 : GFXFormat::RGB8;
_renderFormat = config.input.has_alpha ? gfx::GFXFormat::RGBA8 : gfx::GFXFormat::RGB8;
_width = config.input.width;
_height = config.input.height;
@@ -1131,7 +1131,7 @@ bool Image::initWithRawData(const unsigned char * data, ssize_t dataLen, int wid
_height = height;
_width = width;
_hasPremultipliedAlpha = preMulti;
_renderFormat = GFXFormat::RGBA8;
_renderFormat = gfx::GFXFormat::RGBA8;
// only RGBA8888 supported
int bytesPerComponent = 4;
@@ -1151,7 +1151,7 @@ bool Image::initWithRawData(const unsigned char * data, ssize_t dataLen, int wid
bool Image::saveToFile(const std::string& filename, bool isToRGB)
{
//only support for Image::PixelFormat::RGB888 or Image::PixelFormat::RGBA8888 uncompressed data
if (isCompressed() || (_renderFormat != GFXFormat::RGB8 && _renderFormat != GFXFormat::RGBA8))
if (isCompressed() || (_renderFormat != gfx::GFXFormat::RGB8 && _renderFormat != gfx::GFXFormat::RGBA8))
{
CCLOG("saveToFile: Image: saveToFile is only support for Image::PixelFormat::RGB888 or Image::PixelFormat::RGBA8888 uncompressed data for now");
return false;
@@ -1405,7 +1405,7 @@ bool Image::saveImageToJPG(const std::string& filePath)
void Image::premultipliedAlpha()
{
if (PNG_PREMULTIPLIED_ALPHA_ENABLED && _renderFormat == GFXFormat::RGBA8)
if (PNG_PREMULTIPLIED_ALPHA_ENABLED && _renderFormat == gfx::GFXFormat::RGBA8)
{
unsigned int* fourBytes = (unsigned int*)_data;
for(int i = 0; i < _width * _height; i++)
+54 -58
View File
@@ -31,15 +31,17 @@ THE SOFTWARE.
// premultiply alpha, or the effect will wrong when want to use other pixel format in Texture2D,
// such as RGB888, RGB5A1
#define CC_RGB_PREMULTIPLY_ALPHA(vr, vg, vb, va) \
(unsigned)(((unsigned)((unsigned char)(vr) * ((unsigned char)(va) + 1)) >> 8) | \
((unsigned)((unsigned char)(vg) * ((unsigned char)(va) + 1) >> 8) << 8) | \
((unsigned)((unsigned char)(vb) * ((unsigned char)(va) + 1) >> 8) << 16) | \
((unsigned)(unsigned char)(va) << 24))
#define CC_RGB_PREMULTIPLY_ALPHA(vr, vg, vb, va) \
(unsigned)(((unsigned)((unsigned char)(vr) * ((unsigned char)(va) + 1)) >> 8) | \
((unsigned)((unsigned char)(vg) * ((unsigned char)(va) + 1) >> 8) << 8) | \
((unsigned)((unsigned char)(vb) * ((unsigned char)(va) + 1) >> 8) << 16) | \
((unsigned)(unsigned char)(va) << 24))
namespace cc {
namespace gfx {
enum class GFXFormat : unsigned int;
} // namespace gfx
/**
* @addtogroup platform
@@ -49,15 +51,13 @@ enum class GFXFormat : unsigned int;
/**
@brief Structure which can tell where mipmap begins and how long is it
*/
typedef struct _MipmapInfo
{
unsigned char* address = nullptr;
typedef struct _MipmapInfo {
unsigned char *address = nullptr;
int offset = 0;
int len = 0;
}MipmapInfo;
} MipmapInfo;
class Image : public Ref
{
class Image : public Ref {
public:
/**
* @js ctor
@@ -65,8 +65,7 @@ public:
Image();
/** Supported formats for Image */
enum class Format
{
enum class Format {
//! JPEG
JPG,
//! PNG
@@ -88,17 +87,14 @@ public:
struct PixelFormatInfo {
PixelFormatInfo(int aBpp, bool aCompressed, bool anAlpha)
: bpp(aBpp)
, compressed(aCompressed)
, alpha(anAlpha)
{}
: bpp(aBpp), compressed(aCompressed), alpha(anAlpha) {}
int bpp;
bool compressed;
bool alpha;
};
typedef std::map<GFXFormat, const PixelFormatInfo> PixelFormatInfoMap;
typedef std::map<gfx::GFXFormat, const PixelFormatInfo> PixelFormatInfoMap;
/**
* Enables or disables premultiplied alpha for PNG files.
@@ -106,7 +102,7 @@ public:
* @param enabled (default: true)
*/
static void setPNGPremultipliedAlphaEnabled(bool enabled) { PNG_PREMULTIPLIED_ALPHA_ENABLED = enabled; }
/** treats (or not) PVR files as if they have alpha premultiplied.
Since it is impossible to know at runtime if the PVR images have the alpha channel premultiplied, it is
possible load them as if they have (or not) the alpha channel premultiplied.
@@ -120,7 +116,7 @@ public:
@param path the absolute file path.
@return true if loaded correctly.
*/
bool initWithImageFile(const std::string& path);
bool initWithImageFile(const std::string &path);
/**
@brief Load image from stream buffer.
@@ -130,25 +126,25 @@ public:
* @js NA
* @lua NA
*/
bool initWithImageData(const unsigned char * data, ssize_t dataLen);
bool initWithImageData(const unsigned char *data, ssize_t dataLen);
// @warning kFmtRawData only support RGBA8888
bool initWithRawData(const unsigned char * data, ssize_t dataLen, int width, int height, int bitsPerComponent, bool preMulti = false);
bool initWithRawData(const unsigned char *data, ssize_t dataLen, int width, int height, int bitsPerComponent, bool preMulti = false);
// Getters
inline unsigned char* getData() const { return _data; }
inline ssize_t getDataLen() const { return _dataLen; }
inline Format getFileType() const { return _fileType; }
inline GFXFormat getRenderFormat() const { return _renderFormat; }
inline int getWidth() const { return _width; }
inline int getHeight() const { return _height; }
inline int getNumberOfMipmaps() const { return _numberOfMipmaps; }
inline const MipmapInfo* getMipmaps() const { return _mipmaps; }
inline bool hasPremultipliedAlpha() const { return _hasPremultipliedAlpha; }
inline std::string getFilePath() const { return _filePath; }
inline unsigned char *getData() const { return _data; }
inline ssize_t getDataLen() const { return _dataLen; }
inline Format getFileType() const { return _fileType; }
inline gfx::GFXFormat getRenderFormat() const { return _renderFormat; }
inline int getWidth() const { return _width; }
inline int getHeight() const { return _height; }
inline int getNumberOfMipmaps() const { return _numberOfMipmaps; }
inline const MipmapInfo *getMipmaps() const { return _mipmaps; }
inline bool hasPremultipliedAlpha() const { return _hasPremultipliedAlpha; }
inline std::string getFilePath() const { return _filePath; }
bool hasAlpha() const;
bool isCompressed() const;
bool hasAlpha() const;
bool isCompressed() const;
/**
@brief Save Image data to the specified file, with specified format.
@@ -158,17 +154,17 @@ public:
bool saveToFile(const std::string &filename, bool isToRGB = true);
protected:
bool initWithJpgData(const unsigned char * data, ssize_t dataLen);
bool initWithPngData(const unsigned char * data, ssize_t dataLen);
bool initWithWebpData(const unsigned char * data, ssize_t dataLen);
bool initWithPVRData(const unsigned char * data, ssize_t dataLen);
bool initWithPVRv2Data(const unsigned char * data, ssize_t dataLen);
bool initWithPVRv3Data(const unsigned char * data, ssize_t dataLen);
bool initWithETCData(const unsigned char * data, ssize_t dataLen);
bool initWithETC2Data(const unsigned char * data, ssize_t dataLen);
bool initWithJpgData(const unsigned char *data, ssize_t dataLen);
bool initWithPngData(const unsigned char *data, ssize_t dataLen);
bool initWithWebpData(const unsigned char *data, ssize_t dataLen);
bool initWithPVRData(const unsigned char *data, ssize_t dataLen);
bool initWithPVRv2Data(const unsigned char *data, ssize_t dataLen);
bool initWithPVRv3Data(const unsigned char *data, ssize_t dataLen);
bool initWithETCData(const unsigned char *data, ssize_t dataLen);
bool initWithETC2Data(const unsigned char *data, ssize_t dataLen);
bool saveImageToPNG(const std::string& filePath, bool isToRGB = true);
bool saveImageToJPG(const std::string& filePath);
bool saveImageToPNG(const std::string &filePath, bool isToRGB = true);
bool saveImageToJPG(const std::string &filePath);
void premultipliedAlpha();
@@ -187,8 +183,8 @@ protected:
int _width = 0;
int _height = 0;
Format _fileType = Format::UNKNOWN;
GFXFormat _renderFormat;
MipmapInfo _mipmaps[MIPMAP_MAX]; // pointer to mipmap images
gfx::GFXFormat _renderFormat;
MipmapInfo _mipmaps[MIPMAP_MAX]; // pointer to mipmap images
int _numberOfMipmaps = 0;
// false if we can't auto detect the image is premultiplied or not.
bool _hasPremultipliedAlpha = false;
@@ -196,12 +192,12 @@ protected:
protected:
// noncopyable
Image(const Image&) = delete;
Image& operator=(const Image&) = delete;
Image(const Image &) = delete;
Image &operator=(const Image &) = delete;
// nonmoveable
Image(Image&&) = delete;
Image& operator=(Image&&) = delete;
Image(Image &&) = delete;
Image &operator=(Image &&) = delete;
/**
* @js NA
@@ -209,18 +205,18 @@ protected:
*/
virtual ~Image();
Format detectFormat(const unsigned char * data, ssize_t dataLen);
bool isPng(const unsigned char * data, ssize_t dataLen);
bool isJpg(const unsigned char * data, ssize_t dataLen);
bool isWebp(const unsigned char * data, ssize_t dataLen);
bool isPvr(const unsigned char * data, ssize_t dataLen);
bool isEtc(const unsigned char * data, ssize_t dataLen);
bool isEtc2(const unsigned char * data, ssize_t dataLen);
Format detectFormat(const unsigned char *data, ssize_t dataLen);
bool isPng(const unsigned char *data, ssize_t dataLen);
bool isJpg(const unsigned char *data, ssize_t dataLen);
bool isWebp(const unsigned char *data, ssize_t dataLen);
bool isPvr(const unsigned char *data, ssize_t dataLen);
bool isEtc(const unsigned char *data, ssize_t dataLen);
bool isEtc2(const unsigned char *data, ssize_t dataLen);
};
// end of platform group
/// @}
}
} // namespace cc
/// @endcond
+342 -288
View File
@@ -1,257 +1,311 @@
#include "base/ccMacros.h"
#ifndef CC_CORE_CORE_DEF_H_
#define CC_CORE_CORE_DEF_H_
#define CC_CORE_CORE_DEF_H_
// Initial compiler-related stuff to set.
#define CC_COMPILER_MSVC 1
#define CC_COMPILER_CLANG 2
#define CC_COMPILER_GNUC 3
// Initial compiler-related stuff to set.
#define CC_COMPILER_MSVC 1
#define CC_COMPILER_CLANG 2
#define CC_COMPILER_GNUC 3
// CPU Architecture
#define CC_CPU_UNKNOWN 0
#define CC_CPU_X86 1
#define CC_CPU_PPC 2
#define CC_CPU_ARM 3
#define CC_CPU_MIPS 4
// CPU Architecture
#define CC_CPU_UNKNOWN 0
#define CC_CPU_X86 1
#define CC_CPU_PPC 2
#define CC_CPU_ARM 3
#define CC_CPU_MIPS 4
// 32-bits or 64-bits CPU
#define CC_CPU_ARCH_32 1
#define CC_CPU_ARCH_64 2
// 32-bits or 64-bits CPU
#define CC_CPU_ARCH_32 1
#define CC_CPU_ARCH_64 2
// Endian
#define CC_ENDIAN_LITTLE 1
#define CC_ENDIAN_BIG 2
// Endian
#define CC_ENDIAN_LITTLE 1
#define CC_ENDIAN_BIG 2
// Charset
#define CC_CHARSET_UNICODE 1
#define CC_CHARSET_MULTIBYTE 2
// Charset
#define CC_CHARSET_UNICODE 1
#define CC_CHARSET_MULTIBYTE 2
// Precision
#define CC_PRECISION_FLOAT 1
#define CC_PRECISION_DOUBLE 2
// Precision
#define CC_PRECISION_FLOAT 1
#define CC_PRECISION_DOUBLE 2
// Mode
#define CC_MODE_DEBUG 1
#define CC_MODE_RELEASE 2
// Mode
#define CC_MODE_DEBUG 1
#define CC_MODE_RELEASE 2
// Memory Allocator
#define CC_MEMORY_ALLOCATOR_STD 0
#define CC_MEMORY_ALLOCATOR_NEDPOOLING 1
#define CC_MEMORY_ALLOCATOR_JEMALLOC 2
// Memory Allocator
#define CC_MEMORY_ALLOCATOR_STD 0
#define CC_MEMORY_ALLOCATOR_NEDPOOLING 1
#define CC_MEMORY_ALLOCATOR_JEMALLOC 2
// STL Memory Allocator
#define CC_STL_MEMORY_ALLOCATOR_STANDARD 1
#define CC_STL_MEMORY_ALLOCATOR_CUSTOM 2
// STL Memory Allocator
#define CC_STL_MEMORY_ALLOCATOR_STANDARD 1
#define CC_STL_MEMORY_ALLOCATOR_CUSTOM 2
// Compiler type and version recognition
#if defined( _MSC_VER )
# define CC_COMPILER CC_COMPILER_MSVC
# if _MSC_VER >= 1900
# define CC_COMPILER_VERSION 130
# elif _MSC_VER >= 1800
# define CC_COMPILER_VERSION 120
# elif _MSC_VER >= 1700
# define CC_COMPILER_VERSION 110
# elif _MSC_VER >= 1600
# define CC_COMPILER_VERSION 100
# elif _MSC_VER >= 1500
# define CC_COMPILER_VERSION 90
# elif _MSC_VER >= 1400
# define CC_COMPILER_VERSION 80
# elif _MSC_VER >= 1300
# define CC_COMPILER_VERSION 70
# endif
#elif defined( __clang__ )
# define CC_COMPILER CC_COMPILER_CLANG
# define CC_COMPILER_VERSION (((__clang_major__)*100) + (__clang_minor__*10) + __clang_patchlevel__)
#elif defined( __GNUC__ )
# define CC_COMPILER CC_COMPILER_GNUC
# define CC_COMPILER_VERSION (((__GNUC__)*100) + (__GNUC_MINOR__*10) + __GNUC_PATCHLEVEL__)
#else
# error "Unknown compiler. Abort!"
#endif
// Compiler type and version recognition
#if defined(_MSC_VER)
#define CC_COMPILER CC_COMPILER_MSVC
#if _MSC_VER >= 1900
#define CC_COMPILER_VERSION 130
#elif _MSC_VER >= 1800
#define CC_COMPILER_VERSION 120
#elif _MSC_VER >= 1700
#define CC_COMPILER_VERSION 110
#elif _MSC_VER >= 1600
#define CC_COMPILER_VERSION 100
#elif _MSC_VER >= 1500
#define CC_COMPILER_VERSION 90
#elif _MSC_VER >= 1400
#define CC_COMPILER_VERSION 80
#elif _MSC_VER >= 1300
#define CC_COMPILER_VERSION 70
#endif
#elif defined(__clang__)
#define CC_COMPILER CC_COMPILER_CLANG
#define CC_COMPILER_VERSION (((__clang_major__)*100) + (__clang_minor__ * 10) + __clang_patchlevel__)
#elif defined(__GNUC__)
#define CC_COMPILER CC_COMPILER_GNUC
#define CC_COMPILER_VERSION (((__GNUC__)*100) + (__GNUC_MINOR__ * 10) + __GNUC_PATCHLEVEL__)
#else
#error "Unknown compiler. Abort!"
#endif
#if (CC_PLATFORM == CC_PLATFORM_WINDOWS)
# define CC_ENDIAN CC_ENDIAN_LITTLE
#else
# if (CC_PLATFORM == CC_PLATFORM_MAC_OSX)
# include <machine/endian.h>
# else
# include <endian.h>
# endif // (CC_PLATFORM == CC_PLATFORM_MAC_OSX)
#
# if __BYTE_ORDER == __LITTLE_ENDIAN
# define CC_ENDIAN CC_ENDIAN_LITTLE
# else
# define CC_ENDIAN CC_ENDIAN_BIG
# endif //__BYTE_ORDER == __LITTLE_ENDIAN
#endif
#if (CC_PLATFORM == CC_PLATFORM_WINDOWS)
#define CC_ENDIAN CC_ENDIAN_LITTLE
#else
#if (CC_PLATFORM == CC_PLATFORM_MAC_OSX)
#include <machine/endian.h>
#else
#include <endian.h>
#endif // (CC_PLATFORM == CC_PLATFORM_MAC_OSX)
#
#if __BYTE_ORDER == __LITTLE_ENDIAN
#define CC_ENDIAN CC_ENDIAN_LITTLE
#else
#define CC_ENDIAN CC_ENDIAN_BIG
#endif //__BYTE_ORDER == __LITTLE_ENDIAN
#endif
// CPU architecture type recognition
#if (defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64))) ||(defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)))
# define CC_CPU CC_CPU_X86
#elif CC_PLATFORM == CC_PLATFORM_MAC_OSX && CC_ENDIAN == CC_ENDIAN_BIG
# define CC_CPU CC_CPU_PPC
#elif CC_PLATFORM == CC_PLATFORM_MAC_OSX
# define COCOS_CPU CC_CPU_X86
#elif CC_PLATFORM == CC_PLATFORM_MAC_IOS && (defined(__i386__) || defined(__x86_64__))
# define CC_CPU CC_CPU_X86
#elif defined(__arm__) || defined(_M_ARM) || defined(__arm64__) || defined(_aarch64_)
# define CC_CPU CC_CPU_ARM
#elif defined(__mips64) || defined(__mips64_)
# define CC_CPU CC_CPU_MIPS
#else
# define CC_CPU CC_CPU_UNKNOWN
#endif
// CPU architecture type recognition
#if (defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64))) || (defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)))
#define CC_CPU CC_CPU_X86
#elif CC_PLATFORM == CC_PLATFORM_MAC_OSX && CC_ENDIAN == CC_ENDIAN_BIG
#define CC_CPU CC_CPU_PPC
#elif CC_PLATFORM == CC_PLATFORM_MAC_OSX
#define COCOS_CPU CC_CPU_X86
#elif CC_PLATFORM == CC_PLATFORM_MAC_IOS && (defined(__i386__) || defined(__x86_64__))
#define CC_CPU CC_CPU_X86
#elif defined(__arm__) || defined(_M_ARM) || defined(__arm64__) || defined(_aarch64_)
#define CC_CPU CC_CPU_ARM
#elif defined(__mips64) || defined(__mips64_)
#define CC_CPU CC_CPU_MIPS
#else
#define CC_CPU CC_CPU_UNKNOWN
#endif
#if defined(__x86_64__) || defined(_M_X64) || defined(__powerpc64__) || defined(__alpha__) || defined(__ia64__) || defined(__s390__) || defined(__s390x__) || defined(__arm64__) || defined(_aarch64_) || defined(__mips64) || defined(__mips64_)
# define CC_CPU_ARCH CC_CPU_ARCH_64
#else
# define CC_CPU_ARCH CC_CPU_ARCH_32
#endif
#if defined(__x86_64__) || defined(_M_X64) || defined(__powerpc64__) || defined(__alpha__) || defined(__ia64__) || defined(__s390__) || defined(__s390x__) || defined(__arm64__) || defined(_aarch64_) || defined(__mips64) || defined(__mips64_)
#define CC_CPU_ARCH CC_CPU_ARCH_64
#else
#define CC_CPU_ARCH CC_CPU_ARCH_32
#endif
#if (__cplusplus >= 201103L)
# define CC_C11
# define register
#endif
#if (__cplusplus >= 201103L)
#define CC_C11
#define register
#endif
// C11 features
#if (CC_COMPILER == CC_COMPILER_MSVC)
# if (_MSC_VER >= 1700)
# define CC_C11_TYPED_ENUMS
# endif
#elif (CC_COMPILER == CC_COMPILER_GNUC)
# if (__GNUC_MINOR__ >= 4)
# define CC_C11_TYPED_ENUMS
# endif
#endif
// C11 features
#if (CC_COMPILER == CC_COMPILER_MSVC)
#if (_MSC_VER >= 1700)
#define CC_C11_TYPED_ENUMS
#endif
#elif (CC_COMPILER == CC_COMPILER_GNUC)
#if (__GNUC_MINOR__ >= 4)
#define CC_C11_TYPED_ENUMS
#endif
#endif
// Disable MSVC warning
#if (CC_COMPILER == CC_COMPILER_MSVC)
# pragma warning(disable:4251 4275 4819)
# ifndef _CRT_SECURE_NO_DEPRECATE
# define _CRT_SECURE_NO_DEPRECATE
# endif
# ifndef _SCL_SECURE_NO_DEPRECATE
# define _SCL_SECURE_NO_DEPRECATE
# endif
#endif
// Disable MSVC warning
#if (CC_COMPILER == CC_COMPILER_MSVC)
#pragma warning(disable : 4251 4275 4819)
#ifndef _CRT_SECURE_NO_DEPRECATE
#define _CRT_SECURE_NO_DEPRECATE
#endif
#ifndef _SCL_SECURE_NO_DEPRECATE
#define _SCL_SECURE_NO_DEPRECATE
#endif
#endif
// Charset Settings
#if defined(_UNICODE) || defined(UNICODE)
# define CC_CHARSET CC_CHARSET_UNICODE
#else
# define CC_CHARSET CC_CHARSET_MULTIBYTE
#endif
// Charset Settings
#if defined(_UNICODE) || defined(UNICODE)
#define CC_CHARSET CC_CHARSET_UNICODE
#else
#define CC_CHARSET CC_CHARSET_MULTIBYTE
#endif
#if CC_COMPILER == CC_COMPILER_MSVC
# if CC_COMPILER_VERSION >= 120
# define CC_INLINE __forceinline
# else
# define CC_INLINE inline
# endif
#elif defined(__MINGW32__)
# if !defined(CC_INLINE)
# define CC_INLINE __inline
# endif
#elif !defined(ANDROID) && (CC_COMPILER == CC_COMPILER_GNUC || CC_COMPILER == CC_COMPILER_CLANG)
# define CC_INLINE inline __attribute__((always_inline))
#else
# define CC_INLINE __inline
#endif
#if CC_COMPILER == CC_COMPILER_MSVC
#if CC_COMPILER_VERSION >= 120
#define CC_INLINE __forceinline
#else
#define CC_INLINE inline
#endif
#elif defined(__MINGW32__)
#if !defined(CC_INLINE)
#define CC_INLINE __inline
#endif
#elif !defined(ANDROID) && (CC_COMPILER == CC_COMPILER_GNUC || CC_COMPILER == CC_COMPILER_CLANG)
#define CC_INLINE inline __attribute__((always_inline))
#else
#define CC_INLINE __inline
#endif
// Asserts expression is true at compile-time
#define CC_COMPILER_ASSERT(x) typedef int COMPILER_ASSERT_[!!(x)]
// Asserts expression is true at compile-time
#define CC_COMPILER_ASSERT(x) typedef int COMPILER_ASSERT_[!!(x)]
#if (CC_COMPILER == CC_COMPILER_MSVC)
# define CC_RESTRICT __restrict //MSVC
#else
# define CC_RESTRICT __restrict__ //GCC... and others?
#endif
#if (CC_COMPILER == CC_COMPILER_MSVC)
#define CC_RESTRICT __restrict //MSVC
#else
#define CC_RESTRICT __restrict__ //GCC... and others?
#endif
#define CC_CACHELINE_SIZE 64
#define CC_CACHELINE_SIZE 64
#if (CC_COMPILER == CC_COMPILER_MSVC)
// MSVC ENABLE/DISABLE WARNING DEFINITION
# define CC_DISABLE_WARNINGS() \
__pragma(warning(push, 0))
#if (CC_COMPILER == CC_COMPILER_MSVC)
// MSVC ENABLE/DISABLE WARNING DEFINITION
#define CC_DISABLE_WARNINGS() \
__pragma(warning(push, 0))
# define CC_ENABLE_WARNINGS() \
__pragma(warning(pop))
#elif (CC_COMPILER == CC_COMPILER_GNUC)
// GCC ENABLE/DISABLE WARNING DEFINITION
# define CC_DISABLE_WARNINGS() \
_Pragma("GCC diagnostic push") \
_Pragma("GCC diagnostic ignored \"-Wall\"") \
_Pragma("clang diagnostic ignored \"-Wextra\"") \
_Pragma("clang diagnostic ignored \"-Wtautological-compare\"")
#define CC_ENABLE_WARNINGS() \
__pragma(warning(pop))
#elif (CC_COMPILER == CC_COMPILER_GNUC)
// GCC ENABLE/DISABLE WARNING DEFINITION
#define CC_DISABLE_WARNINGS() \
_Pragma("GCC diagnostic push") \
_Pragma("GCC diagnostic ignored \"-Wall\"") \
_Pragma("clang diagnostic ignored \"-Wextra\"") \
_Pragma("clang diagnostic ignored \"-Wtautological-compare\"")
# define CC_ENABLE_WARNINGS() \
_Pragma("GCC diagnostic pop")
#elif (CC_COMPILER == CC_COMPILER_CLANG)
// CLANG ENABLE/DISABLE WARNING DEFINITION
# define CC_DISABLE_WARNINGS() \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Wall\"") \
_Pragma("clang diagnostic ignored \"-Wextra\"") \
_Pragma("clang diagnostic ignored \"-Wtautological-compare\"")
#define CC_ENABLE_WARNINGS() \
_Pragma("GCC diagnostic pop")
#elif (CC_COMPILER == CC_COMPILER_CLANG)
// CLANG ENABLE/DISABLE WARNING DEFINITION
#define CC_DISABLE_WARNINGS() \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Wall\"") \
_Pragma("clang diagnostic ignored \"-Wextra\"") \
_Pragma("clang diagnostic ignored \"-Wtautological-compare\"")
# define CC_ENABLE_WARNINGS() \
_Pragma("clang diagnostic pop")
#endif
#define CC_ENABLE_WARNINGS() \
_Pragma("clang diagnostic pop")
#endif
#if (CC_COMPILER == CC_COMPILER_MSVC)
# define CC_ALIGN(N) __declspec(align(N))
# define CC_CACHE_ALIGN __declspec(align(CC_CACHELINE_SIZE))
# define CC_PACKED_ALIGN(N) __declspec(align(N))
#if (CC_COMPILER == CC_COMPILER_MSVC)
#define CC_ALIGN(N) __declspec(align(N))
#define CC_CACHE_ALIGN __declspec(align(CC_CACHELINE_SIZE))
#define CC_PACKED_ALIGN(N) __declspec(align(N))
# define CC_ALIGNED_DECL(type, var, alignment) __declspec(align(alignment)) type var
#define CC_ALIGNED_DECL(type, var, alignment) __declspec(align(alignment)) type var
# define CC_READ_COMPILER_BARRIER() _ReadBarrier()
# define CC_WRITE_COMPILER_BARRIER() _WriteBarrier()
# define CC_COMPILER_BARRIER() _ReadWriteBarrier()
#define CC_READ_COMPILER_BARRIER() _ReadBarrier()
#define CC_WRITE_COMPILER_BARRIER() _WriteBarrier()
#define CC_COMPILER_BARRIER() _ReadWriteBarrier()
# define CC_READ_MEMORY_BARRIER() MemoryBarrier()
# define CC_WRITE_MEMORY_BARRIER() MemoryBarrier()
# define CC_MEMORY_BARRIER() MemoryBarrier()
#define CC_READ_MEMORY_BARRIER() MemoryBarrier()
#define CC_WRITE_MEMORY_BARRIER() MemoryBarrier()
#define CC_MEMORY_BARRIER() MemoryBarrier()
# define CC_CPU_READ_MEMORY_BARRIER() do { __asm { lfence } } while (0)
# define CC_CPU_WRITE_MEMORY_BARRIER() do { __asm { sfence } } while (0)
# define CC_CPU_MEMORY_BARRIER() do { __asm { mfence } } while (0)
#define CC_CPU_READ_MEMORY_BARRIER() \
do { \
__asm { lfence} \
} while (0)
#define CC_CPU_WRITE_MEMORY_BARRIER() \
do { \
__asm { sfence} \
} while (0)
#define CC_CPU_MEMORY_BARRIER() \
do { \
__asm { mfence} \
} while (0)
#elif (CC_COMPILER == CC_COMPILER_GNUC) || (CC_COMPILER == CC_COMPILER_CLANG)
# define CC_ALIGN(N) __attribute__((__aligned__((N))))
# define CC_CACHE_ALIGN __attribute__((__aligned__((CC_CACHELINE_SIZE))))
# define CC_PACKED_ALIGN(N) __attribute__((packed, aligned(N)))
#elif (CC_COMPILER == CC_COMPILER_GNUC) || (CC_COMPILER == CC_COMPILER_CLANG)
#define CC_ALIGN(N) __attribute__((__aligned__((N))))
#define CC_CACHE_ALIGN __attribute__((__aligned__((CC_CACHELINE_SIZE))))
#define CC_PACKED_ALIGN(N) __attribute__((packed, aligned(N)))
# define CC_ALIGNED_DECL(type, var, alignment) type var __attribute__((__aligned__(alignment)))
#define CC_ALIGNED_DECL(type, var, alignment) type var __attribute__((__aligned__(alignment)))
# define CC_READ_COMPILER_BARRIER() do { __asm__ __volatile__ ("" : : : "memory"); } while (0)
# define CC_WRITE_COMPILER_BARRIER() do { __asm__ __volatile__ ("" : : : "memory"); } while (0)
# define CC_COMPILER_BARRIER() do { __asm__ __volatile__ ("" : : : "memory"); } while (0)
#define CC_READ_COMPILER_BARRIER() \
do { \
__asm__ __volatile__("" \
: \
: \
: "memory"); \
} while (0)
#define CC_WRITE_COMPILER_BARRIER() \
do { \
__asm__ __volatile__("" \
: \
: \
: "memory"); \
} while (0)
#define CC_COMPILER_BARRIER() \
do { \
__asm__ __volatile__("" \
: \
: \
: "memory"); \
} while (0)
# define CC_READ_MEMORY_BARRIER() do { __sync_synchronize(); } while (0)
# define CC_WRITE_MEMORY_BARRIER() do { __sync_synchronize(); } while (0)
# define CC_MEMORY_BARRIER() do { __sync_synchronize(); } while (0)
#define CC_READ_MEMORY_BARRIER() \
do { \
__sync_synchronize(); \
} while (0)
#define CC_WRITE_MEMORY_BARRIER() \
do { \
__sync_synchronize(); \
} while (0)
#define CC_MEMORY_BARRIER() \
do { \
__sync_synchronize(); \
} while (0)
# define CC_CPU_READ_MEMORY_BARRIER() do { __asm__ __volatile__ ("lfence" : : : "memory"); } while (0)
# define CC_CPU_WRITE_MEMORY_BARRIER() do { __asm__ __volatile__ ("sfence" : : : "memory"); } while (0)
# define CC_CPU_MEMORY_BARRIER() do { __asm__ __volatile__ ("mfence" : : : "memory"); } while (0)
#define CC_CPU_READ_MEMORY_BARRIER() \
do { \
__asm__ __volatile__("lfence" \
: \
: \
: "memory"); \
} while (0)
#define CC_CPU_WRITE_MEMORY_BARRIER() \
do { \
__asm__ __volatile__("sfence" \
: \
: \
: "memory"); \
} while (0)
#define CC_CPU_MEMORY_BARRIER() \
do { \
__asm__ __volatile__("mfence" \
: \
: \
: "memory"); \
} while (0)
#else
# error "Unsupported compiler!"
#endif
#else
#error "Unsupported compiler!"
#endif
#define CC_SIMD_ALIGNMENT 16
#define CC_SIMD_ALIGNMENT 16
#if (CC_COMPILER == CC_COMPILER_MSVC)
# define CC_DECL_MALLOC __declspec(restrict) __declspec(noalias)
#else
# define CC_DECL_MALLOC __attribute__ ((malloc))
#endif
#if (CC_COMPILER == CC_COMPILER_MSVC)
#define CC_DECL_MALLOC __declspec(restrict) __declspec(noalias)
#else
#define CC_DECL_MALLOC __attribute__((malloc))
#endif
/* Stack-alignment
/* Stack-alignment
If macro __CC_SIMD_ALIGN_STACK defined, means there requests
special code to ensure stack align to a 16-bytes boundary.
@@ -262,90 +316,90 @@ Note:
variables, so you need to wrap those alignment required functions
with extra function call.
*/
#if defined(__INTEL_COMPILER)
// For intel's compiler, simply calling alloca seems to do the right
// thing. The size of the allocated block seems to be irrelevant.
# define CC_SIMD_ALIGN_STACK() _alloca(16)
# define CC_SIMD_ALIGN_ATTRIBUTE
#if defined(__INTEL_COMPILER)
// For intel's compiler, simply calling alloca seems to do the right
// thing. The size of the allocated block seems to be irrelevant.
#define CC_SIMD_ALIGN_STACK() _alloca(16)
#define CC_SIMD_ALIGN_ATTRIBUTE
#elif (CC_CPU == CC_CPU_X86) && (CC_COMPILER == CC_COMPILER_GNUC || CC_COMPILER == CC_COMPILER_CLANG) && (CC_CPU_ARCH != CC_CPU_ARCH_64)
// mark functions with GCC attribute to force stack alignment to 16 bytes
# define CC_SIMD_ALIGN_ATTRIBUTE __attribute__((force_align_arg_pointer))
#elif (CC_COMPILER == CC_COMPILER_MSVC)
// Fortunately, MSVC will align the stack automatically
# define CC_SIMD_ALIGN_ATTRIBUTE
#else
# define CC_SIMD_ALIGN_ATTRIBUTE
#endif
#elif (CC_CPU == CC_CPU_X86) && (CC_COMPILER == CC_COMPILER_GNUC || CC_COMPILER == CC_COMPILER_CLANG) && (CC_CPU_ARCH != CC_CPU_ARCH_64)
// mark functions with GCC attribute to force stack alignment to 16 bytes
#define CC_SIMD_ALIGN_ATTRIBUTE __attribute__((force_align_arg_pointer))
#elif (CC_COMPILER == CC_COMPILER_MSVC)
// Fortunately, MSVC will align the stack automatically
#define CC_SIMD_ALIGN_ATTRIBUTE
#else
#define CC_SIMD_ALIGN_ATTRIBUTE
#endif
#if defined (__GNUC__)
# define CC_FUNC ((const char*) (__PRETTY_FUNCTION__))
#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 19901L
# define CC_FUNC ((const char*) (__func__))
#else
# define CC_FUNC ((const char*) (__FUNCTION__))
#endif
#if defined(__GNUC__)
#define CC_FUNC ((const char *)(__PRETTY_FUNCTION__))
#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 19901L
#define CC_FUNC ((const char *)(__func__))
#else
#define CC_FUNC ((const char *)(__FUNCTION__))
#endif
// mode
#if (defined(_DEBUG) || defined(DEBUG)) && (CC_PLATFORM == CC_PLATFORM_WINDOWS)
# define CC_MODE CC_MODE_DEBUG
#else
# define CC_MODE CC_MODE_RELEASE
#endif
// mode
#if (defined(_DEBUG) || defined(DEBUG)) && (CC_PLATFORM == CC_PLATFORM_WINDOWS)
#define CC_MODE CC_MODE_DEBUG
#else
#define CC_MODE CC_MODE_RELEASE
#endif
// Engine Memory Management
#if (CC_PLATFORM == CC_PLATFORM_WINDOWS)
#if (CC_MODE == CC_MODE_DEBUG)
# define CC_MEMORY_TRACKER
#endif
#elif (CC_PLATFORM == CC_PLATFORM_ANDROID)
//# define CC_MEMORY_TRACKER
#else
#endif
// Engine Memory Management
#if (CC_PLATFORM == CC_PLATFORM_WINDOWS)
#if (CC_MODE == CC_MODE_DEBUG)
#define CC_MEMORY_TRACKER
#endif
#elif (CC_PLATFORM == CC_PLATFORM_ANDROID)
//# define CC_MEMORY_TRACKER
#else
#endif
// use simd
//#define CC_USE_SIMD
// use simd
//#define CC_USE_SIMD
// Memory Allocator
#if (CC_PLATFORM == CC_PLATFORM_WINDOWS)
# define CC_MEMORY_ALLOCATOR CC_MEMORY_ALLOCATOR_STD
# undef CC_MEMORY_TRACKER
//#if defined(CC_MEMORY_TRACKER)
//# define CC_MEMORY_ALLOCATOR CC_MEMORY_ALLOCATOR_JEMALLOC
//#else
//# define CC_MEMORY_ALLOCATOR CC_MEMORY_ALLOCATOR_STD
//#endif
#elif (CC_PLATFORM == CC_PLATFORM_ANDROID)
#if defined(CC_MEMORY_TRACKER)
# define CC_MEMORY_ALLOCATOR CC_MEMORY_ALLOCATOR_JEMALLOC
#else
# define CC_MEMORY_ALLOCATOR CC_MEMORY_ALLOCATOR_STD
#endif
#else
# define CC_MEMORY_ALLOCATOR CC_MEMORY_ALLOCATOR_STD
#endif
// Memory Allocator
#if (CC_PLATFORM == CC_PLATFORM_WINDOWS)
#define CC_MEMORY_ALLOCATOR CC_MEMORY_ALLOCATOR_STD
#undef CC_MEMORY_TRACKER
//#if defined(CC_MEMORY_TRACKER)
//# define CC_MEMORY_ALLOCATOR CC_MEMORY_ALLOCATOR_JEMALLOC
//#else
//# define CC_MEMORY_ALLOCATOR CC_MEMORY_ALLOCATOR_STD
//#endif
#elif (CC_PLATFORM == CC_PLATFORM_ANDROID)
#if defined(CC_MEMORY_TRACKER)
#define CC_MEMORY_ALLOCATOR CC_MEMORY_ALLOCATOR_JEMALLOC
#else
#define CC_MEMORY_ALLOCATOR CC_MEMORY_ALLOCATOR_STD
#endif
#else
#define CC_MEMORY_ALLOCATOR CC_MEMORY_ALLOCATOR_STD
#endif
// STL memory allocator
#if (CC_MEMORY_ALLOCATOR == CC_MEMORY_ALLOCATOR_STD)
#define CC_STL_MEMORY_ALLOCATOR CC_STL_MEMORY_ALLOCATOR_STANDARD
#else
#define CC_STL_MEMORY_ALLOCATOR CC_STL_MEMORY_ALLOCATOR_CUSTOM
#endif
// STL memory allocator
#if (CC_MEMORY_ALLOCATOR == CC_MEMORY_ALLOCATOR_STD)
#define CC_STL_MEMORY_ALLOCATOR CC_STL_MEMORY_ALLOCATOR_STANDARD
#else
#define CC_STL_MEMORY_ALLOCATOR CC_STL_MEMORY_ALLOCATOR_CUSTOM
#endif
#define CC_TOSTR(s) #s
#define CC_TOSTR(s) #s
#if (CC_PLATFORM == CC_PLATFORM_WINDOWS)
# ifdef CC_STATIC
# define CC_CORE_API
# else
# ifdef CC_CORE_EXPORTS
# define CC_CORE_API __declspec(dllexport)
# else
# define CC_CORE_API __declspec(dllimport)
# endif
# endif
#else
# define CC_CORE_API
#endif
#if (CC_PLATFORM == CC_PLATFORM_WINDOWS)
#ifdef CC_STATIC
#define CC_CORE_API
#else
#ifdef CC_CORE_EXPORTS
#define CC_CORE_API __declspec(dllexport)
#else
#define CC_CORE_API __declspec(dllimport)
#endif
#endif
#else
#define CC_CORE_API
#endif
#endif // CC_CORE_CORE_DEF_H_
+11 -12
View File
@@ -1,19 +1,18 @@
#ifndef CC_CORE_TYPE_DEF_H_
#define CC_CORE_TYPE_DEF_H_
typedef unsigned int uint;
typedef unsigned short ushort;
typedef unsigned long ulong;
typedef unsigned int uint;
typedef unsigned short ushort;
typedef unsigned long ulong;
typedef unsigned int FlagBits;
#define CC_ENUM_OPERATORS(type_) \
CC_INLINE type_ operator | (type_ lhs, type_ rhs) { return (type_)(static_cast<std::underlying_type<type_>::type/**/>(lhs) | static_cast<std::underlying_type<type_>::type/**/>(rhs)); } \
CC_INLINE void operator |= (type_& lhs, type_ rhs) { lhs = (type_)(static_cast<std::underlying_type<type_>::type/**/>(lhs) | static_cast<std::underlying_type<type_>::type/**/>(rhs)); } \
CC_INLINE int operator & (type_ lhs, type_ rhs) { return (int)(static_cast<std::underlying_type<type_>::type/**/>(lhs) & static_cast<std::underlying_type<type_>::type/**/>(rhs)); } \
CC_INLINE void operator &= (type_& lhs, type_ rhs) { lhs = (type_)(static_cast<std::underlying_type<type_>::type/**/>(lhs) & static_cast<std::underlying_type<type_>::type/**/>(rhs)); } \
CC_INLINE bool operator || (type_ lhs, type_ rhs) { return (static_cast<std::underlying_type<type_>::type/**/>(lhs) || static_cast<std::underlying_type<type_>::type/**/>(rhs)); } \
CC_INLINE bool operator && (type_ lhs, type_ rhs) { return (static_cast<std::underlying_type<type_>::type/**/>(lhs) && static_cast<std::underlying_type<type_>::type/**/>(rhs)); }
typedef unsigned int FlagBits;
#define CC_ENUM_OPERATORS(type_) \
CC_INLINE type_ operator|(type_ lhs, type_ rhs) { return (type_)(static_cast<std::underlying_type<type_>::type /**/>(lhs) | static_cast<std::underlying_type<type_>::type /**/>(rhs)); } \
CC_INLINE void operator|=(type_ &lhs, type_ rhs) { lhs = (type_)(static_cast<std::underlying_type<type_>::type /**/>(lhs) | static_cast<std::underlying_type<type_>::type /**/>(rhs)); } \
CC_INLINE int operator&(type_ lhs, type_ rhs) { return (int)(static_cast<std::underlying_type<type_>::type /**/>(lhs) & static_cast<std::underlying_type<type_>::type /**/>(rhs)); } \
CC_INLINE void operator&=(type_ &lhs, type_ rhs) { lhs = (type_)(static_cast<std::underlying_type<type_>::type /**/>(lhs) & static_cast<std::underlying_type<type_>::type /**/>(rhs)); } \
CC_INLINE bool operator||(type_ lhs, type_ rhs) { return (static_cast<std::underlying_type<type_>::type /**/>(lhs) || static_cast<std::underlying_type<type_>::type /**/>(rhs)); } \
CC_INLINE bool operator&&(type_ lhs, type_ rhs) { return (static_cast<std::underlying_type<type_>::type /**/>(lhs) && static_cast<std::underlying_type<type_>::type /**/>(rhs)); }
#endif // CC_CORE_TYPE_DEF_H_
@@ -2,6 +2,7 @@
#include "GFXBindingLayout.h"
namespace cc {
namespace gfx {
GFXBindingLayout::GFXBindingLayout(GFXDevice *device)
: GFXObject(GFXObjectType::BINDING_LAYOUT), _device(device) {
@@ -61,4 +62,5 @@ void GFXBindingLayout::bindSampler(uint binding, GFXSampler *sampler) {
}
}
}
} // namespace gfx
} // namespace cc
@@ -4,6 +4,7 @@
#include "GFXDef.h"
namespace cc {
namespace gfx {
class CC_CORE_API GFXBindingLayout : public GFXObject {
public:
@@ -28,6 +29,7 @@ protected:
bool _isDirty = false;
};
}
} // namespace gfx
} // namespace cc
#endif // CC_CORE_GFX_BINDING_LAYOUT_H_
+3 -1
View File
@@ -2,6 +2,7 @@
#include "GFXBuffer.h"
namespace cc {
namespace gfx {
GFXBuffer::GFXBuffer(GFXDevice *device)
: GFXObject(GFXObjectType::BUFFER), _device(device) {
@@ -10,4 +11,5 @@ GFXBuffer::GFXBuffer(GFXDevice *device)
GFXBuffer::~GFXBuffer() {
}
}
} // namespace gfx
} // namespace cc
+3 -1
View File
@@ -4,6 +4,7 @@
#include "GFXDef.h"
namespace cc {
namespace gfx {
class CC_CORE_API GFXBuffer : public GFXObject {
public:
@@ -36,6 +37,7 @@ protected:
uint8_t *_buffer = nullptr;
};
}
} // namespace gfx
} // namespace cc
#endif // CC_CORE_GFX_BUFFER_H_
+3 -1
View File
@@ -1,6 +1,7 @@
#pragma once
namespace cc {
namespace gfx {
enum class GFXCmdType : uint8_t {
BEGIN_RENDER_PASS,
@@ -23,4 +24,5 @@ public:
virtual void clear() = 0;
};
}
} // namespace gfx
} // namespace cc
@@ -2,6 +2,7 @@
#include "GFXCommandAllocator.h"
namespace cc {
namespace gfx {
GFXCommandAllocator::GFXCommandAllocator(GFXDevice *device)
: GFXObject(GFXObjectType::COMMAND_ALLOCATOR), _device(device) {
@@ -10,4 +11,5 @@ GFXCommandAllocator::GFXCommandAllocator(GFXDevice *device)
GFXCommandAllocator::~GFXCommandAllocator() {
}
}
} // namespace gfx
} // namespace cc
@@ -4,6 +4,7 @@
#include "GFXDef.h"
namespace cc {
namespace gfx {
class CC_CORE_API GFXCommandAllocator : public GFXObject {
public:
@@ -20,6 +21,7 @@ protected:
GFXDevice *_device = nullptr;
};
}
} // namespace gfx
} // namespace cc
#endif // CC_CORE_GFX_COMMAND_ALLOCATOR_H_
@@ -2,6 +2,7 @@
#include "GFXCommandBuffer.h"
namespace cc {
namespace gfx {
GFXCommandBuffer::GFXCommandBuffer(GFXDevice *device)
: GFXObject(GFXObjectType::COMMAND_BUFFER), _device(device) {
@@ -10,4 +11,5 @@ GFXCommandBuffer::GFXCommandBuffer(GFXDevice *device)
GFXCommandBuffer::~GFXCommandBuffer() {
}
}
} // namespace gfx
} // namespace cc
@@ -4,6 +4,7 @@
#include "GFXDef.h"
namespace cc {
namespace gfx {
class CC_CORE_API GFXCommandBuffer : public GFXObject {
public:
@@ -49,6 +50,7 @@ protected:
uint32_t _numTriangles = 0;
};
}
} // namespace gfx
} // namespace cc
#endif // CC_CORE_GFX_COMMAND_ALLOCATOR_H_
@@ -3,6 +3,7 @@
#include "GFXCommand.h"
namespace cc {
namespace gfx {
#define INITIAL_CAPACITY 1
@@ -85,4 +86,5 @@ private:
int _freeIdx = 0;
};
}
} // namespace gfx
} // namespace cc
+3 -1
View File
@@ -2,6 +2,7 @@
#include "GFXContext.h"
namespace cc {
namespace gfx {
GFXContext::GFXContext(GFXDevice *device)
: _device(device) {
@@ -10,4 +11,5 @@ GFXContext::GFXContext(GFXDevice *device)
GFXContext::~GFXContext() {
}
}
} // namespace gfx
} // namespace cc
+3 -1
View File
@@ -4,6 +4,7 @@
#include "GFXDef.h"
namespace cc {
namespace gfx {
class CC_CORE_API GFXContext : public Object {
public:
@@ -30,6 +31,7 @@ protected:
GFXFormat _depthStencilFmt = GFXFormat::UNKNOWN;
};
}
} // namespace gfx
} // namespace cc
#endif // CC_CORE_GFX_CONTEXT_H_
+3 -1
View File
@@ -2,6 +2,7 @@
#include "GFXDef.h"
namespace cc {
namespace gfx {
const GFXFormatInfo GFX_FORMAT_INFOS[] = {
{"UNKNOWN", 0, 0, GFXFormatType::NONE, false, false, false, false},
@@ -207,4 +208,5 @@ uint GFXFormatSurfaceSize(GFXFormat format, uint width, uint height, uint depth,
return size;
}
}
} // namespace gfx
} // namespace cc
+3 -1
View File
@@ -2,6 +2,7 @@
#define CC_CORE_GFX_DEF_H_
namespace cc {
namespace gfx {
class GFXDevice;
class GFXBuffer;
@@ -1027,6 +1028,7 @@ extern CC_CORE_API uint GFXFormatSize(GFXFormat format, uint width, uint height,
extern CC_CORE_API uint GFXFormatSurfaceSize(GFXFormat format, uint width, uint height, uint depth, uint mips);
}
} // namespace gfx
} // namespace cc
#endif // CC_CORE_GFX_DEF_H_
+3 -1
View File
@@ -2,6 +2,7 @@
#include "GFXDevice.h"
#include "GFXContext.h"
namespace cc {
namespace gfx {
GFXDevice::GFXDevice() {
memset(_features, 0, sizeof(_features));
@@ -18,4 +19,5 @@ GFXFormat GFXDevice::getDepthStencilFormat() const {
return _context->getDepthStencilFormat();
}
}
} // namespace gfx
} // namespace cc
+3 -1
View File
@@ -4,6 +4,7 @@
#include "GFXDef.h"
namespace cc {
namespace gfx {
class CC_CORE_API GFXDevice : public Object {
public:
@@ -106,6 +107,7 @@ protected:
float _projectionSignY = 1.0f;
};
}
} // namespace gfx
} // namespace cc
#endif // CC_CORE_GFX_DEVICE_H_
+3 -1
View File
@@ -2,6 +2,7 @@
#include "GFXFence.h"
namespace cc {
namespace gfx {
GFXFence::GFXFence(GFXDevice *device)
: GFXObject(GFXObjectType::FENCE), _device(device) {
@@ -10,4 +11,5 @@ GFXFence::GFXFence(GFXDevice *device)
GFXFence::~GFXFence() {
}
}
} // namespace gfx
} // namespace cc
+3 -1
View File
@@ -4,6 +4,7 @@
#include "GFXDef.h"
namespace cc {
namespace gfx {
class CC_CORE_API GFXFence : public GFXObject {
public:
@@ -20,6 +21,7 @@ protected:
GFXDevice *_device = nullptr;
};
}
} // namespace gfx
} // namespace cc
#endif // CC_CORE_GFX_FENCE_H_
@@ -2,6 +2,7 @@
#include "GFXFramebuffer.h"
namespace cc {
namespace gfx {
GFXFramebuffer::GFXFramebuffer(GFXDevice *device)
: GFXObject(GFXObjectType::FRAMEBUFFER), _device(device) {
@@ -10,4 +11,5 @@ GFXFramebuffer::GFXFramebuffer(GFXDevice *device)
GFXFramebuffer::~GFXFramebuffer() {
}
}
} // namespace gfx
} // namespace cc
@@ -4,6 +4,7 @@
#include "GFXDef.h"
namespace cc {
namespace gfx {
class CC_CORE_API GFXFramebuffer : public GFXObject {
public:
@@ -28,6 +29,7 @@ protected:
bool _isOffscreen = true;
};
}
} // namespace gfx
} // namespace cc
#endif // CC_CORE_GFX_FRAME_BUFFER_H_
@@ -2,6 +2,7 @@
#include "GFXInputAssembler.h"
namespace cc {
namespace gfx {
GFXInputAssembler::GFXInputAssembler(GFXDevice *device)
: GFXObject(GFXObjectType::INPUT_ASSEMBLER), _device(device) {
@@ -35,4 +36,5 @@ uint GFXInputAssembler::computeAttributesHash() const {
return seed;
}
}
} // namespace gfx
} // namespace cc
@@ -4,6 +4,7 @@
#include "GFXDef.h"
namespace cc {
namespace gfx {
class CC_CORE_API GFXInputAssembler : public GFXObject {
public:
@@ -56,6 +57,7 @@ protected:
uint _attributesHash = 0;
};
}
} // namespace gfx
} // namespace cc
#endif // CC_CORE_GFX_INPUT_ASSEMBLER_H_
+3 -1
View File
@@ -2,8 +2,10 @@
#include "GFXObject.h"
namespace cc {
namespace gfx {
GFXObject::GFXObject(GFXObjectType gfxType)
: _gfxType(gfxType) {}
}
} // namespace gfx
} // namespace cc
+3 -1
View File
@@ -3,6 +3,7 @@
#include "GFXDef.h"
namespace cc {
namespace gfx {
class GFXObject : public Object {
public:
@@ -17,4 +18,5 @@ protected:
GFXStatus _status = GFXStatus::UNREADY;
};
}
} // namespace gfx
} // namespace cc
@@ -2,6 +2,7 @@
#include "GFXPipelineLayout.h"
namespace cc {
namespace gfx {
GFXPipelineLayout::GFXPipelineLayout(GFXDevice *device)
: GFXObject(GFXObjectType::PIPELINE_LAYOUT), _device(device) {
@@ -10,4 +11,5 @@ GFXPipelineLayout::GFXPipelineLayout(GFXDevice *device)
GFXPipelineLayout::~GFXPipelineLayout() {
}
}
} // namespace gfx
} // namespace cc
@@ -4,6 +4,7 @@
#include "GFXDef.h"
namespace cc {
namespace gfx {
class CC_CORE_API GFXPipelineLayout : public GFXObject {
public:
@@ -24,6 +25,7 @@ protected:
GFXBindingLayoutList _layouts;
};
}
} // namespace gfx
} // namespace cc
#endif // CC_CORE_GFX_PIPELINE_LAYOUT_H_
@@ -2,6 +2,7 @@
#include "GFXPipelineState.h"
namespace cc {
namespace gfx {
GFXPipelineState::GFXPipelineState(GFXDevice *device)
: GFXObject(GFXObjectType::PIPELINE_STATE), _device(device) {
@@ -10,4 +11,5 @@ GFXPipelineState::GFXPipelineState(GFXDevice *device)
GFXPipelineState::~GFXPipelineState() {
}
}
} // namespace gfx
} // namespace cc
@@ -4,6 +4,7 @@
#include "GFXDef.h"
namespace cc {
namespace gfx {
class CC_CORE_API GFXPipelineState : public GFXObject {
public:
@@ -38,6 +39,7 @@ protected:
GFXRenderPass *_renderPass = nullptr;
};
}
} // namespace gfx
} // namespace cc
#endif // CC_CORE_GFX_PIPELINE_STATE_H_
+3 -1
View File
@@ -2,6 +2,7 @@
#include "GFXQueue.h"
namespace cc {
namespace gfx {
GFXQueue::GFXQueue(GFXDevice *device)
: GFXObject(GFXObjectType::QUEUE), _device(device) {
@@ -10,4 +11,5 @@ GFXQueue::GFXQueue(GFXDevice *device)
GFXQueue::~GFXQueue() {
}
}
} // namespace gfx
} // namespace cc
+3 -1
View File
@@ -4,6 +4,7 @@
#include "GFXDef.h"
namespace cc {
namespace gfx {
class CC_CORE_API GFXQueue : public GFXObject {
public:
@@ -24,6 +25,7 @@ protected:
GFXQueueType _type = GFXQueueType::GRAPHICS;
};
}
} // namespace gfx
} // namespace cc
#endif // CC_CORE_GFX_QUEUE_H_
@@ -2,6 +2,7 @@
#include "GFXRenderPass.h"
namespace cc {
namespace gfx {
GFXRenderPass::GFXRenderPass(GFXDevice *device)
: GFXObject(GFXObjectType::RENDER_PASS), _device(device) {
@@ -36,4 +37,5 @@ uint GFXRenderPass::computeHash() const {
return seed;
}
}
} // namespace gfx
} // namespace cc
@@ -4,6 +4,7 @@
#include "GFXDef.h"
namespace cc {
namespace gfx {
class CC_CORE_API GFXRenderPass : public GFXObject {
public:
@@ -30,6 +31,7 @@ protected:
uint _hash = 0;
};
}
} // namespace gfx
} // namespace cc
#endif // CC_CORE_GFX_RENDER_PASS_H_
+3 -1
View File
@@ -2,6 +2,7 @@
#include "GFXSampler.h"
namespace cc {
namespace gfx {
GFXSampler::GFXSampler(GFXDevice *device)
: GFXObject(GFXObjectType::SAMPLER), _device(device) {
@@ -14,4 +15,5 @@ GFXSampler::GFXSampler(GFXDevice *device)
GFXSampler::~GFXSampler() {
}
}
} // namespace gfx
} // namespace cc
+3 -1
View File
@@ -4,6 +4,7 @@
#include "GFXDef.h"
namespace cc {
namespace gfx {
class CC_CORE_API GFXSampler : public GFXObject {
public:
@@ -46,6 +47,7 @@ protected:
float _mipLODBias = 0.0f;
};
}
} // namespace gfx
} // namespace cc
#endif // CC_CORE_GFX_SAMPLER_H_
+3 -1
View File
@@ -2,6 +2,7 @@
#include "GFXShader.h"
namespace cc {
namespace gfx {
GFXShader::GFXShader(GFXDevice *device)
: GFXObject(GFXObjectType::SHADER), _device(device) {
@@ -10,4 +11,5 @@ GFXShader::GFXShader(GFXDevice *device)
GFXShader::~GFXShader() {
}
}
} // namespace gfx
} // namespace cc
+3 -1
View File
@@ -4,6 +4,7 @@
#include "GFXDef.h"
namespace cc {
namespace gfx {
class CC_CORE_API GFXShader : public GFXObject {
public:
@@ -33,6 +34,7 @@ protected:
GFXUniformSamplerList _samplers;
};
}
} // namespace gfx
} // namespace cc
#endif // CC_CORE_GFX_TEXTURE_VIEW_H_
+3 -1
View File
@@ -2,6 +2,7 @@
#include "GFXTexture.h"
namespace cc {
namespace gfx {
GFXTexture::GFXTexture(GFXDevice *device)
: GFXObject(GFXObjectType::TEXTURE), _device(device) {
@@ -10,4 +11,5 @@ GFXTexture::GFXTexture(GFXDevice *device)
GFXTexture::~GFXTexture() {
}
}
} // namespace gfx
} // namespace cc
+3 -1
View File
@@ -4,6 +4,7 @@
#include "GFXDef.h"
namespace cc {
namespace gfx {
class CC_CORE_API GFXTexture : public GFXObject {
public:
@@ -45,6 +46,7 @@ protected:
uint8_t *_buffer = nullptr;
};
}
} // namespace gfx
} // namespace cc
#endif // CC_CORE_GFX_TEXTURE_H_
+105 -113
View File
@@ -3,148 +3,140 @@
// Platform head file including
#if (CC_PLATFORM == CC_PLATFORM_WINDOWS)
#include <Windows.h>
# undef _T
# include <tchar.h>
#define snprintf _snprintf_s
#include <Windows.h>
#undef _T
#include <tchar.h>
#define snprintf _snprintf_s
#elif (CC_PLATFORM == CC_PLATFORM_ANDROID)
# include <android/log.h>
#include <android/log.h>
#endif
namespace cc {
namespace gfx {
#if (CC_PLATFORM == CC_PLATFORM_WINDOWS)
enum ErrRet {
ERRRET_IGNORE = 0,
ERRRET_BREAKPOINT,
ERRRET_EXIT
ERRRET_IGNORE = 0,
ERRRET_BREAKPOINT,
ERRRET_EXIT
};
LRESULT __stdcall CBTHookProc(long nCode, WPARAM wParam, LPARAM lParam) {
if (nCode == HCBT_ACTIVATE) {
SetDlgItemTextA((HWND)wParam, IDRETRY, "&Debug");
SetDlgItemTextA((HWND)wParam, IDIGNORE, "&Ignore");
SetDlgItemTextA((HWND)wParam, IDABORT, "&Exit");
}
return 0;
if (nCode == HCBT_ACTIVATE) {
SetDlgItemTextA((HWND)wParam, IDRETRY, "&Debug");
SetDlgItemTextA((HWND)wParam, IDIGNORE, "&Ignore");
SetDlgItemTextA((HWND)wParam, IDABORT, "&Exit");
}
return 0;
}
ErrRet _DisplayError(const char* title, const char* content, const char* desc, const char* fileName, int lineNum) {
const int MODULE_NAME_SIZE = 255;
char moduleName[MODULE_NAME_SIZE];
// attempt to get the module name
if (!GetModuleFileNameA(NULL, moduleName, MODULE_NAME_SIZE))
{
char *msg = "<unknown application>";
strcpy_s(moduleName, strlen(msg), msg);
}
// build a collosal string containing the entire asster message
const int MAX_BUFFER_SIZE = 4096;
char buffer[MAX_BUFFER_SIZE];
snprintf(buffer,
MAX_BUFFER_SIZE,
"%s\n\nProgram : %s\nFile : %s\nLine : %d\nError: %s\nComment: %s\n",
title,
moduleName,
fileName,
lineNum,
content,
desc);
// place a copy of the message into the clipboard
if (OpenClipboard(NULL)) {
size_t bufferLength = strlen(buffer);
HGLOBAL hMem = GlobalAlloc(GHND|GMEM_DDESHARE, bufferLength+1);
if (hMem) {
uint8_t* pMem = (uint8_t*)GlobalLock(hMem);
memcpy(pMem, buffer, bufferLength);
GlobalUnlock(hMem);
EmptyClipboard();
SetClipboardData(CF_TEXT, hMem);
}
CloseClipboard();
}
// find the top most window of the current application
HWND hWndParent = GetActiveWindow();
if (NULL != hWndParent) {
hWndParent = GetLastActivePopup(hWndParent);
}
ErrRet _DisplayError(const char *title, const char *content, const char *desc, const char *fileName, int lineNum) {
const int MODULE_NAME_SIZE = 255;
char moduleName[MODULE_NAME_SIZE];
HHOOK hHook = SetWindowsHookEx(WH_CBT, (HOOKPROC)CBTHookProc, GetModuleHandle(NULL), GetCurrentThreadId());
// put up a message box with the error
int iRet = MessageBoxA ( hWndParent,
buffer,
"ERROR NOTIFICATION...",
MB_TASKMODAL|MB_SETFOREGROUND|MB_ABORTRETRYIGNORE|MB_ICONERROR);
UnhookWindowsHookEx(hHook);
// attempt to get the module name
if (!GetModuleFileNameA(NULL, moduleName, MODULE_NAME_SIZE)) {
char *msg = "<unknown application>";
strcpy_s(moduleName, strlen(msg), msg);
}
if (iRet == IDRETRY)
{
// ignore this error and continue
return ERRRET_BREAKPOINT;
}
else if (iRet == IDIGNORE)
{
// ignore this error and continue,
// plus never stop on this error again (handled by the caller)
return (ERRRET_IGNORE);
}
else
{
return ERRRET_EXIT;
}
// build a collosal string containing the entire asster message
const int MAX_BUFFER_SIZE = 4096;
char buffer[MAX_BUFFER_SIZE];
snprintf(buffer,
MAX_BUFFER_SIZE,
"%s\n\nProgram : %s\nFile : %s\nLine : %d\nError: %s\nComment: %s\n",
title,
moduleName,
fileName,
lineNum,
content,
desc);
// place a copy of the message into the clipboard
if (OpenClipboard(NULL)) {
size_t bufferLength = strlen(buffer);
HGLOBAL hMem = GlobalAlloc(GHND | GMEM_DDESHARE, bufferLength + 1);
if (hMem) {
uint8_t *pMem = (uint8_t *)GlobalLock(hMem);
memcpy(pMem, buffer, bufferLength);
GlobalUnlock(hMem);
EmptyClipboard();
SetClipboardData(CF_TEXT, hMem);
}
CloseClipboard();
}
// find the top most window of the current application
HWND hWndParent = GetActiveWindow();
if (NULL != hWndParent) {
hWndParent = GetLastActivePopup(hWndParent);
}
HHOOK hHook = SetWindowsHookEx(WH_CBT, (HOOKPROC)CBTHookProc, GetModuleHandle(NULL), GetCurrentThreadId());
// put up a message box with the error
int iRet = MessageBoxA(hWndParent,
buffer,
"ERROR NOTIFICATION...",
MB_TASKMODAL | MB_SETFOREGROUND | MB_ABORTRETRYIGNORE | MB_ICONERROR);
UnhookWindowsHookEx(hHook);
if (iRet == IDRETRY) {
// ignore this error and continue
return ERRRET_BREAKPOINT;
} else if (iRet == IDIGNORE) {
// ignore this error and continue,
// plus never stop on this error again (handled by the caller)
return (ERRRET_IGNORE);
} else {
return ERRRET_EXIT;
}
}
int _ExecAssert(const char* condition, const char* filename, int line, const char* formats, ...)
{
char buffer[4096];
va_list args;
va_start(args, formats);
vsnprintf(buffer, sizeof(buffer) - 1, formats, args);
va_end(args);
int _ExecAssert(const char *condition, const char *filename, int line, const char *formats, ...) {
char buffer[4096];
va_list args;
va_start(args, formats);
vsnprintf(buffer, sizeof(buffer) - 1, formats, args);
va_end(args);
ErrRet ret = _DisplayError("Assert Failed!", condition, buffer, filename, line);
if (ret == ERRRET_BREAKPOINT) {
return 1;
}
else if (ret == ERRRET_EXIT) {
ExitProcess((UINT)-1);
}
return 0;
ErrRet ret = _DisplayError("Assert Failed!", condition, buffer, filename, line);
if (ret == ERRRET_BREAKPOINT) {
return 1;
} else if (ret == ERRRET_EXIT) {
ExitProcess((UINT)-1);
}
return 0;
}
#else
int _ExecAssert(const char* condition, const char* filename, int line, const char* formats, ...)
{
char buffer[4096];
va_list args;
va_start(args, formats);
int _ExecAssert(const char *condition, const char *filename, int line, const char *formats, ...) {
char buffer[4096];
va_list args;
va_start(args, formats);
vsnprintf(buffer, sizeof(buffer) - 1, formats, args);
va_end(args);
va_end(args);
_ExecAssertOutput(condition, filename, line, buffer);
return 0;
_ExecAssertOutput(condition, filename, line, buffer);
return 0;
}
#endif
void _ExecAssertOutput(const char* condition, const char* filename, int line, const char* msg) {
char buffer[4096];
snprintf(buffer, sizeof(buffer) - 1, "[ASSERT] %s (%s:%d) %s", condition, filename, line, msg);
void _ExecAssertOutput(const char *condition, const char *filename, int line, const char *msg) {
char buffer[4096];
snprintf(buffer, sizeof(buffer) - 1, "[ASSERT] %s (%s:%d) %s", condition, filename, line, msg);
#if (CC_PLATFORM == CC_PLATFORM_WINDOWS)
OutputDebugStringA(buffer);
OutputDebugStringA(buffer);
#elif (CC_PLATFORM == CC_PLATFORM_ANDROID)
__android_log_write(ANDROID_LOG_FATAL, "Cocos", buffer);
__android_log_write(ANDROID_LOG_FATAL, "Cocos", buffer);
#else
fputs(buffer, stdout);
fputs(buffer, stdout);
#endif
}
}
} // namespace gfx
} // namespace cc
@@ -2,18 +2,19 @@
#define CC_CORE_KERNEL_ASSERTION_H_
namespace cc {
namespace gfx {
//#if defined(__GNUC__)
#if 0
#define LIKELY(x) (__builtin_expect(!!(x), 1))
#define UNLIKELY(x) (__builtin_expect(!!(x), 0))
#define LIKELY(x) (__builtin_expect(!!(x), 1))
#define UNLIKELY(x) (__builtin_expect(!!(x), 0))
#else
#define LIKELY(x) (x)
#define UNLIKELY(x) (x)
#define LIKELY(x) (x)
#define UNLIKELY(x) (x)
#endif
CC_CORE_API int _ExecAssert(const char *condition, const char *fileName, int lineNumber, const char *formats, ...);
CC_CORE_API void _ExecAssertOutput(const char *condition, const char *fileName, int lineNumber, const char* msg);
CC_CORE_API int _ExecAssert(const char *condition, const char *fileName, int lineNumber, const char *formats, ...);
CC_CORE_API void _ExecAssertOutput(const char *condition, const char *fileName, int lineNumber, const char *msg);
//#if (CC_MODE == CC_MODE_DEBUG)
//# if (CC_PLATFORM == CC_PLATFORM_WINDOWS)
@@ -27,6 +28,7 @@ CC_CORE_API void _ExecAssertOutput(const char *condition, const char *fileName,
//#define CCASSERT(x) CCASSERT(x, "%s", "")
}
} // namespace gfx
} // namespace cc
#endif // CC_CORE_KERNEL_ASSERTION_H_
+65 -63
View File
@@ -2,76 +2,78 @@
#define CC_CORE_KERNEL_CACHED_ARRAY_H_
namespace cc {
namespace gfx {
template <typename T>
class CachedArray {
public:
CachedArray(uint size = 1) {
_size = 0;
_capacity = std::max(size, 1U);
_array = new T[_capacity];
}
~CachedArray() {
delete [] (_array);
}
T& operator [] (int index) {
return _array[index];
}
const T& operator [] (int index) const {
return _array[index];
}
void clear() {
// memset(_array, 0, _size * sizeof(T));
_size = 0;
}
void push(T item) {
if (_size >= _capacity) {
T* temp = _array;
_array = new T[_capacity*2];
for (uint i = 0; i < _capacity; ++i) {
_array[i] = temp[i];
}
_capacity *= 2;
delete [] (temp);
public:
CachedArray(uint size = 1) {
_size = 0;
_capacity = std::max(size, 1U);
_array = new T[_capacity];
}
_array[_size++] = item;
}
T pop() {
return _array[--_size];
}
uint size() const {
return _size;
}
void concat(const CachedArray<T>& array) {
if (_size + array.size() >= _capacity) {
T* temp = _array;
uint size = std::max(_capacity*2, _size + array.size());
_array = new T[size];
for (uint i = 0; i < _capacity; ++i) {
_array[i] = temp[i];
}
_capacity = size;
delete [] (temp);
~CachedArray() {
delete[](_array);
}
for (uint i = 0; i < array.size(); ++i) {
_array[_size++] = array[i];
T &operator[](int index) {
return _array[index];
}
}
private:
uint _size = 0;
uint _capacity = 0;
T* _array = nullptr;
const T &operator[](int index) const {
return _array[index];
}
void clear() {
// memset(_array, 0, _size * sizeof(T));
_size = 0;
}
void push(T item) {
if (_size >= _capacity) {
T *temp = _array;
_array = new T[_capacity * 2];
for (uint i = 0; i < _capacity; ++i) {
_array[i] = temp[i];
}
_capacity *= 2;
delete[](temp);
}
_array[_size++] = item;
}
T pop() {
return _array[--_size];
}
uint size() const {
return _size;
}
void concat(const CachedArray<T> &array) {
if (_size + array.size() >= _capacity) {
T *temp = _array;
uint size = std::max(_capacity * 2, _size + array.size());
_array = new T[size];
for (uint i = 0; i < _capacity; ++i) {
_array[i] = temp[i];
}
_capacity = size;
delete[](temp);
}
for (uint i = 0; i < array.size(); ++i) {
_array[_size++] = array[i];
}
}
private:
uint _size = 0;
uint _capacity = 0;
T *_array = nullptr;
};
}
} // namespace gfx
} // namespace cc
#endif // CC_CORE_KERNEL_CACHED_ARRAY_H_
+115 -114
View File
@@ -4,142 +4,143 @@
#include "util/StringUtil.h"
#if (CC_PLATFORM == CC_PLATFORM_WINDOWS)
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# include <Windows.h>
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <Windows.h>
#define COLOR_FATAL FOREGROUND_INTENSITY | FOREGROUND_RED
#define COLOR_ERROR FOREGROUND_RED
#define COLOR_WARN 6
#define COLOR_INFO FOREGROUND_GREEN | FOREGROUND_BLUE
#define COLOR_DEBUG 7
#define COLOR_NORMAL 8
#define SET_CONSOLE_TEXT_COLOR(color) SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color)
#define COLOR_FATAL FOREGROUND_INTENSITY | FOREGROUND_RED
#define COLOR_ERROR FOREGROUND_RED
#define COLOR_WARN 6
#define COLOR_INFO FOREGROUND_GREEN | FOREGROUND_BLUE
#define COLOR_DEBUG 7
#define COLOR_NORMAL 8
#define SET_CONSOLE_TEXT_COLOR(color) SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color)
#elif (CC_PLATFORM == CC_PLATFORM_ANDROID)
# include <android/log.h>
#include <android/log.h>
#endif
namespace cc {
namespace gfx {
#define LOG_USE_TIMESTAMP
LogLevel Log::log_level = LogLevel::DEBUG;
FILE* Log::log_file_ = nullptr;
const char* LOG_LEVEL_DESCS[] = { "FATAL", "ERROR", "WARN", "INFO", "DEBUG" };
FILE *Log::log_file_ = nullptr;
const char *LOG_LEVEL_DESCS[] = {"FATAL", "ERROR", "WARN", "INFO", "DEBUG"};
void Log::set_log_file(const std::string& filename) {
void Log::set_log_file(const std::string &filename) {
#if (CC_PLATFORM == CC_PLATFORM_WINDOWS)
if (log_file_) {
fclose(log_file_);
}
log_file_ = fopen(filename.c_str(), "w");
if (log_file_) {
String msg;
msg += "------------------------------------------------------\n";
struct tm* tm_time;
time_t ct_time;
time(&ct_time);
tm_time = localtime(&ct_time);
msg += StringUtil::Format("LOG DATE: %04d-%02d-%02d %02d:%02d:%02d\n",
tm_time->tm_year + 1900,
tm_time->tm_mon + 1,
tm_time->tm_mday,
tm_time->tm_hour,
tm_time->tm_min,
tm_time->tm_sec);
msg += "------------------------------------------------------\n";
fputs(msg.c_str(), log_file_);
fflush(log_file_);
}
if (log_file_) {
fclose(log_file_);
}
log_file_ = fopen(filename.c_str(), "w");
if (log_file_) {
String msg;
msg += "------------------------------------------------------\n";
struct tm *tm_time;
time_t ct_time;
time(&ct_time);
tm_time = localtime(&ct_time);
msg += StringUtil::Format("LOG DATE: %04d-%02d-%02d %02d:%02d:%02d\n",
tm_time->tm_year + 1900,
tm_time->tm_mon + 1,
tm_time->tm_mday,
tm_time->tm_hour,
tm_time->tm_min,
tm_time->tm_sec);
msg += "------------------------------------------------------\n";
fputs(msg.c_str(), log_file_);
fflush(log_file_);
}
#endif
}
void Log::Close() {
if (log_file_) {
fclose(log_file_);
log_file_ = nullptr;
}
if (log_file_) {
fclose(log_file_);
log_file_ = nullptr;
}
}
void Log::LogMessage(LogType type, LogLevel level, const char* formats, ...) {
char buff[4096];
char* p = buff;
char* last = buff + sizeof(buff) - 3;
void Log::LogMessage(LogType type, LogLevel level, const char *formats, ...) {
char buff[4096];
char *p = buff;
char *last = buff + sizeof(buff) - 3;
#if defined(LOG_USE_TIMESTAMP)
struct tm* tm_time;
time_t ct_time;
time(&ct_time);
tm_time = localtime(&ct_time);
p += sprintf(p, "%02d:%02d:%02d ", tm_time->tm_hour, tm_time->tm_min, tm_time->tm_sec);
struct tm *tm_time;
time_t ct_time;
time(&ct_time);
tm_time = localtime(&ct_time);
p += sprintf(p, "%02d:%02d:%02d ", tm_time->tm_hour, tm_time->tm_min, tm_time->tm_sec);
#endif
p += sprintf(p, "[%s]: ", LOG_LEVEL_DESCS[(int)level]);
va_list args;
va_start(args, formats);
// p += StringUtil::VPrintf(p, last, formats, args);
int count = (int)(last - p);
int ret = vsnprintf(p, count, formats, args);
if (ret >= count - 1) {
p += (count - 1);
} else if (ret >= 0) {
p += ret;
}
va_end(args);
*p++ = '\n';
*p = 0;
if (log_file_)
{
fputs(buff, log_file_);
fflush(log_file_);
}
p += sprintf(p, "[%s]: ", LOG_LEVEL_DESCS[(int)level]);
va_list args;
va_start(args, formats);
// p += StringUtil::VPrintf(p, last, formats, args);
int count = (int)(last - p);
int ret = vsnprintf(p, count, formats, args);
if (ret >= count - 1) {
p += (count - 1);
} else if (ret >= 0) {
p += ret;
}
va_end(args);
*p++ = '\n';
*p = 0;
if (log_file_) {
fputs(buff, log_file_);
fflush(log_file_);
}
#if (CC_PLATFORM == CC_PLATFORM_WINDOWS)
UTFString utfstr(buff);
const wchar_t* ustr = utfstr.asWStr_c_str();
WORD color;
switch (level) {
case LogLevel::DEBUG: color = COLOR_DEBUG; break;
case LogLevel::INFO: color = COLOR_INFO; break;
case LogLevel::WARN: color = COLOR_WARN; break;
case LogLevel::ERR: color = COLOR_ERROR; break;
case LogLevel::FATAL: color = COLOR_FATAL; break;
default: color = COLOR_INFO;
}
SET_CONSOLE_TEXT_COLOR(color);
wprintf(L"%s", ustr);
SET_CONSOLE_TEXT_COLOR(COLOR_NORMAL);
OutputDebugStringW(ustr);
UTFString utfstr(buff);
const wchar_t *ustr = utfstr.asWStr_c_str();
WORD color;
switch (level) {
case LogLevel::DEBUG: color = COLOR_DEBUG; break;
case LogLevel::INFO: color = COLOR_INFO; break;
case LogLevel::WARN: color = COLOR_WARN; break;
case LogLevel::ERR: color = COLOR_ERROR; break;
case LogLevel::FATAL: color = COLOR_FATAL; break;
default: color = COLOR_INFO;
}
SET_CONSOLE_TEXT_COLOR(color);
wprintf(L"%s", ustr);
SET_CONSOLE_TEXT_COLOR(COLOR_NORMAL);
OutputDebugStringW(ustr);
#elif (CC_PLATFORM == CC_PLATFORM_ANDROID)
android_LogPriority priority;
switch (level) {
case LogLevel::DEBUG: priority = ANDROID_LOG_DEBUG; break;
case LogLevel::INFO: priority = ANDROID_LOG_INFO; break;
case LogLevel::WARN: priority = ANDROID_LOG_WARN; break;
case LogLevel::ERR: priority = ANDROID_LOG_ERROR; break;
case LogLevel::FATAL: priority = ANDROID_LOG_FATAL; break;
default: priority = ANDROID_LOG_INFO;
}
__android_log_write(priority, (type == LogType::KERNEL? "Cocos" : "CocosScript"), buff);
android_LogPriority priority;
switch (level) {
case LogLevel::DEBUG: priority = ANDROID_LOG_DEBUG; break;
case LogLevel::INFO: priority = ANDROID_LOG_INFO; break;
case LogLevel::WARN: priority = ANDROID_LOG_WARN; break;
case LogLevel::ERR: priority = ANDROID_LOG_ERROR; break;
case LogLevel::FATAL: priority = ANDROID_LOG_FATAL; break;
default: priority = ANDROID_LOG_INFO;
}
__android_log_write(priority, (type == LogType::KERNEL ? "Cocos" : "CocosScript"), buff);
#else
fputs(buff, stdout);
fputs(buff, stdout);
#endif
}
}
} // namespace gfx
} // namespace cc
+40 -29
View File
@@ -4,44 +4,55 @@
#include <string>
namespace cc {
namespace gfx {
enum class LogType: uint8_t {
KERNEL,
SCRIPT,
COUNT,
enum class LogType : uint8_t {
KERNEL,
SCRIPT,
COUNT,
};
enum class LogLevel: uint8_t {
FATAL,
ERR,
WARN,
INFO,
DEBUG,
COUNT,
enum class LogLevel : uint8_t {
FATAL,
ERR,
WARN,
INFO,
DEBUG,
COUNT,
};
class CC_CORE_API Log {
public:
static LogLevel log_level; // for read only
static CC_INLINE void set_log_level(LogLevel level) { log_level = level; }
static CC_INLINE FILE* log_file() { return log_file_; }
static void set_log_file(const std::string& filename);
static void Close();
static void LogMessage(LogType type, LogLevel level, const char* formats, ...);
private:
static FILE* log_file_;
public:
static LogLevel log_level; // for read only
static CC_INLINE void set_log_level(LogLevel level) { log_level = level; }
static CC_INLINE FILE *log_file() { return log_file_; }
static void set_log_file(const std::string &filename);
static void Close();
static void LogMessage(LogType type, LogLevel level, const char *formats, ...);
private:
static FILE *log_file_;
};
}
} // namespace gfx
} // namespace cc
#define CC_LOG_DEBUG(formats, ...) if(cc::Log::log_level >= cc::LogLevel::DEBUG) cc::Log::LogMessage(cc::LogType::KERNEL, cc::LogLevel::DEBUG, formats, ##__VA_ARGS__)
#define CC_LOG_INFO(formats, ...) if(cc::Log::log_level >= cc::LogLevel::INFO) cc::Log::LogMessage(cc::LogType::KERNEL, cc::LogLevel::INFO, formats, ##__VA_ARGS__)
#define CC_LOG_WARNING(formats, ...) if(cc::Log::log_level >= cc::LogLevel::WARN) cc::Log::LogMessage(cc::LogType::KERNEL, cc::LogLevel::WARN, formats, ##__VA_ARGS__)
#define CC_LOG_ERROR_(formats, ...) if(cc::Log::log_level >= cc::LogLevel::ERR) cc::Log::LogMessage(cc::LogType::KERNEL, cc::LogLevel::ERR, formats, ##__VA_ARGS__)
#define CC_LOG_FATAL(formats, ...) if(cc::Log::logLevel >= cc::LogLevel::FATAL) cc::Log::LogMessage(cc::LogType::KERNEL, cc::LogLevel::FATAL, formats, ##__VA_ARGS__)
#define CC_LOG_DEBUG(formats, ...) \
if (cc::gfx::Log::log_level >= cc::gfx::LogLevel::DEBUG) cc::gfx::Log::LogMessage(cc::gfx::LogType::KERNEL, cc::gfx::LogLevel::DEBUG, formats, ##__VA_ARGS__)
#define CC_LOG_INFO(formats, ...) \
if (cc::gfx::Log::log_level >= cc::gfx::LogLevel::INFO) cc::gfx::Log::LogMessage(cc::gfx::LogType::KERNEL, cc::gfx::LogLevel::INFO, formats, ##__VA_ARGS__)
#define CC_LOG_WARNING(formats, ...) \
if (cc::gfx::Log::log_level >= cc::gfx::LogLevel::WARN) cc::gfx::Log::LogMessage(cc::gfx::LogType::KERNEL, cc::gfx::LogLevel::WARN, formats, ##__VA_ARGS__)
#define CC_LOG_ERROR_(formats, ...) \
if (cc::gfx::Log::log_level >= cc::gfx::LogLevel::ERR) cc::gfx::Log::LogMessage(cc::gfx::LogType::KERNEL, cc::gfx::LogLevel::ERR, formats, ##__VA_ARGS__)
#define CC_LOG_FATAL(formats, ...) \
if (cc::gfx::Log::logLevel >= cc::gfx::LogLevel::FATAL) cc::gfx::Log::LogMessage(cc::gfx::LogType::KERNEL, cc::gfx::LogLevel::FATAL, formats, ##__VA_ARGS__)
#define CC_LOG_ERROR(formats, ...) do {CC_LOG_ERROR_("[ERROR] file %s: line %d ", __FILE__, __LINE__); CC_LOG_ERROR_(formats, ##__VA_ARGS__); } while(0)
#define CC_LOG_ERROR(formats, ...) \
do { \
CC_LOG_ERROR_("[ERROR] file %s: line %d ", __FILE__, __LINE__); \
CC_LOG_ERROR_(formats, ##__VA_ARGS__); \
} while (0)
#endif // CC_CORE_KERNEL_LOG_H_
+3 -1
View File
@@ -2,10 +2,12 @@
#define CC_CORE_KERNEL_OBJECT_H_
namespace cc {
namespace gfx {
// Now define all the base classes for each allocation
typedef AllocatedObject<GAP> Object;
}
} // namespace gfx
} // namespace cc
#endif // CC_CORE_KERNEL_OBJECT_H_
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -1,8 +1,8 @@
#ifndef CC_CORE_MATH_CC_MATH_H_
#define CC_CORE_MATH_CC_MATH_H_
#define CC_MATH_NAMESPACE_BEGIN namespace cc { namespace math {
#define CC_MATH_NAMESPACE_END }}
#define CC_MATH_NAMESPACE_BEGIN namespace cc { namespace gfx { namespace math {
#define CC_MATH_NAMESPACE_END }}}
CC_MATH_NAMESPACE_BEGIN
@@ -3,6 +3,7 @@
#include "AllocatedObj.h"
namespace cc {
namespace gfx {
/*
The problem is that operator new/delete are *implicitly* static. We have to
@@ -12,4 +13,5 @@ namespace cc {
template class AllocatedObject<GAP>;
}
} // namespace gfx
} // namespace cc
@@ -4,15 +4,16 @@
// Anything that has done a #define new <blah> will screw operator new definitions up
// so undefine
#ifdef new
# undef new
#undef new
#endif
#ifdef delete
# undef delete
#undef delete
#endif
#include "core/CoreDef.h"
namespace cc {
namespace gfx {
/** Superclass for all objects that wish to use custom memory allocators
when their new / delete operators are called.
@@ -20,62 +21,61 @@ namespace cc {
to use (e.g. see StdAllocPolicy).
*/
template <class Alloc>
class CC_CORE_API AllocatedObject
{
public:
explicit AllocatedObject() {}
~AllocatedObject() {}
// operator new, with debug line info
void* operator new(size_t sz, const char *file, int line, const char *func) {
return Alloc::AllocateBytes(sz, file, line, func);
}
/// array operator new, with debug line info
void* operator new[] ( size_t sz, const char *file, int line, const char *func ) {
return Alloc::AllocateBytes(sz, file, line, func);
}
class CC_CORE_API AllocatedObject {
public:
explicit AllocatedObject() {}
~AllocatedObject() {}
/// placement operator new
void* operator new(size_t sz, void *ptr) {
(void)sz;
return ptr;
}
// operator new, with debug line info
void *operator new(size_t sz, const char *file, int line, const char *func) {
return Alloc::AllocateBytes(sz, file, line, func);
}
/// array operator new, with debug line info
void *operator new[](size_t sz, const char *file, int line, const char *func) {
return Alloc::AllocateBytes(sz, file, line, func);
}
/// placement operator new
void *operator new(size_t sz, void *ptr) {
(void)sz;
return ptr;
}
#if 1
void* operator new(size_t sz) {
return Alloc::AllocateBytes(sz);
}
void *operator new(size_t sz) {
return Alloc::AllocateBytes(sz);
}
void* operator new[]( size_t sz ) {
return Alloc::AllocateBytes(sz);
}
void *operator new[](size_t sz) {
return Alloc::AllocateBytes(sz);
}
#endif
void operator delete(void* ptr) {
Alloc::DeallocateBytes(ptr);
}
// Corresponding operator for placement delete (second param same as the first)
void operator delete(void* ptr, void*) {
Alloc::DeallocateBytes(ptr);
}
// only called if there is an exception in corresponding 'new'
void operator delete(void* ptr, const char*, int , const char*) {
Alloc::DeallocateBytes(ptr);
}
void operator delete[](void *ptr) {
Alloc::DeallocateBytes(ptr);
}
void operator delete[](void* ptr, const char*, int, const char*) {
Alloc::DeallocateBytes(ptr);
}
void operator delete(void *ptr) {
Alloc::DeallocateBytes(ptr);
}
// Corresponding operator for placement delete (second param same as the first)
void operator delete(void *ptr, void *) {
Alloc::DeallocateBytes(ptr);
}
// only called if there is an exception in corresponding 'new'
void operator delete(void *ptr, const char *, int, const char *) {
Alloc::DeallocateBytes(ptr);
}
void operator delete[](void *ptr) {
Alloc::DeallocateBytes(ptr);
}
void operator delete[](void *ptr, const char *, int, const char *) {
Alloc::DeallocateBytes(ptr);
}
};
}
} // namespace gfx
} // namespace cc
#endif // CC_CORE_ALLOCATED_OBJ_H_
+116 -115
View File
@@ -4,150 +4,151 @@
#if (CC_MEMORY_ALLOCATOR == CC_MEMORY_ALLOCATOR_JEMALLOC)
#include "jemalloc/jemalloc.h"
extern const char* je_malloc_conf = "narenas:4";
#include "jemalloc/jemalloc.h"
extern const char *je_malloc_conf = "narenas:4";
namespace cc {
namespace gfx {
#ifdef CC_MEMORY_TRACKER
#define MEM_CHECKTAG_SIZE 4
#define MEM_CHECKTAG 0x20170719
#ifdef CC_MEMORY_TRACKER
#define MEM_CHECKTAG_SIZE 4
#define MEM_CHECKTAG 0x20170719
CC_INLINE static void CheckOverflowAlloc(void* ptr) {
size_t size = je_malloc_usable_size(ptr);
char* p = (char*)ptr + size - MEM_CHECKTAG_SIZE;
uint tag = MEM_CHECKTAG;
memcpy(p, &tag, MEM_CHECKTAG_SIZE);
CC_INLINE static void CheckOverflowAlloc(void *ptr) {
size_t size = je_malloc_usable_size(ptr);
char *p = (char *)ptr + size - MEM_CHECKTAG_SIZE;
uint tag = MEM_CHECKTAG;
memcpy(p, &tag, MEM_CHECKTAG_SIZE);
}
CC_INLINE static void CheckOverflowFree(void* ptr) {
size_t size = je_malloc_usable_size(ptr);
char* p = (char*)ptr + size - MEM_CHECKTAG_SIZE;
uint tag;
memcpy(&tag, p, MEM_CHECKTAG_SIZE);
CCASSERT(tag == MEM_CHECKTAG);
CC_INLINE static void CheckOverflowFree(void *ptr) {
size_t size = je_malloc_usable_size(ptr);
char *p = (char *)ptr + size - MEM_CHECKTAG_SIZE;
uint tag;
memcpy(&tag, p, MEM_CHECKTAG_SIZE);
CCASSERT(tag == MEM_CHECKTAG);
}
#else
#define MEM_CHECKTAG_SIZE 0
#endif
#else
#define MEM_CHECKTAG_SIZE 0
#endif
CC_DECL_MALLOC void* JeAllocImpl::AllocBytes(size_t count, const char* file, int line, const char* func) {
void* ptr = je_malloc(count + MEM_CHECKTAG_SIZE);
#ifdef CC_MEMORY_TRACKER
CheckOverflowAlloc(ptr);
MemTracker::Instance()->RecordAlloc(ptr, count, file, line, func);
#else
// avoid unused params warning
(void)file;
(void)line;
(void)func;
#endif
return ptr;
CC_DECL_MALLOC void *JeAllocImpl::AllocBytes(size_t count, const char *file, int line, const char *func) {
void *ptr = je_malloc(count + MEM_CHECKTAG_SIZE);
#ifdef CC_MEMORY_TRACKER
CheckOverflowAlloc(ptr);
MemTracker::Instance()->RecordAlloc(ptr, count, file, line, func);
#else
// avoid unused params warning
(void)file;
(void)line;
(void)func;
#endif
return ptr;
}
CC_DECL_MALLOC void* JeAllocImpl::ReallocBytes(void* ptr, size_t count, const char* file, int line, const char* func) {
#ifdef CC_MEMORY_TRACKER
if (ptr)
{
if(count == 0) {
CheckOverflowFree(ptr);
MemTracker::Instance()->RecordFree(ptr);
je_free(ptr);
return nullptr;
} else {
size_t oldsz = je_malloc_usable_size(ptr) - MEM_CHECKTAG_SIZE;
if (oldsz > count) oldsz = count;
CC_DECL_MALLOC void *JeAllocImpl::ReallocBytes(void *ptr, size_t count, const char *file, int line, const char *func) {
#ifdef CC_MEMORY_TRACKER
if (ptr) {
if (count == 0) {
CheckOverflowFree(ptr);
MemTracker::Instance()->RecordFree(ptr);
je_free(ptr);
return nullptr;
} else {
size_t oldsz = je_malloc_usable_size(ptr) - MEM_CHECKTAG_SIZE;
if (oldsz > count) oldsz = count;
void* nptr = je_malloc(count + MEM_CHECKTAG_SIZE);
memcpy(nptr, ptr, oldsz);
CheckOverflowAlloc(nptr);
MemTracker::Instance()->RecordAlloc(nptr, count, file, line, func);
void *nptr = je_malloc(count + MEM_CHECKTAG_SIZE);
memcpy(nptr, ptr, oldsz);
CheckOverflowAlloc(nptr);
MemTracker::Instance()->RecordAlloc(nptr, count, file, line, func);
CheckOverflowFree(ptr);
MemTracker::Instance()->RecordFree(ptr);
je_free(ptr);
return nptr;
}
} else {
if (count) {
ptr = je_malloc(count + MEM_CHECKTAG_SIZE);
CheckOverflowAlloc(ptr);
MemTracker::Instance()->RecordAlloc(ptr, count, file, line, func);
return ptr;
} else {
return nullptr;
}
}
#else
// avoid unused params warning
(void)file;
(void)line;
(void)func;
return je_realloc(ptr, count);
#endif
CheckOverflowFree(ptr);
MemTracker::Instance()->RecordFree(ptr);
je_free(ptr);
return nptr;
}
} else {
if (count) {
ptr = je_malloc(count + MEM_CHECKTAG_SIZE);
CheckOverflowAlloc(ptr);
MemTracker::Instance()->RecordAlloc(ptr, count, file, line, func);
return ptr;
} else {
return nullptr;
}
}
#else
// avoid unused params warning
(void)file;
(void)line;
(void)func;
return je_realloc(ptr, count);
#endif
}
CC_DECL_MALLOC void* JeAllocImpl::AllocBytesAligned(size_t align, size_t count, const char* file, int line, const char* func) {
// default to platform SIMD alignment if none specified
void* ptr = je_aligned_alloc(align, count + MEM_CHECKTAG_SIZE);
#ifdef COCOS_MEMORY_TRACKER
CheckOverflowAlloc(ptr);
MemTracker::Instance()->RecordAlloc(ptr, count, file, line, func);
#else
// avoid unused params warning
(void)file;
(void)line;
(void)func;
#endif
return ptr;
CC_DECL_MALLOC void *JeAllocImpl::AllocBytesAligned(size_t align, size_t count, const char *file, int line, const char *func) {
// default to platform SIMD alignment if none specified
void *ptr = je_aligned_alloc(align, count + MEM_CHECKTAG_SIZE);
#ifdef COCOS_MEMORY_TRACKER
CheckOverflowAlloc(ptr);
MemTracker::Instance()->RecordAlloc(ptr, count, file, line, func);
#else
// avoid unused params warning
(void)file;
(void)line;
(void)func;
#endif
return ptr;
}
void JeAllocImpl::DeallocBytes(void* ptr) {
// deal with null
if (!ptr)
return;
#ifdef CC_MEMORY_TRACKER
CheckOverflowFree(ptr);
MemTracker::Instance()->RecordFree(ptr);
#endif
je_free(ptr);
void JeAllocImpl::DeallocBytes(void *ptr) {
// deal with null
if (!ptr)
return;
#ifdef CC_MEMORY_TRACKER
CheckOverflowFree(ptr);
MemTracker::Instance()->RecordFree(ptr);
#endif
je_free(ptr);
}
struct JeDumpData {
char* buf;
int size;
char *buf;
int size;
};
static void JeStatsPrint(void* param, const char* msg) {
JeDumpData* jd = (JeDumpData*)param;
if (jd->size == 0) return;
static void JeStatsPrint(void *param, const char *msg) {
JeDumpData *jd = (JeDumpData *)param;
if (jd->size == 0) return;
int len = (int)strlen(msg);
if (len > jd->size) len = jd->size;
memcpy(jd->buf, msg, len);
jd->buf[len] = 0;
jd->buf += len;
jd->size -= len;
int len = (int)strlen(msg);
if (len > jd->size) len = jd->size;
memcpy(jd->buf, msg, len);
jd->buf[len] = 0;
jd->buf += len;
jd->size -= len;
}
void JeAllocImpl::DumpStats(char* buf, int bufsize) {
JeDumpData jd;
jd.buf = buf;
jd.size = bufsize - 1;
je_malloc_stats_print(JeStatsPrint, &jd, "ma");
void JeAllocImpl::DumpStats(char *buf, int bufsize) {
JeDumpData jd;
jd.buf = buf;
jd.size = bufsize - 1;
je_malloc_stats_print(JeStatsPrint, &jd, "ma");
}
void JeAllocImpl::TrimAlloc() {
int narenas = 0;
size_t sz = sizeof(narenas);
je_mallctl("arenas.narenas", (void *)&narenas, &sz, nullptr, 0);
char buf[24];
sprintf(buf, "arena.%d.purge", narenas);
printf("jemalloc trim: %s\n", buf);
je_mallctl(buf, NULL, NULL, NULL, 0);
int narenas = 0;
size_t sz = sizeof(narenas);
je_mallctl("arenas.narenas", (void *)&narenas, &sz, nullptr, 0);
char buf[24];
sprintf(buf, "arena.%d.purge", narenas);
printf("jemalloc trim: %s\n", buf);
je_mallctl(buf, NULL, NULL, NULL, 0);
}
}
} // namespace gfx
} // namespace cc
#endif // end - #ifdef CC_MEMORY_ALLOCATOR_JEMALLOC
+34 -32
View File
@@ -4,16 +4,17 @@
#if (CC_MEMORY_ALLOCATOR == CC_MEMORY_ALLOCATOR_JEMALLOC)
namespace cc {
namespace gfx {
//Non-templated utility class just to hide jemalloc.
class CC_CORE_API JeAllocImpl {
public:
static CC_DECL_MALLOC void* AllocBytes(size_t count, const char* file, int line, const char* func);
static CC_DECL_MALLOC void* ReallocBytes(void* ptr, size_t count, const char* file, int line, const char *func);
static CC_DECL_MALLOC void* AllocBytesAligned(size_t align, size_t count, const char* file, int line, const char* func);
static void DeallocBytes(void* ptr);
static void DumpStats(char* buf, int bufsize);
static void TrimAlloc();
public:
static CC_DECL_MALLOC void *AllocBytes(size_t count, const char *file, int line, const char *func);
static CC_DECL_MALLOC void *ReallocBytes(void *ptr, size_t count, const char *file, int line, const char *func);
static CC_DECL_MALLOC void *AllocBytesAligned(size_t align, size_t count, const char *file, int line, const char *func);
static void DeallocBytes(void *ptr);
static void DumpStats(char *buf, int bufsize);
static void TrimAlloc();
};
/** An allocation policy for use with AllocatedObject and
@@ -22,38 +23,39 @@ class CC_CORE_API JeAllocImpl {
provide a custom version of if you wish to change how memory is allocated.
*/
class CC_CORE_API JeAllocPolicy {
public:
static CC_INLINE CC_DECL_MALLOC void* AllocateBytes(size_t count, const char* file = nullptr, int line = 0, const char* func = nullptr) {
return JeAllocImpl::AllocBytes(count, file, line, func);
}
public:
static CC_INLINE CC_DECL_MALLOC void *AllocateBytes(size_t count, const char *file = nullptr, int line = 0, const char *func = nullptr) {
return JeAllocImpl::AllocBytes(count, file, line, func);
}
static CC_INLINE CC_DECL_MALLOC void* ReallocateBytes(void* ptr, size_t count, const char* file = nullptr, int line = 0, const char* func = nullptr) {
return JeAllocImpl::ReallocBytes(ptr, count, file, line, func);
}
static CC_INLINE CC_DECL_MALLOC void *ReallocateBytes(void *ptr, size_t count, const char *file = nullptr, int line = 0, const char *func = nullptr) {
return JeAllocImpl::ReallocBytes(ptr, count, file, line, func);
}
static CC_INLINE void DeallocateBytes(void* ptr) {
JeAllocImpl::DeallocBytes(ptr);
}
static CC_INLINE void DeallocateBytes(void *ptr) {
JeAllocImpl::DeallocBytes(ptr);
}
static CC_INLINE CC_DECL_MALLOC void* AllocateBytesAligned(size_t alignment, size_t count, const char* file = nullptr, int line = 0, const char* func = nullptr) {
return JeAllocImpl::AllocBytesAligned(alignment, count, file, line, func);
}
static CC_INLINE CC_DECL_MALLOC void *AllocateBytesAligned(size_t alignment, size_t count, const char *file = nullptr, int line = 0, const char *func = nullptr) {
return JeAllocImpl::AllocBytesAligned(alignment, count, file, line, func);
}
static CC_INLINE void DeallocateBytesAligned(void* ptr) {
JeAllocImpl::DeallocBytes(ptr);
}
static CC_INLINE void DeallocateBytesAligned(void *ptr) {
JeAllocImpl::DeallocBytes(ptr);
}
// Get the maximum size of a single allocation
static CC_INLINE size_t GetMaxAllocationSize() {
return (std::numeric_limits<size_t>::max)();
}
private:
// No instantiation
JeAllocPolicy() {}
// Get the maximum size of a single allocation
static CC_INLINE size_t GetMaxAllocationSize() {
return (std::numeric_limits<size_t>::max)();
}
private:
// No instantiation
JeAllocPolicy() {}
};
}
} // namespace gfx
} // namespace cc
#endif // end - #ifdef COCOS_MEMORY_ALLOCATOR_JEMALLOC
+148 -107
View File
@@ -7,6 +7,7 @@
#include "JeAlloc.h"
namespace cc {
namespace gfx {
#if (CC_MEMORY_ALLOCATOR == CC_MEMORY_ALLOCATOR_STD)
@@ -34,7 +35,6 @@ class CategorisedAllocPolicy : public JeAllocPolicy {};
#endif
// Useful shortcuts
typedef CategorisedAllocPolicy GAP;
typedef CategorisedAllocPolicy STLAP;
@@ -42,7 +42,7 @@ typedef CategorisedAllocPolicy STLAP;
// Containers (by-value only)
// Will be of the form:
// typedef STLAllocator<T, DefaultAllocPolicy, Category> TAlloc;
// for use in vector<T, TAlloc>::type
// for use in vector<T, TAlloc>::type
//////////////////////////////////////////////////////////////////////////
@@ -50,127 +50,168 @@ typedef CategorisedAllocPolicy STLAP;
without using new[] (which allocates an undocumented amount of extra memory
and so isn't appropriate for custom allocators).
*/
template<typename T>
T* ConstructN(T* basePtr, size_t count) {
for (size_t i = 0; i < count; ++i) {
new ((void*)(basePtr+i)) T();
}
return basePtr;
template <typename T>
T *ConstructN(T *basePtr, size_t count) {
for (size_t i = 0; i < count; ++i) {
new ((void *)(basePtr + i)) T();
}
return basePtr;
}
}
} // namespace gfx
} // namespace cc
#ifdef CC_MEMORY_TRACKER
/// Allocate a block of raw memory.
# define _CC_MALLOC(bytes) ::cc::CategorisedAllocPolicy::AllocateBytes(bytes, __FILE__, __LINE__, __FUNCTION__)
/// Reallocate a block of raw memory.
# define _CC_REALLOC(ptr, bytes) ::cc::CategorisedAllocPolicy::ReallocateBytes(ptr, bytes, __FILE__, __LINE__, __FUNCTION__)
/// Allocate a block of memory for a primitive type.
# define _CC_ALLOC_T(T, count) static_cast<T*>(::cc::CategorisedAllocPolicy::AllocateBytes(sizeof(T)*(count), __FILE__, __LINE__, __FUNCTION__))
/// Free the memory allocated with _CC_MALLOC or _CC_ALLOC_T.
# define _CC_FREE(ptr) ::cc::CategorisedAllocPolicy::DeallocateBytes((void*)ptr)
/// Allocate a block of raw memory.
#define _CC_MALLOC(bytes) ::cc::gfx::CategorisedAllocPolicy::AllocateBytes(bytes, __FILE__, __LINE__, __FUNCTION__)
/// Reallocate a block of raw memory.
#define _CC_REALLOC(ptr, bytes) ::cc::gfx::CategorisedAllocPolicy::ReallocateBytes(ptr, bytes, __FILE__, __LINE__, __FUNCTION__)
/// Allocate a block of memory for a primitive type.
#define _CC_ALLOC_T(T, count) static_cast<T *>(::cc::gfx::CategorisedAllocPolicy::AllocateBytes(sizeof(T) * (count), __FILE__, __LINE__, __FUNCTION__))
/// Free the memory allocated with _CC_MALLOC or _CC_ALLOC_T.
#define _CC_FREE(ptr) ::cc::gfx::CategorisedAllocPolicy::DeallocateBytes((void *)ptr)
/// Allocate space for one primitive type, external type or non-virtual type with constructor parameters
# define _CC_NEW_T(T) new (::cc::CategorisedAllocPolicy::AllocateBytes(sizeof(T), __FILE__, __LINE__, __FUNCTION__)) T
/// Allocate a block of memory for 'count' primitive types - do not use for classes that inherit from AllocatedObject
# define _CC_NEW_ARRAY_T(T, count) ::cc::ConstructN(static_cast<T*>(::cc::CategorisedAllocPolicy::AllocateBytes(sizeof(T)*(count), __FILE__, __LINE__, __FUNCTION__)), count)
/// Free the memory allocated with _CC_NEW_T.
# define _CC_DELETE_T(ptr, T) if(ptr){(ptr)->~T(); ::cc::CategorisedAllocPolicy::DeallocateBytes((void*)ptr);}
/// Free the memory allocated with _CC_NEW_ARRAY_T.
# define _CC_DELETE_ARRAY_T(ptr, T, count) if(ptr){for (size_t b = 0; b < (size_t)count; ++b) {(ptr)[b].~T();} ::cc::CategorisedAllocPolicy::DeallocateBytes((void*)ptr);}
/// Allocate space for one primitive type, external type or non-virtual type with constructor parameters
#define _CC_NEW_T(T) new (::cc::gfx::CategorisedAllocPolicy::AllocateBytes(sizeof(T), __FILE__, __LINE__, __FUNCTION__)) T
/// Allocate a block of memory for 'count' primitive types - do not use for classes that inherit from AllocatedObject
#define _CC_NEW_ARRAY_T(T, count) ::cc::gfx::ConstructN(static_cast<T *>(::cc::gfx::CategorisedAllocPolicy::AllocateBytes(sizeof(T) * (count), __FILE__, __LINE__, __FUNCTION__)), count)
/// Free the memory allocated with _CC_NEW_T.
#define _CC_DELETE_T(ptr, T) \
if (ptr) { \
(ptr)->~T(); \
::cc::gfx::CategorisedAllocPolicy::DeallocateBytes((void *)ptr); \
}
/// Free the memory allocated with _CC_NEW_ARRAY_T.
#define _CC_DELETE_ARRAY_T(ptr, T, count) \
if (ptr) { \
for (size_t b = 0; b < (size_t)count; ++b) { \
(ptr)[b].~T(); \
} \
::cc::gfx::CategorisedAllocPolicy::DeallocateBytes((void *)ptr); \
}
// aligned allocation
/// Allocate a block of raw memory aligned to user defined boundaries.
# define _CC_MALLOC_ALIGN(bytes, align) ::cc::CategorisedAllocPolicy::AllocateBytesAligned(align, bytes, __FILE__, __LINE__, __FUNCTION__)
/// Allocate a block of memory for a primitive type aligned to user defined boundaries.
# define _CC_ALLOC_T_ALIGN(T, count, align) static_cast<T*>(::cc::CategorisedAllocPolicy::AllocateBytesAligned(align, sizeof(T)*(count), __FILE__, __LINE__, __FUNCTION__))
/// Free the memory allocated with either _CC_MALLOC_ALIGN or _CC_ALLOC_T_ALIGN.
# define _CC_FREE_ALIGN(ptr, align) ::cc::CategorisedAllocPolicy::DeallocateBytesAligned(ptr)
/// Allocate a block of raw memory aligned to SIMD boundaries.
# define _CC_MALLOC_SIMD(bytes) _CC_MALLOC_ALIGN(bytes, CC_SIMD_ALIGNMENT)
/// Allocate a block of memory for a primitive type aligned to SIMD boundaries.
# define _CC_ALLOC_T_SIMD(T, count) _CC_ALLOC_T_ALIGN(T, count, CC_SIMD_ALIGNMENT)
/// Free the memory allocated with either _CC_MALLOC_SIMD or _CC_ALLOC_T_SIMD.
# define _CC_FREE_SIMD(ptr) _CC_FREE_ALIGN(ptr, CC_SIMD_ALIGNMENT)
// aligned allocation
/// Allocate a block of raw memory aligned to user defined boundaries.
#define _CC_MALLOC_ALIGN(bytes, align) ::cc::gfx::CategorisedAllocPolicy::AllocateBytesAligned(align, bytes, __FILE__, __LINE__, __FUNCTION__)
/// Allocate a block of memory for a primitive type aligned to user defined boundaries.
#define _CC_ALLOC_T_ALIGN(T, count, align) static_cast<T *>(::cc::gfx::CategorisedAllocPolicy::AllocateBytesAligned(align, sizeof(T) * (count), __FILE__, __LINE__, __FUNCTION__))
/// Free the memory allocated with either _CC_MALLOC_ALIGN or _CC_ALLOC_T_ALIGN.
#define _CC_FREE_ALIGN(ptr, align) ::cc::gfx::CategorisedAllocPolicy::DeallocateBytesAligned(ptr)
/// Allocate a block of raw memory aligned to SIMD boundaries.
#define _CC_MALLOC_SIMD(bytes) _CC_MALLOC_ALIGN(bytes, CC_SIMD_ALIGNMENT)
/// Allocate a block of memory for a primitive type aligned to SIMD boundaries.
#define _CC_ALLOC_T_SIMD(T, count) _CC_ALLOC_T_ALIGN(T, count, CC_SIMD_ALIGNMENT)
/// Free the memory allocated with either _CC_MALLOC_SIMD or _CC_ALLOC_T_SIMD.
#define _CC_FREE_SIMD(ptr) _CC_FREE_ALIGN(ptr, CC_SIMD_ALIGNMENT)
/// Allocate space for one primitive type, external type or non-virtual type aligned to user defined boundaries
# define _CC_NEW_T_ALIGN(T, align) new (::cc::CategorisedAllocPolicy::AllocateBytesAligned(align, sizeof(T), __FILE__, __LINE__, __FUNCTION__)) T
/// Allocate a block of memory for 'count' primitive types aligned to user defined boundaries - do not use for classes that inherit from AllocatedObject
# define _CC_NEW_ARRAY_T_ALIGN(T, count, align) ::cc::ConstructN(static_cast<T*>(::cc::CategorisedAllocPolicy::AllocateBytesAligned(align, sizeof(T)*(count), __FILE__, __LINE__, __FUNCTION__)), count)
/// Free the memory allocated with _CC_NEW_T_ALIGN.
# define _CC_DELETE_T_ALIGN(ptr, T, align) if(ptr){(ptr)->~T(); ::cc::CategorisedAllocPolicy::DeallocateBytesAligned(ptr);}
/// Free the memory allocated with _CC_NEW_ARRAY_T_ALIGN.
# define _CC_DELETE_ARRAY_T_ALIGN(ptr, T, count, align) if(ptr){for (size_t _b = 0; _b < (size_t)count; ++_b) {(ptr)[_b].~T();} ::cc::CategorisedAllocPolicy::DeallocateBytesAligned(ptr);}
/// Allocate space for one primitive type, external type or non-virtual type aligned to SIMD boundaries
# define _CC_NEW_T_SIMD(T) _CC_NEW_T_ALIGN(T, CC_SIMD_ALIGNMENT)
/// Allocate a block of memory for 'count' primitive types aligned to SIMD boundaries - do not use for classes that inherit from AllocatedObject
# define _CC_NEW_ARRAY_T_SIMD(T, count) _CC_NEW_ARRAY_T_ALIGN(T, count, CC_SIMD_ALIGNMENT)
/// Free the memory allocated with _CC_NEW_T_SIMD.
# define _CC_DELETE_T_SIMD(ptr, T) _CC_DELETE_T_ALIGN(ptr, T, CC_SIMD_ALIGNMENT)
/// Free the memory allocated with _CC_NEW_ARRAY_T_SIMD.
# define _CC_DELETE_ARRAY_T_SIMD(ptr, T, count) _CC_DELETE_ARRAY_T_ALIGN(ptr, T, CC_SIMD_ALIGNMENT)
/// Allocate space for one primitive type, external type or non-virtual type aligned to user defined boundaries
#define _CC_NEW_T_ALIGN(T, align) new (::cc::gfx::CategorisedAllocPolicy::AllocateBytesAligned(align, sizeof(T), __FILE__, __LINE__, __FUNCTION__)) T
/// Allocate a block of memory for 'count' primitive types aligned to user defined boundaries - do not use for classes that inherit from AllocatedObject
#define _CC_NEW_ARRAY_T_ALIGN(T, count, align) ::cc::gfx::ConstructN(static_cast<T *>(::cc::gfx::CategorisedAllocPolicy::AllocateBytesAligned(align, sizeof(T) * (count), __FILE__, __LINE__, __FUNCTION__)), count)
/// Free the memory allocated with _CC_NEW_T_ALIGN.
#define _CC_DELETE_T_ALIGN(ptr, T, align) \
if (ptr) { \
(ptr)->~T(); \
::cc::gfx::CategorisedAllocPolicy::DeallocateBytesAligned(ptr); \
}
/// Free the memory allocated with _CC_NEW_ARRAY_T_ALIGN.
#define _CC_DELETE_ARRAY_T_ALIGN(ptr, T, count, align) \
if (ptr) { \
for (size_t _b = 0; _b < (size_t)count; ++_b) { \
(ptr)[_b].~T(); \
} \
::cc::gfx::CategorisedAllocPolicy::DeallocateBytesAligned(ptr); \
}
/// Allocate space for one primitive type, external type or non-virtual type aligned to SIMD boundaries
#define _CC_NEW_T_SIMD(T) _CC_NEW_T_ALIGN(T, CC_SIMD_ALIGNMENT)
/// Allocate a block of memory for 'count' primitive types aligned to SIMD boundaries - do not use for classes that inherit from AllocatedObject
#define _CC_NEW_ARRAY_T_SIMD(T, count) _CC_NEW_ARRAY_T_ALIGN(T, count, CC_SIMD_ALIGNMENT)
/// Free the memory allocated with _CC_NEW_T_SIMD.
#define _CC_DELETE_T_SIMD(ptr, T) _CC_DELETE_T_ALIGN(ptr, T, CC_SIMD_ALIGNMENT)
/// Free the memory allocated with _CC_NEW_ARRAY_T_SIMD.
#define _CC_DELETE_ARRAY_T_SIMD(ptr, T, count) _CC_DELETE_ARRAY_T_ALIGN(ptr, T, CC_SIMD_ALIGNMENT)
// new / delete for classes deriving from AllocatedObject (alignment determined by per-class policy)
// Also hooks up the file/line/function params
// Can only be used with classes that derive from AllocatedObject since customized new/delete needed
# define _CC_NEW new (__FILE__, __LINE__, __FUNCTION__)
# define _CC_DELETE delete
// new / delete for classes deriving from AllocatedObject (alignment determined by per-class policy)
// Also hooks up the file/line/function params
// Can only be used with classes that derive from AllocatedObject since customized new/delete needed
#define _CC_NEW new (__FILE__, __LINE__, __FUNCTION__)
#define _CC_DELETE delete
#else
/// Allocate a block of raw memory.
# define _CC_MALLOC(bytes) ::cc::CategorisedAllocPolicy::AllocateBytes(bytes)
/// Reallocate a block of raw memory.
# define _CC_REALLOC(ptr, bytes) ::cc::CategorisedAllocPolicy::ReallocateBytes(ptr, bytes)
/// Allocate a block of memory for a primitive type.
# define _CC_ALLOC_T(T, count) static_cast<T*>(::cc::CategorisedAllocPolicy::AllocateBytes(sizeof(T)*(count)))
/// Free the memory allocated with _CC_MALLOC or _CC_ALLOC_T. Category is required to be restated to ensure the matching policy is used
# define _CC_FREE(ptr) ::cc::CategorisedAllocPolicy::DeallocateBytes((void*)ptr)
/// Allocate a block of raw memory.
#define _CC_MALLOC(bytes) ::cc::gfx::CategorisedAllocPolicy::AllocateBytes(bytes)
/// Reallocate a block of raw memory.
#define _CC_REALLOC(ptr, bytes) ::cc::gfx::CategorisedAllocPolicy::ReallocateBytes(ptr, bytes)
/// Allocate a block of memory for a primitive type.
#define _CC_ALLOC_T(T, count) static_cast<T *>(::cc::gfx::CategorisedAllocPolicy::AllocateBytes(sizeof(T) * (count)))
/// Free the memory allocated with _CC_MALLOC or _CC_ALLOC_T. Category is required to be restated to ensure the matching policy is used
#define _CC_FREE(ptr) ::cc::gfx::CategorisedAllocPolicy::DeallocateBytes((void *)ptr)
/// Allocate space for one primitive type, external type or non-virtual type with constructor parameters
# define _CC_NEW_T(T) new (::cc::CategorisedAllocPolicy::AllocateBytes(sizeof(T))) T
/// Allocate a block of memory for 'count' primitive types - do not use for classes that inherit from AllocatedObject
# define _CC_NEW_ARRAY_T(T, count) ::cc::ConstructN(static_cast<T*>(::cc::CategorisedAllocPolicy::AllocateBytes(sizeof(T)*(count))), count)
/// Free the memory allocated with _CC_NEW_T.
# define _CC_DELETE_T(ptr, T) if(ptr){(ptr)->~T(); ::cc::CategorisedAllocPolicy::DeallocateBytes((void*)ptr);}
/// Free the memory allocated with _CC_NEW_ARRAY_T.
# define _CC_DELETE_ARRAY_T(ptr, T, count) if(ptr){for (size_t b = 0; b < (size_t)count; ++b) {(ptr)[b].~T();} ::cc::CategorisedAllocPolicy::DeallocateBytes((void*)ptr);}
/// Allocate space for one primitive type, external type or non-virtual type with constructor parameters
#define _CC_NEW_T(T) new (::cc::gfx::CategorisedAllocPolicy::AllocateBytes(sizeof(T))) T
/// Allocate a block of memory for 'count' primitive types - do not use for classes that inherit from AllocatedObject
#define _CC_NEW_ARRAY_T(T, count) ::cc::gfx::ConstructN(static_cast<T *>(::cc::gfx::CategorisedAllocPolicy::AllocateBytes(sizeof(T) * (count))), count)
/// Free the memory allocated with _CC_NEW_T.
#define _CC_DELETE_T(ptr, T) \
if (ptr) { \
(ptr)->~T(); \
::cc::gfx::CategorisedAllocPolicy::DeallocateBytes((void *)ptr); \
}
/// Free the memory allocated with _CC_NEW_ARRAY_T.
#define _CC_DELETE_ARRAY_T(ptr, T, count) \
if (ptr) { \
for (size_t b = 0; b < (size_t)count; ++b) { \
(ptr)[b].~T(); \
} \
::cc::gfx::CategorisedAllocPolicy::DeallocateBytes((void *)ptr); \
}
// aligned allocation
/// Allocate a block of raw memory aligned to user defined boundaries.
# define _CC_MALLOC_ALIGN(bytes, align) ::cc::CategorisedAllocPolicy::AllocateBytesAligned(align, bytes)
/// Allocate a block of memory for a primitive type aligned to user defined boundaries.
# define _CC_ALLOC_T_ALIGN(T, count, align) static_cast<T*>(::cc::CategorisedAllocPolicy::AllocateBytesAligned(align, sizeof(T)*(count)))
/// Free the memory allocated with either _CC_MALLOC_ALIGN or _CC_ALLOC_T_ALIGN.
# define _CC_FREE_ALIGN(ptr, align) ::cc::CategorisedAllocPolicy::DeallocateBytesAligned((void*)ptr)
/// Allocate a block of raw memory aligned to SIMD boundaries.
# define _CC_MALLOC_SIMD(bytes) _CC_MALLOC_ALIGN(bytes, CC_SIMD_ALIGNMENT)
/// Allocate a block of memory for a primitive type aligned to SIMD boundaries.
# define _CC_ALLOC_T_SIMD(T, count) _CC_ALLOC_T_ALIGN(T, count, CC_SIMD_ALIGNMENT)
/// Free the memory allocated with either _CC_MALLOC_SIMD or _CC_ALLOC_T_SIMD.
# define _CC_FREE_SIMD(ptr) _CC_FREE_ALIGN(ptr, CC_SIMD_ALIGNMENT)
// aligned allocation
/// Allocate a block of raw memory aligned to user defined boundaries.
#define _CC_MALLOC_ALIGN(bytes, align) ::cc::gfx::CategorisedAllocPolicy::AllocateBytesAligned(align, bytes)
/// Allocate a block of memory for a primitive type aligned to user defined boundaries.
#define _CC_ALLOC_T_ALIGN(T, count, align) static_cast<T *>(::cc::gfx::CategorisedAllocPolicy::AllocateBytesAligned(align, sizeof(T) * (count)))
/// Free the memory allocated with either _CC_MALLOC_ALIGN or _CC_ALLOC_T_ALIGN.
#define _CC_FREE_ALIGN(ptr, align) ::cc::gfx::CategorisedAllocPolicy::DeallocateBytesAligned((void *)ptr)
/// Allocate a block of raw memory aligned to SIMD boundaries.
#define _CC_MALLOC_SIMD(bytes) _CC_MALLOC_ALIGN(bytes, CC_SIMD_ALIGNMENT)
/// Allocate a block of memory for a primitive type aligned to SIMD boundaries.
#define _CC_ALLOC_T_SIMD(T, count) _CC_ALLOC_T_ALIGN(T, count, CC_SIMD_ALIGNMENT)
/// Free the memory allocated with either _CC_MALLOC_SIMD or _CC_ALLOC_T_SIMD.
#define _CC_FREE_SIMD(ptr) _CC_FREE_ALIGN(ptr, CC_SIMD_ALIGNMENT)
/// Allocate space for one primitive type, external type or non-virtual type aligned to user defined boundaries
# define _CC_NEW_T_ALIGN(T, align) new (::cc::CategorisedAllocPolicy::AllocateBytesAligned(align, sizeof(T))) T
/// Allocate a block of memory for 'count' primitive types aligned to user defined boundaries - do not use for classes that inherit from AllocatedObject
# define _CC_NEW_ARRAY_T_ALIGN(T, count, align) ::cc::ConstructN(static_cast<T*>(::cc::CategorisedAllocPolicy::AllocateBytesAligned(align, sizeof(T)*(count))), count)
/// Free the memory allocated with _CC_NEW_T_ALIGN.
# define _CC_DELETE_T_ALIGN(ptr, T, align) if(ptr){(ptr)->~T(); ::cc::CategorisedAllocPolicy::DeallocateBytesAligned((void*)ptr);}
/// Free the memory allocated with _CC_NEW_ARRAY_T_ALIGN.
# define _CC_DELETE_ARRAY_T_ALIGN(ptr, T, count, align) if(ptr){for (size_t _b = 0; _b < (size_t)count; ++_b) { (ptr)[_b].~T();} ::cc::CategorisedAllocPolicy::DeallocateBytesAligned((void*)ptr);}
/// Allocate space for one primitive type, external type or non-virtual type aligned to SIMD boundaries
# define _CC_NEW_T_SIMD(T) _CC_NEW_T_ALIGN(T, CC_SIMD_ALIGNMENT)
/// Allocate a block of memory for 'count' primitive types aligned to SIMD boundaries - do not use for classes that inherit from AllocatedObject
# define _CC_NEW_ARRAY_T_SIMD(T, count) _CC_NEW_ARRAY_T_ALIGN(T, count, CC_SIMD_ALIGNMENT)
/// Free the memory allocated with _CC_NEW_T_SIMD.
# define _CC_DELETE_T_SIMD(ptr, T) _CC_DELETE_T_ALIGN(ptr, T, CC_SIMD_ALIGNMENT)
/// Free the memory allocated with _CC_NEW_ARRAY_T_SIMD.
# define _CC_DELETE_ARRAY_T_SIMD(ptr, T, count) _CC_DELETE_ARRAY_T_ALIGN(ptr, T, count, CC_SIMD_ALIGNMENT)
/// Allocate space for one primitive type, external type or non-virtual type aligned to user defined boundaries
#define _CC_NEW_T_ALIGN(T, align) new (::cc::gfx::CategorisedAllocPolicy::AllocateBytesAligned(align, sizeof(T))) T
/// Allocate a block of memory for 'count' primitive types aligned to user defined boundaries - do not use for classes that inherit from AllocatedObject
#define _CC_NEW_ARRAY_T_ALIGN(T, count, align) ::cc::gfx::ConstructN(static_cast<T *>(::cc::gfx::CategorisedAllocPolicy::AllocateBytesAligned(align, sizeof(T) * (count))), count)
/// Free the memory allocated with _CC_NEW_T_ALIGN.
#define _CC_DELETE_T_ALIGN(ptr, T, align) \
if (ptr) { \
(ptr)->~T(); \
::cc::gfx::CategorisedAllocPolicy::DeallocateBytesAligned((void *)ptr); \
}
/// Free the memory allocated with _CC_NEW_ARRAY_T_ALIGN.
#define _CC_DELETE_ARRAY_T_ALIGN(ptr, T, count, align) \
if (ptr) { \
for (size_t _b = 0; _b < (size_t)count; ++_b) { \
(ptr)[_b].~T(); \
} \
::cc::gfx::CategorisedAllocPolicy::DeallocateBytesAligned((void *)ptr); \
}
/// Allocate space for one primitive type, external type or non-virtual type aligned to SIMD boundaries
#define _CC_NEW_T_SIMD(T) _CC_NEW_T_ALIGN(T, CC_SIMD_ALIGNMENT)
/// Allocate a block of memory for 'count' primitive types aligned to SIMD boundaries - do not use for classes that inherit from AllocatedObject
#define _CC_NEW_ARRAY_T_SIMD(T, count) _CC_NEW_ARRAY_T_ALIGN(T, count, CC_SIMD_ALIGNMENT)
/// Free the memory allocated with _CC_NEW_T_SIMD.
#define _CC_DELETE_T_SIMD(ptr, T) _CC_DELETE_T_ALIGN(ptr, T, CC_SIMD_ALIGNMENT)
/// Free the memory allocated with _CC_NEW_ARRAY_T_SIMD.
#define _CC_DELETE_ARRAY_T_SIMD(ptr, T, count) _CC_DELETE_ARRAY_T_ALIGN(ptr, T, count, CC_SIMD_ALIGNMENT)
// new / delete for classes deriving from AllocatedObject (alignment determined by per-class policy)
# define _CC_NEW new
# define _CC_DELETE delete
// new / delete for classes deriving from AllocatedObject (alignment determined by per-class policy)
#define _CC_NEW new
#define _CC_DELETE delete
#endif
+182 -184
View File
@@ -3,266 +3,264 @@
#include "util/StringUtil.h"
#if (CC_PLATFORM == CC_PLATFORM_ANDROID)
# include <android/log.h>
#include <android/log.h>
#endif
#ifdef CC_MEMORY_TRACKER
extern "C"
{
#include <tommyhashdyn.h>
extern "C" {
#include <tommyhashdyn.h>
}
#if (CC_PLATFORM == CC_PLATFORM_WINDOWS)
#if (CC_PLATFORM == CC_PLATFORM_WINDOWS)
#ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
#endif
#if !defined(NOMINMAX) && defined(_MSC_VER)
# define NOMINMAX // required to stop windows.h messing up std::min
#endif
# include <Windows.h>
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#if !defined(NOMINMAX) && defined(_MSC_VER)
#define NOMINMAX // required to stop windows.h messing up std::min
#endif
#include <Windows.h>
# define CC_OUTPUT_STR(str) ::OutputDebugStringA(str)
#else
# define CC_OUTPUT_STR(str) fputs(str, stdout)
#endif
#define CC_OUTPUT_STR(str) ::OutputDebugStringA(str)
#else
#define CC_OUTPUT_STR(str) fputs(str, stdout)
#endif
#define LEAK_FILENAME "MemoryLeaks.log"
#define LEAK_FILENAME "MemoryLeaks.log"
namespace cc {
namespace gfx {
struct AllocHashNode {
tommy_hashdyn_node node;
void* key;
unsigned int bytes;
const char* filename;
const char* function;
unsigned int line;
tommy_hashdyn_node node;
void *key;
unsigned int bytes;
const char *filename;
const char *function;
unsigned int line;
};
struct AllocListParam {
char* buf;
char* last;
char *buf;
char *last;
};
struct AllocDumpParam {
std::map<std::string, unsigned int> allocMap;
std::map<std::string, unsigned int> allocMap;
};
CC_INLINE static void FreeHashNode(AllocHashNode *n) {
free(n);
free(n);
}
static int HashNodeCompare(const void* arg, const void* obj) {
return ((AllocHashNode*)obj)->key != (void*)arg;
static int HashNodeCompare(const void *arg, const void *obj) {
return ((AllocHashNode *)obj)->key != (void *)arg;
}
static void HashNodeListAndFree(void *arg, void *obj) {
AllocHashNode* node = (AllocHashNode*)obj;
AllocListParam* param = (AllocListParam*)arg;
int len = StringUtil::Printf(param->buf, param->last, "%s(%u): {%u bytes} functions: %s\n", (node->filename ? node->filename : "(unknown source)"),
node->line, node->bytes, (node->function ? node->function : ""));
param->buf += len;
FreeHashNode(node);
AllocHashNode *node = (AllocHashNode *)obj;
AllocListParam *param = (AllocListParam *)arg;
int len = StringUtil::Printf(param->buf, param->last, "%s(%u): {%u bytes} functions: %s\n", (node->filename ? node->filename : "(unknown source)"),
node->line, node->bytes, (node->function ? node->function : ""));
param->buf += len;
FreeHashNode(node);
}
static void HashNodeListAndDump(void *arg, void *obj) {
AllocHashNode* node = (AllocHashNode*)obj;
AllocDumpParam* param = (AllocDumpParam*)arg;
const char* key = node->filename ? node->filename : "null";
std::map<std::string, unsigned int>::iterator ptr = param->allocMap.find(key);
if (ptr == param->allocMap.end()) {
param->allocMap[key] = node->bytes;
} else {
ptr->second += node->bytes;
}
//char tmpbuf[1024];
//sprintf(tmpbuf, "%s|%s|%u\n", node->filename, node->function, node->bytes);
//fputs(tmpbuf, param);
AllocHashNode *node = (AllocHashNode *)obj;
AllocDumpParam *param = (AllocDumpParam *)arg;
const char *key = node->filename ? node->filename : "null";
std::map<std::string, unsigned int>::iterator ptr = param->allocMap.find(key);
if (ptr == param->allocMap.end()) {
param->allocMap[key] = node->bytes;
} else {
ptr->second += node->bytes;
}
//char tmpbuf[1024];
//sprintf(tmpbuf, "%s|%s|%u\n", node->filename, node->function, node->bytes);
//fputs(tmpbuf, param);
}
/////////////////////////////////////////////////////////
MemTracker::MemTracker()
: total_memory_allocated_(0) {
allocations_ = malloc(sizeof(tommy_hashdyn));
tommy_hashdyn_init((tommy_hashdyn*)allocations_);
: total_memory_allocated_(0) {
allocations_ = malloc(sizeof(tommy_hashdyn));
tommy_hashdyn_init((tommy_hashdyn *)allocations_);
}
MemTracker::~MemTracker() {
ReportLeaks();
tommy_hashdyn_done((tommy_hashdyn*)allocations_);
free(allocations_);
ReportLeaks();
tommy_hashdyn_done((tommy_hashdyn *)allocations_);
free(allocations_);
}
void MemTracker::RecordAlloc(void *ptr, size_t sz, const char *file, size_t ln, const char *func) {
tommy_hash_t hash = tommy_inthash_u32((tommy_uint32_t)reinterpret_cast<size_t>(ptr));
tommy_hash_t hash = tommy_inthash_u32((tommy_uint32_t) reinterpret_cast<size_t>(ptr));
mutex_.lock();
mutex_.lock();
AllocHashNode* node = (AllocHashNode*)tommy_hashdyn_search((tommy_hashdyn*)allocations_, HashNodeCompare, ptr, hash);
if (node) {
CCASSERT(0, "Double allocation with same address - this probably means you have a mismatched allocation / deallocation style.");
} else {
node = (AllocHashNode*)malloc(sizeof(AllocHashNode));
node->key = ptr;
node->bytes = (unsigned int)sz;
node->filename = file;
node->function = func;
node->line = (unsigned int)ln;
tommy_hashdyn_insert((tommy_hashdyn*)allocations_, &node->node, node, hash);
total_memory_allocated_ += sz;
}
AllocHashNode *node = (AllocHashNode *)tommy_hashdyn_search((tommy_hashdyn *)allocations_, HashNodeCompare, ptr, hash);
if (node) {
CCASSERT(0, "Double allocation with same address - this probably means you have a mismatched allocation / deallocation style.");
} else {
node = (AllocHashNode *)malloc(sizeof(AllocHashNode));
node->key = ptr;
node->bytes = (unsigned int)sz;
node->filename = file;
node->function = func;
node->line = (unsigned int)ln;
tommy_hashdyn_insert((tommy_hashdyn *)allocations_, &node->node, node, hash);
total_memory_allocated_ += sz;
}
mutex_.unlock();
mutex_.unlock();
}
void MemTracker::RecordReAlloc(void* oldptr, void* ptr, size_t sz, const char* file, size_t ln, const char* func) {
if (oldptr != ptr) {
if (oldptr) RecordFree(oldptr);
RecordAlloc(ptr, sz, file, ln, func);
return;
}
void MemTracker::RecordReAlloc(void *oldptr, void *ptr, size_t sz, const char *file, size_t ln, const char *func) {
if (oldptr != ptr) {
if (oldptr) RecordFree(oldptr);
RecordAlloc(ptr, sz, file, ln, func);
return;
}
if (sz == 0) {
RecordFree(oldptr);
return;
}
if (sz == 0) {
RecordFree(oldptr);
return;
}
tommy_hash_t hash = tommy_inthash_u32((tommy_uint32_t)reinterpret_cast<size_t>(ptr));
tommy_hash_t hash = tommy_inthash_u32((tommy_uint32_t) reinterpret_cast<size_t>(ptr));
mutex_.lock();
mutex_.lock();
AllocHashNode* node = (AllocHashNode*)tommy_hashdyn_search((tommy_hashdyn*)allocations_, HashNodeCompare, ptr, hash);
if (node) {
int oldsize = (int)node->bytes;
node->bytes = (unsigned int)sz;
node->filename = file;
node->function = func;
node->line = (unsigned int)ln;
total_memory_allocated_ += ((int)sz - oldsize);
} else {
CCASSERT(0, "Reallocation address not found.");
}
AllocHashNode *node = (AllocHashNode *)tommy_hashdyn_search((tommy_hashdyn *)allocations_, HashNodeCompare, ptr, hash);
if (node) {
int oldsize = (int)node->bytes;
node->bytes = (unsigned int)sz;
node->filename = file;
node->function = func;
node->line = (unsigned int)ln;
total_memory_allocated_ += ((int)sz - oldsize);
} else {
CCASSERT(0, "Reallocation address not found.");
}
mutex_.unlock();
mutex_.unlock();
}
void MemTracker::RecordFree(void* ptr)
{
// deal cleanly with null pointers
if (!ptr)
return;
void MemTracker::RecordFree(void *ptr) {
// deal cleanly with null pointers
if (!ptr)
return;
tommy_hash_t hash = tommy_inthash_u32((tommy_uint32_t)reinterpret_cast<size_t>(ptr));
tommy_hash_t hash = tommy_inthash_u32((tommy_uint32_t) reinterpret_cast<size_t>(ptr));
mutex_.lock();
mutex_.lock();
AllocHashNode* node = (AllocHashNode*)tommy_hashdyn_remove((tommy_hashdyn*)allocations_, HashNodeCompare, ptr, hash);
if (node)
{
total_memory_allocated_ -= node->bytes;
FreeHashNode(node);
}
else
{
CCASSERT(0, "Unable to locate allocation unit - this probably means you have a mismatched allocation / deallocation style.");
}
AllocHashNode *node = (AllocHashNode *)tommy_hashdyn_remove((tommy_hashdyn *)allocations_, HashNodeCompare, ptr, hash);
if (node) {
total_memory_allocated_ -= node->bytes;
FreeHashNode(node);
} else {
CCASSERT(0, "Unable to locate allocation unit - this probably means you have a mismatched allocation / deallocation style.");
}
mutex_.unlock();
mutex_.unlock();
}
int MemTracker::GetAllocSize(void* ptr) {
int sz = -1;
tommy_hash_t hash = tommy_inthash_u32((tommy_uint32_t)reinterpret_cast<size_t>(ptr));
int MemTracker::GetAllocSize(void *ptr) {
int sz = -1;
tommy_hash_t hash = tommy_inthash_u32((tommy_uint32_t) reinterpret_cast<size_t>(ptr));
mutex_.lock();
AllocHashNode* node = (AllocHashNode*)tommy_hashdyn_search((tommy_hashdyn*)allocations_, HashNodeCompare, ptr, hash);
if (node) {
sz = (int)node->bytes;
}
mutex_.unlock();
return sz;
mutex_.lock();
AllocHashNode *node = (AllocHashNode *)tommy_hashdyn_search((tommy_hashdyn *)allocations_, HashNodeCompare, ptr, hash);
if (node) {
sz = (int)node->bytes;
}
mutex_.unlock();
return sz;
}
void MemTracker::ReportLeaks() {
char* buffer;
char *buffer;
unsigned int count = (unsigned int)tommy_hashdyn_count((tommy_hashdyn*)allocations_);
if (count == 0) {
buffer = (char*)malloc(256);
strcpy(buffer, "MemoryTracker: No memory leaks.\n");
} else {
int len = 768 * 1024;
buffer = (char*)malloc(len);
char* last = buffer + len - 3;
char* buf = buffer;
buf += sprintf(buffer, "MemoryTracker: Detected memory leaks !!!\n"
"MemoryTracker: (%u) Allocation(s) with total %u bytes.\n"
"MemoryTracker: Dumping allocations ->\n", count, (unsigned int)total_memory_allocated_);
unsigned int count = (unsigned int)tommy_hashdyn_count((tommy_hashdyn *)allocations_);
if (count == 0) {
buffer = (char *)malloc(256);
strcpy(buffer, "MemoryTracker: No memory leaks.\n");
} else {
int len = 768 * 1024;
buffer = (char *)malloc(len);
char *last = buffer + len - 3;
char *buf = buffer;
buf += sprintf(buffer, "MemoryTracker: Detected memory leaks !!!\n"
"MemoryTracker: (%u) Allocation(s) with total %u bytes.\n"
"MemoryTracker: Dumping allocations ->\n",
count, (unsigned int)total_memory_allocated_);
AllocListParam param;
param.buf = buf;
param.last = last;
tommy_hashdyn_foreach_arg((tommy_hashdyn*)allocations_, HashNodeListAndFree, &param);
}
AllocListParam param;
param.buf = buf;
param.last = last;
tommy_hashdyn_foreach_arg((tommy_hashdyn *)allocations_, HashNodeListAndFree, &param);
}
FILE* f = fopen(LEAK_FILENAME, "w");
if (f) {
fputs(buffer, f);
fclose(f);
}
CC_OUTPUT_STR(buffer);
free(buffer);
FILE *f = fopen(LEAK_FILENAME, "w");
if (f) {
fputs(buffer, f);
fclose(f);
}
CC_OUTPUT_STR(buffer);
free(buffer);
}
struct AllocDumpNode {
std::string name;
unsigned int bytes;
std::string name;
unsigned int bytes;
};
bool operator < (const AllocDumpNode& a, const AllocDumpNode& b) {
return a.bytes < b.bytes;
bool operator<(const AllocDumpNode &a, const AllocDumpNode &b) {
return a.bytes < b.bytes;
}
void MemTracker::DumpMemoryAllocation() {
AllocDumpParam param;
tommy_hashdyn_foreach_arg((tommy_hashdyn*)allocations_, HashNodeListAndDump, &param);
std::priority_queue<AllocDumpNode> q;
for (std::map<std::string, unsigned int>::iterator ptr = param.allocMap.begin(); ptr != param.allocMap.end(); ++ptr) {
AllocDumpNode node;
node.name = ptr->first;
node.bytes = ptr->second;
q.push(std::move(node));
}
AllocDumpParam param;
tommy_hashdyn_foreach_arg((tommy_hashdyn *)allocations_, HashNodeListAndDump, &param);
std::priority_queue<AllocDumpNode> q;
for (std::map<std::string, unsigned int>::iterator ptr = param.allocMap.begin(); ptr != param.allocMap.end(); ++ptr) {
AllocDumpNode node;
node.name = ptr->first;
node.bytes = ptr->second;
q.push(std::move(node));
}
unsigned int total = 0;
char tmpbuf[1024];
sprintf(tmpbuf, "total memory: %u\n", (unsigned int)total_memory_allocated_);
std::string str = tmpbuf;
while (!q.empty()) {
const AllocDumpNode& n = q.top();
sprintf(tmpbuf, "%s:%u\n", n.name.c_str(), n.bytes);
str += tmpbuf;
total += n.bytes;
q.pop();
}
sprintf(tmpbuf, "calc total memory: %u\n", total);
str += tmpbuf;
unsigned int total = 0;
char tmpbuf[1024];
sprintf(tmpbuf, "total memory: %u\n", (unsigned int)total_memory_allocated_);
std::string str = tmpbuf;
while (!q.empty()) {
const AllocDumpNode &n = q.top();
sprintf(tmpbuf, "%s:%u\n", n.name.c_str(), n.bytes);
str += tmpbuf;
total += n.bytes;
q.pop();
}
sprintf(tmpbuf, "calc total memory: %u\n", total);
str += tmpbuf;
#if (CC_PLATFORM == CC_PLATFORM_WINDOWS)
FILE* f = fopen("MemDump.txt", "w");
if (f) {
fputs(str.c_str(), f);
fclose(f);
}
#elif (CC_PLATFORM == CC_PLATFORM_ANDROID)
__android_log_write(ANDROID_LOG_WARN, "Tao", str.c_str());
#else
fputs(str.c_str(), stdout);
#endif
#if (CC_PLATFORM == CC_PLATFORM_WINDOWS)
FILE *f = fopen("MemDump.txt", "w");
if (f) {
fputs(str.c_str(), f);
fclose(f);
}
#elif (CC_PLATFORM == CC_PLATFORM_ANDROID)
__android_log_write(ANDROID_LOG_WARN, "Tao", str.c_str());
#else
fputs(str.c_str(), stdout);
#endif
}
}
} // namespace gfx
} // namespace cc
#endif
+37 -34
View File
@@ -4,6 +4,7 @@
#ifdef CC_MEMORY_TRACKER
namespace cc {
namespace gfx {
/** This class tracks the allocations and deallocations made, and
is able to report memory statistics and leaks.
@@ -11,19 +12,20 @@ is able to report memory statistics and leaks.
This class is only available in debug builds.
*/
class CC_CORE_API MemTracker {
public:
~MemTracker();
private:
// protected ctor
MemTracker();
public:
// Get the total amount of memory allocated currently.
CC_INLINE size_t total_memory_allocated() const { return total_memory_allocated_; }
public:
~MemTracker();
void DumpMemoryAllocation();
private:
// protected ctor
MemTracker();
/** Record an allocation that has been made. Only to be called by
public:
// Get the total amount of memory allocated currently.
CC_INLINE size_t total_memory_allocated() const { return total_memory_allocated_; }
void DumpMemoryAllocation();
/** Record an allocation that has been made. Only to be called by
the memory management subsystem.
@param ptr The pointer to the memory
@param sz The size of the memory in bytes
@@ -31,33 +33,34 @@ class CC_CORE_API MemTracker {
@param file The file in which the allocation is being made
@param ln The line on which the allocation is being made
@param func The function in which the allocation is being made
*/
void RecordAlloc(void* ptr, size_t sz,
const char* file = nullptr, size_t ln = 0, const char* func = nullptr);
// Record the deallocation of memory.
void RecordFree(void* ptr);
void RecordReAlloc(void* oldptr, void* ptr, size_t sz,
const char *file = nullptr, size_t ln = 0, const char *func = nullptr);
*/
void RecordAlloc(void *ptr, size_t sz,
const char *file = nullptr, size_t ln = 0, const char *func = nullptr);
// Record the deallocation of memory.
void RecordFree(void *ptr);
void RecordReAlloc(void *oldptr, void *ptr, size_t sz,
const char *file = nullptr, size_t ln = 0, const char *func = nullptr);
int GetAllocSize(void *ptr);
int GetAllocSize(void *ptr);
// Static utility method to get the memory tracker instance
CC_INLINE static MemTracker* Instance() {
static MemTracker tracker;
return &tracker;
}
private:
void ReportLeaks();
private:
std::mutex mutex_;
size_t total_memory_allocated_;
//tommy_hashdyn m_allocations;
void* allocations_;
// Static utility method to get the memory tracker instance
CC_INLINE static MemTracker *Instance() {
static MemTracker tracker;
return &tracker;
}
private:
void ReportLeaks();
private:
std::mutex mutex_;
size_t total_memory_allocated_;
//tommy_hashdyn m_allocations;
void *allocations_;
};
}
} // namespace gfx
} // namespace cc
#endif
+4 -1
View File
@@ -3,11 +3,14 @@
#include "StlAlloc.h"
namespace cc {
namespace gfx {
CC_CORE_API SA<char, STLAP> stl_char_allocator;
}
#if 0
CC_CORE_API void* BareNewErroneouslyCalled(size_t sz) {
return malloc(sz);
}
#endif
} // namespace gfx
} // namespace cc
+167 -166
View File
@@ -4,200 +4,201 @@
#if (CC_MEMORY_ALLOCATOR == CC_MEMORY_ALLOCATOR_NEDPOOLING)
// include Ned implementation
#if (CC_COMPILER == CC_COMPILER_MSVC)
# pragma warning(disable: 4005 4189 4267 4565 4702 4706)
#endif
// include Ned implementation
#if (CC_COMPILER == CC_COMPILER_MSVC)
#pragma warning(disable : 4005 4189 4267 4565 4702 4706)
#endif
#define USE_LOCKS 1
#define INSECURE 1
#include <nedmalloc.c>
#define USE_LOCKS 1
#define INSECURE 1
#include <nedmalloc.c>
namespace cc {
namespace gfx {
namespace nedPoolingIntern {
const size_t ned_poolCount = 14; // Needs to be greater than 4
#if (CC_CPU_ARCH == CC_CPU_ARCH_32)
void* ned_poolFootprint = reinterpret_cast<void*>(0xBB1AA45A);
#else
void* ned_poolFootprint = reinterpret_cast<void*>((ui64)0xBB1AA45A);
#endif
nedalloc::nedpool *ned_pools[ned_poolCount + 1] = { 0 };
nedalloc::nedpool *ned_poolsAligned[ned_poolCount + 1] = { 0 };
#if (CC_CPU_ARCH == CC_CPU_ARCH_32)
void *ned_poolFootprint = reinterpret_cast<void *>(0xBB1AA45A);
#else
void *ned_poolFootprint = reinterpret_cast<void *>((ui64)0xBB1AA45A);
#endif
nedalloc::nedpool *ned_pools[ned_poolCount + 1] = {0};
nedalloc::nedpool *ned_poolsAligned[ned_poolCount + 1] = {0};
size_t PoolIDFromSize(size_t a_reqSize) {
// Requests size 16 or smaller are allocated at a 4 byte granularity.
// Requests size 17 or larger are allocated at a 16 byte granularity.
// With a ned_poolCount of 14, requests size 177 or larger go in the default pool.
// spreadsheet style =IF(B35<=16; FLOOR((B35-1)/4;1); MIN(FLOOR((B35-1)/16; 1) + 3; 14))
size_t poolID = 0;
if (a_reqSize > 0) {
if (a_reqSize <= 16) {
poolID = (a_reqSize - 1) >> 2;
} else {
poolID = std::min<size_t>(((a_reqSize - 1) >> 4) + 3, ned_poolCount);
// Requests size 16 or smaller are allocated at a 4 byte granularity.
// Requests size 17 or larger are allocated at a 16 byte granularity.
// With a ned_poolCount of 14, requests size 177 or larger go in the default pool.
// spreadsheet style =IF(B35<=16; FLOOR((B35-1)/4;1); MIN(FLOOR((B35-1)/16; 1) + 3; 14))
size_t poolID = 0;
if (a_reqSize > 0) {
if (a_reqSize <= 16) {
poolID = (a_reqSize - 1) >> 2;
} else {
poolID = std::min<size_t>(((a_reqSize - 1) >> 4) + 3, ned_poolCount);
}
}
}
return poolID;
}
CC_DECL_MALLOC void* InternalAlloc(size_t a_reqSize) {
size_t poolID = PoolIDFromSize(a_reqSize);
nedalloc::nedpool* pool(0); // A pool pointer of 0 means the default pool.
if (poolID < ned_poolCount) {
if (ned_pools[poolID] == 0) {
// Init pool if first use
ned_pools[poolID] = nedalloc::nedcreatepool(0, 8);
nedalloc::nedpsetvalue(ned_pools[poolID], ned_poolFootprint); // All pools are stamped with a footprint
}
pool = ned_pools[poolID];
}
return nedalloc::nedpmalloc(pool, a_reqSize);
return poolID;
}
CC_DECL_MALLOC void* InternalRealloc(void* ptr, size_t a_reqSize) {
size_t poolID = PoolIDFromSize(a_reqSize);
nedalloc::nedpool* pool(0); // A pool pointer of 0 means the default pool.
CC_DECL_MALLOC void *InternalAlloc(size_t a_reqSize) {
size_t poolID = PoolIDFromSize(a_reqSize);
nedalloc::nedpool *pool(0); // A pool pointer of 0 means the default pool.
if (poolID < ned_poolCount) {
if (ned_pools[poolID] == 0) {
// Init pool if first use
if (poolID < ned_poolCount) {
if (ned_pools[poolID] == 0) {
// Init pool if first use
ned_pools[poolID] = nedalloc::nedcreatepool(0, 8);
nedalloc::nedpsetvalue(ned_pools[poolID], ned_poolFootprint); // All pools are stamped with a footprint
}
ned_pools[poolID] = nedalloc::nedcreatepool(0, 8);
nedalloc::nedpsetvalue(ned_pools[poolID], ned_poolFootprint); // All pools are stamped with a footprint
}
pool = ned_pools[poolID];
}
return nedalloc::nedprealloc(pool, ptr, a_reqSize);
}
CC_DECL_MALLOC void* InternalAllocAligned(size_t a_align, size_t a_reqSize) {
size_t poolID = PoolIDFromSize(a_reqSize);
nedalloc::nedpool* pool(0); // A pool pointer of 0 means the default pool.
if (poolID < ned_poolCount) {
if (ned_poolsAligned[poolID] == 0) {
// Init pool if first use
ned_poolsAligned[poolID] = nedalloc::nedcreatepool(0, 8);
nedalloc::nedpsetvalue(ned_poolsAligned[poolID], ned_poolFootprint); // All pools are stamped with a footprint
pool = ned_pools[poolID];
}
pool = ned_poolsAligned[poolID];
}
return nedalloc::nedpmemalign(pool, a_align, a_reqSize);
return nedalloc::nedpmalloc(pool, a_reqSize);
}
void InternalFree(void* a_mem) {
if (a_mem) {
nedalloc::nedpool* pool(0);
// nedalloc lets us get the pool pointer from the memory pointer
void* footprint = nedalloc::nedgetvalue(&pool, a_mem);
// Check footprint
if (footprint == ned_poolFootprint) {
// If we allocated the pool, deallocate from this pool...
nedalloc::nedpfree(pool, a_mem);
} else {
// ...otherwise let nedalloc handle it.
nedalloc::nedfree(a_mem);
CC_DECL_MALLOC void *InternalRealloc(void *ptr, size_t a_reqSize) {
size_t poolID = PoolIDFromSize(a_reqSize);
nedalloc::nedpool *pool(0); // A pool pointer of 0 means the default pool.
if (poolID < ned_poolCount) {
if (ned_pools[poolID] == 0) {
// Init pool if first use
ned_pools[poolID] = nedalloc::nedcreatepool(0, 8);
nedalloc::nedpsetvalue(ned_pools[poolID], ned_poolFootprint); // All pools are stamped with a footprint
}
pool = ned_pools[poolID];
}
}
return nedalloc::nedprealloc(pool, ptr, a_reqSize);
}
} // end - namespace:nedPoolingIntern
CC_DECL_MALLOC void *InternalAllocAligned(size_t a_align, size_t a_reqSize) {
size_t poolID = PoolIDFromSize(a_reqSize);
nedalloc::nedpool *pool(0); // A pool pointer of 0 means the default pool.
if (poolID < ned_poolCount) {
if (ned_poolsAligned[poolID] == 0) {
// Init pool if first use
ned_poolsAligned[poolID] = nedalloc::nedcreatepool(0, 8);
nedalloc::nedpsetvalue(ned_poolsAligned[poolID], ned_poolFootprint); // All pools are stamped with a footprint
}
pool = ned_poolsAligned[poolID];
}
return nedalloc::nedpmemalign(pool, a_align, a_reqSize);
}
void InternalFree(void *a_mem) {
if (a_mem) {
nedalloc::nedpool *pool(0);
// nedalloc lets us get the pool pointer from the memory pointer
void *footprint = nedalloc::nedgetvalue(&pool, a_mem);
// Check footprint
if (footprint == ned_poolFootprint) {
// If we allocated the pool, deallocate from this pool...
nedalloc::nedpfree(pool, a_mem);
} else {
// ...otherwise let nedalloc handle it.
nedalloc::nedfree(a_mem);
}
}
}
} // namespace nedPoolingIntern
//////////////////////////////////////////////////////////////////////////
CC_DECL_MALLOC void* NedPoolingImpl::AllocBytes(size_t count, const char* file, int line, const char* func)
{
void* ptr = nedPoolingIntern::InternalAlloc(count);
#ifdef CC_MEMORY_TRACKER
MemTracker::Instance()->RecordAlloc(ptr, count, file, line, func);
#else
// avoid unused params warning
(void)file;
(void)line;
(void)func;
#endif
return ptr;
CC_DECL_MALLOC void *NedPoolingImpl::AllocBytes(size_t count, const char *file, int line, const char *func) {
void *ptr = nedPoolingIntern::InternalAlloc(count);
#ifdef CC_MEMORY_TRACKER
MemTracker::Instance()->RecordAlloc(ptr, count, file, line, func);
#else
// avoid unused params warning
(void)file;
(void)line;
(void)func;
#endif
return ptr;
}
CC_DECL_MALLOC void* NedPoolingImpl::ReallocBytes(void* ptr, size_t count, const char* file, int line, const char* func) {
#ifdef CC_MEMORY_TRACKER
if (ptr) {
if (count == 0) {
MemTracker::Instance()->RecordFree(ptr);
nedPoolingIntern::InternalFree(ptr);
return nullptr;
} else {
int oldsz = MemTracker::Instance()->GetAllocSize(ptr);
if (oldsz < 0) {
CCASSERT(false, "ned realloc: get old size of ptr fail!");
return realloc(ptr, count);
} else {
if (oldsz >(int)count) oldsz = (int)count;
}
CC_DECL_MALLOC void *NedPoolingImpl::ReallocBytes(void *ptr, size_t count, const char *file, int line, const char *func) {
#ifdef CC_MEMORY_TRACKER
if (ptr) {
if (count == 0) {
MemTracker::Instance()->RecordFree(ptr);
nedPoolingIntern::InternalFree(ptr);
return nullptr;
} else {
int oldsz = MemTracker::Instance()->GetAllocSize(ptr);
if (oldsz < 0) {
CCASSERT(false, "ned realloc: get old size of ptr fail!");
return realloc(ptr, count);
} else {
if (oldsz > (int)count) oldsz = (int)count;
}
void* nptr = nedPoolingIntern::InternalAlloc(count);
memcpy(nptr, ptr, oldsz);
MemTracker::Instance()->RecordAlloc(nptr, count, file, line, func);
MemTracker::Instance()->RecordFree(ptr);
nedPoolingIntern::InternalFree(ptr);
return nptr;
}
} else {
if (count) {
ptr = nedPoolingIntern::InternalAlloc(count);
MemTracker::Instance()->RecordAlloc(ptr, count, file, line, func);
return ptr;
} else {
return nullptr;
}
}
#else
return nedPoolingIntern::InternalRealloc(ptr, count);
#endif
void *nptr = nedPoolingIntern::InternalAlloc(count);
memcpy(nptr, ptr, oldsz);
MemTracker::Instance()->RecordAlloc(nptr, count, file, line, func);
MemTracker::Instance()->RecordFree(ptr);
nedPoolingIntern::InternalFree(ptr);
return nptr;
}
} else {
if (count) {
ptr = nedPoolingIntern::InternalAlloc(count);
MemTracker::Instance()->RecordAlloc(ptr, count, file, line, func);
return ptr;
} else {
return nullptr;
}
}
#else
return nedPoolingIntern::InternalRealloc(ptr, count);
#endif
}
CC_DECL_MALLOC void* NedPoolingImpl::AllocBytesAligned(size_t align, size_t count, const char* file, int line, const char* func) {
// default to platform SIMD alignment if none specified
void* ptr = nedPoolingIntern::InternalAllocAligned(align, count);
#ifdef CC_MEMORY_TRACKER
MemTracker::Instance()->RecordAlloc(ptr, count, file, line, func);
#else
// avoid unused params warning
(void)file;
(void)line;
(void)func;
#endif
return ptr;
CC_DECL_MALLOC void *NedPoolingImpl::AllocBytesAligned(size_t align, size_t count, const char *file, int line, const char *func) {
// default to platform SIMD alignment if none specified
void *ptr = nedPoolingIntern::InternalAllocAligned(align, count);
#ifdef CC_MEMORY_TRACKER
MemTracker::Instance()->RecordAlloc(ptr, count, file, line, func);
#else
// avoid unused params warning
(void)file;
(void)line;
(void)func;
#endif
return ptr;
}
void NedPoolingImpl::DeallocBytes(void* ptr) {
// deal with null
if (!ptr) {
return;
}
#ifdef CC_MEMORY_TRACKER
MemTracker::Instance()->RecordFree(ptr);
#endif
nedPoolingIntern::InternalFree(ptr);
void NedPoolingImpl::DeallocBytes(void *ptr) {
// deal with null
if (!ptr) {
return;
}
#ifdef CC_MEMORY_TRACKER
MemTracker::Instance()->RecordFree(ptr);
#endif
nedPoolingIntern::InternalFree(ptr);
}
}
} // namespace gfx
} // namespace cc
#endif // end - #ifdef CC_MEMORY_ALLOCATOR_NEDPOOLING
+31 -30
View File
@@ -4,15 +4,15 @@
#if (CC_MEMORY_ALLOCATOR == CC_MEMORY_ALLOCATOR_NEDPOOLING)
namespace cc {
namespace gfx {
//Non-templated utility class just to hide nedmalloc.
class CC_CORE_API NedPoolingImpl
{
class CC_CORE_API NedPoolingImpl {
public:
static CC_DECL_MALLOC void* AllocBytes(size_t count, const char* file, int line, const char* func);
static CC_DECL_MALLOC void* ReallocBytes(void* ptr, size_t count, const char* file, int line, const char* func);
static CC_DECL_MALLOC void* AllocBytesAligned(size_t align, size_t count, const char* file, int line, const char* func);
static void DeallocBytes(void* ptr);
static CC_DECL_MALLOC void *AllocBytes(size_t count, const char *file, int line, const char *func);
static CC_DECL_MALLOC void *ReallocBytes(void *ptr, size_t count, const char *file, int line, const char *func);
static CC_DECL_MALLOC void *AllocBytesAligned(size_t align, size_t count, const char *file, int line, const char *func);
static void DeallocBytes(void *ptr);
};
/** An allocation policy for use with AllocatedObject and
@@ -23,34 +23,35 @@ public:
This allocation policy uses nedmalloc (http://nedprod.com/programs/portable/nedmalloc/index.html).
*/
class CC_CORE_API NedPoolingAllocPolicy {
public:
static CC_INLINE CC_DECL_MALLOC void* AllocateBytes(size_t count, const char* file = nullptr, int line = 0, const char* func = nullptr) {
return NedPoolingImpl::AllocBytes(count, file, line, func);
}
static CC_INLINE CC_DECL_MALLOC void* ReallocateBytes(void* ptr, size_t count, const char* file = nullptr, int line = 0, const char* func = nullptr) {
return NedPoolingImpl::ReallocBytes(ptr, count, file, line, func);
}
static CC_INLINE void DeallocateBytes(void* ptr) {
NedPoolingImpl::DeallocBytes(ptr);
}
static CC_INLINE CC_DECL_MALLOC void* AllocateBytesAligned(size_t alignment, size_t count, const char *file = nullptr, int line = 0, const char *func = nullptr) {
return NedPoolingImpl::AllocBytesAligned(alignment, count, file, line, func);
}
static CC_INLINE void DeallocateBytesAligned(void *ptr) {
NedPoolingImpl::DeallocBytes(ptr);
}
public:
static CC_INLINE CC_DECL_MALLOC void *AllocateBytes(size_t count, const char *file = nullptr, int line = 0, const char *func = nullptr) {
return NedPoolingImpl::AllocBytes(count, file, line, func);
}
static CC_INLINE CC_DECL_MALLOC void *ReallocateBytes(void *ptr, size_t count, const char *file = nullptr, int line = 0, const char *func = nullptr) {
return NedPoolingImpl::ReallocBytes(ptr, count, file, line, func);
}
static CC_INLINE void DeallocateBytes(void *ptr) {
NedPoolingImpl::DeallocBytes(ptr);
}
static CC_INLINE CC_DECL_MALLOC void *AllocateBytesAligned(size_t alignment, size_t count, const char *file = nullptr, int line = 0, const char *func = nullptr) {
return NedPoolingImpl::AllocBytesAligned(alignment, count, file, line, func);
}
static CC_INLINE void DeallocateBytesAligned(void *ptr) {
NedPoolingImpl::DeallocBytes(ptr);
}
// Get the maximum size of a single allocation
static CC_INLINE size_t getMaxAllocationSize() {
return (std::numeric_limits<size_t>::max)();
}
// Get the maximum size of a single allocation
static CC_INLINE size_t getMaxAllocationSize() {
return (std::numeric_limits<size_t>::max)();
}
private:
// No instantiation
NedPoolingAllocPolicy() {}
// No instantiation
NedPoolingAllocPolicy() {}
};
}
} // namespace gfx
} // namespace cc
#endif // end - #ifdef CC_MEMORY_ALLOCATOR_NEDPOOLING
+113 -113
View File
@@ -4,6 +4,7 @@
#if (CC_MEMORY_ALLOCATOR == CC_MEMORY_ALLOCATOR_STD)
namespace cc {
namespace gfx {
/** A "standard" allocation policy for use with AllocatedObject and
STLAllocator. This is the class that actually does the allocation
@@ -13,129 +14,128 @@ namespace cc {
This class just delegates to the global malloc/free.
*/
class CC_CORE_API StdAllocPolicy {
public:
static CC_INLINE CC_DECL_MALLOC void* AllocateBytes(size_t count,
#ifdef CC_MEMORY_TRACKER
const char* file = nullptr, int line = 0, const char* func = nullptr
#else
const char* = nullptr, int = 0, const char* = nullptr
#endif
) {
void* ptr = malloc(count);
#ifdef CC_MEMORY_TRACKER
MemTracker::Instance()->RecordAlloc(ptr, count, file, line, func);
#endif
return ptr;
}
public:
static CC_INLINE CC_DECL_MALLOC void *AllocateBytes(size_t count,
#ifdef CC_MEMORY_TRACKER
const char *file = nullptr, int line = 0, const char *func = nullptr
#else
const char * = nullptr, int = 0, const char * = nullptr
#endif
) {
void *ptr = malloc(count);
#ifdef CC_MEMORY_TRACKER
MemTracker::Instance()->RecordAlloc(ptr, count, file, line, func);
#endif
return ptr;
}
static CC_INLINE CC_DECL_MALLOC void* ReallocateBytes(void* ptr, size_t count,
#ifdef CC_MEMORY_TRACKER
const char* file = nullptr, int line = 0, const char* func = nullptr
#else
const char* = nullptr, int = 0, const char* = nullptr
#endif
) {
#ifdef CC_MEMORY_TRACKER
if (ptr) {
if (count == 0) {
MemTracker::Instance()->RecordFree(ptr);
free(ptr);
return NULL;
} else {
int oldsz = MemTracker::Instance()->GetAllocSize(ptr);
if (oldsz < 0) {
printf("realloc: get old size of ptr fail!\n");
assert(0);
return realloc(ptr, count);
} else {
if (oldsz >(int)count) oldsz = (int)count;
}
static CC_INLINE CC_DECL_MALLOC void *ReallocateBytes(void *ptr, size_t count,
#ifdef CC_MEMORY_TRACKER
const char *file = nullptr, int line = 0, const char *func = nullptr
#else
const char * = nullptr, int = 0, const char * = nullptr
#endif
) {
#ifdef CC_MEMORY_TRACKER
if (ptr) {
if (count == 0) {
MemTracker::Instance()->RecordFree(ptr);
free(ptr);
return NULL;
} else {
int oldsz = MemTracker::Instance()->GetAllocSize(ptr);
if (oldsz < 0) {
printf("realloc: get old size of ptr fail!\n");
assert(0);
return realloc(ptr, count);
} else {
if (oldsz > (int)count) oldsz = (int)count;
}
void* nptr = malloc(count);
memcpy(nptr, ptr, oldsz);
MemTracker::Instance()->RecordAlloc(nptr, count, file, line, func);
MemTracker::Instance()->RecordFree(ptr);
free(ptr);
return nptr;
}
} else {
if (count) {
ptr = malloc(count);
MemTracker::Instance()->RecordAlloc(ptr, count, file, line, func);
return ptr;
} else {
return nullptr;
}
}
#else
return realloc(ptr, count);
#endif
}
void *nptr = malloc(count);
memcpy(nptr, ptr, oldsz);
MemTracker::Instance()->RecordAlloc(nptr, count, file, line, func);
MemTracker::Instance()->RecordFree(ptr);
free(ptr);
return nptr;
}
} else {
if (count) {
ptr = malloc(count);
MemTracker::Instance()->RecordAlloc(ptr, count, file, line, func);
return ptr;
} else {
return nullptr;
}
}
#else
return realloc(ptr, count);
#endif
}
static CC_INLINE void DeallocateBytes(void* ptr) {
#ifdef CC_MEMORY_TRACKER
MemTracker::Instance()->RecordFree(ptr);
#endif
free(ptr);
}
static CC_INLINE void DeallocateBytes(void *ptr) {
#ifdef CC_MEMORY_TRACKER
MemTracker::Instance()->RecordFree(ptr);
#endif
free(ptr);
}
static CC_INLINE CC_DECL_MALLOC void* AllocateBytesAligned(size_t alignment, size_t count,
#ifdef CC_MEMORY_TRACKER
const char* file = NULL, int line = 0, const char* func = NULL
#else
const char* = NULL, int = 0, const char* = NULL
#endif
) {
#ifdef _MSC_VER
void* ptr = _aligned_malloc(count, alignment);
#elif defined(__ANDROID__)
//void* ptr = memalign(alignment, count);
unsigned char* p = (unsigned char*)malloc(count + alignment);
size_t offset = alignment - (size_t(p) & (alignment - 1));
unsigned char* ptr = p + offset;
ptr[-1] = (unsigned char)offset;
#else
void* ptr = NULL;
posix_memalign(&ptr, alignment, count);
#endif
static CC_INLINE CC_DECL_MALLOC void *AllocateBytesAligned(size_t alignment, size_t count,
#ifdef CC_MEMORY_TRACKER
const char *file = NULL, int line = 0, const char *func = NULL
#else
const char * = NULL, int = 0, const char * = NULL
#endif
) {
#ifdef _MSC_VER
void *ptr = _aligned_malloc(count, alignment);
#elif defined(__ANDROID__)
//void* ptr = memalign(alignment, count);
unsigned char *p = (unsigned char *)malloc(count + alignment);
size_t offset = alignment - (size_t(p) & (alignment - 1));
unsigned char *ptr = p + offset;
ptr[-1] = (unsigned char)offset;
#else
void *ptr = NULL;
posix_memalign(&ptr, alignment, count);
#endif
#ifdef CC_MEMORY_TRACKER
MemTracker::Instance()->RecordAlloc(ptr, count, file, line, func);
#endif
return ptr;
}
#ifdef CC_MEMORY_TRACKER
MemTracker::Instance()->RecordAlloc(ptr, count, file, line, func);
#endif
return ptr;
}
static CC_INLINE void DeallocateBytesAligned(void *ptr)
{
#ifdef CC_MEMORY_TRACKER
MemTracker::Instance()->RecordFree(ptr);
#endif
static CC_INLINE void DeallocateBytesAligned(void *ptr) {
#ifdef CC_MEMORY_TRACKER
MemTracker::Instance()->RecordFree(ptr);
#endif
#ifdef _MSC_VER
_aligned_free(ptr);
#elif defined(__ANDROID__)
if (ptr)
{
unsigned char* mem = (unsigned char*)ptr;
mem = mem - mem[-1];
free(mem);
}
#else
free(ptr);
#endif
}
#ifdef _MSC_VER
_aligned_free(ptr);
#elif defined(__ANDROID__)
if (ptr) {
unsigned char *mem = (unsigned char *)ptr;
mem = mem - mem[-1];
free(mem);
}
#else
free(ptr);
#endif
}
// Get the maximum size of a single allocation
static CC_INLINE size_t getMaxAllocationSize() {
return (std::numeric_limits<size_t>::max)();
}
private:
// No instantiation
StdAllocPolicy() {}
// Get the maximum size of a single allocation
static CC_INLINE size_t getMaxAllocationSize() {
return (std::numeric_limits<size_t>::max)();
}
private:
// No instantiation
StdAllocPolicy() {}
};
}
} // namespace gfx
} // namespace cc
#endif
+197 -195
View File
@@ -6,133 +6,133 @@
#include <set>
namespace cc {
namespace gfx {
// Base STL allocator class.
template<typename T>
template <typename T>
struct STLAllocatorBase {
// base class for generic allocators
typedef T value_type;
// base class for generic allocators
typedef T value_type;
};
// Base STL allocator class. (const T version).
template<typename T>
template <typename T>
struct STLAllocatorBase<const T> {
// base class for generic allocators for const T
typedef T value_type;
// base class for generic allocators for const T
typedef T value_type;
};
template<typename T, typename AllocPolicy>
template <typename T, typename AllocPolicy>
class SA : public STLAllocatorBase<T> {
public:
/// define our types, as per ISO C++
typedef STLAllocatorBase<T> Base;
typedef typename Base::value_type value_type;
typedef value_type* pointer;
typedef const value_type* const_pointer;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
public:
/// define our types, as per ISO C++
typedef STLAllocatorBase<T> Base;
typedef typename Base::value_type value_type;
typedef value_type *pointer;
typedef const value_type *const_pointer;
typedef value_type &reference;
typedef const value_type &const_reference;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
/// the standard rebind mechanism
template <typename U>
struct rebind {
typedef SA<U, AllocPolicy> other;
};
/// the standard rebind mechanism
template <typename U>
struct rebind {
typedef SA<U, AllocPolicy> other;
};
/// ctor
inline explicit SA() {}
/// ctor
inline explicit SA() {}
/// dtor
virtual ~SA() {}
/// dtor
virtual ~SA() {}
/// copy ctor - done component wise
inline SA(SA const &) {}
/// copy ctor - done component wise
inline SA(SA const&) {}
/// cast
template <typename U>
inline SA(SA<U, AllocPolicy> const &) {}
/// cast
template <typename U>
inline SA(SA<U, AllocPolicy> const&) {}
/// cast
template <typename U, typename P>
inline SA(SA<U, P> const &) {}
/// cast
template <typename U, typename P>
inline SA(SA<U, P> const&) {}
inline pointer allocate(size_type count, typename std::allocator<void>::const_pointer ptr = 0) {
(void)ptr;
inline pointer allocate(size_type count, typename std::allocator<void>::const_pointer ptr = 0) {
(void)ptr;
// convert request to bytes
register size_type sz = count * sizeof(T);
return static_cast<pointer>(AllocPolicy::AllocateBytes(sz));
}
// convert request to bytes
register size_type sz = count * sizeof(T);
return static_cast<pointer>(AllocPolicy::AllocateBytes(sz));
}
inline void deallocate(pointer ptr, size_type) {
AllocPolicy::DeallocateBytes(ptr);
}
inline void deallocate(pointer ptr, size_type) {
AllocPolicy::DeallocateBytes(ptr);
}
pointer address(reference x) const {
return &x;
}
pointer address(reference x) const {
return &x;
}
const_pointer address(const_reference x) const {
return &x;
}
const_pointer address(const_reference x) const {
return &x;
}
size_type max_size() const throw() {
return size_t(-1) / sizeof(T);
}
size_type max_size() const throw() {
return size_t(-1) / sizeof(T);
}
#if __cplusplus >= 201103L
template<typename Up, typename... Args>
void construct(Up* p, Args&&... args) {
::new((void *)p) Up(std::forward<Args>(args)...);
}
template <typename Up, typename... Args>
void construct(Up *p, Args &&... args) {
::new ((void *)p) Up(std::forward<Args>(args)...);
}
template<typename Up>
void destroy(Up* p) {
p->~Up();
}
template <typename Up>
void destroy(Up *p) {
p->~Up();
}
#else
void construct(pointer p, const T& val) {
// call placement new
::new((void *)p) T(val);
}
void construct(pointer p, const T &val) {
// call placement new
::new ((void *)p) T(val);
}
void destroy(pointer p) {
// do we have to protect against non-classes here?
// some articles suggest yes, some no
p->~T();
}
void destroy(pointer p) {
// do we have to protect against non-classes here?
// some articles suggest yes, some no
p->~T();
}
#endif
};
/// determine equality, can memory from another allocator
/// be released by this allocator, (ISO C++)
template<typename T, typename T2, typename P>
inline bool operator ==(SA<T,P> const&, SA<T2,P> const&) {
// same alloc policy (P), memory can be freed
return true;
template <typename T, typename T2, typename P>
inline bool operator==(SA<T, P> const &, SA<T2, P> const &) {
// same alloc policy (P), memory can be freed
return true;
}
/// determine equality, can memory from another allocator
/// be released by this allocator, (ISO C++)
template<typename T, typename P, typename OtherAllocator>
inline bool operator ==(SA<T,P> const&, OtherAllocator const&) {
return false;
template <typename T, typename P, typename OtherAllocator>
inline bool operator==(SA<T, P> const &, OtherAllocator const &) {
return false;
}
/// determine equality, can memory from another allocator
/// be released by this allocator, (ISO C++)
template<typename T, typename T2, typename P>
inline bool operator!=(SA<T,P> const&, SA<T2,P> const&) {
// same alloc policy (P), memory can be freed
return false;
template <typename T, typename T2, typename P>
inline bool operator!=(SA<T, P> const &, SA<T2, P> const &) {
// same alloc policy (P), memory can be freed
return false;
}
/// determine equality, can memory from another allocator
/// be released by this allocator, (ISO C++)
template<typename T, typename P, typename OtherAllocator>
inline bool operator!=(SA<T,P> const&, OtherAllocator const&) {
return true;
template <typename T, typename P, typename OtherAllocator>
inline bool operator!=(SA<T, P> const &, OtherAllocator const &) {
return true;
}
////////////////////////////////////////////////////////////////////
@@ -142,191 +142,192 @@ extern CC_CORE_API SA<char, STLAP> stl_char_allocator;
template <typename T, typename A = SA<T, STLAP>>
struct vector {
#if (CC_STL_MEMORY_ALLOCATOR == CC_STL_MEMORY_ALLOCATOR_CUSTOM)
typedef typename std::vector<T, A> type;
typedef typename std::vector<T, A>::iterator iterator;
typedef typename std::vector<T, A>::const_iterator const_iterator;
typedef typename std::vector<T, A> type;
typedef typename std::vector<T, A>::iterator iterator;
typedef typename std::vector<T, A>::const_iterator const_iterator;
#else
typedef typename std::vector<T> type;
typedef typename std::vector<T>::iterator iterator;
typedef typename std::vector<T>::const_iterator const_iterator;
typedef typename std::vector<T> type;
typedef typename std::vector<T>::iterator iterator;
typedef typename std::vector<T>::const_iterator const_iterator;
#endif
};
template <typename T, typename A = SA<T, STLAP> >
template <typename T, typename A = SA<T, STLAP>>
struct list {
#if (CC_STL_MEMORY_ALLOCATOR == CC_STL_MEMORY_ALLOCATOR_CUSTOM)
typedef typename std::list<T, A> type;
typedef typename std::list<T, A>::iterator iterator;
typedef typename std::list<T, A>::const_iterator const_iterator;
typedef typename std::list<T, A> type;
typedef typename std::list<T, A>::iterator iterator;
typedef typename std::list<T, A>::const_iterator const_iterator;
#else
typedef typename std::list<T> type;
typedef typename std::list<T>::iterator iterator;
typedef typename std::list<T>::const_iterator const_iterator;
typedef typename std::list<T> type;
typedef typename std::list<T>::iterator iterator;
typedef typename std::list<T>::const_iterator const_iterator;
#endif
};
template <typename T, typename A = SA<T, STLAP> >
template <typename T, typename A = SA<T, STLAP>>
struct queue {
#if (CC_STL_MEMORY_ALLOCATOR == CC_STL_MEMORY_ALLOCATOR_CUSTOM)
typedef typename std::queue<T, A> type;
typedef typename std::queue<T, A>::iterator iterator;
typedef typename std::queue<T, A>::const_iterator const_iterator;
typedef typename std::queue<T, A> type;
typedef typename std::queue<T, A>::iterator iterator;
typedef typename std::queue<T, A>::const_iterator const_iterator;
#else
typedef typename std::queue<T> type;
typedef typename std::queue<T>::iterator iterator;
typedef typename std::queue<T>::const_iterator const_iterator;
typedef typename std::queue<T> type;
typedef typename std::queue<T>::iterator iterator;
typedef typename std::queue<T>::const_iterator const_iterator;
#endif
};
template <typename T, typename C = typename vector<T>::type, typename P = std::less<typename C::value_type>>
struct priority_queue {
#if (CC_STL_MEMORY_ALLOCATOR == CC_STL_MEMORY_ALLOCATOR_CUSTOM)
typedef typename std::priority_queue<T, C, P> type;
typedef typename std::priority_queue<T, C, P> type;
#else
typedef typename std::priority_queue<T, C, P> type;
typedef typename std::priority_queue<T, C, P> type;
#endif
};
template <typename T, typename A = SA<T, STLAP> >
template <typename T, typename A = SA<T, STLAP>>
struct deque {
#if (CC_STL_MEMORY_ALLOCATOR == CC_STL_MEMORY_ALLOCATOR_CUSTOM)
typedef typename std::deque<T, A> type;
typedef typename std::deque<T, A>::iterator iterator;
typedef typename std::deque<T, A>::const_iterator const_iterator;
typedef typename std::deque<T, A> type;
typedef typename std::deque<T, A>::iterator iterator;
typedef typename std::deque<T, A>::const_iterator const_iterator;
#else
typedef typename std::deque<T> type;
typedef typename std::deque<T>::iterator iterator;
typedef typename std::deque<T>::const_iterator const_iterator;
typedef typename std::deque<T> type;
typedef typename std::deque<T>::iterator iterator;
typedef typename std::deque<T>::const_iterator const_iterator;
#endif
};
template <typename T, typename P = std::less<T>, typename A = SA<T, STLAP>>
struct set {
#if (CC_STL_MEMORY_ALLOCATOR == CC_STL_MEMORY_ALLOCATOR_CUSTOM)
typedef typename std::set<T, P, A> type;
typedef typename std::set<T, P, A>::iterator iterator;
typedef typename std::set<T, P, A>::const_iterator const_iterator;
typedef typename std::set<T, P, A> type;
typedef typename std::set<T, P, A>::iterator iterator;
typedef typename std::set<T, P, A>::const_iterator const_iterator;
#else
typedef typename std::set<T, P> type;
typedef typename std::set<T, P>::iterator iterator;
typedef typename std::set<T, P>::const_iterator const_iterator;
typedef typename std::set<T, P> type;
typedef typename std::set<T, P>::iterator iterator;
typedef typename std::set<T, P>::const_iterator const_iterator;
#endif
};
template <typename K, typename V, typename P = std::less<K>, typename A = SA<std::pair<const K, V>, STLAP> >
template <typename K, typename V, typename P = std::less<K>, typename A = SA<std::pair<const K, V>, STLAP>>
struct map {
#if (CC_STL_MEMORY_ALLOCATOR == CC_STL_MEMORY_ALLOCATOR_CUSTOM)
typedef typename std::map<K, V, P, A> type;
typedef typename std::map<K, V, P, A>::iterator iterator;
typedef typename std::map<K, V, P, A>::const_iterator const_iterator;
typedef typename std::map<K, V, P, A> type;
typedef typename std::map<K, V, P, A>::iterator iterator;
typedef typename std::map<K, V, P, A>::const_iterator const_iterator;
#else
typedef typename std::map<K, V, P> type;
typedef typename std::map<K, V, P>::iterator iterator;
typedef typename std::map<K, V, P>::const_iterator const_iterator;
typedef typename std::map<K, V, P> type;
typedef typename std::map<K, V, P>::iterator iterator;
typedef typename std::map<K, V, P>::const_iterator const_iterator;
#endif
};
template <typename K, typename V, typename P = std::less<K>, typename A = SA<std::pair<const K, V>, STLAP> >
template <typename K, typename V, typename P = std::less<K>, typename A = SA<std::pair<const K, V>, STLAP>>
struct multimap {
#if (CC_STL_MEMORY_ALLOCATOR == CC_STL_MEMORY_ALLOCATOR_CUSTOM)
typedef typename std::multimap<K, V, P, A> type;
typedef typename std::multimap<K, V, P, A>::iterator iterator;
typedef typename std::multimap<K, V, P, A>::const_iterator const_iterator;
typedef typename std::multimap<K, V, P, A> type;
typedef typename std::multimap<K, V, P, A>::iterator iterator;
typedef typename std::multimap<K, V, P, A>::const_iterator const_iterator;
#else
typedef typename std::multimap<K, V, P> type;
typedef typename std::multimap<K, V, P>::iterator iterator;
typedef typename std::multimap<K, V, P>::const_iterator const_iterator;
typedef typename std::multimap<K, V, P> type;
typedef typename std::multimap<K, V, P>::iterator iterator;
typedef typename std::multimap<K, V, P>::const_iterator const_iterator;
#endif
};
template <typename K, typename V, typename H = std::hash<K>, typename P = std::equal_to<K>, typename A = SA<std::pair<const K, V>, STLAP>>
struct unordered_map {
#if (CC_STL_MEMORY_ALLOCATOR == CC_STL_MEMORY_ALLOCATOR_CUSTOM)
typedef typename std::unordered_map<K, V, H, P, A> type;
typedef typename std::unordered_map<K, V, H, P, A>::iterator iterator;
typedef typename std::unordered_map<K, V, H, P, A>::const_iterator const_iterator;
typedef typename std::unordered_map<K, V, H, P, A> type;
typedef typename std::unordered_map<K, V, H, P, A>::iterator iterator;
typedef typename std::unordered_map<K, V, H, P, A>::const_iterator const_iterator;
#else
typedef typename std::unordered_map<K, V, H, P> type;
typedef typename std::unordered_map<K, V, H, P>::iterator iterator;
typedef typename std::unordered_map<K, V, H, P>::const_iterator const_iterator;
typedef typename std::unordered_map<K, V, H, P> type;
typedef typename std::unordered_map<K, V, H, P>::iterator iterator;
typedef typename std::unordered_map<K, V, H, P>::const_iterator const_iterator;
#endif
};
#define StdStringT(T) std::basic_string<T, std::char_traits<T>, std::allocator<T> >
#define CustomMemoryStringT(T) std::basic_string<T, std::char_traits<T>, SA<T, STLAP> >
#define StdStringT(T) std::basic_string<T, std::char_traits<T>, std::allocator<T>>
#define CustomMemoryStringT(T) std::basic_string<T, std::char_traits<T>, SA<T, STLAP>>
template<typename T>
bool operator <(const CustomMemoryStringT(T)& l, const StdStringT(T)& o) {
return l.compare(0,l.length(), o.c_str(), o.length()) < 0;
template <typename T>
bool operator<(const CustomMemoryStringT(T) & l, const StdStringT(T) & o) {
return l.compare(0, l.length(), o.c_str(), o.length()) < 0;
}
template<typename T>
bool operator <(const StdStringT(T)& l, const CustomMemoryStringT(T)& o) {
return l.compare(0,l.length(), o.c_str(), o.length()) < 0;
template <typename T>
bool operator<(const StdStringT(T) & l, const CustomMemoryStringT(T) & o) {
return l.compare(0, l.length(), o.c_str(), o.length()) < 0;
}
template<typename T>
bool operator <=(const CustomMemoryStringT(T)& l, const StdStringT(T)& o) {
return l.compare(0, l.length(), o.c_str(),o.length()) <= 0;
template <typename T>
bool operator<=(const CustomMemoryStringT(T) & l, const StdStringT(T) & o) {
return l.compare(0, l.length(), o.c_str(), o.length()) <= 0;
}
template<typename T>
bool operator <=(const StdStringT(T)& l, const CustomMemoryStringT(T)& o) {
return l.compare(0, l.length(), o.c_str(), o.length()) <= 0;
template <typename T>
bool operator<=(const StdStringT(T) & l, const CustomMemoryStringT(T) & o) {
return l.compare(0, l.length(), o.c_str(), o.length()) <= 0;
}
template<typename T>
bool operator >(const CustomMemoryStringT(T)& l, const StdStringT(T)& o) {
return l.compare(0, l.length(), o.c_str(), o.length()) > 0;
template <typename T>
bool operator>(const CustomMemoryStringT(T) & l, const StdStringT(T) & o) {
return l.compare(0, l.length(), o.c_str(), o.length()) > 0;
}
template<typename T>
bool operator >(const StdStringT(T)& l, const CustomMemoryStringT(T)& o) {
return l.compare(0, l.length(), o.c_str(), o.length()) > 0;
template <typename T>
bool operator>(const StdStringT(T) & l, const CustomMemoryStringT(T) & o) {
return l.compare(0, l.length(), o.c_str(), o.length()) > 0;
}
template<typename T>
bool operator >=(const CustomMemoryStringT(T)& l, const StdStringT(T)& o) {
return l.compare(0, l.length(), o.c_str(), o.length()) >= 0;
template <typename T>
bool operator>=(const CustomMemoryStringT(T) & l, const StdStringT(T) & o) {
return l.compare(0, l.length(), o.c_str(), o.length()) >= 0;
}
template<typename T>
bool operator >=(const StdStringT(T)& l, const CustomMemoryStringT(T)& o) {
return l.compare(0, l.length(), o.c_str(), o.length()) >= 0;
template <typename T>
bool operator>=(const StdStringT(T) & l, const CustomMemoryStringT(T) & o) {
return l.compare(0, l.length(), o.c_str(), o.length()) >= 0;
}
template<typename T>
bool operator ==(const CustomMemoryStringT(T)& l, const StdStringT(T)& o) {
return l.compare(0, l.length(), o.c_str(), o.length()) == 0;
template <typename T>
bool operator==(const CustomMemoryStringT(T) & l, const StdStringT(T) & o) {
return l.compare(0, l.length(), o.c_str(), o.length()) == 0;
}
template<typename T> bool operator ==(const StdStringT(T)& l, const CustomMemoryStringT(T)& o) {
return l.compare(0, l.length(), o.c_str(), o.length()) == 0;
template <typename T>
bool operator==(const StdStringT(T) & l, const CustomMemoryStringT(T) & o) {
return l.compare(0, l.length(), o.c_str(), o.length()) == 0;
}
template<typename T>
bool operator !=(const CustomMemoryStringT(T)& l, const StdStringT(T)& o) {
return l.compare(0, l.length(), o.c_str(), o.length())!=0;
template <typename T>
bool operator!=(const CustomMemoryStringT(T) & l, const StdStringT(T) & o) {
return l.compare(0, l.length(), o.c_str(), o.length()) != 0;
}
template<typename T>
bool operator !=(const StdStringT(T)& l, const CustomMemoryStringT(T)& o) {
return l.compare(0, l.length(), o.c_str(), o.length()) != 0;
template <typename T>
bool operator!=(const StdStringT(T) & l, const CustomMemoryStringT(T) & o) {
return l.compare(0, l.length(), o.c_str(), o.length()) != 0;
}
template<typename T>
CustomMemoryStringT(T) operator +=(const CustomMemoryStringT(T)& l, const StdStringT(T)& o) {
return CustomMemoryStringT(T)(l) += o.c_str();
template <typename T>
CustomMemoryStringT(T) operator+=(const CustomMemoryStringT(T) & l, const StdStringT(T) & o) {
return CustomMemoryStringT(T)(l) += o.c_str();
}
template<typename T>
CustomMemoryStringT(T) operator +=(const StdStringT(T)& l, const CustomMemoryStringT(T)& o) {
return CustomMemoryStringT(T)(l.c_str()) += o.c_str();
template <typename T>
CustomMemoryStringT(T) operator+=(const StdStringT(T) & l, const CustomMemoryStringT(T) & o) {
return CustomMemoryStringT(T)(l.c_str()) += o.c_str();
}
template<typename T>
CustomMemoryStringT(T) operator +(const CustomMemoryStringT(T)& l, const StdStringT(T)& o) {
return CustomMemoryStringT(T)(l) += o.c_str();
template <typename T>
CustomMemoryStringT(T) operator+(const CustomMemoryStringT(T) & l, const StdStringT(T) & o) {
return CustomMemoryStringT(T)(l) += o.c_str();
}
template<typename T>
CustomMemoryStringT(T) operator +(const StdStringT(T)& l, const CustomMemoryStringT(T)& o) {
return CustomMemoryStringT(T)(l.c_str()) += o.c_str();
template <typename T>
CustomMemoryStringT(T) operator+(const StdStringT(T) & l, const CustomMemoryStringT(T) & o) {
return CustomMemoryStringT(T)(l.c_str()) += o.c_str();
}
template<typename T>
CustomMemoryStringT(T) operator +(const T* l, const CustomMemoryStringT(T)& o) {
return CustomMemoryStringT(T)(l) += o;
template <typename T>
CustomMemoryStringT(T) operator+(const T *l, const CustomMemoryStringT(T) & o) {
return CustomMemoryStringT(T)(l) += o;
}
#undef StdStringT
@@ -334,14 +335,15 @@ CustomMemoryStringT(T) operator +(const T* l, const CustomMemoryStringT(T)& o) {
#if (CC_STL_MEMORY_ALLOCATOR == CC_STL_MEMORY_ALLOCATOR_CUSTOM)
typedef std::basic_string<char, std::char_traits<char>, SA<char, STLAP>> String;
typedef std::basic_string<wchar_t, std::char_traits<wchar_t>, SA<wchar_t, STLAP>> WString;
typedef std::basic_string<wchar_t, std::char_traits<wchar_t>, SA<wchar_t, STLAP>> WString;
#else
typedef std::string String;
typedef std::string String;
typedef std::wstring WString;
#endif
typedef vector<String>::type StringArray;
typedef vector<String>::type StringArray;
}
} // namespace gfx
} // namespace cc
#endif // CC_CORE_STL_ALLOC_H_
+73 -71
View File
@@ -2,95 +2,97 @@
#include "StringUtil.h"
#if (CC_PLATFORM == CC_PLATFORM_WINDOWS)
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# include <Windows.h>
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <Windows.h>
#endif
namespace cc {
namespace gfx {
#if defined(_WIN32)
int StringUtil::VPrintf(char* buf, char* last, const char* fmt, va_list args) {
if (last <= buf) return 0;
int count = (int)(last - buf);
int ret = _vsnprintf_s(buf, count, _TRUNCATE, fmt, args);
if (ret < 0) {
if (errno == 0) {
return count - 1;
int StringUtil::VPrintf(char *buf, char *last, const char *fmt, va_list args) {
if (last <= buf) return 0;
int count = (int)(last - buf);
int ret = _vsnprintf_s(buf, count, _TRUNCATE, fmt, args);
if (ret < 0) {
if (errno == 0) {
return count - 1;
} else {
return 0;
}
} else {
return 0;
return ret;
}
} else {
return ret;
}
}
#else
int StringUtil::VPrintf(char* buf, char* last, const char* fmt, va_list args) {
if (last <= buf) return 0;
int StringUtil::VPrintf(char *buf, char *last, const char *fmt, va_list args) {
if (last <= buf) return 0;
int count = (int)(last - buf);
int ret = vsnprintf(buf, count, fmt, args);
if (ret >= count - 1) {
return count - 1;
} else if (ret < 0) {
return 0;
}
return ret;
int count = (int)(last - buf);
int ret = vsnprintf(buf, count, fmt, args);
if (ret >= count - 1) {
return count - 1;
} else if (ret < 0) {
return 0;
}
return ret;
}
#endif
int StringUtil::Printf(char* buf, char* last, const char* fmt, ...) {
va_list args;
va_start(args, fmt);
int ret = VPrintf(buf, last, fmt, args);
va_end(args);
return ret;
int StringUtil::Printf(char *buf, char *last, const char *fmt, ...) {
va_list args;
va_start(args, fmt);
int ret = VPrintf(buf, last, fmt, args);
va_end(args);
return ret;
}
String StringUtil::Format(const char* fmt, ...) {
char sz[4096];
va_list args;
va_start(args, fmt);
VPrintf(sz, sz + sizeof(sz) - 1, fmt, args);
va_end(args);
return sz;
String StringUtil::Format(const char *fmt, ...) {
char sz[4096];
va_list args;
va_start(args, fmt);
VPrintf(sz, sz + sizeof(sz) - 1, fmt, args);
va_end(args);
return sz;
}
StringArray StringUtil::Split(const String &str, const String &delims, uint max_splits) {
StringArray strs;
if (str.empty())
StringArray strs;
if (str.empty())
return strs;
// Pre-allocate some space for performance
strs.reserve(max_splits ? max_splits + 1 : 16); // 16 is guessed capacity for most case
uint num_splits = 0;
// Use STL methods
size_t start, pos;
start = 0;
do {
pos = str.find_first_of(delims, start);
if (pos == start) {
// Do nothing
start = pos + 1;
} else if (pos == String::npos || (max_splits && num_splits == max_splits)) {
// Copy the rest of the string
strs.push_back(str.substr(start));
break;
} else {
// Copy up to delimiter
strs.push_back(str.substr(start, pos - start));
start = pos + 1;
}
// parse up to next real data
start = str.find_first_not_of(delims, start);
++num_splits;
} while (pos != String::npos);
return strs;
// Pre-allocate some space for performance
strs.reserve(max_splits ? max_splits + 1 : 16); // 16 is guessed capacity for most case
uint num_splits = 0;
// Use STL methods
size_t start, pos;
start = 0;
do {
pos = str.find_first_of(delims, start);
if (pos == start) {
// Do nothing
start = pos + 1;
} else if (pos == String::npos || (max_splits && num_splits == max_splits)) {
// Copy the rest of the string
strs.push_back(str.substr(start));
break;
} else {
// Copy up to delimiter
strs.push_back(str.substr(start, pos - start));
start = pos + 1;
}
// parse up to next real data
start = str.find_first_not_of(delims, start);
++num_splits;
} while (pos != String::npos);
return strs;
}
}
} // namespace gfx
} // namespace cc
+8 -6
View File
@@ -2,15 +2,17 @@
#define CC_CORE_KERNEL_UTIL_STRING_UTIL_H_
namespace cc {
namespace gfx {
class CC_CORE_API StringUtil {
public:
static int VPrintf(char* buf, char* last, const char* fmt, va_list args);
static int Printf(char* buf, char* last, const char* fmt, ...);
static String Format(const char* fmt, ...);
static StringArray Split(const String &str, const String &delims, uint max_splits = 0);
public:
static int VPrintf(char *buf, char *last, const char *fmt, va_list args);
static int Printf(char *buf, char *last, const char *fmt, ...);
static String Format(const char *fmt, ...);
static StringArray Split(const String &str, const String &delims, uint max_splits = 0);
};
}
} // namespace gfx
} // namespace cc
#endif // CC_CORE_KERNEL_UTIL_STRING_UTIL_H_
@@ -6,6 +6,7 @@
#include "GLES2Texture.h"
namespace cc {
namespace gfx {
GLES2BindingLayout::GLES2BindingLayout(GFXDevice *device)
: GFXBindingLayout(device) {
@@ -78,4 +79,5 @@ void GLES2BindingLayout::update() {
}
}
}
} // namespace gfx
} // namespace cc
@@ -2,6 +2,7 @@
#define CC_GFXGLES2_GLES2_BINDING_LAYOUT_H_
namespace cc {
namespace gfx {
class GLES2GPUBindingLayout;
@@ -21,6 +22,7 @@ private:
GLES2GPUBindingLayout *_gpuBindingLayout = nullptr;
};
}
} // namespace gfx
} // namespace cc
#endif
@@ -3,6 +3,7 @@
#include "GLES2Commands.h"
namespace cc {
namespace gfx {
GLES2Buffer::GLES2Buffer(GFXDevice *device)
: GFXBuffer(device) {
@@ -113,4 +114,5 @@ void GLES2Buffer::update(void *buffer, uint offset, uint size) {
GLES2CmdFuncUpdateBuffer((GLES2Device *)_device, _gpuBuffer, buffer, offset, size);
}
}
} // namespace gfx
} // namespace cc
@@ -2,6 +2,7 @@
#define CC_GFXGLES2_GLES2_BUFFER_H_
namespace cc {
namespace gfx {
class GLES2GPUBuffer;
@@ -22,6 +23,7 @@ private:
GLES2GPUBuffer *_gpuBuffer = nullptr;
};
}
} // namespace gfx
} // namespace cc
#endif
@@ -2,6 +2,7 @@
#include "GLES2CommandAllocator.h"
namespace cc {
namespace gfx {
GLES2CommandAllocator::GLES2CommandAllocator(GFXDevice *device)
: GFXCommandAllocator(device) {
@@ -39,4 +40,5 @@ void GLES2CommandAllocator::clearCmds(GLES2CmdPackage *cmd_package) {
cmd_package->cmds.clear();
}
}
} // namespace gfx
} // namespace cc
@@ -5,6 +5,7 @@
#include "GLES2Commands.h"
namespace cc {
namespace gfx {
class CC_GLES2_API GLES2CommandAllocator : public GFXCommandAllocator {
public:
@@ -32,6 +33,7 @@ public:
}
};
}
} // namespace gfx
} // namespace cc
#endif
@@ -9,6 +9,7 @@
#include "GLES2Texture.h"
namespace cc {
namespace gfx {
GLES2CommandBuffer::GLES2CommandBuffer(GFXDevice *device)
: GFXCommandBuffer(device) {
@@ -320,4 +321,5 @@ void GLES2CommandBuffer::BindStates() {
_isStateInvalid = false;
}
}
} // namespace gfx
} // namespace cc
@@ -4,6 +4,7 @@
#include "GLES2Commands.h"
namespace cc {
namespace gfx {
class GLES2CommandAllocator;
@@ -59,6 +60,7 @@ private:
bool _isStateInvalid = false;
};
}
} // namespace gfx
} // namespace cc
#endif
@@ -7,6 +7,7 @@
#define BUFFER_OFFSET(idx) (static_cast<char *>(0) + (idx))
namespace cc {
namespace gfx {
namespace {
GLenum MapGLInternalFormat(GFXFormat format) {
@@ -2250,4 +2251,5 @@ void GLES2CmdFuncCopyBuffersToTexture(GLES2Device *device, uint8_t *const *buffe
}
}
}
} // namespace gfx
} // namespace cc
@@ -4,6 +4,7 @@
#include "GLES2GPUObjects.h"
namespace cc {
namespace gfx {
class GLES2Device;
@@ -168,6 +169,7 @@ CC_GLES2_API void GLES2CmdFuncDestroyFramebuffer(GLES2Device *device, GLES2GPUFr
CC_GLES2_API void GLES2CmdFuncExecuteCmds(GLES2Device *device, GLES2CmdPackage *cmd_package);
CC_GLES2_API void GLES2CmdFuncCopyBuffersToTexture(GLES2Device *device, uint8_t *const *buffers, GLES2GPUTexture *gpuTexture, const GFXBufferTextureCopyList &regions);
}
} // namespace gfx
} // namespace cc
#endif
+136 -58
View File
@@ -12,52 +12,104 @@
// #define CC_GFX_DEBUG
namespace cc {
namespace gfx {
#if (CC_PLATFORM == CC_PLATFORM_WINDOWS)
void APIENTRY GLES2EGLDebugProc(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam) {
void APIENTRY
GLES2EGLDebugProc(GLenum
source,
GLenum type, GLuint id,
GLenum severity, GLsizei length,
const GLchar *message,
const void *userParam) {
String source_desc;
switch (source) {
case GL_DEBUG_SOURCE_API_KHR: source_desc = "API"; break;
case GL_DEBUG_SOURCE_SHADER_COMPILER_KHR: source_desc = "SHADER_COMPILER"; break;
case GL_DEBUG_SOURCE_WINDOW_SYSTEM_KHR: source_desc = "WINDOW_SYSTEM"; break;
case GL_DEBUG_SOURCE_THIRD_PARTY_KHR: source_desc = "THIRD_PARTY"; break;
case GL_DEBUG_SOURCE_APPLICATION_KHR: source_desc = "APPLICATION"; break;
default: source_desc = "OTHER";
case GL_DEBUG_SOURCE_API_KHR:
source_desc = "API";
break;
case GL_DEBUG_SOURCE_SHADER_COMPILER_KHR:
source_desc = "SHADER_COMPILER";
break;
case GL_DEBUG_SOURCE_WINDOW_SYSTEM_KHR:
source_desc = "WINDOW_SYSTEM";
break;
case GL_DEBUG_SOURCE_THIRD_PARTY_KHR:
source_desc = "THIRD_PARTY";
break;
case GL_DEBUG_SOURCE_APPLICATION_KHR:
source_desc = "APPLICATION";
break;
default:
source_desc = "OTHER";
}
String type_desc;
switch (severity) {
case GL_DEBUG_TYPE_ERROR_KHR: type_desc = "ERROR"; break;
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_KHR: type_desc = "PEPRECATED_BEHAVIOR"; break;
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_KHR: type_desc = "UNDEFINED_BEHAVIOR"; break;
case GL_DEBUG_TYPE_PERFORMANCE_KHR: type_desc = "PERFORMANCE"; break;
case GL_DEBUG_TYPE_PORTABILITY_KHR: type_desc = "PORTABILITY"; break;
case GL_DEBUG_TYPE_MARKER_KHR: type_desc = "MARKER"; break;
case GL_DEBUG_TYPE_PUSH_GROUP_KHR: type_desc = "PUSH_GROUP"; break;
case GL_DEBUG_TYPE_POP_GROUP_KHR: type_desc = "POP_GROUP"; break;
default: type_desc = "OTHER";
case GL_DEBUG_TYPE_ERROR_KHR:
type_desc = "ERROR";
break;
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_KHR:
type_desc = "PEPRECATED_BEHAVIOR";
break;
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_KHR:
type_desc = "UNDEFINED_BEHAVIOR";
break;
case GL_DEBUG_TYPE_PERFORMANCE_KHR:
type_desc = "PERFORMANCE";
break;
case GL_DEBUG_TYPE_PORTABILITY_KHR:
type_desc = "PORTABILITY";
break;
case GL_DEBUG_TYPE_MARKER_KHR:
type_desc = "MARKER";
break;
case GL_DEBUG_TYPE_PUSH_GROUP_KHR:
type_desc = "PUSH_GROUP";
break;
case GL_DEBUG_TYPE_POP_GROUP_KHR:
type_desc = "POP_GROUP";
break;
default:
type_desc = "OTHER";
}
String severity_desc;
switch (severity) {
case GL_DEBUG_SEVERITY_HIGH_KHR: severity_desc = "HIGH"; break;
case GL_DEBUG_SEVERITY_MEDIUM_KHR: severity_desc = "MEDIUM"; break;
case GL_DEBUG_SEVERITY_LOW_KHR: severity_desc = "LOW"; break;
default: severity_desc = "NOTIFICATION";
case GL_DEBUG_SEVERITY_HIGH_KHR:
severity_desc = "HIGH";
break;
case GL_DEBUG_SEVERITY_MEDIUM_KHR:
severity_desc = "MEDIUM";
break;
case GL_DEBUG_SEVERITY_LOW_KHR:
severity_desc = "LOW";
break;
default:
severity_desc = "NOTIFICATION";
}
String msg = StringUtil::Format("source: %s, type: %s, severity: %s, message: %s",
source_desc.c_str(), type_desc.c_str(), severity_desc.c_str(), message);
source_desc.c_str(), type_desc.c_str(), severity_desc.c_str(),
message);
if (severity == GL_DEBUG_SEVERITY_HIGH_KHR) {
#if (CC_PLATFORM == CC_PLATFORM_WINDOWS)
CCASSERT(false, msg.c_str());
CCASSERT(false, msg.
c_str()
);
#else
CC_LOG_ERROR(msg.c_str());
#endif
} else {
CC_LOG_DEBUG(msg.c_str());
CC_LOG_DEBUG(msg
.
c_str()
);
}
}
@@ -143,7 +195,8 @@ bool GLES2Context::initialize(const GFXContextInfo &info) {
// its needs perfectly, so we limit it to returning a single EGLConfig.
EGLint num_configs;
if (eglChooseConfig(_eglDisplay, attribs, &_eglConfig, 1, &num_configs) == EGL_FALSE || num_configs <= 0) {
if (eglChooseConfig(_eglDisplay, attribs, &_eglConfig, 1, &num_configs) == EGL_FALSE ||
num_configs <= 0) {
CC_LOG_ERROR("Choosing configuration failed.");
return false;
}
@@ -180,7 +233,8 @@ bool GLES2Context::initialize(const GFXContextInfo &info) {
#if (CC_PLATFORM == CC_PLATFORM_ANDROID)
EGLint n_fmt;
if (eglGetConfigAttrib(_eglDisplay, _eglConfig, EGL_NATIVE_VISUAL_ID, &n_fmt) == EGL_FALSE) {
if (eglGetConfigAttrib(_eglDisplay, _eglConfig, EGL_NATIVE_VISUAL_ID, &n_fmt) ==
EGL_FALSE) {
CC_LOG_ERROR("Getting configuration attributes failed.");
return false;
}
@@ -190,7 +244,8 @@ bool GLES2Context::initialize(const GFXContextInfo &info) {
ANativeWindow_setBuffersGeometry((ANativeWindow *)_windowHandle, width, height, n_fmt);
#endif
_eglSurface = eglCreateWindowSurface(_eglDisplay, _eglConfig, (EGLNativeWindowType)_windowHandle, NULL);
_eglSurface = eglCreateWindowSurface(_eglDisplay, _eglConfig,
(EGLNativeWindowType)_windowHandle, NULL);
if (_eglSurface == EGL_NO_SURFACE) {
CC_LOG_ERROR("Window surface created failed.");
return false;
@@ -199,7 +254,8 @@ bool GLES2Context::initialize(const GFXContextInfo &info) {
//String egl_vendor = eglQueryString(_eglDisplay, EGL_VENDOR);
//String egl_version = eglQueryString(_eglDisplay, EGL_VERSION);
_extensions = StringUtil::Split((const char *)eglQueryString(_eglDisplay, EGL_EXTENSIONS), " ");
_extensions = StringUtil::Split((const char *)eglQueryString(_eglDisplay, EGL_EXTENSIONS),
" ");
_majorVersion = 2;
_minorVersion = 0;
@@ -244,12 +300,12 @@ bool GLES2Context::initialize(const GFXContextInfo &info) {
_depthStencilFmt = sharedCtx->getDepthStencilFormat();
EGLint pbuff_attribs[] = {
EGL_WIDTH, 2,
EGL_HEIGHT, 2,
EGL_LARGEST_PBUFFER, EGL_TRUE,
EGL_TEXTURE_FORMAT, EGL_NO_TEXTURE,
EGL_TEXTURE_TARGET, EGL_NO_TEXTURE,
EGL_NONE};
EGL_WIDTH, 2,
EGL_HEIGHT, 2,
EGL_LARGEST_PBUFFER, EGL_TRUE,
EGL_TEXTURE_FORMAT, EGL_NO_TEXTURE,
EGL_TEXTURE_TARGET, EGL_NO_TEXTURE,
EGL_NONE};
_eglSurface = eglCreatePbufferSurface(_eglDisplay, _eglConfig, pbuff_attribs);
if (_eglSurface == EGL_NO_SURFACE) {
@@ -259,7 +315,8 @@ bool GLES2Context::initialize(const GFXContextInfo &info) {
bool has_khr_create_ctx = CheckExtension(CC_TOSTR(EGL_KHR_create_context));
if (!has_khr_create_ctx) {
CC_LOG_INFO("EGL context creation: EGL_KHR_create_context not supported. Minor version will be discarded, and debug disabled.");
CC_LOG_INFO(
"EGL context creation: EGL_KHR_create_context not supported. Minor version will be discarded, and debug disabled.");
_minorVersion = 0;
}
@@ -302,26 +359,35 @@ bool GLES2Context::initialize(const GFXContextInfo &info) {
}
});
EventDispatcher::addCustomEventListener(EVENT_RECREATE_WINDOW, [=](const CustomEvent &event) -> void {
_windowHandle = (uintptr_t)event.args->ptrVal;
EventDispatcher::addCustomEventListener(EVENT_RECREATE_WINDOW,
[=](const CustomEvent &event) -> void {
_windowHandle = (uintptr_t)event.args->ptrVal;
EGLint n_fmt;
if (eglGetConfigAttrib(_eglDisplay, _eglConfig, EGL_NATIVE_VISUAL_ID, &n_fmt) == EGL_FALSE) {
CC_LOG_ERROR("Getting configuration attributes failed.");
return;
}
uint width = _device->getWidth();
uint height = _device->getHeight();
ANativeWindow_setBuffersGeometry((ANativeWindow *)_windowHandle, width, height, n_fmt);
EGLint n_fmt;
if (eglGetConfigAttrib(_eglDisplay, _eglConfig,
EGL_NATIVE_VISUAL_ID,
&n_fmt) == EGL_FALSE) {
CC_LOG_ERROR(
"Getting configuration attributes failed.");
return;
}
uint width = _device->getWidth();
uint height = _device->getHeight();
ANativeWindow_setBuffersGeometry(
(ANativeWindow *)_windowHandle, width,
height, n_fmt);
_eglSurface = eglCreateWindowSurface(_eglDisplay, _eglConfig, (EGLNativeWindowType)_windowHandle, NULL);
if (_eglSurface == EGL_NO_SURFACE) {
CC_LOG_ERROR("Recreate window surface failed.");
return;
}
_eglSurface = eglCreateWindowSurface(_eglDisplay,
_eglConfig,
(EGLNativeWindowType)_windowHandle,
NULL);
if (_eglSurface == EGL_NO_SURFACE) {
CC_LOG_ERROR("Recreate window surface failed.");
return;
}
MakeCurrent();
});
MakeCurrent();
});
#endif
return true;
@@ -371,12 +437,23 @@ bool GLES2Context::MakeCurrent() {
// Turn on or off the vertical sync depending on the input bool value.
int interval = 1;
switch (_vsyncMode) {
case GFXVsyncMode::OFF: interval = 0; break;
case GFXVsyncMode::ON: interval = 1; break;
case GFXVsyncMode::RELAXED: interval = -1; break;
case GFXVsyncMode::MAILBOX: interval = 0; break;
case GFXVsyncMode::HALF: interval = 2; break;
default: break;
case GFXVsyncMode::OFF:
interval = 0;
break;
case GFXVsyncMode::ON:
interval = 1;
break;
case GFXVsyncMode::RELAXED:
interval = -1;
break;
case GFXVsyncMode::MAILBOX:
interval = 0;
break;
case GFXVsyncMode::HALF:
interval = 2;
break;
default:
break;
}
if (eglSwapInterval(_eglDisplay, interval) != 1) {
@@ -446,4 +523,5 @@ bool GLES2Context::CheckExtension(const String &extension) const {
return (std::find(_extensions.begin(), _extensions.end(), extension) != _extensions.end());
}
}
} // namespace gfx
} // namespace cc
@@ -29,6 +29,7 @@
#endif
namespace cc {
namespace gfx {
class CC_GLES2_API GLES2Context : public GFXContext {
public:
@@ -89,6 +90,7 @@ private:
bool _isInitialized = false;
};
}
} // namespace gfx
} // namespace cc
#endif // CC_GFXGLES2_GLES2_EGL_CONTEXT_H_
@@ -6,6 +6,7 @@
#import <QuartzCore/QuartzCore.h>
namespace cc {
namespace gfx {
#if (CC_PLATFORM == CC_PLATFORM_MAC_IOS)
@@ -185,4 +186,5 @@ bool GLES2Context::MakeCurrentImpl() {
#endif
}
} // namespace gfx
} // namespace cc
@@ -19,6 +19,7 @@
#include "GLES2Texture.h"
namespace cc {
namespace gfx {
GLES2Device::GLES2Device() {
}
@@ -304,4 +305,5 @@ void GLES2Device::copyBuffersToTexture(const GFXDataArray &buffers, GFXTexture *
GLES2CmdFuncCopyBuffersToTexture(this, buffers.datas.data(), ((GLES2Texture *)dst)->gpuTexture(), regions);
}
}
} // namespace gfx
} // namespace cc
@@ -2,6 +2,7 @@
#define CC_GFXGLES2_GLES2_DEVICE_H_
namespace cc {
namespace gfx {
class GLES2StateCache;
@@ -57,6 +58,7 @@ private:
bool _useDiscardFramebuffer = false;
};
}
} // namespace gfx
} // namespace cc
#endif
@@ -4,6 +4,7 @@
#include "GLES2GPUObjects.h"
namespace cc {
namespace gfx {
GLES2Fence::GLES2Fence(GFXDevice *device)
: GFXFence(device) {
@@ -43,4 +44,5 @@ void GLES2Fence::reset() {
// TODO
}
}
} // namespace gfx
} // namespace cc
+3 -1
View File
@@ -2,6 +2,7 @@
#define CC_GFXGLES2_GLES2_FENCE_H_
namespace cc {
namespace gfx {
class GLES2GPUFence;
@@ -20,6 +21,7 @@ private:
GLES2GPUFence *_gpuFence = nullptr;
};
}
} // namespace gfx
} // namespace cc
#endif
@@ -6,6 +6,7 @@
#include "GLES2Texture.h"
namespace cc {
namespace gfx {
GLES2Framebuffer::GLES2Framebuffer(GFXDevice *device)
: GFXFramebuffer(device) {
@@ -20,7 +21,7 @@ bool GLES2Framebuffer::initialize(const GFXFramebufferInfo &info) {
_colorTextures = info.colorTextures;
_depthStencilTexture = info.depthStencilTexture;
_isOffscreen = info.isOffscreen;
if (info.depthStencilMipmapLevel != 0) {
CC_LOG_WARNING("Mipmap level of depth stencil attachment should be 0 in GLES2. Convert to 0.");
}
@@ -71,4 +72,5 @@ void GLES2Framebuffer::destroy() {
_status = GFXStatus::UNREADY;
}
}
} // namespace gfx
} // namespace cc
@@ -2,6 +2,7 @@
#define CC_GFXGLES2_GLES2_FRAMEBUFFER_H_
namespace cc {
namespace gfx {
class GLES2GPUFramebuffer;
@@ -20,6 +21,7 @@ private:
GLES2GPUFramebuffer *_gpuFBO = nullptr;
};
}
} // namespace gfx
} // namespace cc
#endif
@@ -4,6 +4,7 @@
#include "gles2w.h"
namespace cc {
namespace gfx {
class GLES2GPUBuffer : public Object {
public:
@@ -237,6 +238,7 @@ class GLES2GPUFence : public Object {
public:
};
}
} // namespace gfx
} // namespace cc
#endif
@@ -4,6 +4,7 @@
#include "GLES2Buffer.h"
namespace cc {
namespace gfx {
GLES2InputAssembler::GLES2InputAssembler(GFXDevice *device)
: GFXInputAssembler(device) {
@@ -64,4 +65,5 @@ void GLES2InputAssembler::ExtractCmdDraw(GLES2CmdDraw *cmd) {
cmd->draw_info.firstInstance = _firstInstance;
}
}
} // namespace gfx
} // namespace cc
@@ -2,6 +2,7 @@
#define CC_GFXGLES2_GLES2_INPUT_ASSEMBLER_H_
namespace cc {
namespace gfx {
class GLES2GPUInputAssembler;
class GLES2CmdDraw;
@@ -23,6 +24,7 @@ private:
GLES2GPUInputAssembler *_gpuInputAssembler = nullptr;
};
}
} // namespace gfx
} // namespace cc
#endif
@@ -3,6 +3,7 @@
#include "GLES2Commands.h"
namespace cc {
namespace gfx {
GLES2PipelineLayout::GLES2PipelineLayout(GFXDevice *device)
: GFXPipelineLayout(device) {
@@ -30,4 +31,5 @@ void GLES2PipelineLayout::destroy() {
_status = GFXStatus::UNREADY;
}
}
} // namespace gfx
} // namespace cc
@@ -2,6 +2,7 @@
#define CC_GFXGLES2_GLES2_PIPELINE_LAYOUT_H_
namespace cc {
namespace gfx {
class GLES2GPUPipelineLayout;
@@ -20,6 +21,7 @@ private:
GLES2GPUPipelineLayout *_gpuPipelineLayout = nullptr;
};
}
} // namespace gfx
} // namespace cc
#endif
@@ -6,6 +6,7 @@
#include "GLES2PipelineLayout.h"
namespace cc {
namespace gfx {
const GLenum GLES2Primitives[] = {
GL_POINTS,
@@ -67,4 +68,5 @@ void GLES2PipelineState::destroy() {
_status = GFXStatus::UNREADY;
}
}
} // namespace gfx
} // namespace cc
@@ -2,6 +2,7 @@
#define CC_GFXGLES2_GLES2_PIPELINE_STATE_H_
namespace cc {
namespace gfx {
class GLES2GPUPipelineState;
@@ -20,6 +21,7 @@ private:
GLES2GPUPipelineState *_gpuPipelineState = nullptr;
};
}
} // namespace gfx
} // namespace cc
#endif
@@ -4,6 +4,7 @@
#include "GLES2CommandBuffer.h"
namespace cc {
namespace gfx {
GLES2Queue::GLES2Queue(GFXDevice *device)
: GFXQueue(device) {
@@ -36,4 +37,5 @@ void GLES2Queue::submit(const vector<GFXCommandBuffer *>::type &cmdBuffs, GFXFen
}
}
}
} // namespace gfx
} // namespace cc
+3 -1
View File
@@ -2,6 +2,7 @@
#define CC_GFXGLES2_GLES2_QUEUE_H_
namespace cc {
namespace gfx {
class CC_GLES2_API GLES2Queue : public GFXQueue {
public:
@@ -24,6 +25,7 @@ private:
uint _numTriangles = 0;
};
}
} // namespace gfx
} // namespace cc
#endif
@@ -3,6 +3,7 @@
#include "GLES2Commands.h"
namespace cc {
namespace gfx {
GLES2RenderPass::GLES2RenderPass(GFXDevice *device)
: GFXRenderPass(device) {
@@ -35,4 +36,5 @@ void GLES2RenderPass::destroy() {
_status = GFXStatus::UNREADY;
}
}
} // namespace gfx
} // namespace cc
@@ -2,6 +2,7 @@
#define CC_GFXGLES2_GLES2_RENDER_PASS_H_
namespace cc {
namespace gfx {
class GLES2GPURenderPass;
@@ -20,6 +21,7 @@ private:
GLES2GPURenderPass *_gpuRenderPass = nullptr;
};
}
} // namespace gfx
} // namespace cc
#endif
@@ -3,6 +3,7 @@
#include "GLES2Commands.h"
namespace cc {
namespace gfx {
GLES2Sampler::GLES2Sampler(GFXDevice *device)
: GFXSampler(device) {
@@ -52,4 +53,5 @@ void GLES2Sampler::destroy() {
_status = GFXStatus::UNREADY;
}
}
} // namespace gfx
} // namespace cc
@@ -2,6 +2,7 @@
#define CC_GFXGLES2_GLES2_SAMPLER_H_
namespace cc {
namespace gfx {
class GLES2GPUSampler;
@@ -33,6 +34,7 @@ private:
float _mipLODBias = 0.0f;
};
}
} // namespace gfx
} // namespace cc
#endif
@@ -3,6 +3,7 @@
#include "GLES2Commands.h"
namespace cc {
namespace gfx {
GLES2Shader::GLES2Shader(GFXDevice *device)
: GFXShader(device) {
@@ -43,4 +44,5 @@ void GLES2Shader::destroy() {
_status = GFXStatus::UNREADY;
}
}
} // namespace gfx
} // namespace cc
@@ -2,6 +2,7 @@
#define CC_GFXGLES2_GLES2_SHADER_H_
namespace cc {
namespace gfx {
class GLES2GPUShader;
@@ -20,6 +21,7 @@ private:
GLES2GPUShader *_gpuShader = nullptr;
};
}
} // namespace gfx
} // namespace cc
#endif
@@ -4,6 +4,7 @@
#include "gles2w.h"
namespace cc {
namespace gfx {
class GLES2StateCache : public Object {
public:
@@ -31,6 +32,7 @@ public:
GLES2StateCache() {}
};
}
} // namespace gfx
} // namespace cc
#endif

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