Added love.math.compress(data, format [, level]) and love.math.decompress(compresseddata) / love.math.decompress(compressedstring, format).

Renamed the love.image CompressedData type to CompressedImageData.

love.math.compress returns a love.math CompressedData object which holds the newly compressed data. Currently supported formats are "lz4" and "zlib". Note that the formats are not file formats and don't compress filesystem hierarchies.
This commit is contained in:
Alex Szpakowski
2015-03-23 11:28:14 -03:00
parent 4d92d00aff
commit a29b349014
45 changed files with 3895 additions and 395 deletions
+4 -2
View File
@@ -58,7 +58,7 @@ static const TypeBits *createTypeFlags()
// Image.
b[IMAGE_IMAGE_DATA_ID] = (one << IMAGE_IMAGE_DATA_ID) | b[DATA_ID];
b[IMAGE_COMPRESSED_DATA_ID] = (one << IMAGE_COMPRESSED_DATA_ID) | b[DATA_ID];
b[IMAGE_COMPRESSED_IMAGE_DATA_ID] = (one << IMAGE_COMPRESSED_IMAGE_DATA_ID) | b[DATA_ID];
// Joystick.
b[JOYSTICK_JOYSTICK_ID] = (one << JOYSTICK_JOYSTICK_ID) | b[OBJECT_ID];
@@ -66,6 +66,7 @@ static const TypeBits *createTypeFlags()
// Math.
b[MATH_RANDOM_GENERATOR_ID] = (one << MATH_RANDOM_GENERATOR_ID) | b[OBJECT_ID];
b[MATH_BEZIER_CURVE_ID] = (one << MATH_BEZIER_CURVE_ID) | b[OBJECT_ID];
b[MATH_COMPRESSED_DATA_ID] = (one <<MATH_COMPRESSED_DATA_ID) | b[DATA_ID];
// Audio.
b[AUDIO_SOURCE_ID] = (one << AUDIO_SOURCE_ID) | b[OBJECT_ID];
@@ -147,7 +148,7 @@ StringMap<Type, TYPE_MAX_ENUM>::Entry typeEntries[] =
// Image
{"ImageData", IMAGE_IMAGE_DATA_ID},
{"CompressedData", IMAGE_COMPRESSED_DATA_ID},
{"CompressedImageData", IMAGE_COMPRESSED_IMAGE_DATA_ID},
// Joystick
{"Joystick", JOYSTICK_JOYSTICK_ID},
@@ -155,6 +156,7 @@ StringMap<Type, TYPE_MAX_ENUM>::Entry typeEntries[] =
// Math
{"RandomGenerator", MATH_RANDOM_GENERATOR_ID},
{"BezierCurve", MATH_BEZIER_CURVE_ID},
{"CompressedData", MATH_COMPRESSED_DATA_ID},
// Audio
{"Source", AUDIO_SOURCE_ID},
+2 -1
View File
@@ -59,7 +59,7 @@ enum Type
// Image
IMAGE_IMAGE_DATA_ID,
IMAGE_COMPRESSED_DATA_ID,
IMAGE_COMPRESSED_IMAGE_DATA_ID,
// Joystick
JOYSTICK_JOYSTICK_ID,
@@ -67,6 +67,7 @@ enum Type
// Math
MATH_RANDOM_GENERATOR_ID,
MATH_BEZIER_CURVE_ID,
MATH_COMPRESSED_DATA_ID,
// Audio
AUDIO_SOURCE_ID,
+1367
View File
File diff suppressed because it is too large Load Diff
+315
View File
@@ -0,0 +1,315 @@
/*
LZ4 - Fast LZ compression algorithm
Header File
Copyright (C) 2011-2014, Yann Collet.
BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
You can contact the author at :
- LZ4 source repository : http://code.google.com/p/lz4/
- LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c
*/
#pragma once
#if defined (__cplusplus)
extern "C" {
#endif
/*
* lz4.h provides raw compression format functions, for optimal performance and integration into programs.
* If you need to generate data using an inter-operable format (respecting the framing specification),
* please use lz4frame.h instead.
*/
/**************************************
Version
**************************************/
#define LZ4_VERSION_MAJOR 1 /* for breaking interface changes */
#define LZ4_VERSION_MINOR 5 /* for new (non-breaking) interface capabilities */
#define LZ4_VERSION_RELEASE 0 /* for tweaks, bug-fixes, or development */
#define LZ4_VERSION_NUMBER (LZ4_VERSION_MAJOR *100*100 + LZ4_VERSION_MINOR *100 + LZ4_VERSION_RELEASE)
int LZ4_versionNumber (void);
/**************************************
Tuning parameter
**************************************/
/*
* LZ4_MEMORY_USAGE :
* Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.)
* Increasing memory usage improves compression ratio
* Reduced memory usage can improve speed, due to cache effect
* Default value is 14, for 16KB, which nicely fits into Intel x86 L1 cache
*/
#define LZ4_MEMORY_USAGE 14
/**************************************
Simple Functions
**************************************/
int LZ4_compress (const char* source, char* dest, int sourceSize);
int LZ4_decompress_safe (const char* source, char* dest, int compressedSize, int maxDecompressedSize);
/*
LZ4_compress() :
Compresses 'sourceSize' bytes from 'source' into 'dest'.
Destination buffer must be already allocated,
and must be sized to handle worst cases situations (input data not compressible)
Worst case size evaluation is provided by function LZ4_compressBound()
inputSize : Max supported value is LZ4_MAX_INPUT_SIZE
return : the number of bytes written in buffer dest
or 0 if the compression fails
LZ4_decompress_safe() :
compressedSize : is obviously the source size
maxDecompressedSize : is the size of the destination buffer, which must be already allocated.
return : the number of bytes decompressed into the destination buffer (necessarily <= maxDecompressedSize)
If the destination buffer is not large enough, decoding will stop and output an error code (<0).
If the source stream is detected malformed, the function will stop decoding and return a negative result.
This function is protected against buffer overflow exploits,
and never writes outside of output buffer, nor reads outside of input buffer.
It is also protected against malicious data packets.
*/
/**************************************
Advanced Functions
**************************************/
#define LZ4_MAX_INPUT_SIZE 0x7E000000 /* 2 113 929 216 bytes */
#define LZ4_COMPRESSBOUND(isize) ((unsigned int)(isize) > (unsigned int)LZ4_MAX_INPUT_SIZE ? 0 : (isize) + ((isize)/255) + 16)
/*
LZ4_compressBound() :
Provides the maximum size that LZ4 compression may output in a "worst case" scenario (input data not compressible)
This function is primarily useful for memory allocation purposes (output buffer size).
Macro LZ4_COMPRESSBOUND() is also provided for compilation-time evaluation (stack memory allocation for example).
isize : is the input size. Max supported value is LZ4_MAX_INPUT_SIZE
return : maximum output size in a "worst case" scenario
or 0, if input size is too large ( > LZ4_MAX_INPUT_SIZE)
*/
int LZ4_compressBound(int isize);
/*
LZ4_compress_limitedOutput() :
Compress 'sourceSize' bytes from 'source' into an output buffer 'dest' of maximum size 'maxOutputSize'.
If it cannot achieve it, compression will stop, and result of the function will be zero.
This saves time and memory on detecting non-compressible (or barely compressible) data.
This function never writes outside of provided output buffer.
sourceSize : Max supported value is LZ4_MAX_INPUT_VALUE
maxOutputSize : is the size of the destination buffer (which must be already allocated)
return : the number of bytes written in buffer 'dest'
or 0 if compression fails
*/
int LZ4_compress_limitedOutput (const char* source, char* dest, int sourceSize, int maxOutputSize);
/*
LZ4_compress_withState() :
Same compression functions, but using an externally allocated memory space to store compression state.
Use LZ4_sizeofState() to know how much memory must be allocated,
and then, provide it as 'void* state' to compression functions.
*/
int LZ4_sizeofState(void);
int LZ4_compress_withState (void* state, const char* source, char* dest, int inputSize);
int LZ4_compress_limitedOutput_withState (void* state, const char* source, char* dest, int inputSize, int maxOutputSize);
/*
LZ4_decompress_fast() :
originalSize : is the original and therefore uncompressed size
return : the number of bytes read from the source buffer (in other words, the compressed size)
If the source stream is detected malformed, the function will stop decoding and return a negative result.
Destination buffer must be already allocated. Its size must be a minimum of 'originalSize' bytes.
note : This function fully respect memory boundaries for properly formed compressed data.
It is a bit faster than LZ4_decompress_safe().
However, it does not provide any protection against intentionally modified data stream (malicious input).
Use this function in trusted environment only (data to decode comes from a trusted source).
*/
int LZ4_decompress_fast (const char* source, char* dest, int originalSize);
/*
LZ4_decompress_safe_partial() :
This function decompress a compressed block of size 'compressedSize' at position 'source'
into destination buffer 'dest' of size 'maxDecompressedSize'.
The function tries to stop decompressing operation as soon as 'targetOutputSize' has been reached,
reducing decompression time.
return : the number of bytes decoded in the destination buffer (necessarily <= maxDecompressedSize)
Note : this number can be < 'targetOutputSize' should the compressed block to decode be smaller.
Always control how many bytes were decoded.
If the source stream is detected malformed, the function will stop decoding and return a negative result.
This function never writes outside of output buffer, and never reads outside of input buffer. It is therefore protected against malicious data packets
*/
int LZ4_decompress_safe_partial (const char* source, char* dest, int compressedSize, int targetOutputSize, int maxDecompressedSize);
/***********************************************
Streaming Compression Functions
***********************************************/
#define LZ4_STREAMSIZE_U64 ((1 << (LZ4_MEMORY_USAGE-3)) + 4)
#define LZ4_STREAMSIZE (LZ4_STREAMSIZE_U64 * sizeof(long long))
/*
* LZ4_stream_t
* information structure to track an LZ4 stream.
* important : init this structure content before first use !
* note : only allocated directly the structure if you are statically linking LZ4
* If you are using liblz4 as a DLL, please use below construction methods instead.
*/
typedef struct { long long table[LZ4_STREAMSIZE_U64]; } LZ4_stream_t;
/*
* LZ4_resetStream
* Use this function to init an allocated LZ4_stream_t structure
*/
void LZ4_resetStream (LZ4_stream_t* LZ4_streamPtr);
/*
* LZ4_createStream will allocate and initialize an LZ4_stream_t structure
* LZ4_freeStream releases its memory.
* In the context of a DLL (liblz4), please use these methods rather than the static struct.
* They are more future proof, in case of a change of LZ4_stream_t size.
*/
LZ4_stream_t* LZ4_createStream(void);
int LZ4_freeStream (LZ4_stream_t* LZ4_streamPtr);
/*
* LZ4_loadDict
* Use this function to load a static dictionary into LZ4_stream.
* Any previous data will be forgotten, only 'dictionary' will remain in memory.
* Loading a size of 0 is allowed.
* Return : dictionary size, in bytes (necessarily <= 64 KB)
*/
int LZ4_loadDict (LZ4_stream_t* LZ4_streamPtr, const char* dictionary, int dictSize);
/*
* LZ4_compress_continue
* Compress data block 'source', using blocks compressed before as dictionary to improve compression ratio
* Previous data blocks are assumed to still be present at their previous location.
*/
int LZ4_compress_continue (LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest, int inputSize);
/*
* LZ4_compress_limitedOutput_continue
* Same as before, but also specify a maximum target compressed size (maxOutputSize)
* If objective cannot be met, compression exits, and returns a zero.
*/
int LZ4_compress_limitedOutput_continue (LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest, int inputSize, int maxOutputSize);
/*
* LZ4_saveDict
* If previously compressed data block is not guaranteed to remain available at its memory location
* save it into a safer place (char* safeBuffer)
* Note : you don't need to call LZ4_loadDict() afterwards,
* dictionary is immediately usable, you can therefore call again LZ4_compress_continue()
* Return : dictionary size in bytes, or 0 if error
* Note : any dictSize > 64 KB will be interpreted as 64KB.
*/
int LZ4_saveDict (LZ4_stream_t* LZ4_streamPtr, char* safeBuffer, int dictSize);
/************************************************
Streaming Decompression Functions
************************************************/
#define LZ4_STREAMDECODESIZE_U64 4
#define LZ4_STREAMDECODESIZE (LZ4_STREAMDECODESIZE_U64 * sizeof(unsigned long long))
typedef struct { unsigned long long table[LZ4_STREAMDECODESIZE_U64]; } LZ4_streamDecode_t;
/*
* LZ4_streamDecode_t
* information structure to track an LZ4 stream.
* init this structure content using LZ4_setStreamDecode or memset() before first use !
*
* In the context of a DLL (liblz4) please prefer usage of construction methods below.
* They are more future proof, in case of a change of LZ4_streamDecode_t size in the future.
* LZ4_createStreamDecode will allocate and initialize an LZ4_streamDecode_t structure
* LZ4_freeStreamDecode releases its memory.
*/
LZ4_streamDecode_t* LZ4_createStreamDecode(void);
int LZ4_freeStreamDecode (LZ4_streamDecode_t* LZ4_stream);
/*
* LZ4_setStreamDecode
* Use this function to instruct where to find the dictionary.
* Setting a size of 0 is allowed (same effect as reset).
* Return : 1 if OK, 0 if error
*/
int LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dictionary, int dictSize);
/*
*_continue() :
These decoding functions allow decompression of multiple blocks in "streaming" mode.
Previously decoded blocks *must* remain available at the memory position where they were decoded (up to 64 KB)
If this condition is not possible, save the relevant part of decoded data into a safe buffer,
and indicate where is its new address using LZ4_setStreamDecode()
*/
int LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int compressedSize, int maxDecompressedSize);
int LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int originalSize);
/*
Advanced decoding functions :
*_usingDict() :
These decoding functions work the same as
a combination of LZ4_setDictDecode() followed by LZ4_decompress_x_continue()
They are stand-alone and don't use nor update an LZ4_streamDecode_t structure.
*/
int LZ4_decompress_safe_usingDict (const char* source, char* dest, int compressedSize, int maxDecompressedSize, const char* dictStart, int dictSize);
int LZ4_decompress_fast_usingDict (const char* source, char* dest, int originalSize, const char* dictStart, int dictSize);
/**************************************
Obsolete Functions
**************************************/
/*
Obsolete decompression functions
These function names are deprecated and should no longer be used.
They are only provided here for compatibility with older user programs.
- LZ4_uncompress is the same as LZ4_decompress_fast
- LZ4_uncompress_unknownOutputSize is the same as LZ4_decompress_safe
These function prototypes are now disabled; uncomment them if you really need them.
It is highly recommended to stop using these functions and migrate to newer ones */
/* int LZ4_uncompress (const char* source, char* dest, int outputSize); */
/* int LZ4_uncompress_unknownOutputSize (const char* source, char* dest, int isize, int maxOutputSize); */
/* Obsolete streaming functions; use new streaming interface whenever possible */
void* LZ4_create (const char* inputBuffer);
int LZ4_sizeofStreamState(void);
int LZ4_resetStreamState(void* state, const char* inputBuffer);
char* LZ4_slideInputBuffer (void* state);
/* Obsolete streaming decoding functions */
int LZ4_decompress_safe_withPrefix64k (const char* source, char* dest, int compressedSize, int maxOutputSize);
int LZ4_decompress_fast_withPrefix64k (const char* source, char* dest, int originalSize);
#if defined (__cplusplus)
}
#endif
+751
View File
@@ -0,0 +1,751 @@
/*
LZ4 HC - High Compression Mode of LZ4
Copyright (C) 2011-2014, Yann Collet.
BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
You can contact the author at :
- LZ4 homepage : http://fastcompression.blogspot.com/p/lz4.html
- LZ4 source repository : http://code.google.com/p/lz4/
*/
/**************************************
Tuning Parameter
**************************************/
static const int LZ4HC_compressionLevel_default = 8;
/**************************************
Includes
**************************************/
#include "lz4hc.h"
/**************************************
Local Compiler Options
**************************************/
#if defined(__GNUC__)
# pragma GCC diagnostic ignored "-Wunused-function"
#endif
#if defined (__clang__)
# pragma clang diagnostic ignored "-Wunused-function"
#endif
/**************************************
Common LZ4 definition
**************************************/
#define LZ4_COMMONDEFS_ONLY
#include "lz4.c"
/**************************************
Local Constants
**************************************/
#define DICTIONARY_LOGSIZE 16
#define MAXD (1<<DICTIONARY_LOGSIZE)
#define MAXD_MASK ((U32)(MAXD - 1))
#define HASH_LOG (DICTIONARY_LOGSIZE-1)
#define HASHTABLESIZE (1 << HASH_LOG)
#define HASH_MASK (HASHTABLESIZE - 1)
#define OPTIMAL_ML (int)((ML_MASK-1)+MINMATCH)
static const int g_maxCompressionLevel = 16;
/**************************************
Local Types
**************************************/
typedef struct
{
U32 hashTable[HASHTABLESIZE];
U16 chainTable[MAXD];
const BYTE* end; /* next block here to continue on current prefix */
const BYTE* base; /* All index relative to this position */
const BYTE* dictBase; /* alternate base for extDict */
const BYTE* inputBuffer;/* deprecated */
U32 dictLimit; /* below that point, need extDict */
U32 lowLimit; /* below that point, no more dict */
U32 nextToUpdate;
U32 compressionLevel;
} LZ4HC_Data_Structure;
/**************************************
Local Macros
**************************************/
#define HASH_FUNCTION(i) (((i) * 2654435761U) >> ((MINMATCH*8)-HASH_LOG))
#define DELTANEXT(p) chainTable[(size_t)(p) & MAXD_MASK]
#define GETNEXT(p) ((p) - (size_t)DELTANEXT(p))
static U32 LZ4HC_hashPtr(const void* ptr) { return HASH_FUNCTION(LZ4_read32(ptr)); }
/**************************************
HC Compression
**************************************/
static void LZ4HC_init (LZ4HC_Data_Structure* hc4, const BYTE* start)
{
MEM_INIT((void*)hc4->hashTable, 0, sizeof(hc4->hashTable));
MEM_INIT(hc4->chainTable, 0xFF, sizeof(hc4->chainTable));
hc4->nextToUpdate = 64 KB;
hc4->base = start - 64 KB;
hc4->inputBuffer = start;
hc4->end = start;
hc4->dictBase = start - 64 KB;
hc4->dictLimit = 64 KB;
hc4->lowLimit = 64 KB;
}
/* Update chains up to ip (excluded) */
FORCE_INLINE void LZ4HC_Insert (LZ4HC_Data_Structure* hc4, const BYTE* ip)
{
U16* chainTable = hc4->chainTable;
U32* HashTable = hc4->hashTable;
const BYTE* const base = hc4->base;
const U32 target = (U32)(ip - base);
U32 idx = hc4->nextToUpdate;
while(idx < target)
{
U32 h = LZ4HC_hashPtr(base+idx);
size_t delta = idx - HashTable[h];
if (delta>MAX_DISTANCE) delta = MAX_DISTANCE;
chainTable[idx & 0xFFFF] = (U16)delta;
HashTable[h] = idx;
idx++;
}
hc4->nextToUpdate = target;
}
FORCE_INLINE int LZ4HC_InsertAndFindBestMatch (LZ4HC_Data_Structure* hc4, /* Index table will be updated */
const BYTE* ip, const BYTE* const iLimit,
const BYTE** matchpos,
const int maxNbAttempts)
{
U16* const chainTable = hc4->chainTable;
U32* const HashTable = hc4->hashTable;
const BYTE* const base = hc4->base;
const BYTE* const dictBase = hc4->dictBase;
const U32 dictLimit = hc4->dictLimit;
const U32 lowLimit = (hc4->lowLimit + 64 KB > (U32)(ip-base)) ? hc4->lowLimit : (U32)(ip - base) - (64 KB - 1);
U32 matchIndex;
const BYTE* match;
int nbAttempts=maxNbAttempts;
size_t ml=0;
/* HC4 match finder */
LZ4HC_Insert(hc4, ip);
matchIndex = HashTable[LZ4HC_hashPtr(ip)];
while ((matchIndex>=lowLimit) && (nbAttempts))
{
nbAttempts--;
if (matchIndex >= dictLimit)
{
match = base + matchIndex;
if (*(match+ml) == *(ip+ml)
&& (LZ4_read32(match) == LZ4_read32(ip)))
{
size_t mlt = LZ4_count(ip+MINMATCH, match+MINMATCH, iLimit) + MINMATCH;
if (mlt > ml) { ml = mlt; *matchpos = match; }
}
}
else
{
match = dictBase + matchIndex;
if (LZ4_read32(match) == LZ4_read32(ip))
{
size_t mlt;
const BYTE* vLimit = ip + (dictLimit - matchIndex);
if (vLimit > iLimit) vLimit = iLimit;
mlt = LZ4_count(ip+MINMATCH, match+MINMATCH, vLimit) + MINMATCH;
if ((ip+mlt == vLimit) && (vLimit < iLimit))
mlt += LZ4_count(ip+mlt, base+dictLimit, iLimit);
if (mlt > ml) { ml = mlt; *matchpos = base + matchIndex; } /* virtual matchpos */
}
}
matchIndex -= chainTable[matchIndex & 0xFFFF];
}
return (int)ml;
}
FORCE_INLINE int LZ4HC_InsertAndGetWiderMatch (
LZ4HC_Data_Structure* hc4,
const BYTE* ip,
const BYTE* iLowLimit,
const BYTE* iHighLimit,
int longest,
const BYTE** matchpos,
const BYTE** startpos,
const int maxNbAttempts)
{
U16* const chainTable = hc4->chainTable;
U32* const HashTable = hc4->hashTable;
const BYTE* const base = hc4->base;
const U32 dictLimit = hc4->dictLimit;
const U32 lowLimit = (hc4->lowLimit + 64 KB > (U32)(ip-base)) ? hc4->lowLimit : (U32)(ip - base) - (64 KB - 1);
const BYTE* const dictBase = hc4->dictBase;
const BYTE* match;
U32 matchIndex;
int nbAttempts = maxNbAttempts;
int delta = (int)(ip-iLowLimit);
/* First Match */
LZ4HC_Insert(hc4, ip);
matchIndex = HashTable[LZ4HC_hashPtr(ip)];
while ((matchIndex>=lowLimit) && (nbAttempts))
{
nbAttempts--;
if (matchIndex >= dictLimit)
{
match = base + matchIndex;
if (*(iLowLimit + longest) == *(match - delta + longest))
if (LZ4_read32(match) == LZ4_read32(ip))
{
const BYTE* startt = ip;
const BYTE* tmpMatch = match;
const BYTE* const matchEnd = ip + MINMATCH + LZ4_count(ip+MINMATCH, match+MINMATCH, iHighLimit);
while ((startt>iLowLimit) && (tmpMatch > iLowLimit) && (startt[-1] == tmpMatch[-1])) {startt--; tmpMatch--;}
if ((matchEnd-startt) > longest)
{
longest = (int)(matchEnd-startt);
*matchpos = tmpMatch;
*startpos = startt;
}
}
}
else
{
match = dictBase + matchIndex;
if (LZ4_read32(match) == LZ4_read32(ip))
{
size_t mlt;
int back=0;
const BYTE* vLimit = ip + (dictLimit - matchIndex);
if (vLimit > iHighLimit) vLimit = iHighLimit;
mlt = LZ4_count(ip+MINMATCH, match+MINMATCH, vLimit) + MINMATCH;
if ((ip+mlt == vLimit) && (vLimit < iHighLimit))
mlt += LZ4_count(ip+mlt, base+dictLimit, iHighLimit);
while ((ip+back > iLowLimit) && (matchIndex+back > lowLimit) && (ip[back-1] == match[back-1])) back--;
mlt -= back;
if ((int)mlt > longest) { longest = (int)mlt; *matchpos = base + matchIndex + back; *startpos = ip+back; }
}
}
matchIndex -= chainTable[matchIndex & 0xFFFF];
}
return longest;
}
typedef enum { noLimit = 0, limitedOutput = 1 } limitedOutput_directive;
#define LZ4HC_DEBUG 0
#if LZ4HC_DEBUG
static unsigned debug = 0;
#endif
FORCE_INLINE int LZ4HC_encodeSequence (
const BYTE** ip,
BYTE** op,
const BYTE** anchor,
int matchLength,
const BYTE* const match,
limitedOutput_directive limitedOutputBuffer,
BYTE* oend)
{
int length;
BYTE* token;
#if LZ4HC_DEBUG
if (debug) printf("literal : %u -- match : %u -- offset : %u\n", (U32)(*ip - *anchor), (U32)matchLength, (U32)(*ip-match));
#endif
/* Encode Literal length */
length = (int)(*ip - *anchor);
token = (*op)++;
if ((limitedOutputBuffer) && ((*op + (length>>8) + length + (2 + 1 + LASTLITERALS)) > oend)) return 1; /* Check output limit */
if (length>=(int)RUN_MASK) { int len; *token=(RUN_MASK<<ML_BITS); len = length-RUN_MASK; for(; len > 254 ; len-=255) *(*op)++ = 255; *(*op)++ = (BYTE)len; }
else *token = (BYTE)(length<<ML_BITS);
/* Copy Literals */
LZ4_wildCopy(*op, *anchor, (*op) + length);
*op += length;
/* Encode Offset */
LZ4_writeLE16(*op, (U16)(*ip-match)); *op += 2;
/* Encode MatchLength */
length = (int)(matchLength-MINMATCH);
if ((limitedOutputBuffer) && (*op + (length>>8) + (1 + LASTLITERALS) > oend)) return 1; /* Check output limit */
if (length>=(int)ML_MASK) { *token+=ML_MASK; length-=ML_MASK; for(; length > 509 ; length-=510) { *(*op)++ = 255; *(*op)++ = 255; } if (length > 254) { length-=255; *(*op)++ = 255; } *(*op)++ = (BYTE)length; }
else *token += (BYTE)(length);
/* Prepare next loop */
*ip += matchLength;
*anchor = *ip;
return 0;
}
static int LZ4HC_compress_generic (
void* ctxvoid,
const char* source,
char* dest,
int inputSize,
int maxOutputSize,
int compressionLevel,
limitedOutput_directive limit
)
{
LZ4HC_Data_Structure* ctx = (LZ4HC_Data_Structure*) ctxvoid;
const BYTE* ip = (const BYTE*) source;
const BYTE* anchor = ip;
const BYTE* const iend = ip + inputSize;
const BYTE* const mflimit = iend - MFLIMIT;
const BYTE* const matchlimit = (iend - LASTLITERALS);
BYTE* op = (BYTE*) dest;
BYTE* const oend = op + maxOutputSize;
unsigned maxNbAttempts;
int ml, ml2, ml3, ml0;
const BYTE* ref=NULL;
const BYTE* start2=NULL;
const BYTE* ref2=NULL;
const BYTE* start3=NULL;
const BYTE* ref3=NULL;
const BYTE* start0;
const BYTE* ref0;
/* init */
if (compressionLevel > g_maxCompressionLevel) compressionLevel = g_maxCompressionLevel;
if (compressionLevel < 1) compressionLevel = LZ4HC_compressionLevel_default;
maxNbAttempts = 1 << (compressionLevel-1);
ctx->end += inputSize;
ip++;
/* Main Loop */
while (ip < mflimit)
{
ml = LZ4HC_InsertAndFindBestMatch (ctx, ip, matchlimit, (&ref), maxNbAttempts);
if (!ml) { ip++; continue; }
/* saved, in case we would skip too much */
start0 = ip;
ref0 = ref;
ml0 = ml;
_Search2:
if (ip+ml < mflimit)
ml2 = LZ4HC_InsertAndGetWiderMatch(ctx, ip + ml - 2, ip + 1, matchlimit, ml, &ref2, &start2, maxNbAttempts);
else ml2 = ml;
if (ml2 == ml) /* No better match */
{
if (LZ4HC_encodeSequence(&ip, &op, &anchor, ml, ref, limit, oend)) return 0;
continue;
}
if (start0 < ip)
{
if (start2 < ip + ml0) /* empirical */
{
ip = start0;
ref = ref0;
ml = ml0;
}
}
/* Here, start0==ip */
if ((start2 - ip) < 3) /* First Match too small : removed */
{
ml = ml2;
ip = start2;
ref =ref2;
goto _Search2;
}
_Search3:
/*
* Currently we have :
* ml2 > ml1, and
* ip1+3 <= ip2 (usually < ip1+ml1)
*/
if ((start2 - ip) < OPTIMAL_ML)
{
int correction;
int new_ml = ml;
if (new_ml > OPTIMAL_ML) new_ml = OPTIMAL_ML;
if (ip+new_ml > start2 + ml2 - MINMATCH) new_ml = (int)(start2 - ip) + ml2 - MINMATCH;
correction = new_ml - (int)(start2 - ip);
if (correction > 0)
{
start2 += correction;
ref2 += correction;
ml2 -= correction;
}
}
/* Now, we have start2 = ip+new_ml, with new_ml = min(ml, OPTIMAL_ML=18) */
if (start2 + ml2 < mflimit)
ml3 = LZ4HC_InsertAndGetWiderMatch(ctx, start2 + ml2 - 3, start2, matchlimit, ml2, &ref3, &start3, maxNbAttempts);
else ml3 = ml2;
if (ml3 == ml2) /* No better match : 2 sequences to encode */
{
/* ip & ref are known; Now for ml */
if (start2 < ip+ml) ml = (int)(start2 - ip);
/* Now, encode 2 sequences */
if (LZ4HC_encodeSequence(&ip, &op, &anchor, ml, ref, limit, oend)) return 0;
ip = start2;
if (LZ4HC_encodeSequence(&ip, &op, &anchor, ml2, ref2, limit, oend)) return 0;
continue;
}
if (start3 < ip+ml+3) /* Not enough space for match 2 : remove it */
{
if (start3 >= (ip+ml)) /* can write Seq1 immediately ==> Seq2 is removed, so Seq3 becomes Seq1 */
{
if (start2 < ip+ml)
{
int correction = (int)(ip+ml - start2);
start2 += correction;
ref2 += correction;
ml2 -= correction;
if (ml2 < MINMATCH)
{
start2 = start3;
ref2 = ref3;
ml2 = ml3;
}
}
if (LZ4HC_encodeSequence(&ip, &op, &anchor, ml, ref, limit, oend)) return 0;
ip = start3;
ref = ref3;
ml = ml3;
start0 = start2;
ref0 = ref2;
ml0 = ml2;
goto _Search2;
}
start2 = start3;
ref2 = ref3;
ml2 = ml3;
goto _Search3;
}
/*
* OK, now we have 3 ascending matches; let's write at least the first one
* ip & ref are known; Now for ml
*/
if (start2 < ip+ml)
{
if ((start2 - ip) < (int)ML_MASK)
{
int correction;
if (ml > OPTIMAL_ML) ml = OPTIMAL_ML;
if (ip + ml > start2 + ml2 - MINMATCH) ml = (int)(start2 - ip) + ml2 - MINMATCH;
correction = ml - (int)(start2 - ip);
if (correction > 0)
{
start2 += correction;
ref2 += correction;
ml2 -= correction;
}
}
else
{
ml = (int)(start2 - ip);
}
}
if (LZ4HC_encodeSequence(&ip, &op, &anchor, ml, ref, limit, oend)) return 0;
ip = start2;
ref = ref2;
ml = ml2;
start2 = start3;
ref2 = ref3;
ml2 = ml3;
goto _Search3;
}
/* Encode Last Literals */
{
int lastRun = (int)(iend - anchor);
if ((limit) && (((char*)op - dest) + lastRun + 1 + ((lastRun+255-RUN_MASK)/255) > (U32)maxOutputSize)) return 0; /* Check output limit */
if (lastRun>=(int)RUN_MASK) { *op++=(RUN_MASK<<ML_BITS); lastRun-=RUN_MASK; for(; lastRun > 254 ; lastRun-=255) *op++ = 255; *op++ = (BYTE) lastRun; }
else *op++ = (BYTE)(lastRun<<ML_BITS);
memcpy(op, anchor, iend - anchor);
op += iend-anchor;
}
/* End */
return (int) (((char*)op)-dest);
}
int LZ4_compressHC2(const char* source, char* dest, int inputSize, int compressionLevel)
{
LZ4HC_Data_Structure ctx;
LZ4HC_init(&ctx, (const BYTE*)source);
return LZ4HC_compress_generic (&ctx, source, dest, inputSize, 0, compressionLevel, noLimit);
}
int LZ4_compressHC(const char* source, char* dest, int inputSize) { return LZ4_compressHC2(source, dest, inputSize, 0); }
int LZ4_compressHC2_limitedOutput(const char* source, char* dest, int inputSize, int maxOutputSize, int compressionLevel)
{
LZ4HC_Data_Structure ctx;
LZ4HC_init(&ctx, (const BYTE*)source);
return LZ4HC_compress_generic (&ctx, source, dest, inputSize, maxOutputSize, compressionLevel, limitedOutput);
}
int LZ4_compressHC_limitedOutput(const char* source, char* dest, int inputSize, int maxOutputSize)
{
return LZ4_compressHC2_limitedOutput(source, dest, inputSize, maxOutputSize, 0);
}
/*****************************
* Using external allocation
* ***************************/
int LZ4_sizeofStateHC(void) { return sizeof(LZ4HC_Data_Structure); }
int LZ4_compressHC2_withStateHC (void* state, const char* source, char* dest, int inputSize, int compressionLevel)
{
if (((size_t)(state)&(sizeof(void*)-1)) != 0) return 0; /* Error : state is not aligned for pointers (32 or 64 bits) */
LZ4HC_init ((LZ4HC_Data_Structure*)state, (const BYTE*)source);
return LZ4HC_compress_generic (state, source, dest, inputSize, 0, compressionLevel, noLimit);
}
int LZ4_compressHC_withStateHC (void* state, const char* source, char* dest, int inputSize)
{ return LZ4_compressHC2_withStateHC (state, source, dest, inputSize, 0); }
int LZ4_compressHC2_limitedOutput_withStateHC (void* state, const char* source, char* dest, int inputSize, int maxOutputSize, int compressionLevel)
{
if (((size_t)(state)&(sizeof(void*)-1)) != 0) return 0; /* Error : state is not aligned for pointers (32 or 64 bits) */
LZ4HC_init ((LZ4HC_Data_Structure*)state, (const BYTE*)source);
return LZ4HC_compress_generic (state, source, dest, inputSize, maxOutputSize, compressionLevel, limitedOutput);
}
int LZ4_compressHC_limitedOutput_withStateHC (void* state, const char* source, char* dest, int inputSize, int maxOutputSize)
{ return LZ4_compressHC2_limitedOutput_withStateHC (state, source, dest, inputSize, maxOutputSize, 0); }
/**************************************
* Streaming Functions
* ************************************/
/* allocation */
LZ4_streamHC_t* LZ4_createStreamHC(void) { return (LZ4_streamHC_t*)malloc(sizeof(LZ4_streamHC_t)); }
int LZ4_freeStreamHC (LZ4_streamHC_t* LZ4_streamHCPtr) { free(LZ4_streamHCPtr); return 0; }
/* initialization */
void LZ4_resetStreamHC (LZ4_streamHC_t* LZ4_streamHCPtr, int compressionLevel)
{
LZ4_STATIC_ASSERT(sizeof(LZ4HC_Data_Structure) <= LZ4_STREAMHCSIZE); /* if compilation fails here, LZ4_STREAMHCSIZE must be increased */
((LZ4HC_Data_Structure*)LZ4_streamHCPtr)->base = NULL;
((LZ4HC_Data_Structure*)LZ4_streamHCPtr)->compressionLevel = (unsigned)compressionLevel;
}
int LZ4_loadDictHC (LZ4_streamHC_t* LZ4_streamHCPtr, const char* dictionary, int dictSize)
{
LZ4HC_Data_Structure* ctxPtr = (LZ4HC_Data_Structure*) LZ4_streamHCPtr;
if (dictSize > 64 KB)
{
dictionary += dictSize - 64 KB;
dictSize = 64 KB;
}
LZ4HC_init (ctxPtr, (const BYTE*)dictionary);
if (dictSize >= 4) LZ4HC_Insert (ctxPtr, (const BYTE*)dictionary +(dictSize-3));
ctxPtr->end = (const BYTE*)dictionary + dictSize;
return dictSize;
}
/* compression */
static void LZ4HC_setExternalDict(LZ4HC_Data_Structure* ctxPtr, const BYTE* newBlock)
{
if (ctxPtr->end >= ctxPtr->base + 4)
LZ4HC_Insert (ctxPtr, ctxPtr->end-3); /* Referencing remaining dictionary content */
/* Only one memory segment for extDict, so any previous extDict is lost at this stage */
ctxPtr->lowLimit = ctxPtr->dictLimit;
ctxPtr->dictLimit = (U32)(ctxPtr->end - ctxPtr->base);
ctxPtr->dictBase = ctxPtr->base;
ctxPtr->base = newBlock - ctxPtr->dictLimit;
ctxPtr->end = newBlock;
ctxPtr->nextToUpdate = ctxPtr->dictLimit; /* match referencing will resume from there */
}
static int LZ4_compressHC_continue_generic (LZ4HC_Data_Structure* ctxPtr,
const char* source, char* dest,
int inputSize, int maxOutputSize, limitedOutput_directive limit)
{
/* auto-init if forgotten */
if (ctxPtr->base == NULL)
LZ4HC_init (ctxPtr, (const BYTE*) source);
/* Check overflow */
if ((size_t)(ctxPtr->end - ctxPtr->base) > 2 GB)
{
size_t dictSize = (size_t)(ctxPtr->end - ctxPtr->base) - ctxPtr->dictLimit;
if (dictSize > 64 KB) dictSize = 64 KB;
LZ4_loadDictHC((LZ4_streamHC_t*)ctxPtr, (const char*)(ctxPtr->end) - dictSize, (int)dictSize);
}
/* Check if blocks follow each other */
if ((const BYTE*)source != ctxPtr->end) LZ4HC_setExternalDict(ctxPtr, (const BYTE*)source);
/* Check overlapping input/dictionary space */
{
const BYTE* sourceEnd = (const BYTE*) source + inputSize;
const BYTE* dictBegin = ctxPtr->dictBase + ctxPtr->lowLimit;
const BYTE* dictEnd = ctxPtr->dictBase + ctxPtr->dictLimit;
if ((sourceEnd > dictBegin) && ((BYTE*)source < dictEnd))
{
if (sourceEnd > dictEnd) sourceEnd = dictEnd;
ctxPtr->lowLimit = (U32)(sourceEnd - ctxPtr->dictBase);
if (ctxPtr->dictLimit - ctxPtr->lowLimit < 4) ctxPtr->lowLimit = ctxPtr->dictLimit;
}
}
return LZ4HC_compress_generic (ctxPtr, source, dest, inputSize, maxOutputSize, ctxPtr->compressionLevel, limit);
}
int LZ4_compressHC_continue (LZ4_streamHC_t* LZ4_streamHCPtr, const char* source, char* dest, int inputSize)
{
return LZ4_compressHC_continue_generic ((LZ4HC_Data_Structure*)LZ4_streamHCPtr, source, dest, inputSize, 0, noLimit);
}
int LZ4_compressHC_limitedOutput_continue (LZ4_streamHC_t* LZ4_streamHCPtr, const char* source, char* dest, int inputSize, int maxOutputSize)
{
return LZ4_compressHC_continue_generic ((LZ4HC_Data_Structure*)LZ4_streamHCPtr, source, dest, inputSize, maxOutputSize, limitedOutput);
}
/* dictionary saving */
int LZ4_saveDictHC (LZ4_streamHC_t* LZ4_streamHCPtr, char* safeBuffer, int dictSize)
{
LZ4HC_Data_Structure* streamPtr = (LZ4HC_Data_Structure*)LZ4_streamHCPtr;
int prefixSize = (int)(streamPtr->end - (streamPtr->base + streamPtr->dictLimit));
if (dictSize > 64 KB) dictSize = 64 KB;
if (dictSize < 4) dictSize = 0;
if (dictSize > prefixSize) dictSize = prefixSize;
memcpy(safeBuffer, streamPtr->end - dictSize, dictSize);
{
U32 endIndex = (U32)(streamPtr->end - streamPtr->base);
streamPtr->end = (const BYTE*)safeBuffer + dictSize;
streamPtr->base = streamPtr->end - endIndex;
streamPtr->dictLimit = endIndex - dictSize;
streamPtr->lowLimit = endIndex - dictSize;
if (streamPtr->nextToUpdate < streamPtr->dictLimit) streamPtr->nextToUpdate = streamPtr->dictLimit;
}
return dictSize;
}
/***********************************
* Deprecated Functions
***********************************/
int LZ4_sizeofStreamStateHC(void) { return LZ4_STREAMHCSIZE; }
int LZ4_resetStreamStateHC(void* state, const char* inputBuffer)
{
if ((((size_t)state) & (sizeof(void*)-1)) != 0) return 1; /* Error : pointer is not aligned for pointer (32 or 64 bits) */
LZ4HC_init((LZ4HC_Data_Structure*)state, (const BYTE*)inputBuffer);
return 0;
}
void* LZ4_createHC (const char* inputBuffer)
{
void* hc4 = ALLOCATOR(1, sizeof(LZ4HC_Data_Structure));
LZ4HC_init ((LZ4HC_Data_Structure*)hc4, (const BYTE*)inputBuffer);
return hc4;
}
int LZ4_freeHC (void* LZ4HC_Data)
{
FREEMEM(LZ4HC_Data);
return (0);
}
/*
int LZ4_compressHC_continue (void* LZ4HC_Data, const char* source, char* dest, int inputSize)
{
return LZ4HC_compress_generic (LZ4HC_Data, source, dest, inputSize, 0, 0, noLimit);
}
int LZ4_compressHC_limitedOutput_continue (void* LZ4HC_Data, const char* source, char* dest, int inputSize, int maxOutputSize)
{
return LZ4HC_compress_generic (LZ4HC_Data, source, dest, inputSize, maxOutputSize, 0, limitedOutput);
}
*/
int LZ4_compressHC2_continue (void* LZ4HC_Data, const char* source, char* dest, int inputSize, int compressionLevel)
{
return LZ4HC_compress_generic (LZ4HC_Data, source, dest, inputSize, 0, compressionLevel, noLimit);
}
int LZ4_compressHC2_limitedOutput_continue (void* LZ4HC_Data, const char* source, char* dest, int inputSize, int maxOutputSize, int compressionLevel)
{
return LZ4HC_compress_generic (LZ4HC_Data, source, dest, inputSize, maxOutputSize, compressionLevel, limitedOutput);
}
char* LZ4_slideInputBufferHC(void* LZ4HC_Data)
{
LZ4HC_Data_Structure* hc4 = (LZ4HC_Data_Structure*)LZ4HC_Data;
int dictSize = LZ4_saveDictHC((LZ4_streamHC_t*)LZ4HC_Data, (char*)(hc4->inputBuffer), 64 KB);
return (char*)(hc4->inputBuffer + dictSize);
}
+174
View File
@@ -0,0 +1,174 @@
/*
LZ4 HC - High Compression Mode of LZ4
Header File
Copyright (C) 2011-2014, Yann Collet.
BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
You can contact the author at :
- LZ4 homepage : http://fastcompression.blogspot.com/p/lz4.html
- LZ4 source repository : http://code.google.com/p/lz4/
*/
#pragma once
#if defined (__cplusplus)
extern "C" {
#endif
int LZ4_compressHC (const char* source, char* dest, int inputSize);
/*
LZ4_compressHC :
return : the number of bytes in compressed buffer dest
or 0 if compression fails.
note : destination buffer must be already allocated.
To avoid any problem, size it to handle worst cases situations (input data not compressible)
Worst case size evaluation is provided by function LZ4_compressBound() (see "lz4.h")
*/
int LZ4_compressHC_limitedOutput (const char* source, char* dest, int inputSize, int maxOutputSize);
/*
LZ4_compress_limitedOutput() :
Compress 'inputSize' bytes from 'source' into an output buffer 'dest' of maximum size 'maxOutputSize'.
If it cannot achieve it, compression will stop, and result of the function will be zero.
This function never writes outside of provided output buffer.
inputSize : Max supported value is 1 GB
maxOutputSize : is maximum allowed size into the destination buffer (which must be already allocated)
return : the number of output bytes written in buffer 'dest'
or 0 if compression fails.
*/
int LZ4_compressHC2 (const char* source, char* dest, int inputSize, int compressionLevel);
int LZ4_compressHC2_limitedOutput (const char* source, char* dest, int inputSize, int maxOutputSize, int compressionLevel);
/*
Same functions as above, but with programmable 'compressionLevel'.
Recommended values are between 4 and 9, although any value between 0 and 16 will work.
'compressionLevel'==0 means use default 'compressionLevel' value.
Values above 16 behave the same as 16.
Equivalent variants exist for all other compression functions below.
*/
/* Note :
Decompression functions are provided within LZ4 source code (see "lz4.h") (BSD license)
*/
/**************************************
Using an external allocation
**************************************/
int LZ4_sizeofStateHC(void);
int LZ4_compressHC_withStateHC (void* state, const char* source, char* dest, int inputSize);
int LZ4_compressHC_limitedOutput_withStateHC (void* state, const char* source, char* dest, int inputSize, int maxOutputSize);
int LZ4_compressHC2_withStateHC (void* state, const char* source, char* dest, int inputSize, int compressionLevel);
int LZ4_compressHC2_limitedOutput_withStateHC(void* state, const char* source, char* dest, int inputSize, int maxOutputSize, int compressionLevel);
/*
These functions are provided should you prefer to allocate memory for compression tables with your own allocation methods.
To know how much memory must be allocated for the compression tables, use :
int LZ4_sizeofStateHC();
Note that tables must be aligned for pointer (32 or 64 bits), otherwise compression will fail (return code 0).
The allocated memory can be provided to the compression functions using 'void* state' parameter.
LZ4_compress_withStateHC() and LZ4_compress_limitedOutput_withStateHC() are equivalent to previously described functions.
They just use the externally allocated memory for state instead of allocating their own (on stack, or on heap).
*/
/**************************************
Experimental Streaming Functions
**************************************/
#define LZ4_STREAMHCSIZE_U64 32774
#define LZ4_STREAMHCSIZE (LZ4_STREAMHCSIZE_U64 * sizeof(unsigned long long))
typedef struct { unsigned long long table[LZ4_STREAMHCSIZE_U64]; } LZ4_streamHC_t;
/*
LZ4_streamHC_t
This structure allows static allocation of LZ4 HC streaming state.
State must then be initialized using LZ4_resetStreamHC() before first use.
Static allocation should only be used with statically linked library.
If you want to use LZ4 as a DLL, please use construction functions below, which are more future-proof.
*/
LZ4_streamHC_t* LZ4_createStreamHC(void);
int LZ4_freeStreamHC (LZ4_streamHC_t* LZ4_streamHCPtr);
/*
These functions create and release memory for LZ4 HC streaming state.
Newly created states are already initialized.
Existing state space can be re-used anytime using LZ4_resetStreamHC().
If you use LZ4 as a DLL, please use these functions instead of direct struct allocation,
to avoid size mismatch between different versions.
*/
void LZ4_resetStreamHC (LZ4_streamHC_t* LZ4_streamHCPtr, int compressionLevel);
int LZ4_loadDictHC (LZ4_streamHC_t* LZ4_streamHCPtr, const char* dictionary, int dictSize);
int LZ4_compressHC_continue (LZ4_streamHC_t* LZ4_streamHCPtr, const char* source, char* dest, int inputSize);
int LZ4_compressHC_limitedOutput_continue (LZ4_streamHC_t* LZ4_streamHCPtr, const char* source, char* dest, int inputSize, int maxOutputSize);
int LZ4_saveDictHC (LZ4_streamHC_t* LZ4_streamHCPtr, char* safeBuffer, int maxDictSize);
/*
These functions compress data in successive blocks of any size, using previous blocks as dictionary.
One key assumption is that each previous block will remain read-accessible while compressing next block.
Before starting compression, state must be properly initialized, using LZ4_resetStreamHC().
A first "fictional block" can then be designated as initial dictionary, using LZ4_loadDictHC() (Optional).
Then, use LZ4_compressHC_continue() or LZ4_compressHC_limitedOutput_continue() to compress each successive block.
They work like usual LZ4_compressHC() or LZ4_compressHC_limitedOutput(), but use previous memory blocks to improve compression.
Previous memory blocks (including initial dictionary when present) must remain accessible and unmodified during compression.
If, for any reason, previous data block can't be preserved in memory during next compression block,
you must save it to a safer memory space,
using LZ4_saveDictHC().
*/
/**************************************
* Deprecated Streaming Functions
* ************************************/
/* Note : these streaming functions follows the older model, and should no longer be used */
void* LZ4_createHC (const char* inputBuffer);
char* LZ4_slideInputBufferHC (void* LZ4HC_Data);
int LZ4_freeHC (void* LZ4HC_Data);
int LZ4_compressHC2_continue (void* LZ4HC_Data, const char* source, char* dest, int inputSize, int compressionLevel);
int LZ4_compressHC2_limitedOutput_continue (void* LZ4HC_Data, const char* source, char* dest, int inputSize, int maxOutputSize, int compressionLevel);
int LZ4_sizeofStreamStateHC(void);
int LZ4_resetStreamStateHC(void* state, const char* inputBuffer);
#if defined (__cplusplus)
}
#endif
+1 -1
View File
@@ -656,7 +656,7 @@ Image *Graphics::newImage(love::image::ImageData *data, const Image::Flags &flag
return new Image(data, flags);
}
Image *Graphics::newImage(love::image::CompressedData *cdata, const Image::Flags &flags)
Image *Graphics::newImage(love::image::CompressedImageData *cdata, const Image::Flags &flags)
{
return new Image(cdata, flags);
}
+1 -1
View File
@@ -158,7 +158,7 @@ public:
* Creates an Image object with padding and/or optimization.
**/
Image *newImage(love::image::ImageData *data, const Image::Flags &flags);
Image *newImage(love::image::CompressedData *cdata, const Image::Flags &flags);
Image *newImage(love::image::CompressedImageData *cdata, const Image::Flags &flags);
Quad *newQuad(Quad::Viewport v, float sw, float sh);
+50 -50
View File
@@ -59,7 +59,7 @@ Image::Image(love::image::ImageData *data, const Flags &flags)
++imageCount;
}
Image::Image(love::image::CompressedData *cdata, const Flags &flags)
Image::Image(love::image::CompressedImageData *cdata, const Flags &flags)
: data(nullptr)
, cdata(cdata)
, texture(0)
@@ -76,7 +76,7 @@ Image::Image(love::image::CompressedData *cdata, const Flags &flags)
if (flags.mipmaps)
{
// The mipmap texture data comes from the CompressedData in this case,
// The mipmap texture data comes from the CompressedImageData in this case,
// so we should make sure it has all necessary mipmap levels.
if (cdata->getMipmapCount() < (int) log2(std::max(width, height)) + 1)
throw love::Exception("Image cannot have mipmaps: compressed image data does not have all required mipmap levels.");
@@ -198,7 +198,7 @@ bool Image::loadVolatile()
if (isCompressed() && !hasCompressedTextureSupport(cdata->getFormat(), flags.sRGB))
{
const char *str;
if (image::CompressedData::getConstant(cdata->getFormat(), str))
if (image::CompressedImageData::getConstant(cdata->getFormat(), str))
{
throw love::Exception("Cannot create image: "
"%s%s compressed images are not supported on this system.", flags.sRGB ? "sRGB " : "", str);
@@ -392,7 +392,7 @@ love::image::ImageData *Image::getImageData() const
return data.get();
}
love::image::CompressedData *Image::getCompressedData() const
love::image::CompressedImageData *Image::getCompressedData() const
{
return cdata.get();
}
@@ -491,87 +491,87 @@ bool Image::isCompressed() const
return compressed;
}
GLenum Image::getCompressedFormat(image::CompressedData::Format cformat) const
GLenum Image::getCompressedFormat(image::CompressedImageData::Format cformat) const
{
switch (cformat)
{
case image::CompressedData::FORMAT_DXT1:
case image::CompressedImageData::FORMAT_DXT1:
if (flags.sRGB)
return GL_COMPRESSED_SRGB_S3TC_DXT1_EXT;
else
return GL_COMPRESSED_RGB_S3TC_DXT1_EXT;
case image::CompressedData::FORMAT_DXT3:
case image::CompressedImageData::FORMAT_DXT3:
if (flags.sRGB)
return GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
else
return GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
case image::CompressedData::FORMAT_DXT5:
case image::CompressedImageData::FORMAT_DXT5:
if (flags.sRGB)
return GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
else
return GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
case image::CompressedData::FORMAT_BC4:
case image::CompressedImageData::FORMAT_BC4:
return GL_COMPRESSED_RED_RGTC1;
case image::CompressedData::FORMAT_BC4s:
case image::CompressedImageData::FORMAT_BC4s:
return GL_COMPRESSED_SIGNED_RED_RGTC1;
case image::CompressedData::FORMAT_BC5:
case image::CompressedImageData::FORMAT_BC5:
return GL_COMPRESSED_RG_RGTC2;
case image::CompressedData::FORMAT_BC5s:
case image::CompressedImageData::FORMAT_BC5s:
return GL_COMPRESSED_SIGNED_RG_RGTC2;
case image::CompressedData::FORMAT_BC6H:
case image::CompressedImageData::FORMAT_BC6H:
return GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT;
case image::CompressedData::FORMAT_BC6Hs:
case image::CompressedImageData::FORMAT_BC6Hs:
return GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT;
case image::CompressedData::FORMAT_BC7:
case image::CompressedImageData::FORMAT_BC7:
if (flags.sRGB)
return GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM;
else
return GL_COMPRESSED_RGBA_BPTC_UNORM;
case image::CompressedData::FORMAT_ETC1:
case image::CompressedImageData::FORMAT_ETC1:
// The ETC2 format can load ETC1 textures.
if (GLAD_ES_VERSION_3_0 || GLAD_VERSION_4_3 || GLAD_ARB_ES3_compatibility)
return GL_COMPRESSED_RGB8_ETC2;
else
return GL_ETC1_RGB8_OES;
case image::CompressedData::FORMAT_ETC2_RGB:
case image::CompressedImageData::FORMAT_ETC2_RGB:
if (flags.sRGB)
return GL_COMPRESSED_SRGB8_ETC2;
else
return GL_COMPRESSED_RGB8_ETC2;
case image::CompressedData::FORMAT_ETC2_RGBA:
case image::CompressedImageData::FORMAT_ETC2_RGBA:
if (flags.sRGB)
return GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC;
else
return GL_COMPRESSED_RGBA8_ETC2_EAC;
case image::CompressedData::FORMAT_ETC2_RGBA1:
case image::CompressedImageData::FORMAT_ETC2_RGBA1:
if (flags.sRGB)
return GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2;
else
return GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2;
case image::CompressedData::FORMAT_EAC_R:
case image::CompressedImageData::FORMAT_EAC_R:
return GL_COMPRESSED_R11_EAC;
case image::CompressedData::FORMAT_EAC_Rs:
case image::CompressedImageData::FORMAT_EAC_Rs:
return GL_COMPRESSED_SIGNED_R11_EAC;
case image::CompressedData::FORMAT_EAC_RG:
case image::CompressedImageData::FORMAT_EAC_RG:
return GL_COMPRESSED_RG11_EAC;
case image::CompressedData::FORMAT_EAC_RGs:
case image::CompressedImageData::FORMAT_EAC_RGs:
return GL_COMPRESSED_SIGNED_RG11_EAC;
case image::CompressedData::FORMAT_PVR1_RGB2:
case image::CompressedImageData::FORMAT_PVR1_RGB2:
if (flags.sRGB)
return GL_COMPRESSED_SRGB_PVRTC_2BPPV1_EXT;
else
return GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
case image::CompressedData::FORMAT_PVR1_RGB4:
case image::CompressedImageData::FORMAT_PVR1_RGB4:
if (flags.sRGB)
return GL_COMPRESSED_SRGB_PVRTC_4BPPV1_EXT;
else
return GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
case image::CompressedData::FORMAT_PVR1_RGBA2:
case image::CompressedImageData::FORMAT_PVR1_RGBA2:
if (flags.sRGB)
return GL_COMPRESSED_SRGB_ALPHA_PVRTC_2BPPV1_EXT;
else
return GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
case image::CompressedData::FORMAT_PVR1_RGBA4:
case image::CompressedImageData::FORMAT_PVR1_RGBA4:
if (flags.sRGB)
return GL_COMPRESSED_SRGB_ALPHA_PVRTC_4BPPV1_EXT;
else
@@ -589,40 +589,40 @@ bool Image::hasAnisotropicFilteringSupport()
return GLAD_EXT_texture_filter_anisotropic;
}
bool Image::hasCompressedTextureSupport(image::CompressedData::Format format, bool sRGB)
bool Image::hasCompressedTextureSupport(image::CompressedImageData::Format format, bool sRGB)
{
switch (format)
{
case image::CompressedData::FORMAT_DXT1:
case image::CompressedImageData::FORMAT_DXT1:
return GLAD_EXT_texture_compression_s3tc || GLAD_EXT_texture_compression_dxt1;
case image::CompressedData::FORMAT_DXT3:
case image::CompressedImageData::FORMAT_DXT3:
return GLAD_EXT_texture_compression_s3tc || GLAD_ANGLE_texture_compression_dxt3;
case image::CompressedData::FORMAT_DXT5:
case image::CompressedImageData::FORMAT_DXT5:
return GLAD_EXT_texture_compression_s3tc || GLAD_ANGLE_texture_compression_dxt5;
case image::CompressedData::FORMAT_BC4:
case image::CompressedData::FORMAT_BC4s:
case image::CompressedData::FORMAT_BC5:
case image::CompressedData::FORMAT_BC5s:
case image::CompressedImageData::FORMAT_BC4:
case image::CompressedImageData::FORMAT_BC4s:
case image::CompressedImageData::FORMAT_BC5:
case image::CompressedImageData::FORMAT_BC5s:
return (GLAD_VERSION_3_0 || GLAD_ARB_texture_compression_rgtc || GLAD_EXT_texture_compression_rgtc);
case image::CompressedData::FORMAT_BC6H:
case image::CompressedData::FORMAT_BC6Hs:
case image::CompressedData::FORMAT_BC7:
case image::CompressedImageData::FORMAT_BC6H:
case image::CompressedImageData::FORMAT_BC6Hs:
case image::CompressedImageData::FORMAT_BC7:
return GLAD_VERSION_4_2 || GLAD_ARB_texture_compression_bptc;
case image::CompressedData::FORMAT_ETC1:
case image::CompressedImageData::FORMAT_ETC1:
// ETC2 support guarantees ETC1 support as well.
return GLAD_ES_VERSION_3_0 || GLAD_VERSION_4_3 || GLAD_ARB_ES3_compatibility || GLAD_OES_compressed_ETC1_RGB8_texture;
case image::CompressedData::FORMAT_ETC2_RGB:
case image::CompressedData::FORMAT_ETC2_RGBA:
case image::CompressedData::FORMAT_ETC2_RGBA1:
case image::CompressedData::FORMAT_EAC_R:
case image::CompressedData::FORMAT_EAC_Rs:
case image::CompressedData::FORMAT_EAC_RG:
case image::CompressedData::FORMAT_EAC_RGs:
case image::CompressedImageData::FORMAT_ETC2_RGB:
case image::CompressedImageData::FORMAT_ETC2_RGBA:
case image::CompressedImageData::FORMAT_ETC2_RGBA1:
case image::CompressedImageData::FORMAT_EAC_R:
case image::CompressedImageData::FORMAT_EAC_Rs:
case image::CompressedImageData::FORMAT_EAC_RG:
case image::CompressedImageData::FORMAT_EAC_RGs:
return GLAD_ES_VERSION_3_0 || GLAD_VERSION_4_3 || GLAD_ARB_ES3_compatibility;
case image::CompressedData::FORMAT_PVR1_RGB2:
case image::CompressedData::FORMAT_PVR1_RGB4:
case image::CompressedData::FORMAT_PVR1_RGBA2:
case image::CompressedData::FORMAT_PVR1_RGBA4:
case image::CompressedImageData::FORMAT_PVR1_RGB2:
case image::CompressedImageData::FORMAT_PVR1_RGB4:
case image::CompressedImageData::FORMAT_PVR1_RGBA2:
case image::CompressedImageData::FORMAT_PVR1_RGBA4:
if (sRGB)
return GLAD_EXT_pvrtc_sRGB;
else
+8 -8
View File
@@ -28,7 +28,7 @@
#include "common/StringMap.h"
#include "common/math.h"
#include "image/ImageData.h"
#include "image/CompressedData.h"
#include "image/CompressedImageData.h"
#include "graphics/Texture.h"
#include "graphics/Volatile.h"
@@ -78,7 +78,7 @@ public:
*
* @param cdata The compressed data from which to load the image.
**/
Image(love::image::CompressedData *cdata, const Flags &flags);
Image(love::image::CompressedImageData *cdata, const Flags &flags);
virtual ~Image();
@@ -99,7 +99,7 @@ public:
virtual const void *getHandle() const;
love::image::ImageData *getImageData() const;
love::image::CompressedData *getCompressedData() const;
love::image::CompressedImageData *getCompressedData() const;
virtual void setFilter(const Texture::Filter &f);
virtual bool setWrap(const Texture::Wrap &w);
@@ -108,12 +108,12 @@ public:
float getMipmapSharpness() const;
/**
* Whether this Image is using a compressed texture (via CompressedData).
* Whether this Image is using a compressed texture (via CompressedImageData).
**/
bool isCompressed() const;
/**
* Re-uploads the ImageData or CompressedData associated with this Image to
* Re-uploads the ImageData or CompressedImageData associated with this Image to
* the GPU.
**/
bool refresh(int xoffset, int yoffset, int w, int h);
@@ -126,7 +126,7 @@ public:
static FilterMode getDefaultMipmapFilter();
static bool hasAnisotropicFilteringSupport();
static bool hasCompressedTextureSupport(image::CompressedData::Format format, bool sRGB);
static bool hasCompressedTextureSupport(image::CompressedImageData::Format format, bool sRGB);
static bool hasSRGBSupport();
static bool getConstant(const char *in, FlagType &out);
@@ -145,7 +145,7 @@ private:
void loadFromCompressedData();
void loadFromImageData();
GLenum getCompressedFormat(image::CompressedData::Format cformat) const;
GLenum getCompressedFormat(image::CompressedImageData::Format cformat) const;
// The ImageData from which the texture is created. May be null if
// Compressed image data was used to create the texture.
@@ -153,7 +153,7 @@ private:
// Or the Compressed Image Data from which the texture is created. May be
// null if raw ImageData was used to create the texture.
StrongRef<love::image::CompressedData> cdata;
StrongRef<love::image::CompressedImageData> cdata;
// OpenGL texture identifier.
GLuint texture;
@@ -231,7 +231,7 @@ static const char *imageFlagName(Image::FlagType flagtype)
int w_newImage(lua_State *L)
{
love::image::ImageData *data = nullptr;
love::image::CompressedData *cdata = nullptr;
love::image::CompressedImageData *cdata = nullptr;
Image::Flags flags;
if (!lua_isnoneornil(L, 2))
@@ -243,7 +243,7 @@ int w_newImage(lua_State *L)
bool releasedata = false;
// Convert to ImageData / CompressedData, if necessary.
// Convert to ImageData / CompressedImageData, if necessary.
if (lua_isstring(L, 1) || luax_istype(L, 1, FILESYSTEM_FILE_ID) || luax_istype(L, 1, FILESYSTEM_FILE_DATA_ID))
{
love::image::Image *image = Module::getInstance<love::image::Image>(Module::M_IMAGE);
@@ -270,8 +270,8 @@ int w_newImage(lua_State *L)
// Lua's GC won't release the image data, so we should do it ourselves.
releasedata = true;
}
else if (luax_istype(L, 1, IMAGE_COMPRESSED_DATA_ID))
cdata = luax_checktype<love::image::CompressedData>(L, 1, IMAGE_COMPRESSED_DATA_ID);
else if (luax_istype(L, 1, IMAGE_COMPRESSED_IMAGE_DATA_ID))
cdata = luax_checktype<love::image::CompressedImageData>(L, 1, IMAGE_COMPRESSED_IMAGE_DATA_ID);
else
data = luax_checktype<love::image::ImageData>(L, 1, IMAGE_IMAGE_DATA_ID);
@@ -1125,17 +1125,17 @@ int w_getCanvasFormats(lua_State *L)
int w_getCompressedImageFormats(lua_State *L)
{
lua_createtable(L, 0, (int) image::CompressedData::FORMAT_MAX_ENUM);
lua_createtable(L, 0, (int) image::CompressedImageData::FORMAT_MAX_ENUM);
for (int i = 0; i < (int) image::CompressedData::FORMAT_MAX_ENUM; i++)
for (int i = 0; i < (int) image::CompressedImageData::FORMAT_MAX_ENUM; i++)
{
image::CompressedData::Format format = (image::CompressedData::Format) i;
image::CompressedImageData::Format format = (image::CompressedImageData::Format) i;
const char *name = nullptr;
if (format == image::CompressedData::FORMAT_UNKNOWN)
if (format == image::CompressedImageData::FORMAT_UNKNOWN)
continue;
if (!image::CompressedData::getConstant(format, name))
if (!image::CompressedImageData::getConstant(format, name))
continue;
luax_pushboolean(L, Image::hasCompressedTextureSupport(format, false));
+1 -1
View File
@@ -94,7 +94,7 @@ int w_Image_getData(lua_State *L)
Image *i = luax_checkimage(L, 1);
if (i->isCompressed())
luax_pushtype(L, IMAGE_COMPRESSED_DATA_ID, i->getCompressedData());
luax_pushtype(L, IMAGE_COMPRESSED_IMAGE_DATA_ID, i->getCompressedData());
else
luax_pushtype(L, IMAGE_IMAGE_DATA_ID, i->getImageData());
-139
View File
@@ -1,139 +0,0 @@
/**
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
#include "CompressedData.h"
namespace love
{
namespace image
{
CompressedData::CompressedData()
: format(FORMAT_UNKNOWN)
, sRGB(false)
, data(nullptr)
, dataSize(0)
{
}
CompressedData::~CompressedData()
{
}
size_t CompressedData::getSize() const
{
return dataSize;
}
void *CompressedData::getData() const
{
return data;
}
int CompressedData::getMipmapCount() const
{
return (int) dataImages.size();
}
size_t CompressedData::getSize(int miplevel) const
{
checkMipmapLevelExists(miplevel);
return dataImages[miplevel].size;
}
void *CompressedData::getData(int miplevel) const
{
checkMipmapLevelExists(miplevel);
return &dataImages[miplevel].data[0];
}
int CompressedData::getWidth(int miplevel) const
{
checkMipmapLevelExists(miplevel);
return dataImages[miplevel].width;
}
int CompressedData::getHeight(int miplevel) const
{
checkMipmapLevelExists(miplevel);
return dataImages[miplevel].height;
}
CompressedData::Format CompressedData::getFormat() const
{
return format;
}
bool CompressedData::isSRGB() const
{
return sRGB;
}
void CompressedData::checkMipmapLevelExists(int miplevel) const
{
if (miplevel < 0 || miplevel >= (int) dataImages.size())
throw love::Exception("Mipmap level %d does not exist", miplevel + 1);
}
bool CompressedData::getConstant(const char *in, CompressedData::Format &out)
{
return formats.find(in, out);
}
bool CompressedData::getConstant(CompressedData::Format in, const char *&out)
{
return formats.find(in, out);
}
StringMap<CompressedData::Format, CompressedData::FORMAT_MAX_ENUM>::Entry CompressedData::formatEntries[] =
{
{"unknown", CompressedData::FORMAT_UNKNOWN},
{"DXT1", CompressedData::FORMAT_DXT1},
{"DXT3", CompressedData::FORMAT_DXT3},
{"DXT5", CompressedData::FORMAT_DXT5},
{"BC4", CompressedData::FORMAT_BC4},
{"BC4s", CompressedData::FORMAT_BC4s},
{"BC5", CompressedData::FORMAT_BC5},
{"BC5s", CompressedData::FORMAT_BC5s},
{"BC6h", CompressedData::FORMAT_BC6H},
{"BC6hs", CompressedData::FORMAT_BC6Hs},
{"BC7", CompressedData::FORMAT_BC7},
{"ETC1", CompressedData::FORMAT_ETC1},
{"ETC2rgb", CompressedData::FORMAT_ETC2_RGB},
{"ETC2rgba", CompressedData::FORMAT_ETC2_RGBA},
{"ETC2rgba1", CompressedData::FORMAT_ETC2_RGBA1},
{"EACr", CompressedData::FORMAT_EAC_R},
{"EACrs", CompressedData::FORMAT_EAC_Rs},
{"EACrg", CompressedData::FORMAT_EAC_RG},
{"EACrgs", CompressedData::FORMAT_EAC_RGs},
{"PVR1rgb2", CompressedData::FORMAT_PVR1_RGB2},
{"PVR1rgb4", CompressedData::FORMAT_PVR1_RGB4},
{"PVR1rgba2", CompressedData::FORMAT_PVR1_RGBA2},
{"PVR1rgba4", CompressedData::FORMAT_PVR1_RGBA4},
};
StringMap<CompressedData::Format, CompressedData::FORMAT_MAX_ENUM> CompressedData::formats(CompressedData::formatEntries, sizeof(CompressedData::formatEntries));
} // image
} // love
+139
View File
@@ -0,0 +1,139 @@
/**
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
#include "CompressedImageData.h"
namespace love
{
namespace image
{
CompressedImageData::CompressedImageData()
: format(FORMAT_UNKNOWN)
, sRGB(false)
, data(nullptr)
, dataSize(0)
{
}
CompressedImageData::~CompressedImageData()
{
}
size_t CompressedImageData::getSize() const
{
return dataSize;
}
void *CompressedImageData::getData() const
{
return data;
}
int CompressedImageData::getMipmapCount() const
{
return (int) dataImages.size();
}
size_t CompressedImageData::getSize(int miplevel) const
{
checkMipmapLevelExists(miplevel);
return dataImages[miplevel].size;
}
void *CompressedImageData::getData(int miplevel) const
{
checkMipmapLevelExists(miplevel);
return &dataImages[miplevel].data[0];
}
int CompressedImageData::getWidth(int miplevel) const
{
checkMipmapLevelExists(miplevel);
return dataImages[miplevel].width;
}
int CompressedImageData::getHeight(int miplevel) const
{
checkMipmapLevelExists(miplevel);
return dataImages[miplevel].height;
}
CompressedImageData::Format CompressedImageData::getFormat() const
{
return format;
}
bool CompressedImageData::isSRGB() const
{
return sRGB;
}
void CompressedImageData::checkMipmapLevelExists(int miplevel) const
{
if (miplevel < 0 || miplevel >= (int) dataImages.size())
throw love::Exception("Mipmap level %d does not exist", miplevel + 1);
}
bool CompressedImageData::getConstant(const char *in, CompressedImageData::Format &out)
{
return formats.find(in, out);
}
bool CompressedImageData::getConstant(CompressedImageData::Format in, const char *&out)
{
return formats.find(in, out);
}
StringMap<CompressedImageData::Format, CompressedImageData::FORMAT_MAX_ENUM>::Entry CompressedImageData::formatEntries[] =
{
{"unknown", FORMAT_UNKNOWN},
{"DXT1", FORMAT_DXT1},
{"DXT3", FORMAT_DXT3},
{"DXT5", FORMAT_DXT5},
{"BC4", FORMAT_BC4},
{"BC4s", FORMAT_BC4s},
{"BC5", FORMAT_BC5},
{"BC5s", FORMAT_BC5s},
{"BC6h", FORMAT_BC6H},
{"BC6hs", FORMAT_BC6Hs},
{"BC7", FORMAT_BC7},
{"ETC1", FORMAT_ETC1},
{"ETC2rgb", FORMAT_ETC2_RGB},
{"ETC2rgba", FORMAT_ETC2_RGBA},
{"ETC2rgba1", FORMAT_ETC2_RGBA1},
{"EACr", FORMAT_EAC_R},
{"EACrs", FORMAT_EAC_Rs},
{"EACrg", FORMAT_EAC_RG},
{"EACrgs", FORMAT_EAC_RGs},
{"PVR1rgb2", FORMAT_PVR1_RGB2},
{"PVR1rgb4", FORMAT_PVR1_RGB4},
{"PVR1rgba2", FORMAT_PVR1_RGBA2},
{"PVR1rgba4", FORMAT_PVR1_RGBA4},
};
StringMap<CompressedImageData::Format, CompressedImageData::FORMAT_MAX_ENUM> CompressedImageData::formats(CompressedImageData::formatEntries, sizeof(CompressedImageData::formatEntries));
} // image
} // love
@@ -18,8 +18,8 @@
* 3. This notice may not be removed or altered from any source distribution.
**/
#ifndef LOVE_IMAGE_COMPRESSED_DATA_H
#define LOVE_IMAGE_COMPRESSED_DATA_H
#ifndef LOVE_IMAGE_COMPRESSED_IMAGE_DATA_H
#define LOVE_IMAGE_COMPRESSED_IMAGE_DATA_H
// LOVE
#include "common/Data.h"
@@ -35,11 +35,11 @@ namespace image
{
/**
* CompressedData represents image data which is designed to be uploaded to the
* GPU and rendered in its compressed form, without being un-compressed.
* CompressedImageData represents image data which is designed to be uploaded to
* the GPU and rendered in its compressed form, without being decompressed.
* http://renderingpipeline.com/2012/07/texture-compression/
**/
class CompressedData : public Data
class CompressedImageData : public Data
{
public:
@@ -81,8 +81,8 @@ public:
uint8 *data; // Should not have ownership of the data.
};
CompressedData();
virtual ~CompressedData();
CompressedImageData();
virtual ~CompressedImageData();
// Implements Data.
virtual void *getData() const;
@@ -144,9 +144,9 @@ private:
static StringMap<Format, FORMAT_MAX_ENUM>::Entry formatEntries[];
static StringMap<Format, FORMAT_MAX_ENUM> formats;
}; // CompressedData
}; // CompressedImageData
} // image
} // love
#endif // LOVE_IMAGE_COMPRESSED_DATA_H
#endif // LOVE_IMAGE_COMPRESSED_IMAGE_DATA_H
+4 -4
View File
@@ -26,7 +26,7 @@
#include "common/Module.h"
#include "filesystem/File.h"
#include "ImageData.h"
#include "CompressedData.h"
#include "CompressedImageData.h"
namespace love
{
@@ -76,11 +76,11 @@ public:
virtual ImageData *newImageData(int width, int height, void *data, bool own = false) = 0;
/**
* Creates new CompressedData from FileData.
* Creates new CompressedImageData from FileData.
* @param data The FileData containing the compressed image data.
* @return The new CompressedData.
* @return The new CompressedImageData.
**/
virtual CompressedData *newCompressedData(love::filesystem::FileData *data) = 0;
virtual CompressedImageData *newCompressedData(love::filesystem::FileData *data) = 0;
/**
* Determines whether a FileData is Compressed image data or not.
@@ -23,7 +23,7 @@
// LOVE
#include "filesystem/FileData.h"
#include "image/CompressedData.h"
#include "image/CompressedImageData.h"
#include "common/Object.h"
namespace love
@@ -34,7 +34,7 @@ namespace magpie
{
/**
* Base class for all CompressedData parser library interfaces.
* Base class for all CompressedImageData parser library interfaces.
* We inherit from love::Object to take advantage of reference counting...
**/
class CompressedFormatHandler : public love::Object
@@ -45,7 +45,7 @@ public:
virtual ~CompressedFormatHandler() {}
/**
* Determines whether a particular FileData can be parsed as CompressedData
* Determines whether a particular FileData can be parsed as CompressedImageData
* by this handler.
* @param data The data to parse.
**/
@@ -64,8 +64,8 @@ public:
*
* @return The single block of memory containing the parsed images.
**/
virtual uint8 *parse(filesystem::FileData *filedata, std::vector<CompressedData::SubImage> &images,
size_t &dataSize, CompressedData::Format &format, bool &sRGB) = 0;
virtual uint8 *parse(filesystem::FileData *filedata, std::vector<CompressedImageData::SubImage> &images,
size_t &dataSize, CompressedImageData::Format &format, bool &sRGB) = 0;
}; // CompressedFormatHandler
@@ -18,7 +18,7 @@
* 3. This notice may not be removed or altered from any source distribution.
**/
#include "CompressedData.h"
#include "CompressedImageData.h"
namespace love
{
@@ -27,7 +27,7 @@ namespace image
namespace magpie
{
CompressedData::CompressedData(std::list<CompressedFormatHandler *> formats, love::filesystem::FileData *filedata)
CompressedImageData::CompressedImageData(std::list<CompressedFormatHandler *> formats, love::filesystem::FileData *filedata)
{
CompressedFormatHandler *parser = nullptr;
@@ -61,7 +61,7 @@ CompressedData::CompressedData(std::list<CompressedFormatHandler *> formats, lov
}
}
CompressedData::~CompressedData()
CompressedImageData::~CompressedImageData()
{
delete[] data;
}
@@ -18,13 +18,13 @@
* 3. This notice may not be removed or altered from any source distribution.
**/
#ifndef LOVE_IMAGE_MAGPIE_COMPRESSED_DATA_H
#define LOVE_IMAGE_MAGPIE_COMPRESSED_DATA_H
#ifndef LOVE_IMAGE_MAGPIE_COMPRESSED_IMAGE_DATA_H
#define LOVE_IMAGE_MAGPIE_COMPRESSED_IMAGE_DATA_H
// LOVE
#include "CompressedFormatHandler.h"
#include "filesystem/FileData.h"
#include "image/CompressedData.h"
#include "image/CompressedImageData.h"
// C++
#include <list>
@@ -36,17 +36,17 @@ namespace image
namespace magpie
{
class CompressedData : public love::image::CompressedData
class CompressedImageData : public love::image::CompressedImageData
{
public:
CompressedData(std::list<CompressedFormatHandler *> formats, love::filesystem::FileData *filedata);
virtual ~CompressedData();
CompressedImageData(std::list<CompressedFormatHandler *> formats, love::filesystem::FileData *filedata);
virtual ~CompressedImageData();
}; // CompressedData
}; // CompressedImageData
} // magpie
} // image
} // love
#endif // LOVE_IMAGE_MAGPIE_COMPRESSED_DATA_H
#endif // LOVE_IMAGE_MAGPIE_COMPRESSED_IMAGE_DATA_H
+3 -3
View File
@@ -21,7 +21,7 @@
#include "Image.h"
#include "ImageData.h"
#include "CompressedData.h"
#include "CompressedImageData.h"
#include "JPEGHandler.h"
#include "PNGHandler.h"
@@ -91,9 +91,9 @@ love::image::ImageData *Image::newImageData(int width, int height, void *data, b
return new ImageData(formatHandlers, width, height, data, own);
}
love::image::CompressedData *Image::newCompressedData(love::filesystem::FileData *data)
love::image::CompressedImageData *Image::newCompressedData(love::filesystem::FileData *data)
{
return new CompressedData(compressedFormatHandlers, data);
return new CompressedImageData(compressedFormatHandlers, data);
}
bool Image::isCompressed(love::filesystem::FileData *data)
+2 -2
View File
@@ -55,7 +55,7 @@ public:
love::image::ImageData *newImageData(int width, int height);
love::image::ImageData *newImageData(int width, int height, void *data, bool own = false);
love::image::CompressedData *newCompressedData(love::filesystem::FileData *data);
love::image::CompressedImageData *newCompressedData(love::filesystem::FileData *data);
bool isCompressed(love::filesystem::FileData *data);
@@ -64,7 +64,7 @@ private:
// Image format handlers we can use for decoding and encoding ImageData.
std::list<FormatHandler *> formatHandlers;
// Compressed image format handers we can use for parsing CompressedData.
// Compressed image format handers we can use for parsing CompressedImageData.
std::list<CompressedFormatHandler *> compressedFormatHandlers;
}; // Image
+24 -24
View File
@@ -90,53 +90,53 @@ enum KTXGLInternalFormat
KTX_GL_COMPRESSED_RGBA_S3TC_DXT5_EXT = 0x83F3
};
CompressedData::Format convertFormat(uint32 glformat, bool &sRGB)
CompressedImageData::Format convertFormat(uint32 glformat, bool &sRGB)
{
sRGB = false;
switch (glformat)
{
case KTX_GL_ETC1_RGB8_OES:
return CompressedData::FORMAT_ETC1;
return CompressedImageData::FORMAT_ETC1;
case KTX_GL_COMPRESSED_R11_EAC:
return CompressedData::FORMAT_EAC_R;
return CompressedImageData::FORMAT_EAC_R;
case KTX_GL_COMPRESSED_SIGNED_R11_EAC:
return CompressedData::FORMAT_EAC_Rs;
return CompressedImageData::FORMAT_EAC_Rs;
case KTX_GL_COMPRESSED_RG11_EAC:
return CompressedData::FORMAT_EAC_RG;
return CompressedImageData::FORMAT_EAC_RG;
case KTX_GL_COMPRESSED_SIGNED_RG11_EAC:
return CompressedData::FORMAT_EAC_RGs;
return CompressedImageData::FORMAT_EAC_RGs;
case KTX_GL_COMPRESSED_RGB8_ETC2:
return CompressedData::FORMAT_ETC2_RGB;
return CompressedImageData::FORMAT_ETC2_RGB;
case KTX_GL_COMPRESSED_SRGB8_ETC2:
sRGB = true;
return CompressedData::FORMAT_ETC2_RGB;
return CompressedImageData::FORMAT_ETC2_RGB;
case KTX_GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2:
return CompressedData::FORMAT_ETC2_RGBA1;
return CompressedImageData::FORMAT_ETC2_RGBA1;
case KTX_GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2:
sRGB = true;
return CompressedData::FORMAT_ETC2_RGBA1;
return CompressedImageData::FORMAT_ETC2_RGBA1;
case KTX_GL_COMPRESSED_RGBA8_ETC2_EAC:
return CompressedData::FORMAT_ETC2_RGBA;
return CompressedImageData::FORMAT_ETC2_RGBA;
case KTX_GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:
sRGB = true;
return CompressedData::FORMAT_ETC2_RGBA;
return CompressedImageData::FORMAT_ETC2_RGBA;
case KTX_GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG:
return CompressedData::FORMAT_PVR1_RGB4;
return CompressedImageData::FORMAT_PVR1_RGB4;
case KTX_GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG:
return CompressedData::FORMAT_PVR1_RGB2;
return CompressedImageData::FORMAT_PVR1_RGB2;
case KTX_GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG:
return CompressedData::FORMAT_PVR1_RGBA4;
return CompressedImageData::FORMAT_PVR1_RGBA4;
case KTX_GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG:
return CompressedData::FORMAT_PVR1_RGBA2;
return CompressedImageData::FORMAT_PVR1_RGBA2;
case KTX_GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
return CompressedData::FORMAT_DXT1;
return CompressedImageData::FORMAT_DXT1;
case KTX_GL_COMPRESSED_RGBA_S3TC_DXT3_EXT:
return CompressedData::FORMAT_DXT3;
return CompressedImageData::FORMAT_DXT3;
case KTX_GL_COMPRESSED_RGBA_S3TC_DXT5_EXT:
return CompressedData::FORMAT_DXT5;
return CompressedImageData::FORMAT_DXT5;
default:
return CompressedData::FORMAT_UNKNOWN;
return CompressedImageData::FORMAT_UNKNOWN;
}
}
@@ -159,7 +159,7 @@ bool KTXHandler::canParse(const filesystem::FileData *data)
return true;
}
uint8 *KTXHandler::parse(filesystem::FileData *filedata, std::vector<CompressedData::SubImage> &images, size_t &dataSize, CompressedData::Format &format, bool &sRGB)
uint8 *KTXHandler::parse(filesystem::FileData *filedata, std::vector<CompressedImageData::SubImage> &images, size_t &dataSize, CompressedImageData::Format &format, bool &sRGB)
{
if (!canParse(filedata))
throw love::Exception("Could not decode compressed data (not a KTX file?)");
@@ -176,9 +176,9 @@ uint8 *KTXHandler::parse(filesystem::FileData *filedata, std::vector<CompressedD
header.numberOfMipmapLevels = std::max(header.numberOfMipmapLevels, 1u);
bool isSRGB = false;
CompressedData::Format cformat = convertFormat(header.glInternalFormat, isSRGB);
CompressedImageData::Format cformat = convertFormat(header.glInternalFormat, isSRGB);
if (cformat == CompressedData::FORMAT_UNKNOWN)
if (cformat == CompressedImageData::FORMAT_UNKNOWN)
throw love::Exception("Unsupported image format in KTX file.");
if (header.numberOfArrayElements > 0)
@@ -241,7 +241,7 @@ uint8 *KTXHandler::parse(filesystem::FileData *filedata, std::vector<CompressedD
uint32 mipsizepadded = (mipsize + 3) & ~uint32(3);
CompressedData::SubImage mip;
CompressedImageData::SubImage mip;
mip.width = (int) std::max(header.pixelWidth >> i, 1u);
mip.height = (int) std::max(header.pixelHeight >> i, 1u);
mip.size = mipsize;
+1 -1
View File
@@ -42,7 +42,7 @@ public:
// Implements CompressedFormatHandler.
virtual bool canParse(const filesystem::FileData *data);
virtual uint8 *parse(filesystem::FileData *filedata, std::vector<CompressedData::SubImage> &images, size_t &dataSize, CompressedData::Format &format, bool &sRGB);
virtual uint8 *parse(filesystem::FileData *filedata, std::vector<CompressedImageData::SubImage> &images, size_t &dataSize, CompressedImageData::Format &format, bool &sRGB);
}; // KTXHandler
+14 -14
View File
@@ -68,29 +68,29 @@ enum PKMTextureFormat
ETC2PACKAGE_RG_SIGNED_NO_MIPMAPS
};
CompressedData::Format convertFormat(uint16 texformat)
static CompressedImageData::Format convertFormat(uint16 texformat)
{
switch (texformat)
{
case ETC1_RGB_NO_MIPMAPS:
return CompressedData::FORMAT_ETC1;
return CompressedImageData::FORMAT_ETC1;
case ETC2PACKAGE_RGB_NO_MIPMAPS:
return CompressedData::FORMAT_ETC2_RGB;
return CompressedImageData::FORMAT_ETC2_RGB;
case ETC2PACKAGE_RGBA_NO_MIPMAPS_OLD:
case ETC2PACKAGE_RGBA_NO_MIPMAPS:
return CompressedData::FORMAT_ETC2_RGBA;
return CompressedImageData::FORMAT_ETC2_RGBA;
case ETC2PACKAGE_RGBA1_NO_MIPMAPS:
return CompressedData::FORMAT_ETC2_RGBA1;
return CompressedImageData::FORMAT_ETC2_RGBA1;
case ETC2PACKAGE_R_NO_MIPMAPS:
return CompressedData::FORMAT_EAC_R;
return CompressedImageData::FORMAT_EAC_R;
case ETC2PACKAGE_RG_NO_MIPMAPS:
return CompressedData::FORMAT_EAC_RG;
return CompressedImageData::FORMAT_EAC_RG;
case ETC2PACKAGE_R_SIGNED_NO_MIPMAPS:
return CompressedData::FORMAT_EAC_Rs;
return CompressedImageData::FORMAT_EAC_Rs;
case ETC2PACKAGE_RG_SIGNED_NO_MIPMAPS:
return CompressedData::FORMAT_EAC_RGs;
return CompressedImageData::FORMAT_EAC_RGs;
default:
return CompressedData::FORMAT_UNKNOWN;
return CompressedImageData::FORMAT_UNKNOWN;
}
}
@@ -113,7 +113,7 @@ bool PKMHandler::canParse(const filesystem::FileData *data)
return true;
}
uint8 *PKMHandler::parse(filesystem::FileData *filedata, std::vector<CompressedData::SubImage> &images, size_t &dataSize, CompressedData::Format &format, bool &sRGB)
uint8 *PKMHandler::parse(filesystem::FileData *filedata, std::vector<CompressedImageData::SubImage> &images, size_t &dataSize, CompressedImageData::Format &format, bool &sRGB)
{
if (!canParse(filedata))
throw love::Exception("Could not decode compressed data (not a PKM file?)");
@@ -126,9 +126,9 @@ uint8 *PKMHandler::parse(filesystem::FileData *filedata, std::vector<CompressedD
header.widthBig = swap16big(header.widthBig);
header.heightBig = swap16big(header.heightBig);
CompressedData::Format cformat = convertFormat(header.textureFormatBig);
CompressedImageData::Format cformat = convertFormat(header.textureFormatBig);
if (cformat == CompressedData::FORMAT_UNKNOWN)
if (cformat == CompressedImageData::FORMAT_UNKNOWN)
throw love::Exception("Could not parse PKM file: unsupported texture format.");
// The rest of the file after the header is all texture data.
@@ -147,7 +147,7 @@ uint8 *PKMHandler::parse(filesystem::FileData *filedata, std::vector<CompressedD
// PKM files only store a single mipmap level.
memcpy(data, (uint8 *) filedata->getData() + sizeof(PKMHeader), totalsize);
CompressedData::SubImage mip;
CompressedImageData::SubImage mip;
// TODO: verify whether glCompressedTexImage works properly with the unpadded
// width and height values (extended == padded.)
+1 -1
View File
@@ -42,7 +42,7 @@ public:
// Implements CompressedFormatHandler.
virtual bool canParse(const filesystem::FileData *data);
virtual uint8 *parse(filesystem::FileData *filedata, std::vector<CompressedData::SubImage> &images, size_t &dataSize, CompressedData::Format &format, bool &sRGB);
virtual uint8 *parse(filesystem::FileData *filedata, std::vector<CompressedImageData::SubImage> &images, size_t &dataSize, CompressedImageData::Format &format, bool &sRGB);
}; // PKMHandler
+14 -14
View File
@@ -163,28 +163,28 @@ void ConvertPVRHeader(PVRTexHeaderV2 header2, PVRTexHeaderV3 *header3)
}
}
CompressedData::Format convertFormat(PVRV3PixelFormat format)
static CompressedImageData::Format convertFormat(PVRV3PixelFormat format)
{
switch (format)
{
case ePVRTPF_PVRTCI_2bpp_RGB:
return CompressedData::FORMAT_PVR1_RGB2;
return CompressedImageData::FORMAT_PVR1_RGB2;
case ePVRTPF_PVRTCI_2bpp_RGBA:
return CompressedData::FORMAT_PVR1_RGBA2;
return CompressedImageData::FORMAT_PVR1_RGBA2;
case ePVRTPF_PVRTCI_4bpp_RGB:
return CompressedData::FORMAT_PVR1_RGB4;
return CompressedImageData::FORMAT_PVR1_RGB4;
case ePVRTPF_PVRTCI_4bpp_RGBA:
return CompressedData::FORMAT_PVR1_RGBA4;
return CompressedImageData::FORMAT_PVR1_RGBA4;
case ePVRTPF_ETC1:
return CompressedData::FORMAT_ETC1;
return CompressedImageData::FORMAT_ETC1;
case ePVRTPF_DXT1:
return CompressedData::FORMAT_DXT1;
return CompressedImageData::FORMAT_DXT1;
case ePVRTPF_DXT3:
return CompressedData::FORMAT_DXT3;
return CompressedImageData::FORMAT_DXT3;
case ePVRTPF_DXT5:
return CompressedData::FORMAT_DXT5;
return CompressedImageData::FORMAT_DXT5;
default:
return CompressedData::FORMAT_UNKNOWN;
return CompressedImageData::FORMAT_UNKNOWN;
}
}
@@ -294,7 +294,7 @@ bool PVRHandler::canParse(const filesystem::FileData *data)
return false;
}
uint8 *PVRHandler::parse(filesystem::FileData *filedata, std::vector<CompressedData::SubImage> &images, size_t &dataSize, CompressedData::Format &format, bool &sRGB)
uint8 *PVRHandler::parse(filesystem::FileData *filedata, std::vector<CompressedImageData::SubImage> &images, size_t &dataSize, CompressedImageData::Format &format, bool &sRGB)
{
if (!canParse(filedata))
throw love::Exception("Could not decode compressed data (not a PVR file?)");
@@ -324,9 +324,9 @@ uint8 *PVRHandler::parse(filesystem::FileData *filedata, std::vector<CompressedD
if (header3.depth > 1)
throw love::Exception("Image depths greater than 1 in PVR files are unsupported.");
CompressedData::Format cformat = convertFormat((PVRV3PixelFormat) header3.pixelFormat);
CompressedImageData::Format cformat = convertFormat((PVRV3PixelFormat) header3.pixelFormat);
if (cformat == CompressedData::FORMAT_UNKNOWN)
if (cformat == CompressedImageData::FORMAT_UNKNOWN)
throw love::Exception("Could not parse PVR file: unsupported image format.");
size_t totalsize = 0;
@@ -361,7 +361,7 @@ uint8 *PVRHandler::parse(filesystem::FileData *filedata, std::vector<CompressedD
if (curoffset + mipsize > totalsize)
break; // Just in case.
CompressedData::SubImage mip;
CompressedImageData::SubImage mip;
mip.width = std::max((int) header3.width >> i, 1);
mip.height = std::max((int) header3.height >> i, 1);
mip.size = mipsize;
+1 -1
View File
@@ -40,7 +40,7 @@ public:
// Implements CompressedFormatHandler.
virtual bool canParse(const filesystem::FileData *data);
virtual uint8 *parse(filesystem::FileData *filedata, std::vector<CompressedData::SubImage> &images, size_t &dataSize, CompressedData::Format &format, bool &sRGB);
virtual uint8 *parse(filesystem::FileData *filedata, std::vector<CompressedImageData::SubImage> &images, size_t &dataSize, CompressedImageData::Format &format, bool &sRGB);
}; // PVRHandler
+18 -18
View File
@@ -32,12 +32,12 @@ bool DDSHandler::canParse(const filesystem::FileData *data)
return dds::isCompressedDDS(data->getData(), data->getSize());
}
uint8 *DDSHandler::parse(filesystem::FileData *filedata, std::vector<CompressedData::SubImage> &images, size_t &dataSize, CompressedData::Format &format, bool &sRGB)
uint8 *DDSHandler::parse(filesystem::FileData *filedata, std::vector<CompressedImageData::SubImage> &images, size_t &dataSize, CompressedImageData::Format &format, bool &sRGB)
{
if (!dds::isDDS(filedata->getData(), filedata->getSize()))
throw love::Exception("Could not decode compressed data (not a DDS file?)");
CompressedData::Format texformat = CompressedData::FORMAT_UNKNOWN;
CompressedImageData::Format texformat = CompressedImageData::FORMAT_UNKNOWN;
bool isSRGB = false;
uint8 *data = nullptr;
@@ -51,7 +51,7 @@ uint8 *DDSHandler::parse(filesystem::FileData *filedata, std::vector<CompressedD
texformat = convertFormat(parser.getFormat(), isSRGB);
if (texformat == CompressedData::FORMAT_UNKNOWN)
if (texformat == CompressedImageData::FORMAT_UNKNOWN)
throw love::Exception("Could not parse compressed data: Unsupported format.");
if (parser.getMipmapCount() == 0)
@@ -68,13 +68,13 @@ uint8 *DDSHandler::parse(filesystem::FileData *filedata, std::vector<CompressedD
size_t dataOffset = 0;
// Copy the parsed mipmap levels from the FileData to our CompressedData.
// Copy the parsed mipmap levels from the FileData to our CompressedImageData.
for (size_t i = 0; i < parser.getMipmapCount(); i++)
{
// Fetch the data for this mipmap level.
const dds::Image *img = parser.getImageData(i);
CompressedData::SubImage mip;
CompressedImageData::SubImage mip;
mip.width = img->width;
mip.height = img->height;
@@ -101,37 +101,37 @@ uint8 *DDSHandler::parse(filesystem::FileData *filedata, std::vector<CompressedD
return data;
}
CompressedData::Format DDSHandler::convertFormat(dds::Format ddsformat, bool &sRGB)
CompressedImageData::Format DDSHandler::convertFormat(dds::Format ddsformat, bool &sRGB)
{
sRGB = false;
switch (ddsformat)
{
case dds::FORMAT_DXT1:
return CompressedData::FORMAT_DXT1;
return CompressedImageData::FORMAT_DXT1;
case dds::FORMAT_DXT3:
return CompressedData::FORMAT_DXT3;
return CompressedImageData::FORMAT_DXT3;
case dds::FORMAT_DXT5:
return CompressedData::FORMAT_DXT5;
return CompressedImageData::FORMAT_DXT5;
case dds::FORMAT_BC4:
return CompressedData::FORMAT_BC4;
return CompressedImageData::FORMAT_BC4;
case dds::FORMAT_BC4s:
return CompressedData::FORMAT_BC4s;
return CompressedImageData::FORMAT_BC4s;
case dds::FORMAT_BC5:
return CompressedData::FORMAT_BC5;
return CompressedImageData::FORMAT_BC5;
case dds::FORMAT_BC5s:
return CompressedData::FORMAT_BC5s;
return CompressedImageData::FORMAT_BC5s;
case dds::FORMAT_BC6H:
return CompressedData::FORMAT_BC6H;
return CompressedImageData::FORMAT_BC6H;
case dds::FORMAT_BC6Hs:
return CompressedData::FORMAT_BC6Hs;
return CompressedImageData::FORMAT_BC6Hs;
case dds::FORMAT_BC7:
return CompressedData::FORMAT_BC7;
return CompressedImageData::FORMAT_BC7;
case dds::FORMAT_BC7srgb:
sRGB = true;
return CompressedData::FORMAT_BC7;
return CompressedImageData::FORMAT_BC7;
default:
return CompressedData::FORMAT_UNKNOWN;
return CompressedImageData::FORMAT_UNKNOWN;
}
}
+3 -3
View File
@@ -38,7 +38,7 @@ namespace magpie
{
/**
* Interface between CompressedData and the ddsparse library.
* Interface between CompressedImageData and the ddsparse library.
**/
class DDSHandler : public CompressedFormatHandler
{
@@ -48,11 +48,11 @@ public:
// Implements CompressedFormatHandler.
virtual bool canParse(const filesystem::FileData *data);
virtual uint8 *parse(filesystem::FileData *filedata, std::vector<CompressedData::SubImage> &images, size_t &dataSize, CompressedData::Format &format, bool &sRGB);
virtual uint8 *parse(filesystem::FileData *filedata, std::vector<CompressedImageData::SubImage> &images, size_t &dataSize, CompressedImageData::Format &format, bool &sRGB);
private:
static CompressedData::Format convertFormat(dds::Format ddsformat, bool &sRGB);
static CompressedImageData::Format convertFormat(dds::Format ddsformat, bool &sRGB);
}; // DDSHandler
@@ -18,7 +18,7 @@
* 3. This notice may not be removed or altered from any source distribution.
**/
#include "wrap_CompressedData.h"
#include "wrap_CompressedImageData.h"
#include "common/wrap_Data.h"
namespace love
@@ -26,14 +26,14 @@ namespace love
namespace image
{
CompressedData *luax_checkcompresseddata(lua_State *L, int idx)
CompressedImageData *luax_checkcompressedimagedata(lua_State *L, int idx)
{
return luax_checktype<CompressedData>(L, idx, IMAGE_COMPRESSED_DATA_ID);
return luax_checktype<CompressedImageData>(L, idx, IMAGE_COMPRESSED_IMAGE_DATA_ID);
}
int w_CompressedData_getWidth(lua_State *L)
int w_CompressedImageData_getWidth(lua_State *L)
{
CompressedData *t = luax_checkcompresseddata(L, 1);
CompressedImageData *t = luax_checkcompressedimagedata(L, 1);
int miplevel = luaL_optint(L, 2, 1);
int width = 0;
@@ -43,9 +43,9 @@ int w_CompressedData_getWidth(lua_State *L)
return 1;
}
int w_CompressedData_getHeight(lua_State *L)
int w_CompressedImageData_getHeight(lua_State *L)
{
CompressedData *t = luax_checkcompresseddata(L, 1);
CompressedImageData *t = luax_checkcompressedimagedata(L, 1);
int miplevel = luaL_optint(L, 2, 1);
int height = 0;
@@ -55,9 +55,9 @@ int w_CompressedData_getHeight(lua_State *L)
return 1;
}
int w_CompressedData_getDimensions(lua_State *L)
int w_CompressedImageData_getDimensions(lua_State *L)
{
CompressedData *t = luax_checkcompresseddata(L, 1);
CompressedImageData *t = luax_checkcompressedimagedata(L, 1);
int miplevel = luaL_optint(L, 2, 1);
int width = 0, height = 0;
@@ -72,21 +72,21 @@ int w_CompressedData_getDimensions(lua_State *L)
return 2;
}
int w_CompressedData_getMipmapCount(lua_State *L)
int w_CompressedImageData_getMipmapCount(lua_State *L)
{
CompressedData *t = luax_checkcompresseddata(L, 1);
CompressedImageData *t = luax_checkcompressedimagedata(L, 1);
lua_pushinteger(L, t->getMipmapCount());
return 1;
}
int w_CompressedData_getFormat(lua_State *L)
int w_CompressedImageData_getFormat(lua_State *L)
{
CompressedData *t = luax_checkcompresseddata(L, 1);
CompressedImageData *t = luax_checkcompressedimagedata(L, 1);
image::CompressedData::Format format = t->getFormat();
image::CompressedImageData::Format format = t->getFormat();
const char *str;
if (image::CompressedData::getConstant(format, str))
if (image::CompressedImageData::getConstant(format, str))
lua_pushstring(L, str);
else
lua_pushstring(L, "unknown");
@@ -101,17 +101,17 @@ static const luaL_Reg functions[] =
{ "getPointer", w_Data_getPointer },
{ "getSize", w_Data_getSize },
{ "getWidth", w_CompressedData_getWidth },
{ "getHeight", w_CompressedData_getHeight },
{ "getDimensions", w_CompressedData_getDimensions },
{ "getMipmapCount", w_CompressedData_getMipmapCount },
{ "getFormat", w_CompressedData_getFormat },
{ "getWidth", w_CompressedImageData_getWidth },
{ "getHeight", w_CompressedImageData_getHeight },
{ "getDimensions", w_CompressedImageData_getDimensions },
{ "getMipmapCount", w_CompressedImageData_getMipmapCount },
{ "getFormat", w_CompressedImageData_getFormat },
{ 0, 0 },
};
extern "C" int luaopen_compresseddata(lua_State *L)
extern "C" int luaopen_compressedimagedata(lua_State *L)
{
return luax_register_type(L, IMAGE_COMPRESSED_DATA_ID, functions);
return luax_register_type(L, IMAGE_COMPRESSED_IMAGE_DATA_ID, functions);
}
} // image
@@ -0,0 +1,44 @@
/**
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
#ifndef LOVE_IMAGE_WRAP_COMRESSED_IMAGE_DATA_H
#define LOVE_IMAGE_WRAP_COMRESSED_IMAGE_DATA_H
// LOVE
#include "common/runtime.h"
#include "CompressedImageData.h"
namespace love
{
namespace image
{
CompressedImageData *luax_checkcompressedimagedata(lua_State *L, int idx);
int w_CompressedImageData_getWidth(lua_State *L);
int w_CompressedImageData_getHeight(lua_State *L);
int w_CompressedImageData_getDimensions(lua_State *L);
int w_CompressedImageData_getMipmapCount(lua_State *L);
int w_CompressedImageData_getFormat(lua_State *L);
extern "C" int luaopen_compressedimagedata(lua_State *L);
} // image
} // love
#endif // LOVE_IMAGE_WRAP_COMRESSED_IMAGE_DATA_H
+3 -3
View File
@@ -70,13 +70,13 @@ int w_newCompressedData(lua_State *L)
{
love::filesystem::FileData *data = love::filesystem::luax_getfiledata(L, 1);
CompressedData *t = nullptr;
CompressedImageData *t = nullptr;
luax_catchexcept(L,
[&]() { t = instance()->newCompressedData(data); },
[&]() { data->release(); }
);
luax_pushtype(L, IMAGE_COMPRESSED_DATA_ID, t);
luax_pushtype(L, IMAGE_COMPRESSED_IMAGE_DATA_ID, t);
t->release();
return 1;
}
@@ -103,7 +103,7 @@ static const luaL_Reg functions[] =
static const lua_CFunction types[] =
{
luaopen_imagedata,
luaopen_compresseddata,
luaopen_compressedimagedata,
0
};
+1 -1
View File
@@ -24,7 +24,7 @@
// LOVE
#include "Image.h"
#include "wrap_ImageData.h"
#include "wrap_CompressedData.h"
#include "wrap_CompressedImageData.h"
namespace love
{
+78
View File
@@ -0,0 +1,78 @@
/**
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
// LOVE
#include "CompressedData.h"
namespace love
{
namespace math
{
CompressedData::CompressedData(Compressor::Format format, char *cdata, size_t compressedsize, size_t rawsize, bool own)
: format(format)
, data(nullptr)
, dataSize(compressedsize)
, originalSize(rawsize)
{
if (own)
data = cdata;
else
{
try
{
data = new char[dataSize];
}
catch (std::bad_alloc &)
{
throw love::Exception("Out of memory.");
}
memcpy(data, cdata, dataSize);
}
}
CompressedData::~CompressedData()
{
delete[] data;
}
Compressor::Format CompressedData::getFormat() const
{
return format;
}
size_t CompressedData::getDecompressedSize() const
{
return originalSize;
}
void *CompressedData::getData() const
{
return data;
}
size_t CompressedData::getSize() const
{
return dataSize;
}
} // math
} // love
+75
View File
@@ -0,0 +1,75 @@
/**
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
#ifndef LOVE_MATH_COMPRESSED_DATA_H
#define LOVE_MATH_COMPRESSED_DATA_H
// LOVE
#include "common/Data.h"
#include "Compressor.h"
namespace love
{
namespace math
{
/**
* Stores byte data compressed via Math::compress.
**/
class CompressedData : public love::Data
{
public:
/**
* Constructor just stores already-compressed data in the object.
**/
CompressedData(Compressor::Format format, char *cdata, size_t compressedsize, size_t rawsize, bool own = true);
virtual ~CompressedData();
/**
* Gets the format that was used to compress the data.
**/
Compressor::Format getFormat() const;
/**
* Gets the original (uncompressed) size of the compressed data. May return
* 0 if the uncompressed size is unknown.
**/
size_t getDecompressedSize() const;
// Implements Data.
void *getData() const override;
size_t getSize() const override;
private:
Compressor::Format format;
char *data;
size_t dataSize;
size_t originalSize;
}; // CompressedData
} // math
} // love
#endif // LOVE_MATH_COMPRESSED_DATA_H
+291
View File
@@ -0,0 +1,291 @@
/**
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
// LOVE
#include "Compressor.h"
#include "common/config.h"
#include "common/int.h"
// LZ4
#include "libraries/lz4/lz4.h"
#include "libraries/lz4/lz4hc.h"
// zlib
#include <zlib.h>
namespace love
{
namespace math
{
class LZ4Compressor : public Compressor
{
public:
char *compress(const char *data, size_t dataSize, int level, size_t &compressedSize) override
{
if (dataSize > LZ4_MAX_INPUT_SIZE)
throw love::Exception("Data is too large for LZ4 compressor.");
// We use a custom header to store some info with the compressed data.
const size_t headersize = sizeof(uint32);
size_t maxsize = headersize + (size_t) LZ4_compressBound((int) dataSize);
char *compressedbytes = nullptr;
try
{
compressedbytes = new char[maxsize];
}
catch (std::bad_alloc &)
{
throw love::Exception("Out of memory.");
}
// Store the size of the uncompressed data as a header.
#ifdef LOVE_BIG_ENDIAN
// Make sure it's little-endian for storage.
*(uint32 *) compressedbytes = swap32((uint32) dataSize);
#else
*(uint32 *) compressedbytes = (uint32) dataSize;
#endif
// Use LZ4-HC for compression level 8 and higher.
int csize = 0;
if (level > 7)
csize = LZ4_compressHC(data, compressedbytes + headersize, (int) dataSize);
else
csize = LZ4_compress(data, compressedbytes + headersize, (int) dataSize);
if (csize <= 0)
{
delete[] compressedbytes;
throw love::Exception("Could not LZ4-compress data.");
}
// We allocated space for the maximum possible amount of data, but the
// actual compressed size might be much smaller, so we should shrink the
// data buffer if so.
if ((double) maxsize / (double) (csize + headersize) >= 1.2)
{
char *cbytes = new (std::nothrow) char[csize + headersize];
if (cbytes)
{
memcpy(cbytes, compressedbytes, csize + headersize);
delete[] compressedbytes;
compressedbytes = cbytes;
}
}
compressedSize = (size_t) csize + headersize;
return compressedbytes;
}
char *decompress(const char *data, size_t dataSize, size_t &decompressedSize) override
{
const size_t headersize = sizeof(uint32);
char *rawbytes = nullptr;
if (dataSize < headersize)
throw love::Exception("Invalid LZ4-compressed data size.");
// Extract the original uncompressed size (stored in our custom header.)
#ifdef LOVE_BIG_ENDIAN
// Convert from stored little-endian to big-endian.
uint32 rawsize = swap32(*(uint32 *) data);
#else
uint32 rawsize = *(uint32 *) data;
#endif
try
{
rawbytes = new char[rawsize];
}
catch (std::bad_alloc &)
{
throw love::Exception("Out of memory.");
}
// If the uncompressed size is passed in as an argument (non-zero) and
// it matches the header's stored size, then we assume it's 100% accurate
// and we use a more efficient decompression function.
if (decompressedSize > 0 && decompressedSize == (size_t) rawsize)
{
// We don't use the header here, but we need to account for its size.
if (LZ4_decompress_fast(data + headersize, rawbytes, (int) decompressedSize) < 0)
{
delete[] rawbytes;
throw love::Exception("Could not decompress LZ4-compressed data.");
}
}
else
{
// Account for our custom header's size in the decompress arguments.
int result = LZ4_decompress_safe(data + headersize, rawbytes,
dataSize - headersize, rawsize);
if (result < 0)
{
delete[] rawbytes;
throw love::Exception("Could not decompress LZ4-compressed data.");
}
decompressedSize = (size_t) result;
}
return rawbytes;
}
Compressor::Format getFormat() const override { return FORMAT_LZ4; }
}; // LZ4Compressor
class zlibCompressor : public Compressor
{
public:
char *compress(const char *data, size_t dataSize, int level, size_t &compressedSize) override
{
if (level < 0)
level = Z_DEFAULT_COMPRESSION;
else if (level > 9)
level = 9;
uLong maxsize = compressBound((uLong) dataSize);
char *compressedbytes = nullptr;
try
{
compressedbytes = new char[maxsize];
}
catch (std::bad_alloc &)
{
throw love::Exception("Out of memory.");
}
uLongf destlen = maxsize;
int status = compress2((Bytef *) compressedbytes, &destlen, (const Bytef *) data, (uLong) dataSize, level);
if (status != Z_OK)
{
delete[] compressedbytes;
throw love::Exception("Could not zlib-compress data.");
}
// We allocated space for the maximum possible amount of data, but the
// actual compressed size might be much smaller, so we should shrink the
// data buffer if so.
if ((double) maxsize / (double) destlen >= 1.2)
{
char *cbytes = new (std::nothrow) char[destlen];
if (cbytes)
{
memcpy(cbytes, compressedbytes, destlen);
delete[] compressedbytes;
compressedbytes = cbytes;
}
}
compressedSize = (size_t) destlen;
return compressedbytes;
}
char *decompress(const char *data, size_t dataSize, size_t &decompressedSize) override
{
char *rawbytes = nullptr;
// We might know the output size before decompression. If not, we guess.
size_t rawsize = decompressedSize > 0 ? decompressedSize : dataSize * 2;
// Repeatedly try to decompress with an increasingly large output buffer.
while (true)
{
try
{
rawbytes = new char[rawsize];
}
catch (std::bad_alloc &)
{
throw love::Exception("Out of memory.");
}
uLongf destLen = (uLongf) rawsize;
int status = uncompress((Bytef *) rawbytes, &destLen, (const Bytef *) data, (uLong) dataSize);
if (status == Z_OK)
{
decompressedSize = (size_t) destLen;
break;
}
else if (status != Z_BUF_ERROR)
{
// For any error other than "not enough room", throw an exception.
delete[] rawbytes;
throw love::Exception("Could not decompress zlib-compressed data.");
}
// Not enough room in the output buffer: try again with a larger size.
delete[] rawbytes;
rawsize *= 2;
}
return rawbytes;
}
Compressor::Format getFormat() const override { return FORMAT_ZLIB; }
}; // zlibCompressor
Compressor *Compressor::Create(Format format)
{
switch (format)
{
case FORMAT_LZ4:
return new LZ4Compressor;
case FORMAT_ZLIB:
return new zlibCompressor;
default:
throw love::Exception("Invalid compressor format.");
return nullptr;
}
}
bool Compressor::getConstant(const char *in, Format &out)
{
return formatNames.find(in, out);
}
bool Compressor::getConstant(Format in, const char *&out)
{
return formatNames.find(in, out);
}
StringMap<Compressor::Format, Compressor::FORMAT_MAX_ENUM>::Entry Compressor::formatEntries[] =
{
{"lz4", Compressor::FORMAT_LZ4},
{"zlib", Compressor::FORMAT_ZLIB},
};
StringMap<Compressor::Format, Compressor::FORMAT_MAX_ENUM> Compressor::formatNames(Compressor::formatEntries, sizeof(Compressor::formatEntries));
} // math
} // love
+101
View File
@@ -0,0 +1,101 @@
/**
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
#ifndef LOVE_MATH_COMPRESSOR_H
#define LOVE_MATH_COMPRESSOR_H
// LOVE
#include "common/StringMap.h"
namespace love
{
namespace math
{
/**
* Base class for backends for different compression formats.
**/
class Compressor
{
public:
enum Format
{
FORMAT_LZ4,
FORMAT_ZLIB,
FORMAT_MAX_ENUM
};
/**
* Creates a new Compressor that can compress and decompress a specific
* format.
**/
static Compressor *Create(Format format);
virtual ~Compressor() {}
/**
* Compresses input data, and returns the compressed result.
*
* @param[in] data The input (uncompressed) data.
* @param[in] dataSize The size in bytes of the input data.
* @param[in] level The amount of compression to apply (between 0 and 9.)
* A value of -1 indicates the default amount of compression.
* Specific formats may not use every level.
* @param[out] compressedSize The size in bytes of the compressed result.
*
* @return The newly compressed data (allocated with new[]).
**/
virtual char *compress(const char *data, size_t dataSize, int level, size_t &compressedSize) = 0;
/**
* Decompresses compressed data, and returns the decompressed result.
*
* @param[in] data The input (compressed) data.
* @param[in] dataSize The size in bytes of the compressed data.
* @param[inout] decompressedSize On input, the size in bytes of the
* original uncompressed data, or 0 if unknown. On return, the
* size in bytes of the decompressed data.
*
* @return The decompressed data (allocated with new[]).
**/
virtual char *decompress(const char *data, size_t dataSize, size_t &decompressedSize) = 0;
/**
* Gets the compression format implemented by this backend.
*
* @return The supported format.
**/
virtual Format getFormat() const = 0;
static bool getConstant(const char *in, Format &out);
static bool getConstant(Format in, const char *&out);
private:
static StringMap<Format, FORMAT_MAX_ENUM>::Entry formatEntries[];
static StringMap<Format, FORMAT_MAX_ENUM> formatNames;
}; // Compressor
} // math
} // love
#endif // LOVE_MATH_COMPRESSOR_H
+59
View File
@@ -86,9 +86,19 @@ Math Math::instance;
Math::Math()
: rng()
, compressors()
{
// prevent the runtime from free()-ing this
retain();
for (int i = 0; i < (int) Compressor::FORMAT_MAX_ENUM; i++)
compressors[i] = Compressor::Create((Compressor::Format) i);
}
Math::~Math()
{
for (Compressor *c : compressors)
delete c;
}
RandomGenerator *Math::newRandomGenerator()
@@ -223,5 +233,54 @@ float Math::linearToGamma(float c) const
return 1.055f * powf(c, 0.41666f) - 0.055f;
}
CompressedData *Math::compress(Compressor::Format format, love::Data *rawdata, int level)
{
return compress(format, (const char *) rawdata->getData(), rawdata->getSize(), level);
}
CompressedData *Math::compress(Compressor::Format format, const char *rawbytes, size_t rawsize, int level)
{
if (format == Compressor::FORMAT_MAX_ENUM || !compressors[format])
throw love::Exception("Invalid compression format.");
size_t compressedsize = 0;
Compressor *compressor = compressors[format];
char *cbytes = compressor->compress(rawbytes, rawsize, level, compressedsize);
CompressedData *data = nullptr;
try
{
data = new CompressedData(format, cbytes, compressedsize, rawsize, true);
}
catch (love::Exception &)
{
delete[] cbytes;
throw;
}
return data;
}
char *Math::decompress(CompressedData *data, size_t &decompressedsize)
{
size_t rawsize = data->getDecompressedSize();
char *rawbytes = decompress(data->getFormat(), (const char *) data->getData(),
data->getSize(), rawsize);
decompressedsize = rawsize;
return rawbytes;
}
char *Math::decompress(Compressor::Format format, const char *cbytes, size_t compressedsize, size_t &rawsize)
{
if (format == Compressor::FORMAT_MAX_ENUM || !compressors[format])
throw love::Exception("Invalid compression format.");
return compressors[format]->decompress(cbytes, compressedsize, rawsize);
}
} // math
} // love
+40 -2
View File
@@ -22,6 +22,8 @@
#define LOVE_MATH_MODMATH_H
#include "RandomGenerator.h"
#include "CompressedData.h"
#include "Compressor.h"
// LOVE
#include "common/Module.h"
@@ -50,8 +52,7 @@ private:
public:
virtual ~Math()
{}
virtual ~Math();
/**
* @copydoc RandomGenerator::random()
@@ -162,12 +163,49 @@ public:
float noise(float x, float y, float z) const;
float noise(float x, float y, float z, float w) const;
/**
* Compresses a block of memory using the given compression format.
*
* @param format The compression format to use.
* @param rawdata The data to compress.
* @param level The amount of compression to apply (between 0 and 9.)
* A value of -1 indicates the default amount of compression.
* Specific formats may not use every level.
* @return The newly compressed data.
**/
CompressedData *compress(Compressor::Format format, Data *rawdata, int level = -1);
CompressedData *compress(Compressor::Format format, const char *rawbytes, size_t rawsize, int level = -1);
/**
* Decompresses existing compressed data into raw bytes.
*
* @param[in] data The compressed data to decompress.
* @param[out] decompressedsize The size in bytes of the decompressed data.
* @return The newly decompressed data (allocated with new[]).
**/
char *decompress(CompressedData *data, size_t &decompressedsize);
/**
* Decompresses existing compressed data into raw bytes.
*
* @param[in] format The compression format the data is in.
* @param[in] cbytes The compressed data to decompress.
* @param[in] compressedSize The size in bytes of the compressed data.
* @param[inout] rawsize On input, the size in bytes of the original
* uncompressed data, or 0 if unknown. On return, the size in
* bytes of the newly decompressed data.
* @return The newly decompressed data (allocated with new[]).
**/
char *decompress(Compressor::Format format, const char *cbytes, size_t compressedsize, size_t &rawsize);
static Math instance;
private:
Math();
Compressor *compressors[Compressor::FORMAT_MAX_ENUM];
}; // Math
inline float Math::noise(float x) const
+65
View File
@@ -0,0 +1,65 @@
/**
* Copyright (c) 2006-2015 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
// LOVE
#include "wrap_CompressedData.h"
#include "common/wrap_Data.h"
namespace love
{
namespace math
{
CompressedData *luax_checkcompresseddata(lua_State *L, int idx)
{
return luax_checktype<CompressedData>(L, idx, MATH_COMPRESSED_DATA_ID);
}
int w_CompressedData_getFormat(lua_State *L)
{
CompressedData *t = luax_checkcompresseddata(L, 1);
const char *fname = nullptr;
if (!Compressor::getConstant(t->getFormat(), fname))
return luaL_error(L, "Unknown compressed data format.");
lua_pushstring(L, fname);
return 1;
}
static const luaL_Reg functions[] =
{
// Data
{ "getString", w_Data_getString },
{ "getPointer", w_Data_getPointer },
{ "getSize", w_Data_getSize },
{ "getFormat", w_CompressedData_getFormat },
{ 0, 0 },
};
extern "C" int luaopen_compresseddata(lua_State *L)
{
return luax_register_type(L, MATH_COMPRESSED_DATA_ID, functions);
}
} // math
} // love
@@ -18,8 +18,8 @@
* 3. This notice may not be removed or altered from any source distribution.
**/
#ifndef LOVE_IMAGE_WRAP_COMRESSED_DATA_H
#define LOVE_IMAGE_WRAP_COMRESSED_DATA_H
#ifndef LOVE_MATH_WRAP_COMPRESSED_DATA_H
#define LOVE_MATH_WRAP_COMPRESSED_DATA_H
// LOVE
#include "common/runtime.h"
@@ -27,18 +27,14 @@
namespace love
{
namespace image
namespace math
{
CompressedData *luax_checkcompresseddata(lua_State *L, int idx);
int w_CompressedData_getWidth(lua_State *L);
int w_CompressedData_getHeight(lua_State *L);
int w_CompressedData_getDimensions(lua_State *L);
int w_CompressedData_getMipmapCount(lua_State *L);
int w_CompressedData_getFormat(lua_State *L);
extern "C" int luaopen_compresseddata(lua_State *L);
} // image
} // math
} // love
#endif // LOVE_IMAGE_WRAP_COMRESSED_DATA_H
#endif // LOVE_MATH_WRAP_COMPRESSED_DATA_H
+62
View File
@@ -21,6 +21,7 @@
#include "wrap_Math.h"
#include "wrap_RandomGenerator.h"
#include "wrap_BezierCurve.h"
#include "wrap_CompressedData.h"
#include "MathModule.h"
#include "BezierCurve.h"
@@ -351,6 +352,64 @@ int w_noise(lua_State *L)
return 1;
}
int w_compress(lua_State *L)
{
const char *fstr = lua_isnoneornil(L, 2) ? nullptr : luaL_checkstring(L, 2);
Compressor::Format format = Compressor::FORMAT_LZ4;
if (fstr && !Compressor::getConstant(fstr, format))
return luaL_error(L, "Invalid compressed format: %s", fstr);
int level = luaL_optint(L, 3, -1);
CompressedData *cdata = nullptr;
if (lua_isstring(L, 1))
{
size_t rawsize = 0;
const char *rawbytes = luaL_checklstring(L, 1, &rawsize);
luax_catchexcept(L, [&](){ cdata = Math::instance.compress(format, rawbytes, rawsize, level); });
}
else
{
Data *rawdata = luax_checktype<Data>(L, 1, DATA_ID);
luax_catchexcept(L, [&](){ cdata = Math::instance.compress(format, rawdata, level); });
}
luax_pushtype(L, MATH_COMPRESSED_DATA_ID, cdata);
return 1;
}
int w_decompress(lua_State *L)
{
char *rawbytes = nullptr;
size_t rawsize = 0;
if (lua_isstring(L, 1))
{
Compressor::Format format = Compressor::FORMAT_LZ4;
const char *fstr = luaL_checkstring(L, 2);
if (!Compressor::getConstant(fstr, format))
return luaL_error(L, "Invalid compressed format: %s", fstr);
size_t compressedsize = 0;
const char *cbytes = luaL_checklstring(L, 1, &compressedsize);
luax_catchexcept(L, [&](){ rawbytes = Math::instance.decompress(format, cbytes, compressedsize, rawsize); });
}
else
{
CompressedData *data = luax_checkcompresseddata(L, 1);
rawsize = data->getDecompressedSize();
luax_catchexcept(L, [&](){ rawbytes = Math::instance.decompress(data, rawsize); });
}
lua_pushlstring(L, rawbytes, rawsize);
delete[] rawbytes;
return 1;
}
// List of functions to wrap.
static const luaL_Reg functions[] =
{
@@ -367,6 +426,8 @@ static const luaL_Reg functions[] =
{ "gammaToLinear", w_gammaToLinear },
{ "linearToGamma", w_linearToGamma },
{ "noise", w_noise },
{ "compress", w_compress },
{ "decompress", w_decompress },
{ 0, 0 }
};
@@ -374,6 +435,7 @@ static const lua_CFunction types[] =
{
luaopen_randomgenerator,
luaopen_beziercurve,
luaopen_compresseddata,
0
};
+2
View File
@@ -43,6 +43,8 @@ int w_isConvex(lua_State *L);
int w_gammaToLinear(lua_State *L);
int w_linearToGamma(lua_State *L);
int w_noise(lua_State *L);
int w_compress(lua_State *L);
int w_decompress(lua_State *L);
extern "C" LOVE_EXPORT int luaopen_love_math(lua_State *L);
} // random