| 1 |
{ |
| 2 |
Copyright 2023-2024 Michalis Kamburelis. |
| 3 |
|
| 4 |
This file is part of "Castle Game Engine". |
| 5 |
|
| 6 |
"Castle Game Engine" is free software; see the file COPYING.txt, |
| 7 |
included in this distribution, for details about the copyright. |
| 8 |
|
| 9 |
"Castle Game Engine" is distributed in the hope that it will be useful, |
| 10 |
but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| 12 |
|
| 13 |
---------------------------------------------------------------------------- |
| 14 |
} |
| 15 |
|
| 16 |
{ Internal compression algorithms. |
| 17 |
|
| 18 |
For now only used to compress embedded images in EXE, |
| 19 |
to make units like src/fonts/castletexturefont_defaultui.pas |
| 20 |
smaller (faster to compile, and not taking huge space in EXE). } |
| 21 |
unit CastleInternalDataCompression; |
| 22 |
|
| 23 |
{$I castleconf.inc} |
| 24 |
|
| 25 |
interface |
| 26 |
|
| 27 |
uses SysUtils, Classes, Generics.Collections; |
| 28 |
|
| 29 |
type |
| 30 |
TChannelsSplit = class |
| 31 |
Data: array of Pointer; |
| 32 |
{ Every Data[I] has this size. } |
| 33 |
DataSize: Cardinal; |
| 34 |
|
| 35 |
{ Allocate all Data[I] arrays using GetMem. |
| 36 |
|
| 37 |
Note that this is not the only way to initialize Data[I] arrays, |
| 38 |
one can also set Data[I] to pointers to some hardcoded arrays. |
| 39 |
Though this use-case is not actually used now in the end. } |
| 40 |
procedure DataAllocate; |
| 41 |
|
| 42 |
{ Free all Data[I] arrays using FreeMem. } |
| 43 |
procedure DataFree; |
| 44 |
end; |
| 45 |
|
| 46 |
{ Split data into per-channel arrays. |
| 47 |
This is good to apply RLE compression to each image channel separately, |
| 48 |
this makes compression most efficient, e.g. RGB image will compress great |
| 49 |
when it contains the single color. |
| 50 |
|
| 51 |
The TChannelsSplit has allocated data with DataAllocate, |
| 52 |
so remember to call DataFree when you're done with it. |
| 53 |
|
| 54 |
While this routine technically doesn't assume anything about "what is the data |
| 55 |
content", but in practice it is useful only with TCastleImage.RawPixels data. |
| 56 |
It splits the data following the TCastleImage.RawPixels layout, |
| 57 |
i.e. assuming that data is a sequence of pixels, each pixel having PixelSize |
| 58 |
bytes. } |
| 59 |
function DataChannelsSplit(const RawPixels: Pointer; const RawPixelsSize: Cardinal; |
| 60 |
const PixelSize: Integer): TChannelsSplit; |
| 61 |
|
| 62 |
{ Fill the RawPixels memory by data from ChannelData. |
| 63 |
Reverses the operation of DataChannelsSplit. } |
| 64 |
procedure DataChannelsCombine(const RawPixels: Pointer; const RawPixelsSize: Cardinal; |
| 65 |
const PixelSize: Integer; const ChannelData: TChannelsSplit); |
| 66 |
|
| 67 |
{ RLE compression / decompression. |
| 68 |
|
| 69 |
Design goals: |
| 70 |
|
| 71 |
- Simple to implement, so we can implement it in Pascal in CGE, |
| 72 |
without depending on any external libs or any FPC/Delphi-specific units. |
| 73 |
So can be used with all platforms, compilers, easily. |
| 74 |
|
| 75 |
- Fast to decompress. |
| 76 |
Compression itself is also fast, but isn't a priority. |
| 77 |
In our main use-case, compression occurs at pre-processing stage |
| 78 |
(texture-to-pascal, font-to-pascal) while decompression occurs at runtime |
| 79 |
(almost every CGE application will need to decompress to use FallbackFont). |
| 80 |
|
| 81 |
- Efficient compression of typical image data, |
| 82 |
where we have often long sequences of the same byte. |
| 83 |
We are not trying to get the best compression ratio, |
| 84 |
we are useful only with specialized data that is really easy to compress. |
| 85 |
See https://en.wikipedia.org/wiki/Run-length_encoding . |
| 86 |
|
| 87 |
- See implementation comments for the exact algorithm. |
| 88 |
This algorithm should be considered an implementation detail only! |
| 89 |
|
| 90 |
Compatibility: |
| 91 |
|
| 92 |
This is not a stable algorithm for now, do not count on it being backward |
| 93 |
compatible between CGE releases, do not compress your files with it! |
| 94 |
It is used internally in CGE only, to temporarily compress some data. |
| 95 |
When we use it, we always depend that compression + decompression |
| 96 |
was done by the same CGE version. |
| 97 |
|
| 98 |
Stream usage: |
| 99 |
|
| 100 |
Since the primary use-case is to compress / decompress data already in memory, |
| 101 |
we assume that whole input is already in memory with known size. |
| 102 |
So we don't try to read source from a general TStream (with unknown size), |
| 103 |
or even TMemoryStream. The Source is just a pointer with content size. |
| 104 |
|
| 105 |
SourceSize is limited to 4 GB (max Cardinal) to allow fast iteration |
| 106 |
using 32-bit Integers. |
| 107 |
|
| 108 |
@groupBegin } |
| 109 |
procedure RleCompress( |
| 110 |
const Source: Pointer; const SourceSize: Cardinal; const Dest: TStream); |
| 111 |
procedure RleDecompress( |
| 112 |
const Source: Pointer; const SourceSize: Cardinal; const Dest: TStream); overload; |
| 113 |
procedure RleDecompress( |
| 114 |
const Source: Pointer; const SourceSize: Cardinal; |
| 115 |
const Dest: Pointer; const DestSize: Cardinal); overload; |
| 116 |
{ @groupEnd } |
| 117 |
|
| 118 |
implementation |
| 119 |
|
| 120 |
uses CastleUtils; |
| 121 |
|
| 122 |
{ TChannelsSplit ------------------------------------------------------------- } |
| 123 |
|
| 124 |
procedure TChannelsSplit.DataAllocate; |
| 125 |
var |
| 126 |
I: Integer; |
| 127 |
begin |
| 128 |
for I := 0 to High(Data) do |
| 129 |
Data[I] := GetMem(DataSize); |
| 130 |
end; |
| 131 |
|
| 132 |
procedure TChannelsSplit.DataFree; |
| 133 |
var |
| 134 |
I: Integer; |
| 135 |
begin |
| 136 |
for I := 0 to High(Data) do |
| 137 |
FreeMemNiling(Data[I]); |
| 138 |
end; |
| 139 |
|
| 140 |
{ DataChannelsSplit / DataChannelsCombine ------------------------------------ } |
| 141 |
|
| 142 |
function DataChannelsSplit(const RawPixels: Pointer; const RawPixelsSize: Cardinal; |
| 143 |
const PixelSize: Integer): TChannelsSplit; |
| 144 |
var |
| 145 |
Channel: Integer; |
| 146 |
SourcePtr, DestPtr: PByte; |
| 147 |
I: Integer; |
| 148 |
begin |
| 149 |
Result := TChannelsSplit.Create; |
| 150 |
try |
| 151 |
{ prepare TChannelsSplit memory } |
| 152 |
SetLength(Result.Data, PixelSize); |
| 153 |
Result.DataSize := RawPixelsSize div PixelSize; |
| 154 |
Assert(RawPixelsSize mod PixelSize = 0); |
| 155 |
Result.DataAllocate; |
| 156 |
|
| 157 |
for Channel := 0 to PixelSize - 1 do |
| 158 |
begin |
| 159 |
// fill Result.Data[Channel] memory contents |
| 160 |
SourcePtr := RawPixels; |
| 161 |
Inc(SourcePtr, Channel); |
| 162 |
DestPtr := Result.Data[Channel]; |
| 163 |
for I := 0 to Result.DataSize - 1 do |
| 164 |
begin |
| 165 |
DestPtr^ := SourcePtr^; |
| 166 |
Inc(SourcePtr, PixelSize); |
| 167 |
Inc(DestPtr); |
| 168 |
end; |
| 169 |
end; |
| 170 |
except FreeAndNil(Result); raise end; |
| 171 |
end; |
| 172 |
|
| 173 |
procedure DataChannelsCombine(const RawPixels: Pointer; const RawPixelsSize: Cardinal; |
| 174 |
const PixelSize: Integer; const ChannelData: TChannelsSplit); |
| 175 |
var |
| 176 |
Channel, I: Integer; |
| 177 |
SourcePtr, DestPtr: PByte; |
| 178 |
begin |
| 179 |
if ChannelData.DataSize <> RawPixelsSize div PixelSize then |
| 180 |
raise EInternalError.Create('Invalid input size to DataChannelsCombine'); |
| 181 |
|
| 182 |
for Channel := 0 to PixelSize - 1 do |
| 183 |
begin |
| 184 |
SourcePtr := ChannelData.Data[Channel]; |
| 185 |
DestPtr := RawPixels; |
| 186 |
Inc(DestPtr, Channel); |
| 187 |
|
| 188 |
for I := 0 to ChannelData.DataSize - 1 do |
| 189 |
begin |
| 190 |
DestPtr^ := SourcePtr^; |
| 191 |
Inc(SourcePtr); |
| 192 |
Inc(DestPtr, PixelSize); |
| 193 |
end; |
| 194 |
end; |
| 195 |
end; |
| 196 |
|
| 197 |
{ ------------------------------------------------------------------------ |
| 198 |
Castle Game Engine RLE compression data format: |
| 199 |
|
| 200 |
We have 2 types of chunks: |
| 201 |
|
| 202 |
- 1st byte has most significant bit not set, IOW it is < 128. |
| 203 |
|
| 204 |
Let's call Length = 1st byte. |
| 205 |
|
| 206 |
Decompression should read next byte, and repeat it Length times. |
| 207 |
This is the core of the RLE compression. |
| 208 |
So, at best, 127 bytes can be compressed into 2 bytes |
| 209 |
(length = 127, and byte to be repeated 127 times). |
| 210 |
|
| 211 |
- 1st byte has most significant bit set, IOW it is >= 128. |
| 212 |
|
| 213 |
Let's call Length = 1st byte - 128 = 1st byte with most significant bit zeroed. |
| 214 |
|
| 215 |
Decompression should read next Length bytes, and copy them to output, once. |
| 216 |
|
| 217 |
This is done to lessed the impact of the least favorable data for |
| 218 |
RLE compression, when all bytes are different. |
| 219 |
So we don't need to encode each unique byte as "1 a", "1 b" etc. |
| 220 |
(effectively doubling the size of unique bytes) |
| 221 |
Instead, we can encode a sequence of unique bytes. |
| 222 |
|
| 223 |
On tests (TTestCastleClassUtils.TestRleCompression), |
| 224 |
this makes compression better, from 17% to 12%. |
| 225 |
|
| 226 |
------------------------------------------------------------------------- |
| 227 |
} |
| 228 |
|
| 229 |
const |
| 230 |
{ max value in least significant 7 digits } |
| 231 |
MaxChunkLength = $7F; |
| 232 |
MaxLeftoverUniqueBytes = $7F; |
| 233 |
|
| 234 |
procedure RleCompress( |
| 235 |
const Source: Pointer; const SourceSize: Cardinal; const Dest: TStream); |
| 236 |
var |
| 237 |
LeftoverUniqueBytes: array [1..MaxLeftoverUniqueBytes] of Byte; |
| 238 |
LeftoverUniqueBytesCount: Byte; |
| 239 |
|
| 240 |
{ Put LeftoverUniqueBytes* into Dest, if LeftoverUniqueBytesCount is zero. |
| 241 |
Set LeftoverUniqueBytesCount to zero. } |
| 242 |
procedure FlushLeftoverUniqueBytes; |
| 243 |
var |
| 244 |
LeftoverUniqueBytesCountEncoded: Byte; |
| 245 |
begin |
| 246 |
if LeftoverUniqueBytesCount <> 0 then |
| 247 |
begin |
| 248 |
{$ifdef CASTLE_DEBUG_RLE} WritelnLog(Format('Compress leftover unique bytes count %d', [LeftoverUniqueBytesCount])); {$endif} |
| 249 |
LeftoverUniqueBytesCountEncoded := LeftoverUniqueBytesCount or (1 shl 7); |
| 250 |
Dest.WriteBuffer(LeftoverUniqueBytesCountEncoded, SizeOf(LeftoverUniqueBytesCountEncoded)); |
| 251 |
Dest.WriteBuffer(LeftoverUniqueBytes, LeftoverUniqueBytesCount); |
| 252 |
LeftoverUniqueBytesCount := 0; |
| 253 |
end; |
| 254 |
end; |
| 255 |
|
| 256 |
var |
| 257 |
I: Cardinal; |
| 258 |
ChunkByte, ChunkSize: Byte; |
| 259 |
Buffer: PByte; |
| 260 |
begin |
| 261 |
LeftoverUniqueBytesCount := 0; |
| 262 |
|
| 263 |
{ Compress contents of Buffer^ into Dest stream. } |
| 264 |
Buffer := PByte(Source); |
| 265 |
|
| 266 |
{ We look at character with index I (1-based). |
| 267 |
We move Buffer pointer, such that Buffer^ always points to ith byte. } |
| 268 |
I := 1; |
| 269 |
while I <= SourceSize do |
| 270 |
begin |
| 271 |
ChunkSize := 1; |
| 272 |
ChunkByte := Buffer^; |
| 273 |
Inc(I); |
| 274 |
Inc(Buffer); |
| 275 |
while |
| 276 |
(I <= SourceSize) and |
| 277 |
(Buffer^ = ChunkByte) and |
| 278 |
(ChunkSize < MaxChunkLength) do |
| 279 |
begin |
| 280 |
Inc(I); |
| 281 |
Inc(Buffer); |
| 282 |
Inc(ChunkSize); |
| 283 |
end; |
| 284 |
|
| 285 |
{ We could ignore now the optimization to use LeftoverUniqueBytes, |
| 286 |
and just do this: |
| 287 |
Dest.WriteBuffer(ChunkSize, SizeOf(ChunkSize)); |
| 288 |
Dest.WriteBuffer(ChunkByte, SizeOf(ChunkByte)); |
| 289 |
This would result in correct, albeit unoptimal, compression. |
| 290 |
} |
| 291 |
|
| 292 |
if ChunkSize = 1 then |
| 293 |
begin |
| 294 |
if LeftoverUniqueBytesCount = MaxLeftoverUniqueBytes then |
| 295 |
FlushLeftoverUniqueBytes; |
| 296 |
Assert(LeftoverUniqueBytesCount < MaxLeftoverUniqueBytes); |
| 297 |
Inc(LeftoverUniqueBytesCount); |
| 298 |
LeftoverUniqueBytes[LeftoverUniqueBytesCount] := ChunkByte; |
| 299 |
end else |
| 300 |
begin |
| 301 |
FlushLeftoverUniqueBytes; |
| 302 |
{$ifdef CASTLE_DEBUG_RLE} WritelnLog(Format('Compress chunk size %d byte %d', [ChunkSize, ChunkByte])); {$endif} |
| 303 |
Dest.WriteBuffer(ChunkSize, SizeOf(ChunkSize)); |
| 304 |
Dest.WriteBuffer(ChunkByte, SizeOf(ChunkByte)); |
| 305 |
end; |
| 306 |
end; |
| 307 |
|
| 308 |
FlushLeftoverUniqueBytes; |
| 309 |
end; |
| 310 |
|
| 311 |
procedure RleDecompress( |
| 312 |
const Source: Pointer; const SourceSize: Cardinal; |
| 313 |
const Dest: Pointer; const DestSize: Cardinal); |
| 314 |
var |
| 315 |
DestStream: TMemoryStream; |
| 316 |
begin |
| 317 |
DestStream := TMemoryStream.Create; |
| 318 |
try |
| 319 |
DestStream.Size := DestSize; // preallocate necessary memory |
| 320 |
RleDecompress(Source, SourceSize, DestStream); |
| 321 |
if DestStream.Size <> DestSize then |
| 322 |
raise Exception.CreateFmt('Decompressed stream size %d is different than expected %d', [ |
| 323 |
DestStream.Size, |
| 324 |
DestSize |
| 325 |
]); |
| 326 |
Move(DestStream.Memory^, Dest^, DestSize); |
| 327 |
finally FreeAndNil(DestStream) end; |
| 328 |
end; |
| 329 |
|
| 330 |
procedure RleDecompress( |
| 331 |
const Source: Pointer; const SourceSize: Cardinal; const Dest: TStream); |
| 332 |
var |
| 333 |
Buffer: PByte; |
| 334 |
I, J: Cardinal; |
| 335 |
ChunkSize, ChunkByte: Byte; |
| 336 |
begin |
| 337 |
{ Decompress contents of Buffer^ into Dest stream. } |
| 338 |
Buffer := PByte(Source); |
| 339 |
|
| 340 |
{ We look at character with index I (1-based). |
| 341 |
We move Buffer pointer, such that Buffer^ always points to ith byte. } |
| 342 |
I := 1; |
| 343 |
while I <= SourceSize do |
| 344 |
begin |
| 345 |
ChunkSize := Buffer^; |
| 346 |
Inc(I); |
| 347 |
Inc(Buffer); |
| 348 |
|
| 349 |
if ChunkSize and (1 shl 7) <> 0 then |
| 350 |
begin |
| 351 |
ChunkSize := ChunkSize and not (1 shl 7); |
| 352 |
|
| 353 |
{ We have ChunkSize of unique bytes to copy from Buffer^ to Dest. } |
| 354 |
{$ifdef CASTLE_DEBUG_RLE} WritelnLog(Format('Decompress leftover unique bytes count %d', [ChunkSize])); {$endif} |
| 355 |
|
| 356 |
if ChunkSize > MaxLeftoverUniqueBytes then |
| 357 |
raise Exception.CreateFmt('Too large leftover chunk size %d, should be <= %d', [ |
| 358 |
ChunkSize, |
| 359 |
MaxLeftoverUniqueBytes |
| 360 |
]); |
| 361 |
if I + ChunkSize - 1 > SourceSize then |
| 362 |
raise Exception.CreateFmt('Compressed stream ended in the middle of leftover chunk (has size %d, should have size at least %d)', [ |
| 363 |
SourceSize, |
| 364 |
I + ChunkSize - 1 |
| 365 |
]); |
| 366 |
|
| 367 |
Dest.WriteBuffer(Buffer^, ChunkSize); |
| 368 |
Inc(I, ChunkSize); |
| 369 |
Inc(Buffer, ChunkSize); |
| 370 |
end else |
| 371 |
begin |
| 372 |
ChunkByte := Buffer^; |
| 373 |
Inc(I); |
| 374 |
Inc(Buffer); |
| 375 |
|
| 376 |
{$ifdef CASTLE_DEBUG_RLE} WritelnLog(Format('Decompress chunk size %d byte %d', [ChunkSize, ChunkByte])); {$endif} |
| 377 |
for J := 1 to ChunkSize do |
| 378 |
Dest.WriteBuffer(ChunkByte, SizeOf(ChunkByte)); |
| 379 |
end; |
| 380 |
end; |
| 381 |
end; |
| 382 |
|
| 383 |
end. |