Debian Codegraph @

src/images/castleinternalcompositeimage_dds.inc

raw
1 {%MainUnit castleinternalcompositeimage.pas}
2 {
3 Copyright 2009-2022 Michalis Kamburelis.
4
5 This file is part of "Castle Game Engine".
6
7 "Castle Game Engine" is free software; see the file COPYING.txt,
8 included in this distribution, for details about the copyright.
9
10 "Castle Game Engine" is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
14 ----------------------------------------------------------------------------
15 }
16
17 { DDS loading and saving. }
18
19 { ----------------------------------------------------------------------------
20 Constants and types for DDS file handling.
21
22 This is based on MS docs on
23 http://msdn.microsoft.com/en-us/library/bb943991(VS.85).aspx
24 and gimp-dds/gimp-dds-2.0.7/dds.h,
25 from gimp-dds plugin source code
26 from http://nifelheim.dyndns.org/~cocidius/dds/.
27
28 (gimp-dds is GNU GPL >= 2, and our engine is on LGPL >= 2,
29 but I think it's Ok --- I did't copy code, just constant values
30 known from DDS spec, and converted to Pascal). }
31
32 const
33 DDSD_CAPS = $00000001;
34 DDSD_HEIGHT = $00000002;
35 DDSD_WIDTH = $00000004;
36 DDSD_PITCH = $00000008;
37 DDSD_PIXELFORMAT = $00001000;
38 DDSD_MIPMAPCOUNT = $00020000;
39 DDSD_LINEARSIZE = $00080000;
40 DDSD_DEPTH = $00800000;
41
42 DDPF_ALPHAPIXELS = $00000001;
43 DDPF_ALPHA = $00000002;
44 DDPF_FOURCC = $00000004;
45 DDPF_PALETTEINDEXED8 = $00000020;
46 DDPF_RGB = $00000040;
47 DDPF_LUMINANCE = $00020000;
48
49 DDSCAPS_COMPLEX = $00000008;
50 DDSCAPS_TEXTURE = $00001000;
51 DDSCAPS_MIPMAP = $00400000;
52
53 DDSCAPS2_CUBEMAP = $00000200;
54 DDSCAPS2_CUBEMAP_POSITIVEX = $00000400;
55 DDSCAPS2_CUBEMAP_NEGATIVEX = $00000800;
56 DDSCAPS2_CUBEMAP_POSITIVEY = $00001000;
57 DDSCAPS2_CUBEMAP_NEGATIVEY = $00002000;
58 DDSCAPS2_CUBEMAP_POSITIVEZ = $00004000;
59 DDSCAPS2_CUBEMAP_NEGATIVEZ = $00008000;
60 DDSCAPS2_VOLUME = $00200000;
61
62 { Special FourCC constants, indicating float textures,
63 from OGRE OgreDDSCodec.cpp. }
64 D3DFMT_R16F = 111;
65 D3DFMT_G16R16F = 112;
66 D3DFMT_A16B16G16R16F = 113;
67 D3DFMT_R32F = 114;
68 D3DFMT_G32R32F = 115;
69 D3DFMT_A32B32G32R32F = 116;
70
71 { Constants for DxgiFormat, see
72 https://msdn.microsoft.com/en-us/library/windows/desktop/bb173059%28v=vs.85%29.aspx }
73 DXGI_FORMAT_UNKNOWN = 0;
74 DXGI_FORMAT_R32G32B32A32_TYPELESS = 1;
75 DXGI_FORMAT_R32G32B32A32_FLOAT = 2;
76 DXGI_FORMAT_R32G32B32A32_UINT = 3;
77 DXGI_FORMAT_R32G32B32A32_SINT = 4;
78 DXGI_FORMAT_R32G32B32_TYPELESS = 5;
79 DXGI_FORMAT_R32G32B32_FLOAT = 6;
80 DXGI_FORMAT_R32G32B32_UINT = 7;
81 DXGI_FORMAT_R32G32B32_SINT = 8;
82 DXGI_FORMAT_R16G16B16A16_TYPELESS = 9;
83 DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
84 DXGI_FORMAT_R16G16B16A16_UNORM = 11;
85 DXGI_FORMAT_R16G16B16A16_UINT = 12;
86 DXGI_FORMAT_R16G16B16A16_SNORM = 13;
87 DXGI_FORMAT_R16G16B16A16_SINT = 14;
88 DXGI_FORMAT_R32G32_TYPELESS = 15;
89 DXGI_FORMAT_R32G32_FLOAT = 16;
90 DXGI_FORMAT_R32G32_UINT = 17;
91 DXGI_FORMAT_R32G32_SINT = 18;
92 DXGI_FORMAT_R32G8X24_TYPELESS = 19;
93 DXGI_FORMAT_D32_FLOAT_S8X24_UINT = 20;
94 DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS = 21;
95 DXGI_FORMAT_X32_TYPELESS_G8X24_UINT = 22;
96 DXGI_FORMAT_R10G10B10A2_TYPELESS = 23;
97 DXGI_FORMAT_R10G10B10A2_UNORM = 24;
98 DXGI_FORMAT_R10G10B10A2_UINT = 25;
99 DXGI_FORMAT_R11G11B10_FLOAT = 26;
100 DXGI_FORMAT_R8G8B8A8_TYPELESS = 27;
101 DXGI_FORMAT_R8G8B8A8_UNORM = 28;
102 DXGI_FORMAT_R8G8B8A8_UNORM_SRGB = 29;
103 DXGI_FORMAT_R8G8B8A8_UINT = 30;
104 DXGI_FORMAT_R8G8B8A8_SNORM = 31;
105 DXGI_FORMAT_R8G8B8A8_SINT = 32;
106 DXGI_FORMAT_R16G16_TYPELESS = 33;
107 DXGI_FORMAT_R16G16_FLOAT = 34;
108 DXGI_FORMAT_R16G16_UNORM = 35;
109 DXGI_FORMAT_R16G16_UINT = 36;
110 DXGI_FORMAT_R16G16_SNORM = 37;
111 DXGI_FORMAT_R16G16_SINT = 38;
112 DXGI_FORMAT_R32_TYPELESS = 39;
113 DXGI_FORMAT_D32_FLOAT = 40;
114 DXGI_FORMAT_R32_FLOAT = 41;
115 DXGI_FORMAT_R32_UINT = 42;
116 DXGI_FORMAT_R32_SINT = 43;
117 DXGI_FORMAT_R24G8_TYPELESS = 44;
118 DXGI_FORMAT_D24_UNORM_S8_UINT = 45;
119 DXGI_FORMAT_R24_UNORM_X8_TYPELESS = 46;
120 DXGI_FORMAT_X24_TYPELESS_G8_UINT = 47;
121 DXGI_FORMAT_R8G8_TYPELESS = 48;
122 DXGI_FORMAT_R8G8_UNORM = 49;
123 DXGI_FORMAT_R8G8_UINT = 50;
124 DXGI_FORMAT_R8G8_SNORM = 51;
125 DXGI_FORMAT_R8G8_SINT = 52;
126 DXGI_FORMAT_R16_TYPELESS = 53;
127 DXGI_FORMAT_R16_FLOAT = 54;
128 DXGI_FORMAT_D16_UNORM = 55;
129 DXGI_FORMAT_R16_UNORM = 56;
130 DXGI_FORMAT_R16_UINT = 57;
131 DXGI_FORMAT_R16_SNORM = 58;
132 DXGI_FORMAT_R16_SINT = 59;
133 DXGI_FORMAT_R8_TYPELESS = 60;
134 DXGI_FORMAT_R8_UNORM = 61;
135 DXGI_FORMAT_R8_UINT = 62;
136 DXGI_FORMAT_R8_SNORM = 63;
137 DXGI_FORMAT_R8_SINT = 64;
138 DXGI_FORMAT_A8_UNORM = 65;
139 DXGI_FORMAT_R1_UNORM = 66;
140 DXGI_FORMAT_R9G9B9E5_SHAREDEXP = 67;
141 DXGI_FORMAT_R8G8_B8G8_UNORM = 68;
142 DXGI_FORMAT_G8R8_G8B8_UNORM = 69;
143 DXGI_FORMAT_BC1_TYPELESS = 70;
144 DXGI_FORMAT_BC1_UNORM = 71;
145 DXGI_FORMAT_BC1_UNORM_SRGB = 72;
146 DXGI_FORMAT_BC2_TYPELESS = 73;
147 DXGI_FORMAT_BC2_UNORM = 74;
148 DXGI_FORMAT_BC2_UNORM_SRGB = 75;
149 DXGI_FORMAT_BC3_TYPELESS = 76;
150 DXGI_FORMAT_BC3_UNORM = 77;
151 DXGI_FORMAT_BC3_UNORM_SRGB = 78;
152 DXGI_FORMAT_BC4_TYPELESS = 79;
153 DXGI_FORMAT_BC4_UNORM = 80;
154 DXGI_FORMAT_BC4_SNORM = 81;
155 DXGI_FORMAT_BC5_TYPELESS = 82;
156 DXGI_FORMAT_BC5_UNORM = 83;
157 DXGI_FORMAT_BC5_SNORM = 84;
158 DXGI_FORMAT_B5G6R5_UNORM = 85;
159 DXGI_FORMAT_B5G5R5A1_UNORM = 86;
160 DXGI_FORMAT_B8G8R8A8_UNORM = 87;
161 DXGI_FORMAT_B8G8R8X8_UNORM = 88;
162 DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM = 89;
163 DXGI_FORMAT_B8G8R8A8_TYPELESS = 90;
164 DXGI_FORMAT_B8G8R8A8_UNORM_SRGB = 91;
165 DXGI_FORMAT_B8G8R8X8_TYPELESS = 92;
166 DXGI_FORMAT_B8G8R8X8_UNORM_SRGB = 93;
167 DXGI_FORMAT_BC6H_TYPELESS = 94;
168 DXGI_FORMAT_BC6H_UF16 = 95;
169 DXGI_FORMAT_BC6H_SF16 = 96;
170 DXGI_FORMAT_BC7_TYPELESS = 97;
171 DXGI_FORMAT_BC7_UNORM = 98;
172 DXGI_FORMAT_BC7_UNORM_SRGB = 99;
173 DXGI_FORMAT_AYUV = 100;
174 DXGI_FORMAT_Y410 = 101;
175 DXGI_FORMAT_Y416 = 102;
176 DXGI_FORMAT_NV12 = 103;
177 DXGI_FORMAT_P010 = 104;
178 DXGI_FORMAT_P016 = 105;
179 DXGI_FORMAT_420_OPAQUE = 106;
180 DXGI_FORMAT_YUY2 = 107;
181 DXGI_FORMAT_Y210 = 108;
182 DXGI_FORMAT_Y216 = 109;
183 DXGI_FORMAT_NV11 = 110;
184 DXGI_FORMAT_AI44 = 111;
185 DXGI_FORMAT_IA44 = 112;
186 DXGI_FORMAT_P8 = 113;
187 DXGI_FORMAT_A8P8 = 114;
188 DXGI_FORMAT_B4G4R4A4_UNORM = 115;
189
190 type
191 TDDSPixelFormat = packed record
192 Size: UInt32;
193 Flags: UInt32;
194 case Integer of
195 0: ( FourCC: array [0 .. 3] of AnsiChar;
196 RGBBitCount: UInt32;
197 RBitMask: UInt32;
198 GBitMask: UInt32;
199 BBitMask: UInt32;
200 ABitMask: UInt32; );
201 1: ( { Alternative FourCC view, as UInt32, always in little endian memory
202 order (process with LEtoN to compare with ints). }
203 FourCCIntLE: UInt32; )
204
205 end;
206 PDDSPixelFormat = ^TDDSPixelFormat;
207
208 { Corresponds to DDS_HEADER (Direct3D 10),
209 http://msdn.microsoft.com/en-us/library/bb943982(VS.85).aspx. }
210 TDDSHeader = packed record
211 Size: UInt32;
212 Flags: UInt32;
213 Height: UInt32;
214 Width: UInt32;
215 PitchOrLinearSize: UInt32;
216 Depth: UInt32;
217 MipMapCount: UInt32;
218 Reserved: array [0 .. 10] of UInt32;
219 PixelFormat: TDDSPixelFormat;
220 Caps1: UInt32;
221 Caps2: UInt32;
222 ReservedCaps: array [0 .. 1] of UInt32;
223 Reserved2: UInt32;
224 end;
225
226 { DDS header extension to handle resource arrays,
227 DXGI pixel formats that don't map to the legacy Microsoft DirectDraw
228 pixel format structures, and additional metadata.
229 From https://msdn.microsoft.com/en-us/library/windows/desktop/bb943983%28v=vs.85%29.aspx }
230 TDDSHeaderDxt10 = packed record
231 DxgiFormat: UInt32;
232 ResourceDimension: UInt32;
233 MiscFlag: UInt32;
234 ArraySize: UInt32;
235 MiscFlags2: UInt32;
236 end;
237
238 { TDDSRowReader -------------------------------------------------------------- }
239
240 type
241 TRGBAChannel = 0..3;
242
243 TChannelInfo = record
244 Mask: UInt32;
245 { Shift (to the right, by ShiftR) to fit into Byte }
246 ShiftToByte: Integer;
247 { Shift (to the right, by ShiftR) to have the least significant bit at
248 1st position. }
249 ShiftToLeast: Integer;
250 { How long is the sequence of 1 bits inside the mask. }
251 MaskOnes: Cardinal;
252 end;
253
254 { Reads DDS image rows, loading them to temporary memory.
255
256 After reading row (by ReadRow) you can uncompress it by
257 using RGBA (returns value as 8-bit Byte, for Red, Green, Blue, Alpha
258 according to Channel parameter)
259 and NextPixel repeatedly.
260
261 It's callers responsibility to make sure that you use
262 RGBA only with channels for which masks are non-zero.
263
264 This is not the most efficient reader (it reads rows to temporary memory,
265 for starters), but it works for all covered uncompressed non-palette
266 DDS pixel formats. For special pixel formats, we use specialized
267 optimized readers in ReadOptimized_*. }
268 TDDSRowReader = class
269 private
270 FPixelFormat: PDDSPixelFormat;
271 FWidth, FRowBytePadding: Cardinal;
272 Row: Pointer;
273 Pixel: Pointer;
274 PixelValue: UInt32;
275 RowByteSize, PixelByteSize: Cardinal;
276 Channels: array [TRGBAChannel] of TChannelInfo;
277 procedure CalculatePixelValue;
278 public
279 constructor Create(const PixelFormat: PDDSPixelFormat;
280 const Width, RowBytePadding: Cardinal);
281 destructor Destroy; override;
282
283 procedure ReadRow(Stream: TStream);
284 procedure NextPixel;
285 function RGBA(Channel: TRGBAChannel): Byte;
286 end;
287
288 { Shift bits to the right if Value is positive.
289 Shift to the left if negative. }
290 function ShiftR(const Value: UInt32; const Shift: Integer): UInt32;
291 begin
292 if Shift >= 0 then
293 Result := Value shr Shift else
294 Result := Value shl (-Shift);
295 end;
296
297 constructor TDDSRowReader.Create(const PixelFormat: PDDSPixelFormat;
298 const Width, RowBytePadding: Cardinal);
299
300 { Calculate TChannelInfo. }
301 procedure CalculateChannelInfo(const Mask: UInt32; var Info: TChannelInfo);
302 const
303 High1 = UInt32(1) shl 31;
304 var
305 LeadingZeros, Ones: Integer;
306 M: UInt32;
307 begin
308 Info.Mask := Mask;
309
310 if Mask = 0 then
311 begin
312 Info.ShiftToByte := 0;
313 Info.ShiftToLeast := 0;
314 Info.MaskOnes := 0;
315 Exit;
316 end;
317
318 M := Mask;
319
320 LeadingZeros := 0;
321 while M and High1 = 0 do
322 begin
323 Inc(LeadingZeros);
324 M := M shl 1;
325 end;
326
327 Ones := 0;
328 while M <> 0 do
329 begin
330 Inc(Ones);
331 M := M shl 1;
332 end;
333 Info.MaskOnes := Ones;
334
335 { So the mask in binary starts with LeadingZeros of 0,
336 then some 1. After Ones digits, the mask is zero.
337
338 (In other words, we have a sequence of Ones bits inside the Mask
339 that start and end with digit 1. We could assume here that
340 this sequence is just full of 1 (nothing produces DDS
341 files with other values, that would be pretty strange).
342 But that's not actually necessary, all we need is to know
343 the position of the most and least significant 1 digit,
344 and then the trivial equation below will work Ok. }
345
346 Info.ShiftToByte := 24 - LeadingZeros;
347 Info.ShiftToLeast := 32 - LeadingZeros - Ones;
348
349 { Assert that after shifting, all bits above Byte are clear
350 and the most significant bit of color is in the most significant bit
351 of byte. }
352 Assert(ShiftR(Mask, Info.ShiftToByte) and $FFFFFF80 = $80);
353 end;
354
355 begin
356 inherited Create;
357 FPixelFormat := PixelFormat;
358 FWidth := Width;
359 FRowBytePadding := RowBytePadding;
360
361 { We already checked in TCompositeImage.LoadFromStream that RGBitCount divides
362 by 8 and is not zero. }
363 PixelByteSize := FPixelFormat^.RGBBitCount div 8;
364
365 if PixelByteSize > SizeOf(PixelValue) then
366 raise EInvalidDDS.CreateFmt('Unsupported DDS pixel format: more than 32 bits per pixel (RGBitCount is %d). Please report with sample image',
367 [FPixelFormat^.RGBBitCount]);
368
369 RowByteSize := PixelByteSize * Width;
370 Row := GetMem(RowByteSize);
371
372 CalculateChannelInfo(FPixelFormat^.RBitMask, Channels[0]);
373 CalculateChannelInfo(FPixelFormat^.GBitMask, Channels[1]);
374 CalculateChannelInfo(FPixelFormat^.BBitMask, Channels[2]);
375 CalculateChannelInfo(FPixelFormat^.ABitMask, Channels[3]);
376 end;
377
378 destructor TDDSRowReader.Destroy;
379 begin
380 FreeMem(Row);
381 inherited;
382 end;
383
384 procedure TDDSRowReader.CalculatePixelValue;
385 begin
386 PixelValue := 0;
387
388 { The tricky memory part: move the meaningful bytes of current pixel
389 (under Pixel^) to appropriate part of PixelValue, such that
390 PixelValue can be directly and'ed with DDS masks (in ChannelMask[]).
391 The copied bytes are the least significant part of UInt32 value
392 (DDS masks are specified like that). }
393
394 Move(Pixel^, Pointer(PtrUInt(PtrUInt(@PixelValue)
395 {$ifdef ENDIAN_BIG} + SizeOf(PixelValue) - PixelByteSize {$endif} ))^,
396 PixelByteSize);
397 end;
398
399 procedure TDDSRowReader.ReadRow(Stream: TStream);
400 begin
401 Stream.ReadBuffer(Row^, RowByteSize);
402
403 if FRowBytePadding <> 0 then
404 Stream.Seek(FRowBytePadding, soFromCurrent);
405
406 Pixel := Row;
407 CalculatePixelValue;
408 end;
409
410 procedure TDDSRowReader.NextPixel;
411 begin
412 PtrUInt(Pixel) := PtrUInt(Pixel) + PixelByteSize;
413 CalculatePixelValue;
414 end;
415
416 function TDDSRowReader.RGBA(Channel: TRGBAChannel): Byte;
417 begin
418 with Channels[Channel] do
419 begin
420 Result := ShiftR(PixelValue and Mask, ShiftToByte);
421
422 { What to with bits that are not set by PixelValue?
423 That is, when the mask is less than 8 bits?
424
425 It's important that pure white be preserved as pure white,
426 and pure black as pure black. This is especially important for alpha
427 channel (otherwise opaque image will suddenly turn into
428 partially transparent, e.g. if you load image with 2 bits for alpha,
429 and fill the remaining 6 bits with 0, then alpha = 11 (binary)
430 will be turned into 11000000 (no longer completely opaque).)
431
432 So it seems most sensible to fill the remaining bits with the contents
433 of least-significant color bit. If this bit is zero, we actually
434 have to do nothing, but when it's one --- we need to insert 1 bits
435 into Result.
436
437 This is done only when MaskOnes < 8, to optimize. }
438 if (MaskOnes < 8) and
439 (ShiftR(PixelValue, ShiftToLeast) and 1 <> 0) then
440 begin
441 { So the least-significant color bit is 1. }
442 Result := Result or (ShiftR(not Mask, ShiftToByte) and $FF);
443 end;
444 end;
445 end;
446
447 { TDDSHandler ----------------------------------------------------------------- }
448
449 type
450 TDDSHandler = class(TCompositeFormatHandler)
451 strict private
452 { A couple of optimized routines for image formats that
453 closely match corresponding Images unit memory format are below.
454 Optimized routines already know the Result memory format (image class)
455 and file format (Header.PixelFormat), they don't have to check them.
456
457 Names for optimized routines follow the naming of DDS ms docs.
458 This means that they are actually inverted in memory,
459 since DDS bit masks should be treated as little-endian.
460 For example for RGB image, RBitMask = $ff0000 means that red is
461 the 3rd (not 1st) byte...)
462
463 That's why DDS format RGB8 must be inverted when writing to TRGBImage.
464 The format matching exactly TRGBImage is actually named BGR8 in DDS.
465
466 The optimized routines are much faster as they don't use TDDSRowReader,
467 so they don't need a temporary row (they load directly into output
468 image memory), they don't need any mask/shift operations for each channel
469 of each pixel (as the pixel format already matches what is needed,
470 eventual swaps BGR<->RGB are fast).
471 Tests shown that optimized versions are 4-7 times faster than
472 if TDDSRowReader would be used to read the same images.
473 }
474
475 class procedure ReadOptimized_G8(const Stream: TStream;
476 const Image: TCastleImage; const RowBytePadding: Integer); static;
477 class procedure ReadOptimized_AG8(const Stream: TStream;
478 const Image: TCastleImage; const RowBytePadding: Integer); static;
479 class procedure ReadOptimized_RGB8(const Stream: TStream;
480 const Image: TCastleImage; const RowBytePadding: Integer); static;
481 class procedure ReadOptimized_BGR8(const Stream: TStream;
482 const Image: TCastleImage; const RowBytePadding: Integer); static;
483 class procedure ReadOptimized_ARGB8(const Stream: TStream;
484 const Image: TCastleImage; const RowBytePadding: Integer); static;
485 class procedure ReadOptimized_ABGR8(const Stream: TStream;
486 const Image: TCastleImage; const RowBytePadding: Integer); static;
487 public
488 procedure LoadFromStream(const Stream: TStream; const Url: String); override;
489 procedure SaveToStream(const Stream: TStream); override;
490 end;
491
492 class procedure TDDSHandler.ReadOptimized_G8(const Stream: TStream;
493 const Image: TCastleImage; const RowBytePadding: Integer);
494 var
495 Y, Z: Integer;
496 begin
497 for Z := 0 to Image.Depth - 1 do
498 for Y := Image.Height - 1 downto 0 do
499 begin
500 Stream.ReadBuffer(Image.RowPtr(Y, Z)^, Image.PixelSize * Image.Width);
501 if RowBytePadding <> 0 then
502 Stream.Seek(RowBytePadding, soFromCurrent);
503 end;
504 end;
505
506 class procedure TDDSHandler.ReadOptimized_AG8(const Stream: TStream;
507 const Image: TCastleImage; const RowBytePadding: Integer);
508 var
509 Y, Z: Integer;
510 begin
511 for Z := 0 to Image.Depth - 1 do
512 for Y := Image.Height - 1 downto 0 do
513 begin
514 Stream.ReadBuffer(Image.RowPtr(Y, Z)^, Image.PixelSize * Image.Width);
515 if RowBytePadding <> 0 then
516 Stream.Seek(RowBytePadding, soFromCurrent);
517 end;
518 end;
519
520 class procedure TDDSHandler.ReadOptimized_RGB8(const Stream: TStream;
521 const Image: TCastleImage; const RowBytePadding: Integer);
522 var
523 X, Y, Z: Integer;
524 Row: PVector3Byte;
525 begin
526 for Z := 0 to Image.Depth - 1 do
527 for Y := Image.Height - 1 downto 0 do
528 begin
529 Row := Image.RowPtr(Y, Z);
530 Stream.ReadBuffer(Row^, Image.PixelSize * Image.Width);
531
532 { Now invert red and blue. (Since all masks are little-endian,
533 RBitMask = $FF0000 means that red is the 3rd (not 1st) byte...) }
534 for X := 0 to Image.Width - 1 do
535 begin
536 SwapValues(Row^.Z, Row^.X);
537 Inc(Row);
538 end;
539
540 if RowBytePadding <> 0 then
541 Stream.Seek(RowBytePadding, soFromCurrent);
542 end;
543 end;
544
545 class procedure TDDSHandler.ReadOptimized_BGR8(const Stream: TStream;
546 const Image: TCastleImage; const RowBytePadding: Integer);
547 var
548 Y, Z: Integer;
549 begin
550 for Z := 0 to Image.Depth - 1 do
551 for Y := Image.Height - 1 downto 0 do
552 begin
553 Stream.ReadBuffer(Image.RowPtr(Y, Z)^, Image.PixelSize * Image.Width);
554 if RowBytePadding <> 0 then
555 Stream.Seek(RowBytePadding, soFromCurrent);
556 end;
557 end;
558
559 class procedure TDDSHandler.ReadOptimized_ARGB8(const Stream: TStream;
560 const Image: TCastleImage; const RowBytePadding: Integer);
561 var
562 X, Y, Z: Integer;
563 Row: PVector4Byte;
564 begin
565 for Z := 0 to Image.Depth - 1 do
566 for Y := Image.Height - 1 downto 0 do
567 begin
568 Row := Image.RowPtr(Y, Z);
569 Stream.ReadBuffer(Row^, Image.PixelSize * Image.Width);
570
571 { Now invert ARGB to ABGR. So swap red<->blue, alpha and green are Ok. }
572 for X := 0 to Image.Width - 1 do
573 begin
574 SwapValues(Row^.Z, Row^.X);
575 Inc(Row);
576 end;
577
578 if RowBytePadding <> 0 then
579 Stream.Seek(RowBytePadding, soFromCurrent);
580 end;
581 end;
582
583 class procedure TDDSHandler.ReadOptimized_ABGR8(const Stream: TStream;
584 const Image: TCastleImage; const RowBytePadding: Integer);
585 var
586 Y, Z: Integer;
587 begin
588 for Z := 0 to Image.Depth - 1 do
589 for Y := Image.Height - 1 downto 0 do
590 begin
591 Stream.ReadBuffer(Image.RowPtr(Y, Z)^, Image.PixelSize * Image.Width);
592 if RowBytePadding <> 0 then
593 Stream.Seek(RowBytePadding, soFromCurrent);
594 end;
595 end;
596
597 procedure TDDSHandler.LoadFromStream(const Stream: TStream; const Url: String);
598
599 procedure CheckWarn(const Check: boolean; const Message: string);
600 begin
601 if not Check then
602 WritelnWarning('DDS image', Message);
603 end;
604
605 var
606 Header: TDDSHeader;
607
608 { Reading header initializes many instance fields:
609 FWidth, FHeight,
610 FMipmaps, FMipmapsCount,
611 FCompositeType, FCubeMapSides, FDepth }
612 procedure ReadHeader;
613 var
614 Magic: array [0 .. 3] of AnsiChar;
615 begin
616 Stream.ReadBuffer(Magic, SizeOf(Magic));
617 Check(Magic = 'DDS ', 'DDS file beginning (magic number) invalid, maybe this is not really a DDS file');
618
619 Stream.ReadBuffer(Header, SizeOf(Header));
620
621 { We could do this code *always*, not only on big-endian machines.
622 But it does nothing on little-endian machines, so it's a waste of time
623 there, so only do it in -dDEBUG mode. }
624 {$if defined(FPC) and (defined(ENDIAN_BIG) or defined(DEBUG))}
625 Header.Size := LEToN(Header.Size );
626 Header.Flags := LEToN(Header.Flags );
627 Header.Height := LEToN(Header.Height );
628 Header.Width := LEToN(Header.Width );
629 Header.PitchOrLinearSize := LEToN(Header.PitchOrLinearSize );
630 Header.Depth := LEToN(Header.Depth );
631 Header.MipMapCount := LEToN(Header.MipMapCount );
632 Header.PixelFormat.Size := LEToN(Header.PixelFormat.Size );
633 Header.PixelFormat.Flags := LEToN(Header.PixelFormat.Flags );
634 Header.PixelFormat.RGBBitCount := LEToN(Header.PixelFormat.RGBBitCount);
635 Header.PixelFormat.RBitMask := LEToN(Header.PixelFormat.RBitMask );
636 Header.PixelFormat.GBitMask := LEToN(Header.PixelFormat.GBitMask );
637 Header.PixelFormat.BBitMask := LEToN(Header.PixelFormat.BBitMask );
638 Header.PixelFormat.ABitMask := LEToN(Header.PixelFormat.ABitMask );
639 Header.Caps1 := LEToN(Header.Caps1 );
640 Header.Caps2 := LEToN(Header.Caps2 );
641 {$endif}
642
643 Assert(SizeOf(Header) = 124); { this is actually constant, as it's part of file format spec... }
644 Check(Header.Size = SizeOf(Header), 'DDS header size incorrect');
645 Check(Header.Flags and DDSD_CAPS <> 0, 'Missing DDSD_CAPS');
646 Check(Header.Flags and DDSD_HEIGHT <> 0, 'Missing DDSD_HEIGHT');
647 Check(Header.Flags and DDSD_WIDTH <> 0, 'Missing DDSD_WIDTH');
648 Check(Header.Flags and DDSD_PIXELFORMAT <> 0, 'Missing DDSD_PIXELFORMAT');
649
650 Height := Header.Height;
651 Width := Header.Width;
652
653 { calculate FMipmaps, FMipmapsCount }
654 Composite.FMipmaps := Header.Caps1 and DDSCAPS_MIPMAP <> 0;
655 if Composite.FMipmaps then
656 begin
657 Check(Header.Flags and DDSD_MIPMAPCOUNT <> 0, 'Missing DDSD_MIPMAPCOUNT, but caps indicate that this DDS image has mipmaps');
658 Check(Header.Caps1 and DDSCAPS_COMPLEX <> 0, 'Missing DDSCAPS_COMPLEX, but caps indicate that this DDS image has mipmaps');
659 Composite.FMipmapsCount := Header.MipMapCount;
660 Check(Composite.MipmapsCount > 0, 'Specified mipmaps, but mipmap count is zero');
661 { ATI Compresonator always sets this flag, even though it does not create mipmaps,
662 and source image has not power-of-two sizes. So turn off FMipmaps flag. }
663 if Composite.FMipmapsCount = 1 then
664 Composite.FMipmaps := false;
665 end else
666 Composite.FMipmapsCount := 1;
667
668 Check(Header.Flags and DDSCAPS_TEXTURE <> 0, 'Missing DDSCAPS_TEXTURE');
669
670 { May be changed later if volume texture }
671 Depth := 1;
672
673 { calculate CompositeType }
674 Check( (Header.Caps2 and DDSCAPS2_VOLUME = 0) or
675 (Header.Caps2 and DDSCAPS2_CUBEMAP = 0),
676 'DDS capabilities indicate CUBEMAP and VOLUME texture at the same time');
677 if Header.Caps2 and DDSCAPS2_CUBEMAP <> 0 then
678 begin
679 Composite.FCompositeType := ctCubeMap;
680
681 { calculate FCubeMapSides }
682 Composite.FCubeMapSides := [];
683 if Header.Caps2 and DDSCAPS2_CUBEMAP_POSITIVEX <> 0 then Include(Composite.FCubeMapSides, dcsPositiveX);
684 if Header.Caps2 and DDSCAPS2_CUBEMAP_NEGATIVEX <> 0 then Include(Composite.FCubeMapSides, dcsNegativeX);
685 if Header.Caps2 and DDSCAPS2_CUBEMAP_POSITIVEY <> 0 then Include(Composite.FCubeMapSides, dcsPositiveY);
686 if Header.Caps2 and DDSCAPS2_CUBEMAP_NEGATIVEY <> 0 then Include(Composite.FCubeMapSides, dcsNegativeY);
687 if Header.Caps2 and DDSCAPS2_CUBEMAP_POSITIVEZ <> 0 then Include(Composite.FCubeMapSides, dcsPositiveZ);
688 if Header.Caps2 and DDSCAPS2_CUBEMAP_NEGATIVEZ <> 0 then Include(Composite.FCubeMapSides, dcsNegativeZ);
689 Check(Composite.FCubeMapSides <> [], 'DDS file is a cube map, but all six sides of the cube are missing');
690 end else
691 if Header.Caps2 and DDSCAPS2_VOLUME <> 0 then
692 begin
693 Composite.FCompositeType := ctVolume;
694
695 { calculate FDepth }
696 Check(Header.Flags and DDSD_DEPTH <> 0, 'Missing DDSD_DEPTH, but DDS is a VOLUME texture');
697 Depth := Header.Depth;
698 end else
699 Composite.FCompositeType := ctTexture;
700 if Composite.FCompositeType <> ctTexture then
701 { This invalid situation happens on
702 http://regedit.gamedev.pl/Download/Rozne/Tekstury%20narzedziowe/NoiseVolume.dds
703 (from
704 http://regedit.gamedev.pl/download.php5?x=Rozne%2FTekstury+narzedziowe) }
705 CheckWarn(Header.Caps1 and DDSCAPS_COMPLEX <> 0, 'Missing DDSCAPS_COMPLEX, but caps indicate that this DDS image has cube map or volume');
706
707 Check(Header.PixelFormat.Size = SizeOf(Header.PixelFormat), 'Incorrect size of DDS pixel format record');
708 end;
709
710 var
711 HeaderDxt10: TDDSHeaderDxt10;
712
713 procedure ReadHeaderDxt10;
714 begin
715 if (Header.PixelFormat.Flags and DDPF_FOURCC <> 0) and
716 (Header.PixelFormat.FourCC = 'DX10') then
717 begin
718 Stream.ReadBuffer(HeaderDxt10, SizeOf(HeaderDxt10));
719
720 { We could do this code *always*, not only on big-endian machines.
721 But it does nothing on little-endian machines, so it's a waste of time
722 there, so only do it in -dDEBUG mode. }
723 {$if defined(FPC) and (defined(ENDIAN_BIG) or defined(DEBUG))}
724 HeaderDxt10.DxgiFormat := LEToN(HeaderDxt10.DxgiFormat );
725 HeaderDxt10.ResourceDimension := LEToN(HeaderDxt10.ResourceDimension);
726 HeaderDxt10.MiscFlag := LEToN(HeaderDxt10.MiscFlag );
727 HeaderDxt10.ArraySize := LEToN(HeaderDxt10.ArraySize );
728 HeaderDxt10.MiscFlags2 := LEToN(HeaderDxt10.MiscFlags2 );
729 {$endif}
730 end else
731 FillChar(HeaderDxt10, SizeOf(HeaderDxt10), #0);
732 end;
733
734 { Read actual image data, initializing FImages contents }
735 procedure ReadImages;
736
737 { Read a single, normal 2D (or 3D) image from DDS file. }
738 function ReadImage(const Width, Height, Depth, MipmapLevel: Cardinal): TEncodedImage;
739
740 { Calculate RowBytePadding for an uncompressed image on this mipmap level. }
741 function GetRowBytePadding(const PixelSize: Integer): Integer;
742 begin
743 { Header.PitchOrLinearSize for uncompressed texture may indicate
744 row length (pitch) in bytes. This is useful to indicate padding of lines.
745 I understand that otherwise I should assume lines are not padded? }
746 if (Header.Flags and DDSD_PITCH <> 0) and
747 (Header.PitchOrLinearSize <> 0) and
748 (MipmapLevel = 0) then
749 Result := Max(Header.PitchOrLinearSize - PixelSize * Width, 0)
750 else
751 Result := 0;
752 end;
753
754 type
755 TUncompressedType = (
756 utRGB_AlphaPossible,
757 utGrayscale_AlphaPossible,
758 utPureAlpha );
759
760 procedure ReadUncompressed(const UncompressedType: TUncompressedType);
761 var
762 RowBytePadding: Integer;
763 { Within ReadUncompressed, Result is always of TCastleImage class }
764 Res: TCastleImage absolute Result;
765
766 procedure ReadToGrayscale;
767 var
768 Reader: TDDSRowReader;
769 X, Y, Z: Integer;
770 G: PByte;
771 begin
772 Reader := TDDSRowReader.Create(@Header.PixelFormat, Width, RowBytePadding);
773 try
774 for Z := 0 to Depth - 1 do
775 for Y := Height - 1 downto 0 do
776 begin
777 Reader.ReadRow(Stream);
778 G := Res.RowPtr(Y, Z);
779 for X := 0 to Width - 1 do
780 begin
781 G^ := Reader.RGBA(0);
782 Reader.NextPixel;
783 Inc(G);
784 end;
785 end;
786 finally FreeAndNil(Reader) end;
787 end;
788
789 procedure ReadToGrayscaleAlpha;
790 var
791 Reader: TDDSRowReader;
792 X, Y, Z: Integer;
793 GA: PVector2Byte;
794 begin
795 Reader := TDDSRowReader.Create(@Header.PixelFormat, Width, RowBytePadding);
796 try
797 for Z := 0 to Depth - 1 do
798 for Y := Height - 1 downto 0 do
799 begin
800 Reader.ReadRow(Stream);
801 GA := Res.RowPtr(Y, Z);
802 for X := 0 to Width - 1 do
803 begin
804 GA^.X := Reader.RGBA(0);
805 GA^.Y := Reader.RGBA(3);
806 Reader.NextPixel;
807 Inc(GA);
808 end;
809 end;
810 finally FreeAndNil(Reader) end;
811 end;
812
813 procedure ReadToRGB;
814 var
815 Reader: TDDSRowReader;
816 X, Y, Z: Integer;
817 RGB: PVector3Byte;
818 begin
819 Reader := TDDSRowReader.Create(@Header.PixelFormat, Width, RowBytePadding);
820 try
821 for Z := 0 to Depth - 1 do
822 for Y := Height - 1 downto 0 do
823 begin
824 Reader.ReadRow(Stream);
825 RGB := Res.RowPtr(Y, Z);
826 for X := 0 to Width - 1 do
827 begin
828 RGB^.X := Reader.RGBA(0);
829 RGB^.Y := Reader.RGBA(1);
830 RGB^.Z := Reader.RGBA(2);
831 Reader.NextPixel;
832 Inc(RGB);
833 end;
834 end;
835 finally FreeAndNil(Reader) end;
836 end;
837
838 procedure ReadToRGBAlpha;
839 var
840 Reader: TDDSRowReader;
841 X, Y, Z: Integer;
842 RGBA: PVector4Byte;
843 begin
844 Reader := TDDSRowReader.Create(@Header.PixelFormat, Width, RowBytePadding);
845 try
846 for Z := 0 to Depth - 1 do
847 for Y := Height - 1 downto 0 do
848 begin
849 Reader.ReadRow(Stream);
850 RGBA := Res.RowPtr(Y, Z);
851 for X := 0 to Width - 1 do
852 begin
853 RGBA^.X := Reader.RGBA(0);
854 RGBA^.Y := Reader.RGBA(1);
855 RGBA^.Z := Reader.RGBA(2);
856 RGBA^.W := Reader.RGBA(3);
857 Reader.NextPixel;
858 Inc(RGBA);
859 end;
860 end;
861 finally FreeAndNil(Reader) end;
862 end;
863
864 { Read alpha-only images (may be produced by GIMP-DDS) }
865 procedure ReadToGrayscaleAlphaPure;
866 var
867 Reader: TDDSRowReader;
868 X, Y, Z: Integer;
869 GA: PVector2Byte;
870 begin
871 Reader := TDDSRowReader.Create(@Header.PixelFormat, Width, RowBytePadding);
872 try
873 for Z := 0 to Depth - 1 do
874 for Y := Height - 1 downto 0 do
875 begin
876 Reader.ReadRow(Stream);
877 GA := Res.RowPtr(Y, Z);
878 for X := 0 to Width - 1 do
879 begin
880 GA^.X := 255;
881 GA^.Y := Reader.RGBA(3);
882 Reader.NextPixel;
883 Inc(GA);
884 end;
885 end;
886 finally FreeAndNil(Reader) end;
887 end;
888
889 begin { ReadUncompressed }
890 Check(Header.PixelFormat.RGBBitCount mod 8 = 0, 'Invalid DDS pixel format: only RGBBitCount being multiple of 8 is supported. Please report with sample image');
891 Check(Header.PixelFormat.RGBBitCount > 0, 'Invalid DDS pixel format: RGBBitCount must be non-zero');
892
893 RowBytePadding := GetRowBytePadding(Header.PixelFormat.RGBBitCount div 8);
894
895 case UncompressedType of
896 utRGB_AlphaPossible:
897 if Header.PixelFormat.Flags and DDPF_ALPHAPIXELS = 0 then
898 begin
899 Result := TRGBImage.Create(Width, Height, Depth);
900
901 if (Header.PixelFormat.RBitMask = $ff0000) and
902 (Header.PixelFormat.GBitMask = $00ff00) and
903 (Header.PixelFormat.BBitMask = $0000ff) then
904 ReadOptimized_RGB8(Stream, Res, RowBytePadding) else
905 if (Header.PixelFormat.RBitMask = $0000ff) and
906 (Header.PixelFormat.GBitMask = $00ff00) and
907 (Header.PixelFormat.BBitMask = $ff0000) then
908 ReadOptimized_BGR8(Stream, Res, RowBytePadding) else
909 ReadToRGB;
910 end else
911 begin
912 Check(Header.PixelFormat.ABitMask <> 0, 'Invalid DDS pixel format: alpha channel flag specified (DDPF_ALPHAPIXELS), but alpha mask is zero');
913
914 Result := TRGBAlphaImage.Create(Width, Height, Depth);
915
916 if (Header.PixelFormat.RGBBitCount = 32) and
917 (Header.PixelFormat.ABitMask = $ff000000) and
918 (Header.PixelFormat.RBitMask = $00ff0000) and
919 (Header.PixelFormat.GBitMask = $0000ff00) and
920 (Header.PixelFormat.BBitMask = $000000ff) then
921 ReadOptimized_ARGB8(Stream, Res, RowBytePadding) else
922 if (Header.PixelFormat.RGBBitCount = 32) and
923 (Header.PixelFormat.ABitMask = $ff000000) and
924 (Header.PixelFormat.RBitMask = $000000ff) and
925 (Header.PixelFormat.GBitMask = $0000ff00) and
926 (Header.PixelFormat.BBitMask = $00ff0000) then
927 ReadOptimized_ABGR8(Stream, Res, RowBytePadding) else
928 ReadToRGBAlpha;
929 end;
930 utGrayscale_AlphaPossible:
931 if Header.PixelFormat.Flags and DDPF_ALPHAPIXELS = 0 then
932 begin
933 Result := TGrayscaleImage.Create(Width, Height, Depth);
934
935 if (Header.PixelFormat.RGBBitCount = 8) and
936 (Header.PixelFormat.RBitMask = $ff) then
937 ReadOptimized_G8(Stream, Res, RowBytePadding) else
938 ReadToGrayscale;
939 end else
940 begin
941 Check(Header.PixelFormat.ABitMask <> 0, 'Invalid DDS pixel format: alpha channel flag specified (DDPF_ALPHAPIXELS), but alpha mask is zero');
942
943 Result := TGrayscaleAlphaImage.Create(Width, Height, Depth);
944
945 if (Header.PixelFormat.RGBBitCount = 16) and
946 (Header.PixelFormat.ABitMask = $ff00) and
947 (Header.PixelFormat.RBitMask = $00ff) then
948 ReadOptimized_AG8(Stream, Res, RowBytePadding) else
949 ReadToGrayscaleAlpha;
950 end;
951 utPureAlpha:
952 begin
953 Check(Header.PixelFormat.ABitMask <> 0, 'Invalid DDS pixel format: pure alpha expected, but alpha mask is zero');
954
955 Result := TGrayscaleAlphaImage.Create(Width, Height, Depth);
956 ReadToGrayscaleAlphaPure;
957 end;
958 {$ifndef COMPILER_CASE_ANALYSIS}
959 else raise EInternalError.Create('UncompressedType?');
960 {$endif}
961 end;
962 end { ReadUncompressed };
963
964 procedure ReadCompressed(Compression: TTextureCompression);
965 var
966 { Within ReadUncompressed, Result is always of TGPUCompressedImage class }
967 Res: TGPUCompressedImage absolute Result;
968 begin
969 Result := TGPUCompressedImage.Create(Width, Height, Depth,
970 Compression);
971 try
972 { check Header.PitchOrLinearSize vs Result.Size }
973 if (Header.Flags and DDSD_LINEARSIZE <> 0) and
974 { It seems there are textures with DDSD_LINEARSIZE set but
975 PitchOrLinearSize 0, and we should ignore
976 PitchOrLinearSize then (e.g. ~/images/dds_tests/greek_imperial_swordsman.tga.dds
977 on chantal). Same for PitchOrLinearSize = -1
978 (e.g. UberPack-1/Torque3D/levels/lonerock_island/
979 inside UberPack-1 on opengameart.org). }
980 (Header.PitchOrLinearSize <> 0) and
981 (Header.PitchOrLinearSize <> High(UInt32)) and
982 { check this only on base level }
983 (MipmapLevel = 0) and
984 (Header.PitchOrLinearSize <> Result.Size) and
985 ( (Compression in [tcDxt1_RGB, tcDxt1_RGBA, tcDxt3, tcDxt5]) or
986 { it seems that pvrtc includes mipmaps sizes too? }
987 ((Compression in [
988 tcPvrtc1_2bpp_RGB,
989 tcPvrtc1_4bpp_RGB,
990 tcPvrtc1_2bpp_RGBA,
991 tcPvrtc1_4bpp_RGBA,
992 tcPvrtc2_4bpp,
993 tcPvrtc2_2bpp]) and not Composite.FMipmaps)
994 ) then
995 WritelnWarning('DDS', Format('Incorrect size for GPU compressed texture (DDS says %d, calculated should be %d, compression is %s)',
996 [Header.PitchOrLinearSize, Result.Size,
997 TextureCompressionInfo[Compression].Name]));
998
999 Stream.ReadBuffer(Res.RawPixels^, Res.Size);
1000
1001 Res.FlipVertical;
1002 { on unhandled error, make sure to free result }
1003 except FreeAndNil(Result); raise; end;
1004 end;
1005
1006 begin
1007 { There are five mutually exclusive types of DDS pixel format:
1008 - uncompressed non-palette (DDPF_RGB, optional DDPF_ALPHAPIXELS) or
1009 - uncompressed palette (DDPF_PALETTEINDEXED8) or
1010 - compressed (DDPF_FOURCC) or
1011 - uncompressed grayscale (DDPF_LUMINANCE, optional DDPF_ALPHAPIXELS,
1012 GIMP-DDS can write such images).
1013 - neighter of the above: only DDPF_ALPHAPIXELS (pure alpha,
1014 GIMP-DDS can write such images; actually, GIMP-DDS omits even
1015 DDPF_ALPHAPIXELS).
1016 }
1017
1018 Result := nil;
1019 try
1020 if Header.PixelFormat.Flags and DDPF_RGB <> 0 then
1021 begin
1022 Check(Header.PixelFormat.Flags and DDPF_FOURCC = 0, 'Invalid DDS pixel format: both uncompressed (DDPF_RGB) and compressed (DDPF_FOURCC) flags specified');
1023 Check(Header.PixelFormat.Flags and DDPF_PALETTEINDEXED8 = 0, 'Invalid DDS pixel format: both non-palette (DDPF_RGB) and palette (DDPF_PALETTEINDEXED8) flags specified');
1024 ReadUncompressed(utRGB_AlphaPossible);
1025 end else
1026 if Header.PixelFormat.Flags and DDPF_PALETTEINDEXED8 <> 0 then
1027 begin
1028 Assert(Header.PixelFormat.Flags and DDPF_RGB = 0);
1029 Check(Header.PixelFormat.Flags and DDPF_FOURCC = 0, 'Invalid DDS pixel format: both uncompressed (palette, DDPF_PALETTEINDEXED8) and compressed (DDPF_FOURCC) flags specified');
1030
1031 raise EInvalidDDS.Create('TODO: Unsupported pixel format for DDS: palette images not supported now, please report with sample image');
1032 end else
1033 if Header.PixelFormat.Flags and DDPF_FOURCC <> 0 then
1034 begin
1035 Assert(Header.PixelFormat.Flags and DDPF_RGB = 0);
1036 Assert(Header.PixelFormat.Flags and DDPF_PALETTEINDEXED8 = 0);
1037
1038 if Header.PixelFormat.FourCC = 'DXT1' then
1039 { There's no way to recognize from DDS file header whether it uses
1040 or not some transparent pixels. (DDPF_ALPHAPIXELS is never
1041 specified for compressed formats.)
1042 Potentially, every DXT1 image may have some transparent pixels,
1043 so use tcDxt1_RGBA. }
1044 ReadCompressed(tcDxt1_RGBA) else
1045 if Header.PixelFormat.FourCC = 'DXT3' then
1046 ReadCompressed(tcDxt3) else
1047 if Header.PixelFormat.FourCC = 'DXT5' then
1048 ReadCompressed(tcDxt5) else
1049 if Header.PixelFormat.FourCC = 'ATC ' then
1050 ReadCompressed(tcATITC_RGB) else
1051 if Header.PixelFormat.FourCC = 'ATCA' then
1052 ReadCompressed(tcATITC_RGBA_ExplicitAlpha) else
1053 if Header.PixelFormat.FourCC = 'ATCI' then
1054 ReadCompressed(tcATITC_RGBA_InterpolatedAlpha) else
1055 if Header.PixelFormat.FourCC = 'PTC2' then
1056 begin
1057 { No way to detect tcPvrtc1_2bpp_RGB? }
1058 ReadCompressed(tcPvrtc1_2bpp_RGBA);
1059 end else
1060 if Header.PixelFormat.FourCC = 'PTC4' then
1061 begin
1062 { No way to detect tcPvrtc1_4bpp_RGB? }
1063 ReadCompressed(tcPvrtc1_4bpp_RGBA);
1064 end else
1065 if Header.PixelFormat.FourCC = 'DX10' then
1066 begin
1067 case HeaderDxt10.DxgiFormat of
1068 DXGI_FORMAT_R8G8B8A8_UNORM:
1069 begin
1070 Result := TRGBAlphaImage.Create(Width, Height, Depth);
1071 ReadOptimized_ARGB8(Stream, TCastleImage(Result), GetRowBytePadding(4));
1072 end;
1073 DXGI_FORMAT_UNKNOWN:
1074 begin
1075 if Composite.AutomaticCompression then
1076 ReadCompressed(Composite.AutomaticCompressionType)
1077 else
1078 raise EInvalidDDS.Create('Unknown texture compression format in DDS: FourCC is DX10 and DxgiFormat is zero (unknown). You need to assign TCompositeImage.AutomaticCompression and TCompositeImage.AutomaticCompressionType in the engine to override this.');
1079 end;
1080 else
1081 raise EInvalidDDS.CreateFmt('Unsupported texture compression format in DDS: FourCC is DX10 and DxgiFormat is %d. Please report this (as Castle Game Engine issue), with the affected DDS file, we can possibly fix this DxgiFormat handling.',
1082 [HeaderDxt10.DxgiFormat]);
1083 end;
1084 end else
1085 if (LEToN(Header.PixelFormat.FourCCIntLE) = D3DFMT_R16F) or
1086 (LEToN(Header.PixelFormat.FourCCIntLE) = D3DFMT_G16R16F) or
1087 (LEToN(Header.PixelFormat.FourCCIntLE) = D3DFMT_A16B16G16R16F) or
1088 (LEToN(Header.PixelFormat.FourCCIntLE) = D3DFMT_R32F) or
1089 (LEToN(Header.PixelFormat.FourCCIntLE) = D3DFMT_G32R32F) or
1090 (LEToN(Header.PixelFormat.FourCCIntLE) = D3DFMT_A32B32G32R32F) then
1091 raise EInvalidDDS.Create('Unsupported texture compression for DDS: FourCC indicates float texture, not supported yet') else
1092 raise EInvalidDDS.CreateFmt('Unsupported texture compression for DDS: FourCC is "%s%s%s%s"',
1093 [ SReadableForm(Header.PixelFormat.FourCC[0]),
1094 SReadableForm(Header.PixelFormat.FourCC[1]),
1095 SReadableForm(Header.PixelFormat.FourCC[2]),
1096 SReadableForm(Header.PixelFormat.FourCC[3]) ]);
1097 end else
1098 if Header.PixelFormat.Flags and DDPF_LUMINANCE <> 0 then
1099 begin
1100 { Uncompressed grayscale image (possibly with alpha). }
1101 Check(Header.PixelFormat.RBitMask <> 0,
1102 'Invalid DDS pixel format: luminance image (DDPF_LUMINANCE flag) specified, but Red mask is zero');
1103 Check(
1104 ( (Header.PixelFormat.RBitMask = Header.PixelFormat.GBitMask) and
1105 (Header.PixelFormat.RBitMask = Header.PixelFormat.BBitMask) ) or
1106 ( (Header.PixelFormat.GBitMask = 0) and
1107 (Header.PixelFormat.BBitMask = 0) ),
1108 'Invalid DDS pixel format: luminance image (DDPF_LUMINANCE flag) specified, so Red = Green = Blue masks should be equal or Green = Blue = should be zero, but they are not');
1109 ReadUncompressed(utGrayscale_AlphaPossible);
1110 end else
1111 begin
1112 { GIMP-DDS plugin doesn't set DDPF_ALPHAPIXELS, but this is wrong IMO,
1113 so I warn about it. }
1114 CheckWarn(Header.PixelFormat.Flags and DDPF_ALPHAPIXELS <> 0, 'Invalid DDS pixel format: no flag specified, even not DDPF_ALPHAPIXELS. We will assume this is alpha-only image, as GIMP-DDS plugin can write such files');
1115 Check(
1116 (Header.PixelFormat.RBitMask = 0) and
1117 (Header.PixelFormat.GBitMask = 0) and
1118 (Header.PixelFormat.BBitMask = 0),
1119 'Invalid DDS pixel format: pure alpha image (only DDPF_ALPHAPIXELS flag) specified, but Red / Green / Blue makss are not zero');
1120 ReadUncompressed(utPureAlpha);
1121 end;
1122 except FreeAndNil(Result); raise end;
1123
1124 // useful to see this URL in logs, TextureMemoryProfiler dumps etc.
1125 Result.Url := Url + '[subimage]';
1126 end { ReadImage };
1127
1128 var
1129 W, H, D: Cardinal;
1130 I: Integer;
1131 Side: TCompositeImage.TDDSCubeMapSide;
1132 begin
1133 { Check that Width/Height are power of two, this is needed to make
1134 sure images reading code is sensible (otherwise, there's no way
1135 to tell what are the sizes of following images). }
1136 if Composite.FMipmaps then
1137 begin
1138 if (not IsPowerOf2(Width)) or
1139 (not IsPowerOf2(Height)) then
1140 begin
1141 { nvcompress can generate such DDS files, if you input a non-power-of-two image }
1142 WritelnWarning('DDS image has mipmaps, but width or height are not a power of 2: %d x %d. We will ignore these mipmaps, since we cannot determine their size', [Width, Height]);
1143 Composite.FMipmaps := false;
1144 end;
1145 end;
1146
1147 case Composite.CompositeType of
1148 ctTexture:
1149 begin
1150 if Composite.Mipmaps then
1151 begin
1152 Images.Count := Composite.FMipmapsCount;
1153 W := Width;
1154 H := Height;
1155 for I := 0 to Composite.FMipmapsCount - 1 do
1156 begin
1157 Images[I] := ReadImage(W, H, 1, I);
1158 W := Max(1, W div 2);
1159 H := Max(1, H div 2);
1160 end;
1161 end else
1162 begin
1163 Images.Count := 1;
1164 Images[0] := ReadImage(Width, Height, 1, 0);
1165 end;
1166 end;
1167 ctCubeMap:
1168 begin
1169 for Side := Low(Side) to High(Side) do
1170 if Side in Composite.FCubeMapSides then
1171 begin
1172 if Composite.Mipmaps then
1173 begin
1174 W := Width;
1175 H := Height;
1176 for I := 0 to Composite.FMipmapsCount - 1 do
1177 begin
1178 Images.Add(ReadImage(W, H, 1, I));
1179 W := Max(1, W div 2);
1180 H := Max(1, H div 2);
1181 end;
1182 end else
1183 begin
1184 Images.Add(ReadImage(Width, Height, 1, 0));
1185 end;
1186 end;
1187 end;
1188 ctVolume:
1189 begin
1190 if Composite.Mipmaps then
1191 begin
1192 W := Width;
1193 H := Height;
1194 D := Depth;
1195 for I := 0 to Composite.FMipmapsCount - 1 do
1196 begin
1197 Images.Add(ReadImage(W, H, D, I));
1198 W := Max(1, W div 2);
1199 H := Max(1, H div 2);
1200 D := Max(1, D div 2);
1201 end;
1202 end else
1203 begin
1204 Images.Add(ReadImage(Width, Height, Depth, 0));
1205 end;
1206 end;
1207 {$ifndef COMPILER_CASE_ANALYSIS}
1208 else raise EInternalError.Create('CompositeType?');
1209 {$endif}
1210 end;
1211 end { ReadImages };
1212
1213 begin
1214 try
1215 ReadHeader;
1216 ReadHeaderDxt10;
1217 ReadImages;
1218 except
1219 { EReadError is raised by Stream.ReadBuffer when it can't read
1220 specified number of bytes }
1221 on E: EReadError do raise EInvalidDDS.Create('Read error: ' + E.Message);
1222 on E: ECheckFailed do raise EInvalidDDS.Create('Wrong DDS file: ' + E.Message);
1223 end;
1224 end;
1225
1226 procedure TDDSHandler.SaveToStream(const Stream: TStream);
1227
1228 procedure WriteHeader;
1229 const
1230 Magic: array [0 .. 3] of AnsiChar = 'DDS ';
1231 var
1232 Header: TDDSHeader;
1233 begin
1234 Stream.WriteBuffer(Magic, SizeOf(Magic));
1235
1236 { initially fill Header with zeros, to avoid writing memory garbage
1237 (which would be potential security risk) to file. }
1238 FillChar(Header, SizeOf(Header), 0);
1239
1240 Header.Size := SizeOf(Header);
1241 Header.Flags := DDSD_CAPS or DDSD_HEIGHT or DDSD_WIDTH or DDSD_PIXELFORMAT
1242 or DDSCAPS_TEXTURE;
1243 Header.Height := Height;
1244 Header.Width := Width;
1245 Header.Caps1 := 0; { for starters }
1246
1247 if Composite.Mipmaps then
1248 begin
1249 Header.Caps1 := Header.Caps1 or DDSCAPS_COMPLEX or DDSCAPS_MIPMAP;
1250 Header.Flags := Header.Flags or DDSD_MIPMAPCOUNT;
1251 Header.MipMapCount := Composite.MipmapsCount;
1252 end;
1253
1254 case Composite.CompositeType of
1255 ctTexture: ;
1256 ctCubeMap:
1257 begin
1258 Header.Caps1 := Header.Caps1 or DDSCAPS_COMPLEX;
1259 Header.Caps2 := Header.Caps2 or DDSCAPS2_CUBEMAP;
1260
1261 if dcsPositiveX in Composite.FCubeMapSides then Header.Caps2 := Header.Caps2 or DDSCAPS2_CUBEMAP_POSITIVEX;
1262 if dcsNegativeX in Composite.FCubeMapSides then Header.Caps2 := Header.Caps2 or DDSCAPS2_CUBEMAP_NEGATIVEX;
1263 if dcsPositiveY in Composite.FCubeMapSides then Header.Caps2 := Header.Caps2 or DDSCAPS2_CUBEMAP_POSITIVEY;
1264 if dcsNegativeY in Composite.FCubeMapSides then Header.Caps2 := Header.Caps2 or DDSCAPS2_CUBEMAP_NEGATIVEY;
1265 if dcsPositiveZ in Composite.FCubeMapSides then Header.Caps2 := Header.Caps2 or DDSCAPS2_CUBEMAP_POSITIVEZ;
1266 if dcsNegativeZ in Composite.FCubeMapSides then Header.Caps2 := Header.Caps2 or DDSCAPS2_CUBEMAP_NEGATIVEZ;
1267 end;
1268 ctVolume:
1269 begin
1270 Header.Caps1 := Header.Caps1 or DDSCAPS_COMPLEX;
1271 Header.Caps2 := Header.Caps2 or DDSCAPS2_VOLUME;
1272 Header.Flags := Header.Flags or DDSD_DEPTH;
1273 Header.Depth := Depth;
1274 end;
1275 {$ifndef COMPILER_CASE_ANALYSIS}
1276 else raise EInternalError.Create('CompositeType');
1277 {$endif}
1278 end;
1279
1280 if Images[0] is TCastleImage then
1281 begin
1282 { For uncompressed image, PitchOrLinearSize is row length }
1283 Header.PitchOrLinearSize := Composite.Width * TCastleImage(Images[0]).PixelSize;
1284 Header.Flags := Header.Flags or DDSD_PITCH;
1285 end else
1286 if Images[0] is TGPUCompressedImage then
1287 begin
1288 { For compressed image, PitchOrLinearSize is image length }
1289 Header.PitchOrLinearSize := TGPUCompressedImage(Images[0]).Size;
1290 Header.Flags := Header.Flags or DDSD_LINEARSIZE;
1291 end else
1292 raise Exception.CreateFmt('Cannot save image class %s to DDS file', [Images[0].ClassName]);
1293
1294 Header.PixelFormat.Size := SizeOf(Header.PixelFormat);
1295 Header.PixelFormat.Flags := 0; { for starters }
1296
1297 if Images[0] is TGrayscaleImage then
1298 begin
1299 Header.PixelFormat.Flags := DDPF_LUMINANCE;
1300 Header.PixelFormat.RGBBitCount := 8;
1301 Header.PixelFormat.RBitMask := $ff;
1302 Header.PixelFormat.GBitMask := $ff;
1303 Header.PixelFormat.BBitMask := $ff;
1304 Header.PixelFormat.ABitMask := 0;
1305 end else
1306 if Images[0] is TGrayscaleAlphaImage then
1307 begin
1308 Header.PixelFormat.Flags := DDPF_LUMINANCE or DDPF_ALPHAPIXELS;
1309 Header.PixelFormat.RGBBitCount := 16;
1310 Header.PixelFormat.RBitMask := $00ff;
1311 Header.PixelFormat.GBitMask := $00ff;
1312 Header.PixelFormat.BBitMask := $00ff;
1313 Header.PixelFormat.ABitMask := $ff00;
1314 end else
1315 if Images[0] is TRGBImage then
1316 begin
1317 Header.PixelFormat.Flags := DDPF_RGB;
1318 Header.PixelFormat.RGBBitCount := 24;
1319 Header.PixelFormat.RBitMask := $000000ff;
1320 Header.PixelFormat.GBitMask := $0000ff00;
1321 Header.PixelFormat.BBitMask := $00ff0000;
1322 Header.PixelFormat.ABitMask := 0;
1323 end else
1324 if Images[0] is TRGBAlphaImage then
1325 begin
1326 Header.PixelFormat.Flags := DDPF_RGB or DDPF_ALPHAPIXELS;
1327 Header.PixelFormat.RGBBitCount := 32;
1328 Header.PixelFormat.RBitMask := $000000ff;
1329 Header.PixelFormat.GBitMask := $0000ff00;
1330 Header.PixelFormat.BBitMask := $00ff0000;
1331 Header.PixelFormat.ABitMask := $ff000000;
1332 end else
1333 if Images[0] is TGPUCompressedImage then
1334 begin
1335 Header.PixelFormat.Flags := DDPF_FOURCC;
1336 case TGPUCompressedImage(Images[0]).Compression of
1337 tcDxt1_RGB,
1338 tcDxt1_RGBA : Header.PixelFormat.FourCC := 'DXT1';
1339 tcDxt3: Header.PixelFormat.FourCC := 'DXT3';
1340 tcDxt5: Header.PixelFormat.FourCC := 'DXT5';
1341 tcPvrtc1_2bpp_RGB,
1342 tcPvrtc1_2bpp_RGBA: Header.PixelFormat.FourCC := 'PTC2';
1343 tcPvrtc1_4bpp_RGB,
1344 tcPvrtc1_4bpp_RGBA: Header.PixelFormat.FourCC := 'PTC4';
1345 tcATITC_RGB : Header.PixelFormat.FourCC := 'ATC ';
1346 tcATITC_RGBA_ExplicitAlpha : Header.PixelFormat.FourCC := 'ATCA';
1347 tcATITC_RGBA_InterpolatedAlpha: Header.PixelFormat.FourCC := 'ATCI';
1348 else raise EImageSaveError.CreateFmt('When saving DDS: Cannot save to DDS with compression %s',
1349 [TextureCompressionInfo[TGPUCompressedImage(Images[0]).Compression].Name]);
1350 end;
1351 end else
1352 raise Exception.CreateFmt('Unable to save image class %s to DDS image',
1353 [Images[0].ClassName]);
1354
1355 { We could do this code *always*, not only on big-endian machines.
1356 But it does nothing on little-endian machines, so it's a waste of time
1357 there, so only do it in -dDEBUG mode. }
1358 {$if defined(FPC) and (defined(ENDIAN_BIG) or defined(DEBUG))}
1359 Header.Size := NToLE(Header.Size );
1360 Header.Flags := NToLE(Header.Flags );
1361 Header.Height := NToLE(Header.Height );
1362 Header.Width := NToLE(Header.Width );
1363 Header.PitchOrLinearSize := NToLE(Header.PitchOrLinearSize );
1364 Header.Depth := NToLE(Header.Depth );
1365 Header.MipMapCount := NToLE(Header.MipMapCount );
1366 Header.PixelFormat.Size := NToLE(Header.PixelFormat.Size );
1367 Header.PixelFormat.Flags := NToLE(Header.PixelFormat.Flags );
1368 Header.PixelFormat.RGBBitCount := NToLE(Header.PixelFormat.RGBBitCount);
1369 Header.PixelFormat.RBitMask := NToLE(Header.PixelFormat.RBitMask );
1370 Header.PixelFormat.GBitMask := NToLE(Header.PixelFormat.GBitMask );
1371 Header.PixelFormat.BBitMask := NToLE(Header.PixelFormat.BBitMask );
1372 Header.PixelFormat.ABitMask := NToLE(Header.PixelFormat.ABitMask );
1373 Header.Caps1 := NToLE(Header.Caps1 );
1374 Header.Caps2 := NToLE(Header.Caps2 );
1375 {$endif}
1376
1377 Stream.WriteBuffer(Header, SizeOf(Header));
1378 end;
1379
1380 procedure WriteImages;
1381
1382 procedure WriteUncompressedImage(Image: TCastleImage);
1383 var
1384 Z, Y: Integer;
1385 begin
1386 for Z := 0 to Image.Depth - 1 do
1387 { We have to invert rows order when saving to DDS }
1388 for Y := Image.Height - 1 downto 0 do
1389 Stream.WriteBuffer(Image.RowPtr(Y, Z)^, Image.Width * Image.PixelSize);
1390 end;
1391
1392 procedure WriteCompressedImage(Image: TGPUCompressedImage);
1393 var
1394 Temp: TGPUCompressedImage;
1395 begin
1396 Temp := Image.MakeCopy;
1397 try
1398 { invert rows when saving to DDS }
1399 Temp.FlipVertical;
1400 Stream.WriteBuffer(Temp.RawPixels^, Temp.Size);
1401 finally FreeAndNil(Temp) end;
1402 end;
1403
1404 var
1405 I: Integer;
1406 begin
1407 for I := 0 to Images.Count - 1 do
1408 if Images[I] is TCastleImage then
1409 WriteUncompressedImage(TCastleImage(Images[I])) else
1410 begin
1411 Assert(Images[I] is TGPUCompressedImage);
1412 WriteCompressedImage(TGPUCompressedImage(Images[I]));
1413 end;
1414 end;
1415
1416 begin
1417 WriteHeader;
1418 WriteImages;
1419 end;