Debian Codegraph @

src/scene/load/spine/x3dloadinternalspine_atlas.inc

raw
1 {%MainUnit x3dloadinternalspine.pas}
2 {
3 Copyright 2014-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 { Spine atlas. }
18
19 type
20 TAtlasRegion = class
21 public
22 Name: String;
23 Rotate: Boolean;
24 { Left-bottom corner of the place in atlas. In pixels of the atlas image. }
25 XY: TVector2Integer;
26 { Size of the place in atlas. In pixels of the atlas image. }
27 Size: TVector2Integer;
28 { Original region size, before whitespace stripping was done.
29 May be equal Size, or just be left 0, if no whitespace stripping was done. }
30 Orig: TVector2Integer;
31 { Offset is non-zero only it whitespace stripping was done,
32 i.e. the complete texture area is not in the atlas file, as it was stripped. }
33 Offset: TVector2Integer;
34 TexCoord: TQuadTexCoord;
35 { When Spine atlas creator uses whitespace compression for texture,
36 the actual 3D points need to be squeezed a little to show smaller
37 part of the texture. Without compression, is starts at (0,0)
38 and ends at (1,1), with compression it is a little smaller. }
39 TexRect: TQuadTexRect;
40 Index: Integer;
41 procedure CalculateTexCoord(const ImageWidth, ImageHeight: Integer);
42 end;
43
44 TAtlasRegionList = {$ifdef FPC}specialize{$endif} TObjectList<TAtlasRegion>;
45
46 TAtlasPage = class
47 public
48 TextureUrl: String;
49 PMA: String;
50 Format: String;
51 Filter: String; //< a value allowed by TextureProperties.MinificationFilter and MagnificationFilter
52 IsRepeat: boolean;
53 Size: TVector2Integer; //< atlas may (but does not have to) contain this
54 Scale: Single; //< scale used at atlas generation; we don't actually need this for anything
55 Regions: TAtlasRegionList;
56 Node: TImageTextureNode;
57 NodeUsedAsChild: boolean;
58 constructor Create;
59 destructor Destroy; override;
60 procedure BuildNodes(const BaseUrl: String);
61 end;
62
63 TAtlasPageList = {$ifdef FPC}specialize{$endif} TObjectList<TAtlasPage>;
64
65 TAtlas = class(TTextureLoader)
66 Pages: TAtlasPageList;
67 constructor Create;
68 destructor Destroy; override;
69 { Read .atlas file as produced by Spine, in format of libgdx, see
70 https://github.com/libgdx/libgdx/wiki/Texture-packer }
71 procedure Parse(const Url: String);
72 procedure BuildNodes(const BaseUrl: String);
73 { Find atlas page and region corresponding to given region name.
74 Returns @false if it does not exist (the out vars are undefined in
75 this case). }
76 function Find(const RegionName: String;
77 out Page: TAtlasPage; out Region: TAtlasRegion): boolean;
78 function UseNode(const RegionName: String;
79 out TexCoord: TQuadTexCoord; out TexRect: TQuadTexRect;
80 out TexRotated: boolean): TImageTextureNode; override;
81 end;
82
83 procedure TAtlasRegion.CalculateTexCoord(const ImageWidth, ImageHeight: Integer);
84 var
85 TextureXY, TextureSize: TVector2;
86 I: Integer;
87 OriginalSize: TVector2Integer;
88 begin
89 TextureXY := Vector2(
90 XY.X / ImageWidth,
91 XY.Y / ImageHeight);
92
93 OriginalSize := Orig;
94 { if not specified, assume Orig is equal Size. }
95 if OriginalSize.X = 0 then
96 OriginalSize.X := Size.X;
97 if OriginalSize.Y = 0 then
98 OriginalSize.Y := Size.Y;
99
100 TexRect[0].X := Offset.X / OriginalSize.X;
101 TexRect[0].Y := Offset.Y / OriginalSize.Y;
102 TexRect[1].X := (Offset.X + Size.X) / OriginalSize.X;
103 TexRect[1].Y := (Offset.Y + Size.Y) / OriginalSize.Y;
104 if Rotate then
105 begin
106 TextureSize := Vector2(
107 Size.X / ImageHeight,
108 Size.Y / ImageWidth);
109 TextureXY.Y :=
110 { flip top-bottom }
111 1 - TextureXY.Y
112 { move corner to bottom }
113 - TextureSize.X;
114 end else
115 begin
116 TextureSize := Vector2(
117 Size.X / ImageWidth,
118 Size.Y / ImageHeight);
119 TextureXY.Y :=
120 { flip top-bottom }
121 1 - TextureXY.Y
122 { move corner to bottom }
123 - TextureSize.Y;
124 end;
125
126 if Rotate then
127 begin
128 TexCoord[0] := Vector2(TextureSize.Y, 0);
129 TexCoord[1] := Vector2(TextureSize.Y, TextureSize.X);
130 TexCoord[2] := Vector2( 0, TextureSize.X);
131 TexCoord[3] := Vector2( 0, 0);
132 end else
133 begin
134 TexCoord[0] := Vector2( 0, 0);
135 TexCoord[1] := Vector2(TextureSize.X, 0);
136 TexCoord[2] := Vector2(TextureSize.X, TextureSize.Y);
137 TexCoord[3] := Vector2( 0, TextureSize.Y);
138 end;
139
140 for I := 0 to 3 do
141 TexCoord[I] := TexCoord[I] + TextureXY;
142 end;
143
144 constructor TAtlasPage.Create;
145 begin
146 inherited;
147 Regions := TAtlasRegionList.Create;
148 Scale := 1;
149 end;
150
151 destructor TAtlasPage.Destroy;
152 begin
153 FreeAndNil(Regions);
154 if NodeUsedAsChild then
155 { in case NodeUsedAsChild, don't even try FreeIfUnusedAndNil,
156 as the check "is it unused" may already cause access violation
157 since it may be already freed by freeing parent. }
158 Node := nil else
159 FreeIfUnusedAndNil(Node);
160 inherited;
161 end;
162
163 procedure TAtlasPage.BuildNodes(const BaseUrl: String);
164 var
165 I, ReferenceImageWidth, ReferenceImageHeight: Integer;
166 begin
167 Node := TImageTextureNode.Create('Page_' + TextureUrl, BaseUrl);
168 Node.SetUrl([TextureUrl]);
169 AddSpineTextureProperties(Node, IsRepeat);
170
171 ReferenceImageWidth := 0;
172 ReferenceImageHeight := 0;
173 if (Size.X > 0) and (Size.Y > 0) then
174 begin
175 { It's best to read reference sizes from .atlas file.
176 This way you can scale the image underneath at any time, without changing
177 the .atlas file, and it will render Ok. }
178 ReferenceImageWidth := Size.X;
179 ReferenceImageHeight := Size.Y;
180 end else
181 begin
182 { Then the only way to calculate tex coords is to actually load the texture.
183 We use the texture Node for this, this way loaded texture will be reused for
184 actual model rendering. }
185 Node.IsTextureLoaded := true;
186 if Node.IsTextureImage then
187 begin
188 ReferenceImageWidth := Node.TextureImage.Width;
189 ReferenceImageHeight := Node.TextureImage.Height;
190 end;
191 end;
192
193 if (ReferenceImageWidth > 0) and
194 (ReferenceImageHeight > 0) then
195 begin
196 for I := 0 to Regions.Count - 1 do
197 Regions[I].CalculateTexCoord(ReferenceImageWidth, ReferenceImageHeight);
198 end else
199 WritelnWarning('Spine', SysUtils.Format('Cannot load texture "%s", texture coordinates cannot be correctly calculated based on Spine atlas information',
200 [TextureUrl]));
201 end;
202
203 constructor TAtlas.Create;
204 begin
205 inherited;
206 Pages := TAtlasPageList.Create;
207 end;
208
209 destructor TAtlas.Destroy;
210 begin
211 FreeAndNil(Pages);
212 inherited;
213 end;
214
215 procedure TAtlas.Parse(const Url: String);
216
217 { Split a Line divided by character Separator into two strings.
218 Assumes that whitespace doesn't matter (so we trim it),
219 and Name must not be empty. }
220 function Split(const Line: String; const Separator: char;
221 out Name, Value: String): boolean;
222 var
223 Index: Integer;
224 begin
225 Result := false;
226 Index := Pos(Separator, Line);
227 if Index <> 0 then
228 begin
229 Name := Trim(Copy(Line, 1, Index - 1));
230 Value := Trim(SEnding(Line, Index + 1));
231 if Name <> '' then
232 Result := true;
233 end;
234 end;
235
236 { All the IsNameValueXxx functions return @true and change Value
237 only if the line contains (corrent) specification of attribute
238 Name. Otherwise, they return @false and leave Value unmodified. }
239
240 function IsNameValueString(const Line, Name: String; var Value: String): boolean;
241 var
242 N, V: String;
243 begin
244 Result := Split(Line, ':', N, V) and (N = Name);
245 if Result then
246 Value := V;
247 end;
248
249 (* Not useful now
250 function IsNameValueBoolean(const Line, Name: String; var Value: boolean): boolean;
251 var
252 ValueStr: String;
253 begin
254 Result := IsNameValueString(Line, Name, ValueStr);
255 if Result then
256 begin
257 if ValueStr = 'false' then
258 Value := false
259 else
260 if ValueStr = 'true' then
261 Value := true
262 else
263 raise ESpineReadError.CreateFmt('Invalid boolean value "%s"', [ValueStr]);
264 end;
265 end;
266 *)
267
268 { Read "rotate" type, which is either boolean or integer (changed somewhere around Spine 4.0 release). }
269 function IsNameValueRotate(const Line, Name: String; var Value: Boolean): Boolean;
270 var
271 ValueStr: String;
272 ValueInt: Integer;
273 begin
274 Result := IsNameValueString(Line, Name, ValueStr);
275 if Result then
276 begin
277 if ValueStr = 'false' then
278 Value := false
279 else
280 if ValueStr = 'true' then
281 Value := true
282 else
283 if TryStrToInt(ValueStr, ValueInt) then
284 begin
285 case ValueInt of
286 0: Value := false;
287 90: Value := true;
288 else
289 begin
290 WritelnWarning('Unsupported "rotate" integer value in atlas "%d"', [ValueInt]);
291 Exit(false);
292 end;
293 end;
294 end else
295 begin
296 WritelnWarning('Unsupported "rotate" value in atlas "%s"', [ValueStr]);
297 Exit(false);
298 end;
299 end;
300 end;
301
302 function IsNameValueInteger(const Line, Name: String; var Value: Integer): boolean;
303 var
304 ValueStr: String;
305 begin
306 Result := IsNameValueString(Line, Name, ValueStr);
307 if Result then
308 begin
309 try
310 Value := StrToInt(ValueStr);
311 except
312 on E: EConvertError do
313 raise ESpineReadError.CreateFmt('Invalid integer value "%s": %s', [ValueStr, E.Message]);
314 end;
315 end;
316 end;
317
318 function IsNameValueSingle(const Line, Name: String; var Value: Single): boolean;
319 var
320 ValueStr: String;
321 begin
322 Result := IsNameValueString(Line, Name, ValueStr);
323 if Result then
324 begin
325 if not TryStrToFloatDot(ValueStr, Value) then
326 begin
327 WritelnWarning('Invalid float value in atlas "%s"', [ValueStr]);
328 Exit(false);
329 end;
330 end;
331 end;
332
333 function IsNameValueVector2Integer(const Line, Name: String; var Vector: TVector2Integer): boolean;
334 var
335 ValueStr, ValueStr0, ValueStr1: String;
336 begin
337 Result := IsNameValueString(Line, Name, ValueStr);
338 if Result then
339 begin
340 if Split(ValueStr, ',', ValueStr0, ValueStr1) then
341 try
342 Vector.X := StrToInt(ValueStr0);
343 Vector.Y := StrToInt(ValueStr1);
344 except
345 on E: EConvertError do
346 raise ESpineReadError.CreateFmt('Invalid integer value in vector of 2 integers "%s": %s', [ValueStr, E.Message]);
347 end else
348 raise ESpineReadError.CreateFmt('Cannot split a vector of 2 integers "%s" by a comma', [ValueStr]);
349 end;
350 end;
351
352 function IsNameValueVector4Integer(const Line, Name: String; var Vector: TVector4Integer): Boolean;
353 var
354 ValueStr: String;
355 Tokens: TCastleStringList;
356 I: Integer;
357 begin
358 Result := IsNameValueString(Line, Name, ValueStr);
359 if Result then
360 begin
361 Tokens := CreateTokens(ValueStr, WhiteSpaces + [',']);
362 try
363 if Tokens.Count <> 4 then
364 begin
365 WritelnWarning('Expected 4 values for "%s", got %d values', [Name, Tokens.Count]);
366 Exit(false);
367 end;
368 try
369 for I := 0 to 3 do
370 Vector.Data[I] := StrToInt(Tokens[I]);
371 except
372 on E: EConvertError do
373 begin
374 WritelnWarning('Invalid integer value in vector of 4 integers "%s": %s', [ValueStr, E.Message]);
375 Exit(false);
376 end;
377 end;
378 finally FreeAndNil(Tokens) end;
379 end;
380 end;
381
382 function IsNameValueTwoVectors2Integer(const Line, Name: String; var V1, V2: TVector2Integer): Boolean;
383 var
384 Bounds: TVector4Integer;
385 begin
386 Result := IsNameValueVector4Integer(Line, Name, Bounds);
387 if Result then
388 begin
389 V1.X := Bounds[0];
390 V1.Y := Bounds[1];
391 V2.X := Bounds[2];
392 V2.Y := Bounds[3];
393 end;
394 end;
395
396 function IsNameValueFilter(const Line, Name: String; var Filter: String): boolean;
397 var
398 ValueStr: String;
399 begin
400 Result := IsNameValueString(Line, Name, ValueStr);
401 if Result then
402 begin
403 if ValueStr = 'Linear,Linear' then
404 Filter := 'AVG_PIXEL'
405 else
406 if ValueStr = 'Nearest,Nearest' then
407 Filter := 'NEAREST_PIXEL'
408 else
409 raise ESpineReadError.CreateFmt('Unsupported filter mode "%s"', [ValueStr]);
410 end;
411 end;
412
413 function IsNameValueRepeat(const Line, Name: String; var IsRepeat: boolean): boolean;
414 var
415 ValueStr: String;
416 begin
417 Result := IsNameValueString(Line, Name, ValueStr);
418 if Result then
419 begin
420 if ValueStr = 'none' then
421 IsRepeat := false
422 else
423 { is there anything else allowed for repeat: field ? }
424 raise ESpineReadError.CreateFmt('Unsupported repeat mode "%s"', [ValueStr]);
425 end;
426 end;
427
428 var
429 Reader: TTextReader;
430 Page: TAtlasPage;
431 Region: TAtlasRegion;
432 Line: String;
433 begin
434 Page := nil;
435 Region := nil;
436 Reader := TTextReader.Create(Url);
437 try
438 while not Reader.Eof do
439 begin
440 Line := Reader.Readln;
441 if Page = nil then
442 begin
443 { start atlas page }
444 if Trim(Line) <> '' then
445 begin
446 Page := TAtlasPage.Create;
447 Page.TextureUrl := Trim(Line);
448 Pages.Add(Page);
449 Region := nil;
450 end;
451 end else
452 if Trim(Line) = '' then
453 begin
454 { end atlas page }
455 Page := nil;
456 Region := nil;
457 end else
458 if Region = nil then
459 begin
460 { read per-page (but not per-region) info }
461 if IsNameValueString(Line, 'format', Page.Format) then else
462 if IsNameValueFilter(Line, 'filter', Page.Filter) then else
463 if IsNameValueRepeat(Line, 'repeat', Page.IsRepeat) then else
464 if IsNameValueSingle(Line, 'scale', Page.Scale) then else
465 if IsNameValueString(Line, 'pma', Page.PMA) then else // We ignore pma
466 if IsNameValueVector2Integer(Line, 'size', Page.Size) then else
467 if Pos(':', Line) <> 0 then
468 raise ESpineReadError.CreateFmt('Unhandled name:value pair (outside region) "%s"', [Line]) else
469 begin
470 { new region }
471 Region := TAtlasRegion.Create;
472 Region.Name := Line;
473 Page.Regions.Add(Region);
474 end;
475 end else
476 begin
477 { read per-region info }
478 if IsNameValueRotate(Line, 'rotate', Region.Rotate) then else
479 if IsNameValueVector2Integer(Line, 'xy', Region.XY) then else
480 if IsNameValueVector2Integer(Line, 'size', Region.Size) then else
481 if IsNameValueVector2Integer(Line, 'orig', Region.Orig) then else
482 if IsNameValueVector2Integer(Line, 'offset', Region.Offset) then else
483 if IsNameValueInteger(Line, 'index', Region.Index) then else
484 if IsNameValueTwoVectors2Integer(Line, 'bounds', Region.XY, Region.Size) then else
485 if IsNameValueTwoVectors2Integer(Line, 'offsets', Region.Offset, Region.Orig) then else
486 if Pos(':', Line) <> 0 then
487 raise ESpineReadError.CreateFmt('Unhandled name:value pair (inside region) "%s"', [Line]) else
488 begin
489 { new region }
490 Region := TAtlasRegion.Create;
491 Region.Name := Line;
492 Page.Regions.Add(Region);
493 end;
494 end;
495 end;
496 finally FreeAndNil(Reader) end;
497
498 //WritelnLog('Spine', Format('Atlas parsed, pages: %d', [Pages.Count]));
499 end;
500
501 procedure TAtlas.BuildNodes(const BaseUrl: String);
502 var
503 I: Integer;
504 begin
505 for I := 0 to Pages.Count - 1 do
506 Pages[I].BuildNodes(BaseUrl);
507 end;
508
509 function TAtlas.Find(const RegionName: String;
510 out Page: TAtlasPage; out Region: TAtlasRegion): boolean;
511 var
512 I, J: Integer;
513 begin
514 for I := 0 to Pages.Count - 1 do
515 begin
516 Page := Pages[I];
517 for J := 0 to Page.Regions.Count - 1 do
518 begin
519 Region := Page.Regions[J];
520 if Region.Name = RegionName then
521 Exit(true);
522 end;
523 end;
524
525 WritelnWarning('Spine', Format('Region name "%s" not found in atlas', [RegionName]));
526 Result := false;
527 end;
528
529 function TAtlas.UseNode(const RegionName: String;
530 out TexCoord: TQuadTexCoord; out TexRect: TQuadTexRect;
531 out TexRotated: boolean): TImageTextureNode;
532 var
533 AtlasPage: TAtlasPage;
534 AtlasRegion: TAtlasRegion;
535 begin
536 if not Find(RegionName, AtlasPage, AtlasRegion) then Exit(nil);
537 Result := AtlasPage.Node;
538 AtlasPage.NodeUsedAsChild := true;
539 TexRect := AtlasRegion.TexRect;
540 TexCoord := AtlasRegion.TexCoord;
541 TexRotated := AtlasRegion.Rotate;
542 end;