| 1 |
{ |
| 2 |
Copyright 2009-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 |
{ Handling of images for textures. |
| 17 |
This unit is not OpenGL-specific, it should be suitable for all 3D libraries. |
| 18 |
See CastleGLImage for OpenGL-specific handling of textures and other images. |
| 19 |
|
| 20 |
Texture is any TEncodedImage instance. This includes not only |
| 21 |
a traditional 2D/3D matrix of pixels represented as TCastleImage, |
| 22 |
but also a texture compressed for GPU (TGPUCompressedImage). Moreover, a texture |
| 23 |
may have mipmaps defined --- they are stored inside TCompositeImage |
| 24 |
instance (that contains a list of TEncodedImage). |
| 25 |
|
| 26 |
Since not everything can really deal with such flexible definition |
| 27 |
of a texture, we decided to separate some routines specifically |
| 28 |
for textures. For example, you have LoadTextureImage to load full texture |
| 29 |
information --- contrast this with LoadImage routine in CastleImages unit, |
| 30 |
that only returns TCastleImage (a "normal" way to deal with image data). } |
| 31 |
unit CastleTextureImages; |
| 32 |
|
| 33 |
{$I castleconf.inc} |
| 34 |
|
| 35 |
interface |
| 36 |
|
| 37 |
uses Generics.Collections, |
| 38 |
CastleImages, CastleInternalCompositeImage, CastleUtils, CastleVideos, CastleRenderOptions; |
| 39 |
|
| 40 |
const |
| 41 |
{ Image classes that are handled by absolutely all OpenGL versions. } |
| 42 |
TextureImageClasses: array [0..3] of TEncodedImageClass = ( |
| 43 |
TRGBImage, |
| 44 |
TRGBAlphaImage, |
| 45 |
TGrayscaleImage, |
| 46 |
TGrayscaleAlphaImage |
| 47 |
); |
| 48 |
|
| 49 |
{ All image classes that may be handled by OpenGL. |
| 50 |
Some of them may require specific OpenGL extensions or versions |
| 51 |
(like GPU-compressed or float textures). } |
| 52 |
TextureImageClassesAll: array [0..8] of TEncodedImageClass = ( |
| 53 |
// 8-bit images |
| 54 |
TRGBImage, |
| 55 |
TRGBAlphaImage, |
| 56 |
TGrayscaleImage, |
| 57 |
TGrayscaleAlphaImage, |
| 58 |
|
| 59 |
// GPU-compressed |
| 60 |
TGPUCompressedImage, |
| 61 |
|
| 62 |
// floating-point precision and range |
| 63 |
TGrayscaleFloatImage, |
| 64 |
TGrayscaleAlphaFloatImage, |
| 65 |
TRGBFloatImage, |
| 66 |
TRGBAlphaFloatImage |
| 67 |
); |
| 68 |
|
| 69 |
{ Load image suitable for a texture. |
| 70 |
This will load image to memory formats supported by common |
| 71 |
3D libraries (like OpenGL), for example it will never return TRGBFloatImage |
| 72 |
(although OpenGL may support it, but we cannot be sure at this point). |
| 73 |
It may return texture compressed using one of the GPU compression algorithms |
| 74 |
(see TTextureCompression). |
| 75 |
|
| 76 |
If the image comes from a TCompositeImage file (DDS, KTX...), it will also return it |
| 77 |
(if not, Composite returned will be @nil). This allows you to e.g. use |
| 78 |
texture mipmaps recorded there. Note that Composite.OwnsFirstImage is set |
| 79 |
to @false, so you can always safely free everything by simple |
| 80 |
@code(FreeAndNil(Image); FreeAndNil(Composite);). |
| 81 |
|
| 82 |
Overloaded version without Composite parameter assumes you're |
| 83 |
not interested in this information (still it handles Composite files of course, |
| 84 |
it just doesn't return Composite object instance). |
| 85 |
|
| 86 |
@groupBegin } |
| 87 |
function LoadTextureImage(const Url: String; |
| 88 |
out Composite: TCompositeImage; |
| 89 |
const LoadOptions: TLoadImageOptions = []): TEncodedImage; overload; |
| 90 |
function LoadTextureImage(const Url: String; |
| 91 |
const LoadOptions: TLoadImageOptions = []): TEncodedImage; overload; |
| 92 |
{ @groupEnd } |
| 93 |
|
| 94 |
type |
| 95 |
{ A cache of loaded images for textures. |
| 96 |
|
| 97 |
Load by TextureImage_IncReference, free by TextureImage_DecReference. |
| 98 |
These replace LoadTextureImage, and manual freeing of Image/Composite. |
| 99 |
|
| 100 |
If you used IncReference that returns Composite, then you should also |
| 101 |
free using DecReference that takes Composite. |
| 102 |
If you used IncReference without Composite parameter, then also |
| 103 |
free using DecReference without Composite parameter. |
| 104 |
|
| 105 |
The idea is that instead of @code(LoadTextureImage(...)) call |
| 106 |
@code(Cache.TextureImage_IncReference(...)). |
| 107 |
Later, instead of freeing this image, call |
| 108 |
@code(TextureImage_DecReference(Image)). From your point of view, things |
| 109 |
will work the same. But if you expect to load many textures from the |
| 110 |
same URL, then you will get a great speed and memory saving, |
| 111 |
because image will only be actually loaded once. Notes: |
| 112 |
|
| 113 |
@unorderedList( |
| 114 |
@item(Note that in case of problems with loading, |
| 115 |
TextureImage_IncReference may raise an exception, just like normal |
| 116 |
LoadTextureImage. In this case it's guaranteed that no reference will |
| 117 |
be incremented, of course. If LoadTextureImage_IncReference returns |
| 118 |
in a normal way, then it will return something non-@nil, just like |
| 119 |
LoadTextureImage does.) |
| 120 |
|
| 121 |
@item(LoadTextureImage_DecReference alwas sets Image to @nil, like FreeAndNil.) |
| 122 |
|
| 123 |
@item(Since detecting image alpha channel type may be a little time-consuming |
| 124 |
(iteration over all pixels is needed), we also do it here |
| 125 |
and save in cache.) |
| 126 |
) |
| 127 |
|
| 128 |
Note that before destroying this object you must free all textures, |
| 129 |
i.e. call LoadTextureImage_DecReference for all images allocated by |
| 130 |
LoadTextureImage_IncReference. @italic(This class is not a lousy way |
| 131 |
of avoiding memory leaks) --- it would be a bad idea, because it would |
| 132 |
cause sloppy programming, where memory is unnecessarily allocated for |
| 133 |
a long time. In fact, this class asserts in destructor that no images |
| 134 |
are in cache anymore, so if you compiled with assertions enabled, |
| 135 |
this class does the job of memory-leak detector. } |
| 136 |
TTexturesVideosCache = class(TVideosCache) |
| 137 |
private |
| 138 |
type |
| 139 |
{ Internal for TTexturesVideosCache. @exclude } |
| 140 |
TCachedTexture = class |
| 141 |
References: Cardinal; |
| 142 |
Url: String; |
| 143 |
LoadOptions: TLoadImageOptions; |
| 144 |
Image: TEncodedImage; |
| 145 |
Composite: TCompositeImage; |
| 146 |
AlphaChannel: TAlphaChannel; |
| 147 |
end; |
| 148 |
TCachedTextureList = {$ifdef FPC}specialize{$endif} TObjectList<TCachedTexture>; |
| 149 |
var |
| 150 |
CachedTextures: TCachedTextureList; |
| 151 |
public |
| 152 |
constructor Create; |
| 153 |
destructor Destroy; override; |
| 154 |
|
| 155 |
function TextureImage_IncReference(const Url: String; |
| 156 |
out Composite: TCompositeImage; |
| 157 |
out AlphaChannel: TAlphaChannel; |
| 158 |
const LoadOptions: TLoadImageOptions = []): TEncodedImage; overload; |
| 159 |
function TextureImage_IncReference(const Url: String; |
| 160 |
out AlphaChannel: TAlphaChannel; |
| 161 |
const LoadOptions: TLoadImageOptions = []): TEncodedImage; overload; |
| 162 |
function TextureImage_IncReference(const Url: String; |
| 163 |
const LoadOptions: TLoadImageOptions = []): TEncodedImage; overload; |
| 164 |
|
| 165 |
procedure TextureImage_DecReference(var Image: TEncodedImage; var Composite: TCompositeImage); overload; |
| 166 |
procedure TextureImage_DecReference(var Image: TEncodedImage); overload; |
| 167 |
|
| 168 |
function Empty: boolean; override; |
| 169 |
end; |
| 170 |
|
| 171 |
var |
| 172 |
{ Log texture cache events. Allows to see how the cache performs, |
| 173 |
and also how alpha channel is detected. |
| 174 |
A @italic(lot) of log messages. |
| 175 |
|
| 176 |
Meaningful only if you initialized log (see CastleLog unit) by InitializeLog first. } |
| 177 |
LogTextureCache: boolean = false; |
| 178 |
|
| 179 |
{ Cache of texture images, equal to X3DCache |
| 180 |
and automatically initialized / finalized if you use X3DNodes unit. } |
| 181 |
TextureCache: TTexturesVideosCache; |
| 182 |
|
| 183 |
{ Use the auto-generated alternative downscaled images. |
| 184 |
This allows to conserve both GPU memory and loading time |
| 185 |
by using a downscaled images versions. |
| 186 |
|
| 187 |
The subset of your images which are affected by this must be declared inside |
| 188 |
the material_properties.xml file. |
| 189 |
And the image files must be prepared earlier by the build tool call |
| 190 |
@code("castle-engine auto-generate-textures"). |
| 191 |
See the https://castle-engine.io/creating_data_auto_generated_textures.php#section_texture_scale . |
| 192 |
|
| 193 |
Each size (width, height, and (for 3D images) depth) is scaled |
| 194 |
by @code(1 / 2^(TextureLoadingScale-1)). |
| 195 |
So value = 1 means no scaling, value = 2 means that each size is 1/2 |
| 196 |
(texture area is 1/4), value = 3 means that each size is 1/4 and so on. |
| 197 |
|
| 198 |
This mechanism will @italic(not) |
| 199 |
automatically downscale textures at runtime. If the downscaled texture version |
| 200 |
should exist, according to the material_properties.xml file, |
| 201 |
but it doesn't, then texture loading will simply fail. |
| 202 |
If you want to scale the texture at runtime, use the similar @link(GLTextureScale) |
| 203 |
instead. |
| 204 |
|
| 205 |
This mechanism is independent from GLTextureScale: |
| 206 |
|
| 207 |
@unorderedList( |
| 208 |
@item(Scaling indicated by GLTextureScale is performed at runtime, |
| 209 |
after loading. It happens @bold(after) the results of |
| 210 |
TextureLoadingScale have already been applied.) |
| 211 |
|
| 212 |
@item(The GLTextureScale works on a different subset of textures. |
| 213 |
|
| 214 |
For GLTextureScale, the usage of a texture determines if it's a GUI texture |
| 215 |
(which cannot be scaled) or not. |
| 216 |
So textures loaded through TDrawableImage, or declared as guiTexture in X3D, |
| 217 |
are not affected by GLTextureScale. All other textures are affected. |
| 218 |
It doesn't matter from where they are loaded -- so it affects also |
| 219 |
texture contents created by code, or downloaded from the Internet. |
| 220 |
|
| 221 |
In contrast, the TextureLoadingScale works (only) on all the images |
| 222 |
declared as having a downscaled version in material_properties.xml. |
| 223 |
It is not affected by how the texture will be used.) |
| 224 |
|
| 225 |
@item(The GLTextureScale works only on texture formats that can be scaled. |
| 226 |
In particular, it cannot scale textures compressed with a GPU compression |
| 227 |
(S3TC and such). It silently ignores them. |
| 228 |
|
| 229 |
In contrast, the TextureLoadingScale can cooperate with GPU-compressed textures, |
| 230 |
if you also compress them automatically using the material_properties.xml |
| 231 |
and the build tool call @code("castle-engine auto-generate-textures"). |
| 232 |
The downscaled image versions are generated from original (uncompressed, |
| 233 |
unscaled) images, and are then compressed.) |
| 234 |
|
| 235 |
@item(The GLTextureScale scaling is usually of worse quality, since it's |
| 236 |
done at runtime. |
| 237 |
|
| 238 |
In contrast, the downscaled textures used by TextureLoadingScale |
| 239 |
are generated as a preprocessing step. |
| 240 |
The build tool @code("castle-engine auto-generate-textures") may use |
| 241 |
a slower but higher-quality scaling.) |
| 242 |
) |
| 243 |
} |
| 244 |
TextureLoadingScale: Cardinal = 1; |
| 245 |
|
| 246 |
const |
| 247 |
{ We recommend using CastleRenderOptions unit to get these constants. |
| 248 |
But for backward compatibility, they are also available here. } |
| 249 |
minNearest = CastleRenderOptions.minNearest; |
| 250 |
minLinear = CastleRenderOptions.minLinear; |
| 251 |
minNearestMipmapNearest = CastleRenderOptions.minNearestMipmapNearest; |
| 252 |
minNearestMipmapLinear = CastleRenderOptions.minNearestMipmapLinear; |
| 253 |
minLinearMipmapNearest = CastleRenderOptions.minLinearMipmapNearest; |
| 254 |
minLinearMipmapLinear = CastleRenderOptions.minLinearMipmapLinear; |
| 255 |
minDefault = CastleRenderOptions.minDefault; |
| 256 |
minFastest = CastleRenderOptions.minFastest; |
| 257 |
minNicest = CastleRenderOptions.minNicest; |
| 258 |
|
| 259 |
magNearest = CastleRenderOptions.magNearest; |
| 260 |
magLinear = CastleRenderOptions.magLinear; |
| 261 |
magDefault = CastleRenderOptions.magDefault; |
| 262 |
magFastest = CastleRenderOptions.magFastest; |
| 263 |
magNicest = CastleRenderOptions.magNicest; |
| 264 |
|
| 265 |
{ Default frame per second for Sprite Sheet animations like Starling |
| 266 |
and Cocos2d. } |
| 267 |
DefaultSpriteSheetFramesPerSecond = 8.0; |
| 268 |
|
| 269 |
implementation |
| 270 |
|
| 271 |
uses SysUtils, CastleStringUtils, CastleLog, CastleUriUtils; |
| 272 |
|
| 273 |
function LoadTextureImage(const Url: String; out Composite: TCompositeImage; |
| 274 |
const LoadOptions: TLoadImageOptions): TEncodedImage; |
| 275 |
begin |
| 276 |
if not TCompositeImage.MatchesUrl(Url) then |
| 277 |
begin |
| 278 |
{ Note: We need to enable here GPU-compressed textures, TGPUCompressedImage, |
| 279 |
which is (for now) in TextureImageClassesAll, but not in TextureImageClasses. |
| 280 |
Otherwise loading non-composite but still GPU-compressed format, like .astc, |
| 281 |
would always fail (or go through DecompressTexture unpacking). |
| 282 |
|
| 283 |
Testcase: |
| 284 |
- fps_game on GPU supporting ASTC (michalis: worm-linux) |
| 285 |
- castle-model-viewer on demo-models/texturing_advanced/astc_compressed/textures_astc_compressed.x3dv |
| 286 |
|
| 287 |
Loading through TCompositeImage also allows them. |
| 288 |
} |
| 289 |
Result := LoadEncodedImage(Url, TextureImageClassesAll, LoadOptions); |
| 290 |
Composite := nil; |
| 291 |
end else |
| 292 |
begin |
| 293 |
Composite := TCompositeImage.Create; |
| 294 |
try |
| 295 |
Composite.LoadFromFile(Url, LoadOptions); |
| 296 |
Composite.OwnsFirstImage := false; |
| 297 |
Result := Composite.Images[0]; |
| 298 |
except |
| 299 |
FreeAndNil(Composite); |
| 300 |
raise; |
| 301 |
end; |
| 302 |
end; |
| 303 |
end; |
| 304 |
|
| 305 |
function LoadTextureImage(const Url: String; |
| 306 |
const LoadOptions: TLoadImageOptions): TEncodedImage; |
| 307 |
var |
| 308 |
Composite: TCompositeImage; |
| 309 |
begin |
| 310 |
Result := LoadTextureImage(Url, Composite, LoadOptions); |
| 311 |
Composite.Free; |
| 312 |
end; |
| 313 |
|
| 314 |
{ TTexturesVideosCache ------------------------------------------------- } |
| 315 |
|
| 316 |
constructor TTexturesVideosCache.Create; |
| 317 |
begin |
| 318 |
inherited; |
| 319 |
CachedTextures := TCachedTextureList.Create; |
| 320 |
end; |
| 321 |
|
| 322 |
destructor TTexturesVideosCache.Destroy; |
| 323 |
begin |
| 324 |
if CachedTextures <> nil then |
| 325 |
begin |
| 326 |
Assert(CachedTextures.Count = 0, ' Some references to texture images still exist ' + |
| 327 |
'when freeing TTexturesVideosCache'); |
| 328 |
FreeAndNil(CachedTextures); |
| 329 |
end; |
| 330 |
inherited; |
| 331 |
end; |
| 332 |
|
| 333 |
function TTexturesVideosCache.TextureImage_IncReference( |
| 334 |
const Url: String; |
| 335 |
out Composite: TCompositeImage; out AlphaChannel: TAlphaChannel; |
| 336 |
const LoadOptions: TLoadImageOptions): TEncodedImage; |
| 337 |
|
| 338 |
function AlphaChannelLog(const AC: TAlphaChannel): string; |
| 339 |
begin |
| 340 |
if AC <> acNone then |
| 341 |
Result := '. Detected as simple yes/no ("test") alpha channel: ' + BoolToStr(AC = acTest, true) else |
| 342 |
Result := ''; |
| 343 |
end; |
| 344 |
|
| 345 |
var |
| 346 |
I: Integer; |
| 347 |
C: TCachedTexture; |
| 348 |
begin |
| 349 |
for I := 0 to CachedTextures.Count - 1 do |
| 350 |
begin |
| 351 |
C := CachedTextures[I]; |
| 352 |
if (C.Url = Url) and |
| 353 |
(C.LoadOptions = LoadOptions) then |
| 354 |
begin |
| 355 |
Inc(C.References); |
| 356 |
|
| 357 |
if LogTextureCache then |
| 358 |
WritelnLog('++', 'Texture image %s: %d', [UriDisplay(Url), C.References]); |
| 359 |
|
| 360 |
Composite := C.Composite; |
| 361 |
AlphaChannel := C.AlphaChannel; |
| 362 |
Exit(C.Image); |
| 363 |
end; |
| 364 |
end; |
| 365 |
|
| 366 |
{ Initialize Result first, before calling CachedTextures.Add. |
| 367 |
That's because in case LoadTextureImage raises exception, |
| 368 |
we don't want to add image to cache (because caller would have |
| 369 |
no way to call TextureImage_DecReference later). } |
| 370 |
|
| 371 |
Result := LoadTextureImage(Url, Composite, LoadOptions); |
| 372 |
AlphaChannel := Result.AlphaChannel; |
| 373 |
|
| 374 |
C := TCachedTexture.Create; |
| 375 |
CachedTextures.Add(C); |
| 376 |
C.References := 1; |
| 377 |
C.Url := Url; |
| 378 |
C.LoadOptions := LoadOptions; |
| 379 |
C.Image := Result; |
| 380 |
C.Composite := Composite; |
| 381 |
C.AlphaChannel := AlphaChannel; |
| 382 |
|
| 383 |
if LogTextureCache then |
| 384 |
WritelnLog('++', 'Texture image %s: %d%s', |
| 385 |
[UriDisplay(Url), 1, AlphaChannelLog(AlphaChannel)]); |
| 386 |
end; |
| 387 |
|
| 388 |
procedure TTexturesVideosCache.TextureImage_DecReference( |
| 389 |
var Image: TEncodedImage; var Composite: TCompositeImage); |
| 390 |
var |
| 391 |
I: Integer; |
| 392 |
C: TCachedTexture; |
| 393 |
begin |
| 394 |
for I := 0 to CachedTextures.Count - 1 do |
| 395 |
begin |
| 396 |
C := CachedTextures[I]; |
| 397 |
if C.Image = Image then |
| 398 |
begin |
| 399 |
if LogTextureCache then |
| 400 |
WritelnLog('--', 'Texture image %s: %d', [UriDisplay(C.Url), C.References - 1]); |
| 401 |
|
| 402 |
{ We cannot simply assert |
| 403 |
|
| 404 |
C.Composite = Composite |
| 405 |
|
| 406 |
because when textures have many references, |
| 407 |
some references may be with and some without Composite information. |
| 408 |
We don't want to force all references to the same Url to always |
| 409 |
have or never have Composite information. (This would be uncomfortable |
| 410 |
for caller, as different nodes may share textures, e.g. VRML/X3D Background |
| 411 |
and ImageTexture nodes. They would all be forced to remember Composite |
| 412 |
information this way.) |
| 413 |
|
| 414 |
So we have to always keep Composite information in the cache, |
| 415 |
and free it, regardless of whether called knows this Composite information. |
| 416 |
|
| 417 |
Only if passed Composite <> nil (we know caller keeps it) then we can |
| 418 |
check it for correctness. } |
| 419 |
|
| 420 |
Assert((Composite = nil) or (C.Composite = Composite), 'Image pointers match in TTexturesVideosCache, Composite pointers should match too'); |
| 421 |
|
| 422 |
Image := nil; |
| 423 |
Composite := nil; |
| 424 |
|
| 425 |
if C.References = 1 then |
| 426 |
begin |
| 427 |
FreeAndNil(C.Image); |
| 428 |
FreeAndNil(C.Composite); |
| 429 |
CachedTextures.Delete(I); |
| 430 |
CheckEmpty; |
| 431 |
end else |
| 432 |
Dec(C.References); |
| 433 |
|
| 434 |
Exit; |
| 435 |
end; |
| 436 |
end; |
| 437 |
|
| 438 |
raise EInternalError.CreateFmt( |
| 439 |
'TTexturesVideosCache.TextureImage_DecReference: no reference found for texture image %s', |
| 440 |
[PointerToStr(Image)]); |
| 441 |
end; |
| 442 |
|
| 443 |
function TTexturesVideosCache.TextureImage_IncReference( |
| 444 |
const Url: String; out AlphaChannel: TAlphaChannel; |
| 445 |
const LoadOptions: TLoadImageOptions): TEncodedImage; |
| 446 |
var |
| 447 |
Dummy: TCompositeImage; |
| 448 |
begin |
| 449 |
Result := TextureImage_IncReference(Url, Dummy, AlphaChannel, LoadOptions); |
| 450 |
end; |
| 451 |
|
| 452 |
function TTexturesVideosCache.TextureImage_IncReference(const Url: String; |
| 453 |
const LoadOptions: TLoadImageOptions): TEncodedImage; |
| 454 |
var |
| 455 |
DummyAlphaChannel: TAlphaChannel; |
| 456 |
begin |
| 457 |
Result := TextureImage_IncReference(Url, DummyAlphaChannel, LoadOptions); |
| 458 |
end; |
| 459 |
|
| 460 |
procedure TTexturesVideosCache.TextureImage_DecReference( |
| 461 |
var Image: TEncodedImage); |
| 462 |
var |
| 463 |
Dummy: TCompositeImage; |
| 464 |
begin |
| 465 |
Dummy := nil; |
| 466 |
TextureImage_DecReference(Image, Dummy); |
| 467 |
end; |
| 468 |
|
| 469 |
function TTexturesVideosCache.Empty: boolean; |
| 470 |
begin |
| 471 |
Result := (inherited Empty) and (CachedTextures.Count = 0); |
| 472 |
end; |
| 473 |
|
| 474 |
end. |