Debian Codegraph @

src/base_rendering/castleglimages_texturememoryprofiler.inc

raw
1 {%MainUnit castleglimages.pas}
2 {
3 Copyright 2001-2023 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 { Part of CastleGLImages unit: texture memory profiler (TextureMemoryProfiler). }
18
19 {$ifdef read_interface}
20
21 {$ifdef read_interface_type}
22 // type (continue type section from previous include file)
23 { OpenGL texture memory profiler. See @link(TextureMemoryProfiler)
24 for usage documentation. }
25 TTextureMemoryProfiler = class
26 private
27 type
28 TAllocatedTexture = class
29 TextureId: TGLTextureId;
30 Url: String;
31 Width, Height, Depth: Integer;
32 Mipmaps: boolean;
33 Size: Int64;
34 ImageFormat: string;
35 end;
36 { Using TObjectList, not map, this way we can sort the list looking
37 at data sizes. }
38 TAllocatedTextures = {$ifdef FPC}specialize{$endif} TObjectList<TAllocatedTexture>;
39 var
40 AllocatedTextures: TAllocatedTextures;
41 FEnabled: boolean;
42 function FindTextureId(const TextureId: Integer): Integer;
43 procedure CheckLeaks;
44 public
45 constructor Create;
46 destructor Destroy; override;
47 property Enabled: boolean read FEnabled write FEnabled;
48
49 { Notify about texture memory allocation.
50 This should be used only by code doing direct OpenGL operations. }
51 procedure Allocate(const TextureId: TGLTextureId;
52 const Url, ImageFormat: string; const Size: Int64; const Mipmaps: boolean;
53 const Width, Height, Depth: Integer);
54
55 { Notify about texture memory deallocation.
56 This should be used only by code doing direct OpenGL operations. }
57 procedure Deallocate(const TextureId: TGLTextureId);
58
59 function Summary: string;
60
61 { Helper function to calculate memory needed by all mipmaps of given Image.
62 Assumes that all mipmaps are generated, as by GenerateMipmap call. }
63 class function MipmapsSize(const Image: TEncodedImage): Int64;
64 end;
65 {$endif read_interface_type}
66
67 {$ifdef read_interface_func}
68 { OpenGL texture memory profiler, to detect which textures use up
69 the GPU texture memory. Especially useful on mobile devices,
70 where texture memory is limited and your application must really optimize
71 texture usage. Also useful to detect texture memory leaks.
72
73 Enable it at the very beginning of the application
74 (for example in the main unit initialization clause), like this:
75
76 @longCode(#
77 TextureMemoryProfiler.Enabled := true
78 #)
79
80 Then at any point during the game you can query texture usage by
81 @link(TTextureMemoryProfiler.Summary) method.
82 For example dump it to the log like this:
83
84 @longCode(#
85 WritelnLog('Textures', TextureMemoryProfiler.Summary);
86 #)
87
88 The resulting output lists the currently allocated textures,
89 in descending order of their size.
90 This tells you which textures are worth optimizing.
91 Maybe scale these textures down, maybe compress them,
92 maybe remove alpha channel or convert them to grayscale...
93
94 The profiler counts the @italic(real texture size on GPU),
95 knowing that some textures are resized to power of 2,
96 that textures may be compressed on GPU, that some textures have mipmaps
97 and so on. All kinds of textures (2D, 3D, cubemaps, float, depth etc.)
98 are covered. Every type is reported --- loaded from files,
99 generated (like by GeneratedCubeMapTexture), embedded in code
100 (by embedding images or fonts in code)... The textures loaded from disk
101 are described by URL, for other textures we invent special URLs like:
102
103 @unorderedList(
104 @itemSpacing compact
105 @item(@code(embedded-font:/CastleTextureFont_CanterBold_120))
106 @item(@code(embedded-image:/PanelSeparator))
107 @item(@code(generated:/GeneratedCubeMapTexture(GenTex2)))
108 )
109
110 You can also use the profiler from castle-model-viewer, run it with
111 "--debug-texture-memory" command-line option, load your 3D model
112 and then use menu option "Console -> Print Texture Memory Usage".
113 }
114 function TextureMemoryProfiler: TTextureMemoryProfiler;
115
116 var
117 { Log (through CastleLog) all texture and image loading to GPU.
118 If additionally @link(TextureMemoryProfiler) is enabled, then we will dump
119 texture memory usage. }
120 LogTextureLoading: boolean = false;
121 {$endif read_interface_func}
122
123 {$endif read_interface}
124
125 {$ifdef read_implementation}
126
127 { TTextureMemoryProfiler ----------------------------------------------------- }
128
129 constructor TTextureMemoryProfiler.Create;
130 begin
131 inherited;
132 AllocatedTextures := TAllocatedTextures.Create(true);
133 end;
134
135 destructor TTextureMemoryProfiler.Destroy;
136 begin
137 FreeAndNil(AllocatedTextures);
138 inherited;
139 end;
140
141 procedure TTextureMemoryProfiler.Allocate(const TextureId: TGLTextureId;
142 const Url, ImageFormat: string;
143 const Size: Int64; const Mipmaps: boolean;
144 const Width, Height, Depth: Integer);
145 var
146 AllocatedTex: TAllocatedTexture;
147 I: Integer;
148 begin
149 if FEnabled then
150 begin
151 AllocatedTex := TAllocatedTexture.Create;
152 AllocatedTex.Url := Url;
153 AllocatedTex.Width := Width;
154 AllocatedTex.Height := Height;
155 AllocatedTex.Depth := Depth;
156 AllocatedTex.Mipmaps := Mipmaps;
157 AllocatedTex.Size := Size;
158 AllocatedTex.ImageFormat := ImageFormat;
159 AllocatedTex.TextureId := TextureId;
160 I := FindTextureId(TextureId);
161 if I <> -1 then
162 AllocatedTextures[I] := AllocatedTex else
163 AllocatedTextures.Add(AllocatedTex);
164 end;
165
166 if LogTextureLoading then
167 begin
168 WritelnLog('Texture Loading', 'Loaded to GPU texture "%s" size %d x %d',
169 [UriDisplay(Url), Width, Height]);
170 if FEnabled then
171 WritelnLogMultiline('Texture Loading', Summary);
172 end;
173 end;
174
175 procedure TTextureMemoryProfiler.Deallocate(const TextureId: TGLTextureId);
176 var
177 I: Integer;
178 begin
179 if not ApplicationProperties.IsGLContextOpen then
180 WritelnWarning('Textures', Format(
181 'Releasing texture id %d after the rendering context has been closed. You release some rendering resources too late. You should release (at the latest) in an event registered on "ApplicationProperties.OnGLContextClose".' + NL +
182 'That said, all classes (like TDrawableImage, TCastleScene, TCastleImageControl, TCastleImageTransform) should do this management correctly automatically, so this warning should never happen.' + ' If you see this -> please submit a bug to Castle Game Engine with a testcase to reproduce this problem.',
183 [TextureId]));
184
185 if FEnabled then
186 begin
187 I := FindTextureId(TextureId);
188 if I = -1 then
189 WritelnWarning('Textures', Format('Texture id %d is released, but was not reported as allocated to TextureMemoryProfiler. Probably TextureMemoryProfiler was not enabled when the texture was created, which may mean TextureMemoryProfiler was enabled too late to accurately capture everything.',
190 [TextureId])) else
191 AllocatedTextures.Delete(I);
192 end;
193 end;
194
195 procedure TTextureMemoryProfiler.CheckLeaks;
196 begin
197 if (AllocatedTextures.Count <> 0) and
198 ((AllocatedTextures.Count <> 1) or
199 { texture id 0 may be allocated, but never released }
200 (AllocatedTextures[0].TextureId = 0)) then
201 begin
202 WritelnWarning('Textures', Format('TextureMemoryProfiler contains some textures when closing the rendering context. Possibly we have texture memory leak (textures will be freed anyway when closing rendering context, but possibly we could free them earlier).'+' Or TextureMemoryProfiler was only enabled for part of program''s code. We have %d textures, 1st one is "%s"',
203 [AllocatedTextures.Count,
204 AllocatedTextures[0].Url]));
205 end;
206 end;
207
208 function TTextureMemoryProfiler.FindTextureId(const TextureId: Integer): Integer;
209 var
210 I: Integer;
211 begin
212 for I := 0 to AllocatedTextures.Count - 1 do
213 if AllocatedTextures[I].TextureId = TextureId then
214 Exit(I);
215 Result := -1;
216 end;
217
218 class function TTextureMemoryProfiler.MipmapsSize(const Image: TEncodedImage): Int64;
219 var
220 W, H, D: Cardinal;
221 Size: Int64;
222 begin
223 W := Image.Width;
224 H := Image.Height;
225 D := Image.Depth;
226 Size := Image.Size;
227
228 Result := 0;
229
230 if (W = 0) or (H = 0) or (D = 0) then Exit; // empty image data
231
232 while (W > 1) or (H > 1) or (D > 1) do
233 begin
234 if W > 1 then begin W := W div 2; Size := Size div 2; end;
235 if H > 1 then begin H := H div 2; Size := Size div 2; end;
236 if D > 1 then begin D := D div 2; Size := Size div 2; end;
237 Result := Result + Size;
238 end;
239
240 { WritelnLog('Mipmaps', Format('Mipmap sizes is %d for original image size %d (%f)',
241 [Result, Image.Size, Result / Image.Size]));}
242 end;
243
244 function AllocatedTexturesSort({$ifdef GENERICS_CONSTREF}constref{$else}const{$endif} Value1, Value2: TTextureMemoryProfiler.TAllocatedTexture): Integer;
245 begin
246 Result := Value2.Size - Value1.Size;
247 end;
248
249 function TTextureMemoryProfiler.Summary: string;
250
251 function FormatSize(const Size: Int64): string;
252 begin
253 if Size >= 1024 * 1024 * 1024 then
254 Result := Format('%f GB', [Size / (1024 * 1024 * 1024)]) else
255 if Size >= 1024 * 1024 then
256 Result := Format('%f MB', [Size / (1024 * 1024)]) else
257 if Size >= 1024 then
258 Result := Format('%f KB', [Size / 1024]) else
259 Result := IntToStr(Size) + ' B';
260 end;
261
262 type
263 TAllocatedTextureComparer = {$ifdef FPC}specialize{$endif} TComparer<TAllocatedTexture>;
264 var
265 S: string;
266 I: Integer;
267 Used: Int64;
268 AllocatedTex: TAllocatedTexture;
269 begin
270 S := '';
271
272 Used := 0;
273 for I := 0 to AllocatedTextures.Count - 1 do
274 Used := Used + AllocatedTextures[I].Size;
275 S := Format('Texture memory used: %s (%d bytes in %d textures)',
276 [FormatSize(Used), Used, AllocatedTextures.Count]) + NL;
277
278 AllocatedTextures.Sort(TAllocatedTextureComparer.Construct({$ifdef FPC}@{$endif}AllocatedTexturesSort));
279 for I := 0 to AllocatedTextures.Count - 1 do
280 begin
281 AllocatedTex := AllocatedTextures[I];
282 S := S + Format(' %f - %s (size %d : format %s, dimensions %d x %d x %d, mipmaps: %s)',
283 [AllocatedTex.Size / Used, AllocatedTex.Url,
284 AllocatedTex.Size, AllocatedTex.ImageFormat,
285 AllocatedTex.Width, AllocatedTex.Height, AllocatedTex.Depth,
286 BoolToStr(AllocatedTex.Mipmaps, true)]) + NL;
287 end;
288 Result := S;
289 end;
290
291 var
292 FTextureMemoryProfiler: TTextureMemoryProfiler;
293
294 function TextureMemoryProfiler: TTextureMemoryProfiler;
295 begin
296 if FTextureMemoryProfiler = nil then
297 FTextureMemoryProfiler := TTextureMemoryProfiler.Create;
298 Result := FTextureMemoryProfiler;
299 end;
300
301 {$endif read_implementation}