Debian Codegraph @

src/scene/castletiledmap_data.inc

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 {%MainUnit castletiledmap.pas}
2 {
3 Copyright 2015-2024 Tomasz Wojtyś, 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 { Loading and manipulating "Tiled" map files (TCastleTiledMapData class). }
18
19 {$ifdef read_interface}
20
21 type
22 { Loading and manipulating "Tiled" map files (http://mapeditor.org). }
23 TCastleTiledMapData = class
24 public
25 type
26 TProperty = class
27 private
28 procedure Load(const Element: TDOMElement; const BaseUrl: String);
29 public
30 { The name of the property. }
31 Name: String;
32 { The value of the property. }
33 Value: String;
34 { The type of the property. Can be string (default), int, float, bool, color
35 or file (since 0.16, with color and file added in 0.17). }
36 AType: String;
37 end;
38
39 { List of properties. }
40 TPropertyList = class({$ifdef FPC}specialize{$endif} TObjectList<TProperty>)
41 private
42 procedure Load(const Element: TDOMElement; const BaseUrl: String);
43 end;
44
45 TEncodingType = (etNone, etBase64, etCSV);
46 TCompressionType = (ctNone, ctGZip, ctZLib);
47
48 { Binary data definition. }
49 TData = class
50 private
51 procedure Load(const Element: TDOMElement; const BaseUrl: String);
52 public
53 { The encoding used to encode the tile layer data. When used, it can be
54 "base64" and "csv" at the moment. }
55 Encoding: TEncodingType;
56 { The compression used to compress the tile layer data. Tiled Qt supports
57 "gzip" and "zlib". }
58 Compression: TCompressionType;
59 { Binary data. Uncompressed and decoded. }
60 Data: array of Cardinal;
61 end;
62
63 { Image definition. }
64 TImage = class
65 private
66 procedure Load(const Element: TDOMElement; const BaseUrl: String);
67 public
68 { Used for embedded images, in combination with a data child element.
69 Valid values are file extensions like png, gif, jpg, bmp, etc. (since 0.9) }
70 Format: String;
71 { The reference to the tileset image file (Tiled supports most common
72 image formats). }
73 Url: String;
74 { Defines a specific color that is treated as transparent. }
75 Trans: TCastleColorRGB;
76 { The image width in pixels (optional, used for tile index correction when
77 the image changes). }
78 Width: Cardinal;
79 { The image height in pixels (optional). }
80 Height: Cardinal;
81 { Embedded image data (since 0.9). }
82 Data: TData;
83 destructor Destroy; override;
84 procedure DetermineSize;
85 end;
86
87 TObjectsDrawOrder = (odoIndex, odoTopDown);
88
89 TTiledObjectPrimitive = (topRectangle, topPoint, topEllipse, topPolygon,
90 topPolyLine);
91
92 { Object definition. }
93 TTiledObject = class
94 private
95 procedure Load(const Element: TDOMElement; const BaseUrl: String);
96 public
97 { Unique ID of the object. Each object that is placed on a map gets
98 a unique id. Even if an object was deleted, no object gets the same ID.
99 Can not be changed in Tiled Qt. (since Tiled 0.11) }
100 Id: Integer;
101 { The name of the object. An arbitrary string. }
102 Name: String;
103 { The type of the object. An arbitrary string. }
104 Type_: String;
105 { The x coordinate of the object in pixels. }
106 X: Single;
107 { The y coordinate of the object in pixels. }
108 Y: Single;
109 { The width of the object in pixels (defaults to 0). }
110 Width: Single;
111 { The height of the object in pixels (defaults to 0). }
112 Height: Single;
113 { The rotation of the object in degrees clockwise (defaults to 0). (since 0.10) }
114 Rotation: Single;
115 { An reference to a tile (optional). }
116 GId: Cardinal;
117 { Whether the object is shown (1) or hidden (0). Defaults to 1. (since 0.9) }
118 Visible: Boolean;
119 Properties: TPropertyList;
120 { List of points for poligon and poliline. }
121 Points: TVector2List;
122 Primitive: TTiledObjectPrimitive;
123 Image: TImage;
124 constructor Create;
125 destructor Destroy; override;
126 { X and Y packed in a vector. }
127 function Position: TVector2;
128 end;
129
130 TTiledObjectList = {$ifdef FPC}specialize{$endif} TObjectList<TTiledObject>;
131
132 TLayer = class
133 private
134 FVisible: Boolean;
135 procedure Load(const Element: TDOMElement; const BaseUrl: String); virtual;
136 procedure SetExists(const Value: Boolean);
137 public
138 { Unique ID of the layer. Defaults to 0.}
139 Id: Cardinal;
140 { The name of the layer. }
141 Name: String;
142 { The class of the layer (since 1.9, defaults to ''). }
143 &Class: String;
144 { The opacity of the layer as a value from 0 to 1. Defaults to 1. }
145 Opacity: Single;
146 { Whether the layer is locked or unlocked. Defaults to false. }
147 Locked: Boolean;
148 { Rendering offset for this layer in pixels. Defaults to 0. (since 0.14). }
149 OffsetX: Single;
150 { Rendering offset for this layer in pixels. Defaults to 0. (since 0.14). }
151 OffsetY: Single;
152 Properties: TPropertyList;
153 Data: TData;
154 { The color used to display the objects in this group. }
155 Color: TCastleColorRGB;
156 { The width of the object group in tiles. Meaningless. }
157 Width: Integer;
158 { The height of the object group in tiles. Meaningless. }
159 Height: Integer;
160 { Used by the Exists-property to show/hide the layer.
161 Not a part of the file format.
162
163 TODO: Maybe rename this to RenderData,
164 consistent with other such data in this file.
165 Possibly do this at new Tiled layers API work:
166 https://castle-engine.io/roadmap#tiled_layers . }
167 SwitchNode: TSwitchNode;
168 constructor Create;
169 destructor Destroy; override;
170 { OffsetX and OffsetY packed in a vector. }
171 function Offset: TVector2;
172 { Hides or shows the layer. Not a part of the file format.
173
174 TODO:
175 This property should move to a different class, TCastleTiledMap.TLayer.
176 See https://castle-engine.io/roadmap#tiled_layers }
177 property Exists: Boolean read FVisible write SetExists;
178 { Whether the layer is shown or hidden. Defaults to true. Use the Exists-property to
179 change the visibility during runtime. }
180 property Visible: Boolean read FVisible;
181 end;
182
183 TObjectGroupLayer = class(TLayer)
184 private
185 procedure Load(const Element: TDOMElement; const BaseUrl: String); override;
186 public
187 { Whether the objects are drawn according to the order of appearance
188 ("index") or sorted by their y-coordinate ("topdown"). Defaults to "topdown". }
189 DrawOrder: TObjectsDrawOrder;
190 Objects: TTiledObjectList;
191 constructor Create;
192 destructor Destroy; override;
193 end;
194
195 TImageLayer = class(TLayer)
196 private
197 procedure Load(const Element: TDOMElement; const BaseUrl: String); override;
198 public
199 { Used by ImageLayer. }
200 Image: TImage;
201 destructor Destroy; override;
202 end;
203
204 { List of layers. }
205 TLayerList = {$ifdef FPC}specialize{$endif} TObjectList<TLayer>;
206
207 { Single frame of animation. }
208 TFrame = class
209 private
210 procedure Load(const Element: TDOMElement; const BaseUrl: String);
211 public
212 { The local ID of a tile within the parent tileset. }
213 TileId: Cardinal;
214 { How long (in milliseconds) this frame should be displayed before advancing
215 to the next frame. }
216 Duration: Cardinal;
217 end;
218
219 { Contains a list of animation frames.
220 As of Tiled 0.10, each tile can have exactly one animation associated with it.
221 In the future, there could be support for multiple named animations on a tile. }
222 TAnimation = class({$ifdef FPC}specialize{$endif} TObjectList<TFrame>)
223 private
224 procedure Load(const Element: TDOMElement; const BaseUrl: String);
225 end;
226
227 TTile = class
228 private
229 procedure Load(const Element: TDOMElement; const BaseUrl: String);
230 public
231 { The local tile ID within its tileset. }
232 Id: Cardinal;
233 { The class of the tile. Is inherited by tile objects. (since 1.0, defaults to '',
234 was saved as class in 1.9) }
235 &Type: String;
236 { Defines the terrain type of each corner of the tile, given as
237 comma-separated indexes in the terrain types array in the order top-left,
238 top-right, bottom-left, bottom-right. Leaving out a value means that corner
239 has no terrain. (optional) (since 0.9) }
240 Terrain: TVector4Integer;
241 { A percentage indicating the probability that this tile is chosen when it
242 competes with others while editing with the terrain tool. (optional) (since 0.9) }
243 Probability: Single;
244 Properties: TPropertyList;
245 Image: TImage;
246 { ObjectGroup since 0.10. }
247 ObjectGroup: TObjectGroupLayer;
248 Animation: TAnimation;
249 { Use to render the tile. Not a part of the file format.
250 In case of X3DLoadInternalTiledMap, this is always TShapeNode. }
251 RendererData: TObject;
252 constructor Create;
253 destructor Destroy; override;
254 end;
255
256 { Tiles list. }
257 TTileList = {$ifdef FPC}specialize{$endif} TObjectList<TTile>;
258
259 TTerrain = class
260 { The name of the terrain type. }
261 Name: String;
262 { The local tile-id of the tile that represents the terrain visually. }
263 Tile: Cardinal;
264 Properties: TPropertyList;
265 end;
266
267 { This element defines an array of terrain types, which can be referenced from
268 the terrain attribute of the tile element. }
269 TTerrainTypes = {$ifdef FPC}specialize{$endif} TObjectList<TTerrain>;
270
271 { Tileset definition. }
272 TTileset = class
273 private
274 procedure Load(const Element: TDOMElement; const BaseUrl: String);
275 public
276 { The first global tile ID of this tileset (this global ID maps to the first
277 tile in this tileset). }
278 FirstGID: Cardinal;
279 { If this tileset is stored in an external TSX (Tile Set XML) file, this
280 attribute refers to that file. That TSX file has the same structure as the
281 <tileset> element described here. (There is the firstgid attribute missing
282 and this source attribute is also not there. These two attributes
283 are kept in the TMX map, since they are map specific.) }
284 Url: String;
285 { The name of this tileset. }
286 Name: String;
287 { The (maximum) width of the tiles in this tileset. }
288 TileWidth: Cardinal;
289 { The (maximum) height of the tiles in this tileset. }
290 TileHeight: Cardinal;
291 { The spacing in pixels between the tiles in this tileset (applies to the
292 tileset image). }
293 Spacing: Cardinal;
294 { The margin around the tiles in this tileset (applies to the tileset image). }
295 Margin: Cardinal;
296 { The number of tiles in this tileset (since 0.13) }
297 TileCount: Cardinal;
298 { The number of tile columns in the tileset. For image collection tilesets
299 it is editable and is used when displaying the tileset. (since 0.15) }
300 Columns: Cardinal;
301 { This element is used to specify an offset in pixels, to be applied when
302 drawing a tile from the related tileset. When not present, no offset is applied. }
303 TileOffset: TVector2Integer;
304 Properties: TPropertyList;
305 Image: TImage;
306 Tiles: TTileList;
307 TerrainTypes: TTerrainTypes; //todo: loading TerrainTypes
308 { Use to render the tileset. Not a part of the file format.
309 In case of TCastleTiledMapControl, this is always TSprite. }
310 RendererData: TObject;
311 constructor Create;
312 destructor Destroy; override;
313 end;
314
315 { List of tilesets. }
316 TTilesetList = {$ifdef FPC}specialize{$endif} TObjectList<TTileset>;
317
318 TMapOrientation = (
319 moOrthogonal,
320 moIsometric,
321 moIsometricStaggered,
322 moHexagonal
323 );
324 TMapRenderOrder = (mroRightDown, mroRightUp, mroLeftDown, mroLeftUp);
325 TStaggerAxis = (saX, saY);
326 TStaggerIndex = (siOdd, siEven);
327
328 strict private
329 { Map stuff. }
330 { The TMX format version, generally 1.0. }
331 FVersion: String;
332 FOrientation: TMapOrientation;
333 FWidth: Cardinal;
334 FHeight: Cardinal;
335 FTileWidth: Cardinal;
336 FTileHeight: Cardinal;
337 FHexSideLength: Cardinal;
338 FStaggerAxis: TStaggerAxis;
339 FStaggerIndex: TStaggerIndex;
340 FBackgroundColor: TCastleColor;
341 FRenderOrder: TMapRenderOrder;
342 FBaseUrl: String;
343 FTilesets: TTilesetList;
344 FProperties: TPropertyList;
345 FLayers: TLayerList;
346 { Load TMX file from stream. }
347 procedure LoadTMXFile(const Stream: TStream; const ABaseUrl: String); overload;
348 { Load TMX file by URL. }
349 procedure LoadTMXFile(const AUrl: String); overload;
350 { Load TMX file internally from XMLDocument instance. }
351 procedure LoadTMXFileInternal(const Doc: TXMLDocument);
352 public
353 property Layers: TLayerList read FLayers;
354 { Map orientation. }
355 property Orientation: TMapOrientation read FOrientation;
356 property Properties: TPropertyList read FProperties;
357 property Tilesets: TTilesetList read FTilesets;
358 { The map width in tiles. }
359 property Width: Cardinal read FWidth;
360 { The map height in tiles. }
361 property Height: Cardinal read FHeight;
362 { The width of a tile. }
363 property TileWidth: Cardinal read FTileWidth;
364 { The height of a tile. }
365 property TileHeight: Cardinal read FTileHeight;
366 { The height of a hexagon side.
367 Only relevant when @link(Orientation) = moHexagonal. }
368 property HexSideLength: Cardinal read FHexSideLength;
369 { Only relevant when @link(Orientation) = moIsometricStaggered or moHexagonal. }
370 property StaggerAxis: TStaggerAxis read FStaggerAxis;
371 { Which rows are shifted by 1.
372 Only relevant when @link(Orientation) = moIsometricStaggered or moHexagonal. }
373 property StaggerIndex: TStaggerIndex read FStaggerIndex;
374 { Background color of the map.
375 It may be unset in Tiled, which results in transparent color here. }
376 property BackgroundColor: TCastleColor read FBackgroundColor;
377 { The order in which tiles on tile layers are rendered. Valid values are
378 right-down (the default), right-up, left-down and left-up. In all cases,
379 the map is drawn row-by-row. (since 0.10, but only supported for orthogonal
380 maps at the moment) }
381 property RenderOrder: TMapRenderOrder read FRenderOrder;
382 { Constructor.
383 @param(AUrl URL to Tiled (TMX) file.) }
384 constructor Create(const Stream: TStream; const ABaseUrl: String); overload;
385 constructor Create(const AUrl: String); overload;
386 destructor Destroy; override;
387
388 { Is the given tile number valid.
389 Valid map tiles are from (0, 0) (lower-left) to
390 (@link(Width) - 1, @link(Height) - 1) (upper-right). }
391 function TilePositionValid(const TilePosition: TVector2Integer): Boolean;
392
393 { Detect tile under given position.
394
395 Input Position is in local map coordinates.
396
397 Output TilePosition must is a tile coordinate,
398 where map bottom-left corner is (0, 0).
399
400 This method returns @false if the position is outside of the map.
401 Valid map tiles are defined as by @link(TilePositionValid).
402
403 Note: Regardless of the result (@true or @false), the TilePosition
404 is reliably defined and set.
405 It is just outside of the map range if the result is @false.
406 If you don't care about it (that is, you want to accept even positions that
407 are outside of map range) that you're free to use TilePosition for
408 whatever calculations. }
409 function PositionToTile(const Position: TVector2;
410 out TilePosition: TVector2Integer): Boolean;
411
412 { Left-bottom corner where the given tile should be rendered. }
413 function TileRenderPosition(const TilePosition: TVector2Integer): TVector2;
414
415 { Information about which image (and how) should be displayed at given map position. }
416 function TileRenderData(const TilePosition: TVector2Integer;
417 const Layer: TLayer;
418 out Tileset: TTileset;
419 out Frame: Integer;
420 out HorizontalFlip, VerticalFlip, DiagonalFlip: Boolean): Boolean;
421
422 { Are the two given tiles neighbors.
423 Takes into account map @link(Orientation), so it works for hexagonal,
424 orthogonal etc. maps. }
425 function TileNeighbor(const Tile1, Tile2: TVector2Integer;
426 const CornersAreNeighbors: Boolean): Boolean;
427 end;
428
429 TTiledMap = TCastleTiledMapData deprecated 'use TCastleTiledMapData';
430
431 {$endif read_interface}
432
433 {$ifdef read_implementation}
434
435 { global helpers ------------------------------------------------------------- }
436
437 function TiledToColorRGB(S: String): TCastleColorRGB;
438 begin
439 if SCharIs(S, 1, '#') then
440 Delete(S, 1, 1);
441 Result := HexToColorRGB(S);
442 end;
443
444 function TiledToColor(const S: String): TCastleColor;
445 begin
446 Result := Vector4(TiledToColorRGB(S), 1);
447 end;
448
449 { TProperty ------------------------------------------------------------------ }
450
451 procedure TCastleTiledMapData.TProperty.Load(const Element: TDOMElement; const BaseUrl: String);
452 begin
453 Name := Element.AttributeStringDef('name', '');
454 Value := Element.AttributeStringDef('value', '');
455 AType := Element.AttributeStringDef('type', '');
456 end;
457
458 { TPropertyList -------------------------------------------------------------- }
459
460 procedure TCastleTiledMapData.TPropertyList.Load(const Element: TDOMElement; const BaseUrl: String);
461 var
462 I: TXMLElementIterator;
463 NewProperty: TProperty;
464 begin
465 I := TXMLElementIterator.Create(Element);
466 try
467 while I.GetNext do
468 begin
469 if LowerCase(I.Current.TagName) = 'property' then
470 begin
471 NewProperty := TProperty.Create;
472 NewProperty.Load(I.Current, BaseUrl);
473 Add(NewProperty);
474 end;
475 end;
476 finally FreeAndNil(I) end;
477 end;
478
479 { TData ---------------------------------------------------------------------- }
480
481 procedure TCastleTiledMapData.TData.Load(const Element: TDOMElement; const BaseUrl: String);
482
483 procedure AddData(const Item: Cardinal);
484 var
485 L: Integer;
486 begin
487 L := Length(Data);
488 SetLength(Data, L + 1);
489 Data[L] := Item;
490 end;
491
492 procedure ReadEncodingNone;
493 var
494 I: TXMLElementIterator;
495 begin
496 I := TXMLElementFilteringIterator.Create(Element, 'tile');
497 try
498 while I.GetNext do
499 AddData(I.Current.AttributeCardinalDef('gid', 0));
500 finally FreeAndNil(I) end;
501 end;
502
503 procedure ReadEncodingBase64;
504 const
505 BufferSize = 16;
506 var
507 Decoder: TBase64DecodingStream;
508 Decompressor: TStream;
509 Buffer: array[0..BufferSize-1] of Cardinal;
510 DataCount, DataLength: Int64;
511 begin
512 Decoder := TBase64DecodingStream.Create(TStringStream.Create(Element.TextData));
513 try
514 Decoder.SourceOwner := true;
515
516 case Compression of
517 ctGzip: WritelnWarning('TData.Load', 'TODO: Gzip format not implemented');
518 ctZLib:
519 begin
520 Decompressor := TDecompressionStream.Create(Decoder);
521 try
522 repeat
523 DataCount := Decompressor.Read(Buffer, BufferSize * SizeOf(Cardinal));
524 DataLength := Length(Data);
525 SetLength(Data, DataLength+(DataCount div SizeOf(Cardinal)));
526 if DataCount > 0 then // because if DataCount=0 then ERangeCheck error
527 Move(Buffer, Data[DataLength], DataCount);
528 until DataCount < SizeOf(Buffer);
529 finally
530 Decompressor.Free;
531 end;
532 end;
533 ctNone:
534 begin
535 repeat
536 DataCount := Decoder.Read(Buffer, BufferSize * SizeOf(Cardinal));
537 DataLength := Length(Data);
538 SetLength(Data, DataLength+(DataCount div SizeOf(Cardinal)));
539 if DataCount > 0 then // because if DataCount=0 then ERangeCheck error
540 Move(Buffer, Data[DataLength], DataCount);
541 until DataCount < SizeOf(Buffer);
542 end;
543 end;
544 finally FreeAndNil(Decoder) end;
545 end;
546
547 procedure ReadEncodingCSV;
548 var
549 RawData, Token: String;
550 SeekPos: Integer;
551 begin
552 RawData := Element.TextData;
553 SeekPos := 1;
554 repeat
555 Token := NextToken(RawData, SeekPos, [','] + WhiteSpaces);
556 if Token = '' then break;
557 { We use StrToDWord, as any value in 32-bit unsigned range is OK,
558 even values > 32-bit signed range.
559 E.g. test_hexagonal_tile_60x60x30.tmx on
560 https://github.com/bjorn/tiled/tree/master/examples
561 has values like 3221225473 . }
562 AddData(StrToDWord(Token));
563 until false;
564 end;
565
566 var
567 TmpStr: String;
568 begin
569 Encoding := etNone;
570 Compression := ctNone;
571
572 if Element.AttributeString('encoding', TmpStr) then
573 begin
574 if TmpStr = 'base64' then
575 Encoding := etBase64
576 else
577 if TmpStr = 'csv' then
578 Encoding := etCSV
579 else
580 WritelnWarning('Invalid Tiled encoding "%s"', [TmpStr]);
581 end;
582
583 if Element.AttributeString('compression', TmpStr) then
584 begin
585 if TmpStr = 'gzip' then
586 Compression := ctGzip
587 else
588 if TmpStr = 'zlib' then
589 Compression := ctZLib
590 else
591 WritelnWarning('Invalid Tiled compression "%s"', [TmpStr]);
592 end;
593
594 case Encoding of
595 etNone: ReadEncodingNone;
596 etBase64: ReadEncodingBase64;
597 etCSV: ReadEncodingCSV;
598 end;
599 end;
600
601 { TImage --------------------------------------------------------------------- }
602
603 destructor TCastleTiledMapData.TImage.Destroy;
604 begin
605 FreeAndNil(Data);
606 inherited;
607 end;
608
609 procedure TCastleTiledMapData.TImage.Load(const Element: TDOMElement; const BaseUrl: String);
610 const
611 DefaultTrans: TCastleColorRGB = (X: 1.0; Y: 0.0; Z: 1.0); {Fuchsia}
612 var
613 I: TXMLElementIterator;
614 TmpStr, UrlPrefix: String;
615 begin
616 if Element.AttributeString('format', TmpStr) then
617 Format := TmpStr;
618 if Element.AttributeString('source', TmpStr) then
619 begin
620 UrlPrefix := CombineUri(BaseUrl, TmpStr);
621 { Tiled allows loading images ignoring the '.png' suffix }
622 if (ExtractFileExt(TmpStr) = '') and not UriFileExists(UrlPrefix) then
623 Url := UrlPrefix + '.png'
624 else
625 Url := UrlPrefix;
626 end;
627 if Element.AttributeString('trans', TmpStr) then
628 Trans := TiledToColorRGB(TmpStr)
629 else
630 Trans := DefaultTrans;
631 if Element.AttributeString('width', TmpStr) then
632 Width := StrToInt(TmpStr);
633 if Element.AttributeString('height', TmpStr) then
634 Height := StrToInt(TmpStr);
635
636 I := TXMLElementIterator.Create(Element);
637 try
638 while I.GetNext do
639 begin
640 if LowerCase(I.Current.TagName) = 'data' then
641 begin
642 if Data = nil then
643 Data := TData.Create;
644 Data.Load(I.Current, BaseUrl);
645 end;
646 end;
647 finally FreeAndNil(I) end;
648 end;
649
650 procedure TCastleTiledMapData.TImage.DetermineSize;
651 var
652 ImageData: TEncodedImage;
653 begin
654 if (Width = 0) and
655 (Height = 0) and
656 { Do not load image when there's no Url (no "source" attribute at <tileset>).
657 This is possible when each <tile> has its own <image> element,
658 we don't support it yet, TCastleTiledMapConverter will later warn and
659 skip such tileset.
660
661 Testcase: Phoenix bugreport,
662 https://discord.com/channels/389676745957310465/1204090530368327690/1247180638520606829 ,
663 Michalis has testcase in private. }
664 (Url <> '') then
665 begin
666 { Note: While we could store Image to use it loader, e.g.
667
668 TilesetTextureNode.LoadFromImage(Tileset.Image, false, Tileset.Image.Url);
669
670 ... but this would be an optimization that complicates code for a seldom use-case
671 (because new Tiled files should include size).
672 So we don't do it, and just load + free image only to read size. }
673
674 WritelnLog('Determining image size by loading it. It is more efficient to store image size in TMX file.');
675 ImageData := LoadEncodedImage(Url);
676 try
677 Width := ImageData.Width;
678 Height := ImageData.Height;
679 finally FreeAndNil(ImageData) end;
680 end;
681 end;
682
683 { TFrame --------------------------------------------------------------------- }
684
685 procedure TCastleTiledMapData.TFrame.Load(const Element: TDOMElement; const BaseUrl: String);
686 var
687 TmpStr: String;
688 begin
689 if Element.AttributeString('tileid', TmpStr) then
690 TileId := StrToInt(TmpStr);
691 if Element.AttributeString('duration', TmpStr) then
692 Duration := StrToInt(TmpStr);
693 end;
694
695 { TAnimation ----------------------------------------------------------------- }
696
697 procedure TCastleTiledMapData.TAnimation.Load(const Element: TDOMElement; const BaseUrl: String);
698 var
699 I: TXMLElementIterator;
700 NewFrame: TFrame;
701 begin
702 I := TXMLElementIterator.Create(Element);
703 try
704 while I.GetNext do
705 begin
706 if LowerCase(I.Current.TagName) = 'frame' then
707 begin
708 NewFrame := TFrame.Create;
709 NewFrame.Load(I.Current, BaseUrl);
710 Add(NewFrame);
711 end;
712 end;
713 finally FreeAndNil(I) end;
714 end;
715
716 { TTile ------------------------------------------------------------------- }
717
718 constructor TCastleTiledMapData.TTile.Create;
719 begin
720 inherited;
721 Properties := TPropertyList.Create;
722 Animation := TAnimation.Create;
723 Image := TImage.Create;
724
725 { Default values }
726 Probability := 1.0;
727 end;
728
729 destructor TCastleTiledMapData.TTile.Destroy;
730 begin
731 FreeAndNil(Properties);
732 FreeAndNil(Animation);
733 FreeAndNil(Image);
734 FreeAndNil(ObjectGroup);
735 inherited;
736 end;
737
738 procedure TCastleTiledMapData.TTile.Load(const Element: TDOMElement; const BaseUrl: String);
739 var
740 I: TXMLElementIterator;
741 TmpStr, LowerTagName: String;
742 SPosition: Integer;
743 begin
744 if Element.AttributeString('id', TmpStr) then
745 Id := StrToInt(TmpStr);
746 &Type := Element.AttributeStringDef('type', '');
747
748 if Element.AttributeString('terrain', TmpStr) then
749 begin
750 SPosition := 1;
751 Terrain.X := StrToInt(NextToken(TmpStr, SPosition, [',']));
752 Terrain.Y := StrToInt(NextToken(TmpStr, SPosition, [',']));
753 Terrain.Z := StrToInt(NextToken(TmpStr, SPosition, [',']));
754 Terrain.W := StrToInt(NextToken(TmpStr, SPosition, [',']));
755 end;
756 if Element.AttributeString('probability', TmpStr) then
757 Probability := StrToFloatDot(TmpStr);
758
759 I := TXMLElementIterator.Create(Element);
760 try
761 while I.GetNext do
762 begin
763 LowerTagName := LowerCase(I.Current.TagName8);
764 if LowerTagName = 'properties' then
765 Properties.Load(I.Current, BaseUrl)
766 else
767 if LowerTagName = 'image' then
768 Image.Load(I.Current, BaseUrl)
769 else
770 if LowerTagName = 'animation' then
771 Animation.Load(I.Current, BaseUrl)
772 else
773 if LowerTagName = 'objectgroup' then
774 begin
775 if ObjectGroup = nil then
776 ObjectGroup := TObjectGroupLayer.Create;
777 ObjectGroup.Load(I.Current, BaseUrl);
778 end;
779 end;
780 finally FreeAndNil(I) end;
781 end;
782
783 { TTiledObject ------------------------------------------------------------------- }
784
785 constructor TCastleTiledMapData.TTiledObject.Create;
786 begin
787 inherited;
788 Properties := TPropertyList.Create;
789 end;
790
791 destructor TCastleTiledMapData.TTiledObject.Destroy;
792 begin
793 FreeAndNil(Properties);
794 FreeAndNil(Points);
795 inherited;
796 end;
797
798 procedure TCastleTiledMapData.TTiledObject.Load(const Element: TDOMElement; const BaseUrl: String);
799 var
800 I: TXMLElementIterator;
801 TmpStr: String;
802
803 function ReadVector(const S: String): TVector2;
804 var
805 SeekPos: Integer;
806 Token: String;
807 begin
808 SeekPos := 1;
809 Token := NextToken(S, SeekPos, [',']);
810 Result.X := StrToFloatDot(Token);
811 Token := NextToken(S, SeekPos, [',']);
812 Result.Y := StrToFloatDot(Token);
813 Token := NextToken(S, SeekPos, [',']);
814 if Token <> '' then
815 raise Exception.CreateFmt('Unexpected vector format in Tiled map: %s', [S]);
816 end;
817
818 procedure ReadPoints(const PointsString: String; var PointsList: TVector2List);
819 var
820 SeekPos: Integer;
821 Token: String;
822 begin
823 if not Assigned(PointsList) then PointsList := TVector2List.Create;
824 SeekPos := 1;
825 repeat
826 Token := NextToken(PointsString, SeekPos, [' ']);
827 if Token = '' then Break;
828 PointsList.Add(ReadVector(Token));
829 until false;
830 end;
831
832 var
833 LowerTagName: String;
834 begin
835 Width := 0;
836 Height := 0;
837 Rotation := 0;
838 Visible := True;
839 if Element.AttributeString('id', TmpStr) then
840 Id := StrToInt(TmpStr);
841 if Element.AttributeString('name', TmpStr) then
842 Name := TmpStr;
843 if Element.AttributeString('type', TmpStr) then
844 Type_ := TmpStr;
845 if Element.AttributeString('x', TmpStr) then
846 X := StrToFloatDot(TmpStr);
847 if Element.AttributeString('y', TmpStr) then
848 Y := StrToFloatDot(TmpStr);
849 if Element.AttributeString('width', TmpStr) then
850 Width := StrToFloatDot(TmpStr);
851 if Element.AttributeString('height', TmpStr) then
852 Height := StrToFloatDot(TmpStr);
853 if Element.AttributeString('rotation', TmpStr) then
854 Rotation := StrToFloatDot(TmpStr);
855 if Element.AttributeString('gid', TmpStr) then
856 GId := StrToDWord(TmpStr);
857 if Element.AttributeString('visible', TmpStr) then
858 if TmpStr = '0' then
859 Visible := False;
860
861 { Assume rectangle TiledObject first as it is the only element which has no
862 sub-element in TMX file which indicates its primitive type. Will be over-
863 ridden by follwing iteration, if a sub-element exists. }
864 Primitive := topRectangle;
865
866 I := TXMLElementIterator.Create(Element);
867 try
868 while I.GetNext do
869 begin
870 LowerTagName := LowerCase(I.Current.TagName8);
871 if LowerTagName = 'properties' then
872 Properties.Load(I.Current, BaseUrl)
873 else
874 if LowerTagName = 'point' then
875 Primitive := topPoint
876 else
877 if LowerTagName = 'ellipse' then
878 Primitive := topEllipse
879 else
880 if LowerTagName = 'polygon' then
881 begin
882 Primitive := topPolygon;
883 ReadPoints(I.Current.AttributeStringDef('points', ''), Points);
884 end else
885 if LowerTagName = 'polyline' then
886 begin
887 Primitive := topPolyLine;
888 ReadPoints(I.Current.AttributeStringDef('points', ''), Points);
889 end else
890 if LowerTagName = 'image' then
891 Image.Load(I.Current, BaseUrl);
892 end;
893 finally FreeAndNil(I) end;
894 end;
895
896 function TCastleTiledMapData.TTiledObject.Position: TVector2;
897 begin
898 Result := Vector2(X, Y);
899 end;
900
901 { TLayer ------------------------------------------------------------------- }
902
903 constructor TCastleTiledMapData.TLayer.Create;
904 begin
905 inherited;
906 Properties := TPropertyList.Create;
907 end;
908
909 destructor TCastleTiledMapData.TLayer.Destroy;
910 begin
911 FreeAndNil(Properties);
912 FreeAndNil(Data);
913 inherited;
914 end;
915
916 procedure TCastleTiledMapData.TLayer.Load(const Element: TDOMElement; const BaseUrl: String);
917 var
918 I: TXMLElementIterator;
919 TmpStr, LowerTagName: String;
920 begin
921 Opacity := 1;
922 FVisible := true;
923 OffsetX := 0;
924 OffsetY := 0;
925 Locked := False;
926 if Element.AttributeString('color', TmpStr) then
927 Color := TiledToColorRGB(TmpStr)
928 else
929 Color := BlackRGB; // Default layer color in Tiled editor if no color is set.
930
931 if Element.AttributeString('id', TmpStr) then
932 Id := StrToInt(TmpStr);
933 Name := Element.AttributeStringDef('name', '');
934 &Class := Element.AttributeStringDef('class', '');
935
936 if Element.AttributeString('opacity', TmpStr) then
937 Opacity := StrToFloatDot(TmpStr);
938 if Element.AttributeStringDef('visible', '1') = '0' then
939 FVisible := false;
940 if Element.AttributeStringDef('locked', '') = '1' then
941 Locked := True;
942
943 OffsetX := Element.AttributeSingleDef('offsetx', 0);
944 OffsetY := Element.AttributeSingleDef('offsety', 0);
945
946 I := TXMLElementIterator.Create(Element);
947 try
948 while I.GetNext do
949 begin
950 LowerTagName := LowerCase(I.Current.TagName8);
951 if LowerTagName = 'properties' then
952 Properties.Load(I.Current, BaseUrl)
953 else
954 if LowerTagName = 'data' then
955 begin
956 if Data = nil then
957 Data := TData.Create;
958 Data.Load(I.Current, BaseUrl);
959 end;
960 end;
961 finally FreeAndNil(I) end;
962 end;
963
964 function TCastleTiledMapData.TLayer.Offset: TVector2;
965 begin
966 Result := Vector2(OffsetX, OffsetY);
967 end;
968
969 procedure TCastleTiledMapData.TLayer.SetExists(const Value: Boolean);
970 begin
971 if FVisible <> Value then
972 begin
973 FVisible := Value;
974 if Assigned(SwitchNode) then
975 SwitchNode.WhichChoice := Iff(Value, 0, -1);
976 end;
977 end;
978
979 { TObjectGroupLayer ---------------------------------------------------------- }
980
981 constructor TCastleTiledMapData.TObjectGroupLayer.Create;
982 begin
983 inherited;
984 Objects := TTiledObjectList.Create;
985 end;
986
987 destructor TCastleTiledMapData.TObjectGroupLayer.Destroy;
988 begin
989 FreeAndNil(Objects);
990 inherited;
991 end;
992
993 procedure TCastleTiledMapData.TObjectGroupLayer.Load(const Element: TDOMElement; const BaseUrl: String);
994 var
995 I: TXMLElementIterator;
996 NewObject: TTiledObject;
997 TmpStr: String;
998 begin
999 inherited;
1000
1001 DrawOrder := odoTopDown;
1002
1003 if Element.AttributeString('draworder', TmpStr) then
1004 begin
1005 if TmpStr = 'index' then
1006 DrawOrder := odoIndex
1007 else
1008 if TmpStr = 'topdown' then
1009 DrawOrder := odoTopDown;
1010 end;
1011
1012 I := TXMLElementIterator.Create(Element);
1013 try
1014 while I.GetNext do
1015 begin
1016 if LowerCase(I.Current.TagName) = 'object' then
1017 begin
1018 NewObject := TTiledObject.Create;
1019 NewObject.Load(I.Current, BaseUrl);
1020 Objects.Add(NewObject);
1021 end;
1022 end;
1023 finally FreeAndNil(I) end;
1024 end;
1025
1026 { TImageLayer ---------------------------------------------------------------- }
1027
1028 destructor TCastleTiledMapData.TImageLayer.Destroy;
1029 begin
1030 FreeAndNil(Image);
1031 inherited;
1032 end;
1033
1034 procedure TCastleTiledMapData.TImageLayer.Load(const Element: TDOMElement; const BaseUrl: String);
1035 var
1036 I: TXMLElementIterator;
1037 begin
1038 inherited;
1039
1040 I := TXMLElementIterator.Create(Element);
1041 try
1042 while I.GetNext do
1043 begin
1044 if LowerCase(I.Current.TagName) = 'image' then
1045 begin
1046 if Image = nil then
1047 Image := TImage.Create;
1048 Image.Load(I.Current, BaseUrl);
1049 end;
1050 end;
1051 finally FreeAndNil(I) end;
1052 end;
1053
1054 { TTileset ------------------------------------------------------------------- }
1055
1056 constructor TCastleTiledMapData.TTileset.Create;
1057 begin
1058 inherited;
1059 Properties := TPropertyList.Create;
1060 Tiles := TTileList.Create;
1061 Image := TImage.Create;
1062 FirstGID := 1;
1063 end;
1064
1065 destructor TCastleTiledMapData.TTileset.Destroy;
1066 begin
1067 FreeAndNil(Image);
1068 FreeAndNil(Tiles);
1069 FreeAndNil(Properties);
1070 inherited;
1071 end;
1072
1073 procedure TCastleTiledMapData.TTileset.Load(const Element: TDOMElement; const BaseUrl: String);
1074
1075 { TSX file loading. }
1076 procedure LoadTilesetFromUrl;
1077 var
1078 Doc: TXMLDocument;
1079 begin
1080 Doc := UrlReadXML(Url);
1081 try
1082 Check(LowerCase(Doc.DocumentElement.TagName) = 'tileset',
1083 'Root element of TSX file must be <tileset>');
1084 Load(Doc.DocumentElement, Url);
1085 finally
1086 FreeAndNil(Doc);
1087 end;
1088 end;
1089
1090 { Reorder and complete Tiles list, to make sure
1091
1092 - Tiles.Count = TileCount
1093 - Tiles list has no nil elements.
1094
1095 Tiled doesn't explicitly write all tiles in TSX file.
1096 When the tile has everything default (probability equals 1.0,
1097 no terrains set, no type set...) it is not present in TSX.
1098 But it is more comfortable to have all instances of TTile available in API.
1099
1100 - All TTile instances are at index corresponding to their Id. }
1101 procedure CompleteTiles;
1102 var
1103 NewTiles: TTileList;
1104 Tile: TTile;
1105 I: Integer;
1106 begin
1107 NewTiles := TTileList.Create(true);
1108 NewTiles.Count := TileCount;
1109
1110 { place existing tiles in NewTiles, making sure they are at proper index }
1111 for Tile in Tiles do
1112 begin
1113 if not Between(Tile.Id, 0, TileCount - 1) then
1114 begin
1115 WritelnWarning('Tile id %d is outside of allowed range 0..%d', [
1116 Tile.Id,
1117 TileCount - 1
1118 ]);
1119 Continue;
1120 end;
1121 Check(NewTiles[Tile.Id] = nil, 'Multiple tiles have the same id');
1122 NewTiles[Tile.Id] := Tile;
1123 end;
1124
1125 { add new tiles to fill the gaps }
1126 for I := 0 to TileCount - 1 do
1127 if NewTiles[I] = nil then
1128 begin
1129 NewTiles[I] := TTile.Create;
1130 NewTiles[I].Id := I;
1131 end;
1132
1133 { swap Tiles into NewTiles }
1134 Tiles.OwnsObjects := false;
1135 FreeAndNil(Tiles);
1136 Tiles := NewTiles;
1137 end;
1138
1139 var
1140 I: TXMLElementIterator;
1141 NewTile: TTile;
1142 TmpStr, LowerTagName: String;
1143 begin
1144 TileOffset := TVector2Integer.Zero;
1145 Spacing := 0;
1146 Margin := 0;
1147
1148 if Element.AttributeString('firstgid', TmpStr) then
1149 FirstGID := StrToDWord(TmpStr);
1150 { Otherwise (if firstgid not specified in XML element), leave FirstGID unchanged.
1151 This is important to correctly read "firstgid" in case <tileset> in TMX points
1152 to external file like
1153
1154 <tileset firstgid="10" source="image3x3-regular.tsx"/>
1155
1156 This means that TCastleTiledMapData.TTileset.Load calls itself,
1157 and outer call set FirstGID to 10 and it should not be overridden by inner call.
1158 Testcases in examples/tiled/map_viewer/data/maps/multiple_tilesets/ . }
1159
1160 if Element.AttributeString('source', TmpStr) then
1161 begin
1162 Url := CombineUri(BaseUrl, TmpStr);
1163 LoadTilesetFromUrl;
1164 Exit;
1165 end;
1166 if Element.AttributeString('name', TmpStr) then
1167 Name := TmpStr;
1168 if Element.AttributeString('tilewidth', TmpStr) then
1169 TileWidth := StrToInt(TmpStr);
1170 if Element.AttributeString('tileheight', TmpStr) then
1171 TileHeight := StrToInt(TmpStr);
1172 if Element.AttributeString('spacing', TmpStr) then
1173 Spacing := StrToInt(TmpStr);
1174 if Element.AttributeString('margin', TmpStr) then
1175 Margin := StrToInt(TmpStr);
1176 if Element.AttributeString('tilecount', TmpStr) then
1177 TileCount := StrToInt(TmpStr)
1178 else
1179 TileCount := 0;
1180 if Element.AttributeString('columns', TmpStr) then
1181 Columns := StrToInt(TmpStr)
1182 else
1183 Columns := 0;
1184
1185 I := TXMLElementIterator.Create(Element);
1186 try
1187 while I.GetNext do
1188 begin
1189 LowerTagName := LowerCase(I.Current.TagName8);
1190 if LowerTagName = 'tileoffset' then
1191 begin
1192 TileOffset.X := I.Current.AttributeIntegerDef('x', 0);
1193 TileOffset.Y := I.Current.AttributeIntegerDef('y', 0);
1194 end else
1195 if LowerTagName = 'properties' then
1196 Properties.Load(I.Current, BaseUrl)
1197 else
1198 if LowerTagName = 'image' then
1199 Image.Load(I.Current, BaseUrl)
1200 else
1201 if LowerTagName = 'tile' then
1202 begin
1203 NewTile := TTile.Create;
1204 NewTile.Load(I.Current, BaseUrl);
1205 Tiles.Add(NewTile);
1206 end;
1207 end;
1208 finally FreeAndNil(I) end;
1209
1210 { In case tileset doesn't specify image size,
1211 testcase: examples/tiled/map_viewer/data/maps/perspective_walls.tmx }
1212 Image.DetermineSize;
1213
1214 { Fix Columns if necessary, testcase: examples/tiled/map_viewer/data/maps/desert.tmx }
1215 if Columns = 0 then
1216 Columns := Image.Width div TileWidth;
1217
1218 { Fix TileCount, if it is not found in (old) tsx-files prior to version 0.13 (Aug 2015). }
1219 if TileCount = 0 then
1220 TileCount := (Image.Height div TileHeight) * Columns;
1221
1222 CompleteTiles;
1223 end;
1224
1225 { TCastleTiledMapData ------------------------------------------------------------------ }
1226
1227 procedure TCastleTiledMapData.LoadTMXFile(const Stream: TStream; const ABaseUrl: String);
1228 var
1229 Doc: TXMLDocument;
1230 begin
1231 ReadXMLFile(Doc, Stream, ABaseUrl);
1232 try
1233 LoadTMXFileInternal(Doc);
1234 finally FreeAndNil(Doc) end;
1235 end;
1236
1237 procedure TCastleTiledMapData.LoadTMXFile(const AUrl: String);
1238 var
1239 Doc: TXMLDocument;
1240 begin
1241 Doc := UrlReadXML(AUrl);
1242 try
1243 LoadTMXFileInternal(Doc);
1244 finally FreeAndNil(Doc) end;
1245 end;
1246
1247 procedure TCastleTiledMapData.LoadTMXFileInternal(const Doc: TXMLDocument);
1248 var
1249 TmpStr, LowerTagName: String;
1250 I: TXMLElementIterator;
1251 NewLayer: TLayer;
1252 NewTileset: TTileset;
1253 begin
1254 // Parse map attributes
1255 Check(LowerCase(Doc.DocumentElement.TagName) = 'map',
1256 'Root element of TMX file must be <map>');
1257 if Doc.DocumentElement.AttributeString('version', TmpStr) then
1258 FVersion := TmpStr;
1259 if Doc.DocumentElement.AttributeString('orientation', TmpStr) then
1260 begin
1261 if TmpStr = 'orthogonal' then
1262 FOrientation := moOrthogonal
1263 else
1264 if TmpStr = 'isometric' then
1265 FOrientation := moIsometric
1266 else
1267 if TmpStr = 'staggered' then
1268 FOrientation := moIsometricStaggered
1269 else
1270 if TmpStr = 'hexagonal' then
1271 FOrientation := moHexagonal
1272 else
1273 WritelnWarning('Invalid orientation "%s" in Tiled map file (TMX)', [TmpStr]);
1274 end;
1275 if Doc.DocumentElement.AttributeString('width', TmpStr) then
1276 FWidth := StrToInt(TmpStr);
1277 if Doc.DocumentElement.AttributeString('height', TmpStr) then
1278 FHeight := StrToInt(TmpStr);
1279 if Doc.DocumentElement.AttributeString('tilewidth', TmpStr) then
1280 FTileWidth := StrToInt(TmpStr);
1281 if Doc.DocumentElement.AttributeString('tileheight', TmpStr) then
1282 FTileHeight := StrToInt(TmpStr);
1283 if Doc.DocumentElement.AttributeString('hexsidelength', TmpStr) then
1284 FHexSideLength := StrToInt(TmpStr);
1285 if Doc.DocumentElement.AttributeString('staggeraxis', TmpStr) then
1286 begin
1287 if TmpStr = 'x' then
1288 FStaggerAxis := saX
1289 else
1290 if TmpStr = 'y' then
1291 FStaggerAxis := saY
1292 else
1293 WritelnWarning('Invalid staggeraxis "%s" in Tiled map file (TMX)', [TmpStr]);
1294 end;
1295 if Doc.DocumentElement.AttributeString('staggerindex', TmpStr) then
1296 begin
1297 if TmpStr = 'odd' then
1298 FStaggerIndex := siOdd
1299 else
1300 if TmpStr = 'even' then
1301 FStaggerIndex := siEven
1302 else
1303 WritelnWarning('Invalid staggerindex "%s" in Tiled map file (TMX)', [TmpStr]);
1304 end;
1305 if Doc.DocumentElement.AttributeString('backgroundcolor', TmpStr) then
1306 FBackgroundColor := TiledToColor(TmpStr);
1307 if Doc.DocumentElement.AttributeString('renderorder', TmpStr) then
1308 begin
1309 if TmpStr = 'right-down' then
1310 FRenderOrder := mroRightDown
1311 else
1312 if TmpStr = 'right-up' then
1313 FRenderOrder := mroRightUp
1314 else
1315 if TmpStr = 'left-down' then
1316 FRenderOrder := mroLeftDown
1317 else
1318 if TmpStr = 'left-up' then
1319 FRenderOrder := mroLeftUp
1320 else
1321 WritelnWarning('Invalid renderOrder "%s" in Tiled map file (TMX)', [TmpStr]);
1322 end;
1323 // Parse map children
1324 I := TXMLElementIterator.Create(Doc.DocumentElement);
1325 try
1326 while I.GetNext do
1327 begin
1328 LowerTagName := LowerCase(I.Current.TagName8);
1329 if LowerTagName = 'tileset' then
1330 begin
1331 NewTileset := TTileset.Create;
1332 NewTileset.Load(I.Current, FBaseUrl);
1333 FTilesets.Add(NewTileset);
1334 end else
1335 if LowerTagName = 'layer' then
1336 begin
1337 NewLayer := TLayer.Create;
1338 NewLayer.Load(I.Current, FBaseUrl);
1339 FLayers.Add(NewLayer);
1340 end else
1341 if LowerTagName = 'objectgroup' then
1342 begin
1343 NewLayer := TObjectGroupLayer.Create;
1344 NewLayer.Load(I.Current, FBaseUrl);
1345 FLayers.Add(NewLayer);
1346 end else
1347 if LowerTagName = 'imagelayer' then
1348 begin
1349 NewLayer := TImageLayer.Create;
1350 NewLayer.Load(I.Current, FBaseUrl);
1351 FLayers.Add(NewLayer);
1352 end else
1353 if LowerTagName = 'properties' then
1354 FProperties.Load(I.Current, FBaseUrl);
1355 end;
1356 finally FreeAndNil(I) end;
1357 end;
1358
1359 constructor TCastleTiledMapData.Create(const Stream: TStream; const ABaseUrl: String);
1360 begin
1361 inherited Create;
1362
1363 FTilesets := TTilesetList.Create;
1364 FProperties := TPropertyList.Create;
1365 FLayers := TLayerList.Create(true);
1366 FBaseUrl := ABaseUrl;
1367
1368 //Load TMX
1369 LoadTMXFile(Stream, ABaseUrl);
1370 end;
1371
1372 constructor TCastleTiledMapData.Create(const AUrl: String);
1373 var
1374 StreamOptions: TStreamOptions;
1375 Gzipped: boolean;
1376 Stream: TStream;
1377 begin
1378 // calculate Stream from AUrl, automatically gunzip if extension says it
1379 StreamOptions := [];
1380 UriMimeType(AUrl, Gzipped);
1381 if Gzipped then
1382 Include(StreamOptions, soGzip);
1383 Stream := Download(AUrl, StreamOptions);
1384 try
1385 Create(Stream, AUrl);
1386 finally FreeAndNil(Stream) end;
1387 end;
1388
1389 destructor TCastleTiledMapData.Destroy;
1390 begin
1391 FreeAndNil(FTilesets);
1392 FreeAndNil(FProperties);
1393 FreeAndNil(FLayers);
1394 inherited Destroy;
1395 end;
1396
1397 function TCastleTiledMapData.TilePositionValid(const TilePosition: TVector2Integer): Boolean;
1398 begin
1399 Result :=
1400 (TilePosition.X >= 0) and
1401 (TilePosition.X < Width) and
1402 (TilePosition.Y >= 0) and
1403 (TilePosition.Y < Height);
1404 end;
1405
1406 function TCastleTiledMapData.PositionToTile(const Position: TVector2;
1407 out TilePosition: TVector2Integer): Boolean;
1408 var
1409 X, Y, ResultYPlusX, ResultYMinusX: Single;
1410 RowIncreaseY: Single;
1411 begin
1412 { unpack vector, for simpler code and for speed }
1413 X := Position.X;
1414 Y := Position.Y;
1415
1416 case Orientation of
1417 moIsometric:
1418 begin
1419 Y := Y - (Width - 1) * TileHeight / 2;
1420 ResultYPlusX := X / (TileWidth / 2);
1421 ResultYMinusX := Y / (TileHeight / 2) - 1; // not sure why this -1 at end is needed...
1422 TilePosition.X := Floor((ResultYPlusX - ResultYMinusX) / 2);
1423 TilePosition.Y := Floor((ResultYPlusX + ResultYMinusX) / 2);
1424 end;
1425 moIsometricStaggered:
1426 begin
1427 // TODO: right now this assumes Stagger Axis = Y
1428 { TODO: This doesn't have smart logic to account for diagonals.
1429 To hide this fact, we do "- 0.25" below, to at least match correct tile
1430 when we're over it's center. }
1431 TilePosition.Y := Floor(Y / (TileHeight / 2) - 0.25);
1432 if (not Odd(TilePosition.Y)) xor (StaggerIndex <> siOdd) then
1433 TilePosition.X := Floor(X / TileWidth - 0.5)
1434 else
1435 TilePosition.X := Floor(X / TileWidth);
1436 end;
1437 moHexagonal:
1438 begin
1439 // TODO: right now this assumes Stagger Axis = Y
1440 { TODO: This doesn't have smart logic to detect exact tile under mouse
1441 in case position is between diagonals.
1442 As such, this works sensibly only for large HexSideLength,
1443 when TileHeight - HexSideLength is small. }
1444 RowIncreaseY := TileHeight - (TileHeight - HexSideLength) / 2;
1445 TilePosition.Y := Floor(Y / RowIncreaseY);
1446 if (not Odd(TilePosition.Y)) xor (StaggerIndex <> siOdd) then
1447 TilePosition.X := Floor(X / TileWidth - 0.5)
1448 else
1449 TilePosition.X := Floor(X / TileWidth);
1450 end;
1451 // As a fallback, unsupported modes are as orthogonal
1452 else
1453 begin
1454 TilePosition.X := Floor(X / TileWidth);
1455 TilePosition.Y := Floor(Y / TileHeight);
1456 end;
1457 end;
1458 Result := TilePositionValid(TilePosition);
1459 end;
1460
1461 function TCastleTiledMapData.TileRenderPosition(const TilePosition: TVector2Integer): TVector2;
1462 var
1463 X, Y: Integer;
1464 RowIncreaseY: Single;
1465 begin
1466 { unpack vector, for simpler code and for speed }
1467 X := TilePosition.X;
1468 Y := TilePosition.Y;
1469
1470 case Orientation of
1471 moIsometric:
1472 begin
1473 { At the beginning imagine a simpler equation:
1474
1475 Result.X := (X + Y) * TileWidth / 2;
1476 Result.Y := (Y - X) * TileHeight / 2;
1477
1478 The Y position of the bottom-most tile, at (Width - 1, 0),
1479 would be -(Width - 1) * TileHeight / 2.
1480 So adjust Result.Y to place the map always at positive Y. }
1481
1482 Result.X := ( X + Y) * TileWidth / 2;
1483 Result.Y := (Width - 1 + Y - X) * TileHeight / 2;
1484 end;
1485 moIsometricStaggered:
1486 begin
1487 // TODO: right now this assumes Stagger Axis = Y
1488 Result.X := X * TileWidth;
1489 if (not Odd(Y)) xor (StaggerIndex <> siOdd) then
1490 Result.X := Result.X + TileWidth / 2;
1491 Result.Y := Y * TileHeight / 2;
1492 end;
1493 moHexagonal:
1494 begin
1495 // TODO: right now this assumes Stagger Axis = Y
1496 RowIncreaseY := TileHeight - (TileHeight - HexSideLength) / 2;
1497 Result.X := X * TileWidth;
1498 if (not Odd(Y)) xor (StaggerIndex <> siOdd) then
1499 Result.X := Result.X + TileWidth / 2;
1500 Result.Y := Y * RowIncreaseY;
1501 end;
1502 // As a fallback, unsupported modes are as orthogonal
1503 else
1504 begin
1505 Result.X := X * TileWidth;
1506 Result.Y := Y * TileHeight;
1507 end;
1508 end;
1509 end;
1510
1511 function TCastleTiledMapData.TileRenderData(const TilePosition: TVector2Integer;
1512 const Layer: TLayer;
1513 out Tileset: TTileset;
1514 out Frame: Integer;
1515 out HorizontalFlip, VerticalFlip, DiagonalFlip: Boolean): Boolean;
1516
1517 { Returns the tileset that contains the global ID. }
1518 function GIDToTileset(const AGID: Cardinal): TTileSet;
1519 var
1520 i: Integer;
1521 begin
1522 for i := 0 to FTilesets.Count - 1 do
1523 if FTilesets.Items[i].FirstGID > AGID then
1524 begin
1525 Result := FTilesets[i-1];
1526 Exit;
1527 end;
1528 Result := FTilesets[FTilesets.Count - 1];
1529 end;
1530
1531 const
1532 HorizontalFlag = $80000000;
1533 VerticalFlag = $40000000;
1534 DiagonalFlag = $20000000;
1535 ClearFlag = $1FFFFFFF;
1536 var
1537 Index: Integer;
1538 GID, Dat: Cardinal;
1539 begin
1540 Result := false;
1541
1542 Index := TilePosition.X + (Height - 1 - TilePosition.Y) * Width;
1543 Dat := Layer.Data.Data[Index];
1544 GID := Dat and ClearFlag;
1545 if GID = 0 then Exit;
1546
1547 Tileset := GIDToTileset(GID);
1548 Frame := GID - Tileset.FirstGID;
1549 HorizontalFlip := Dat and HorizontalFlag > 0;
1550 VerticalFlip := Dat and VerticalFlag > 0;
1551 DiagonalFlip := Dat and DiagonalFlag > 0;
1552
1553 Result := true;
1554 end;
1555
1556 function TCastleTiledMapData.TileNeighbor(const Tile1, Tile2: TVector2Integer;
1557 const CornersAreNeighbors: Boolean): Boolean;
1558 var
1559 XDiff, YDiff: Integer;
1560 begin
1561 // eliminate easy cases first
1562 if (not TilePositionValid(Tile1)) or
1563 (not TilePositionValid(Tile2)) or
1564 TVector2Integer.Equals(Tile1, Tile2) then
1565 Exit(false);
1566
1567 XDiff := Tile1.X - Tile2.X;
1568 YDiff := Tile1.Y - Tile2.Y;
1569
1570 case Orientation of
1571 moIsometricStaggered:
1572 begin
1573 // first check for neighbors touching edges (not only corners)
1574 Result := Between(XDiff, -1, 1) and ((YDiff = -1) or (YDiff = 1));
1575
1576 if Result then
1577 begin
1578 // TODO: right now this assumes Stagger Axis = Y
1579 { The above condition allowed 6 tiles to be neighbors to Tile2.
1580 We need to eliminate 2 cases now.
1581 Which 2 cases to eliminate depends on whether we're on odd or even row. }
1582 if (not Odd(Tile2.Y)) xor (StaggerIndex <> siOdd) then
1583 begin
1584 if (XDiff = -1) and ((YDiff = -1) or (YDiff = 1)) then
1585 Result := false;
1586 end else
1587 begin
1588 if (XDiff = 1) and ((YDiff = -1) or (YDiff = 1)) then
1589 Result := false;
1590 end;
1591 end;
1592
1593 // check for neighbors touching corners
1594 if CornersAreNeighbors then
1595 Result := Result or
1596 ((YDiff = 0) and ((XDiff = -1) or (XDiff = 1))) or
1597 ((XDiff = 0) and ((YDiff = -2) or (YDiff = 2)));
1598 end;
1599 moHexagonal:
1600 begin
1601 Result := Between(XDiff, -1, 1) and Between(YDiff, -1, 1);
1602 if Result then
1603 begin
1604 // TODO: right now this assumes Stagger Axis = Y
1605 { The above condition allowed 8 tiles to be neighbors to Tile2.
1606 We need to eliminate 2 cases now, since there are only 6 neighbors
1607 on hexagonal map. Which 2 cases to eliminate depends on whether
1608 we're on odd or even row. }
1609 if (not Odd(Tile2.Y)) xor (StaggerIndex <> siOdd) then
1610 begin
1611 if (XDiff = -1) and ((YDiff = -1) or (YDiff = 1)) then
1612 Result := false;
1613 end else
1614 begin
1615 if (XDiff = 1) and ((YDiff = -1) or (YDiff = 1)) then
1616 Result := false;
1617 end;
1618 end;
1619 end;
1620 { As a fallback, unsupported modes are as moOrthogonal.
1621 This logic matches also moIsometric. }
1622 else
1623 begin
1624 if CornersAreNeighbors then
1625 Result := Between(XDiff, -1, 1) and Between(YDiff, -1, 1)
1626 else
1627 Result :=
1628 ( (XDiff = 0) and ((YDiff = -1) or (YDiff = 1)) ) or
1629 ( (YDiff = 0) and ((XDiff = -1) or (XDiff = 1)) );
1630 end;
1631 end;
1632 end;
1633
1634 {$endif read_implementation}