Debian Codegraph @

src/scene/load/x3dloadinternaltiledmap.pas

raw
1 {
2 Copyright 2020-2024 Matthias J. Molski, Michalis Kamburelis, Freedomax.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in this distribution, for details about the copyright.
8
9 "Castle Game Engine" is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 ----------------------------------------------------------------------------
14 }
15
16 { Convert Tiled map (tmx file, see https://www.mapeditor.org/) into X3D representation.
17
18 Underneath, the map is loaded using @link(TCastleTiledMapData) class,
19 thus the map-reading logic is shared with TCastleTiledMapControl.
20
21 TODO:
22
23 @orderedList(
24 @item(Tiled image layers)
25 @item(Tiled object ellipsoids)
26 )
27 }
28 unit X3DLoadInternalTiledMap;
29
30 {$I castleconf.inc}
31
32 interface
33
34 uses
35 Classes, Generics.Collections,
36 X3DNodes, X3DLoad, CastleLog, CastleTiledMap, CastleVectors;
37
38 { Load Tiled map into X3D node.
39 This is used by LoadNode, which in turn is used by TCastleSceneCore.Load.
40
41 Underneath, this loads Tiled map using TCastleTiledMapData,
42 then uses internal conversion class to generate X3D node from it. }
43 function LoadTiledMap2d(const Stream: TStream; const BaseUrl: String): TX3DRootNode;
44
45 type
46 { Convert Tiled map into X3D node. }
47 TCastleTiledMapConverter = class
48 strict private
49 type
50 TTilesetNodes = record
51 Coord: TCoordinateNode;
52 TexCoord: TTextureCoordinateNode;
53 end;
54
55 TAnimationNodes = record
56 CoordNodes: TTilesetNodes;
57 TexCoordInterp: TCoordinateInterpolator2DNode;
58 CycleIntervalMs: Cardinal;
59 end;
60
61 { Map from CycleInterval in milliseconds -> TTimeSensorNode. }
62 TLayerTimeSensors = {$ifdef FPC}specialize{$endif} TDictionary<Cardinal, TTimeSensorNode>;
63
64 TLayerAnimations = {$ifdef FPC}specialize{$endif} TDictionary<TCastleTiledMapData.TAnimation, TAnimationNodes>;
65
66 TLayerConversion = class({$ifdef FPC}specialize{$endif} TDictionary<TCastleTiledMapData.TTileset, TTilesetNodes>)
67 strict private
68 FLayerTimeSensors: TLayerTimeSensors;
69 FLayerAnimations: TLayerAnimations;
70 public
71 constructor Create;{$ifdef FPC} override;{$endif}
72 destructor Destroy;override;
73 property LayerTimeSensors: TLayerTimeSensors read FLayerTimeSensors;
74 property LayerAnimations: TLayerAnimations read FLayerAnimations;
75 end;
76
77 var
78 FMap: TCastleTiledMapData;
79 FMapNode: TTransformNode;
80 FRootNode: TX3DRootNode;
81
82 { Fills every TTileset.RendererData with TAppearanceNode with texture of this tileset. }
83 procedure PrepareTilesets;
84
85 { Constructs X3D nodes for each layer. }
86 procedure ConvertLayers;
87
88 procedure FreeUnusedTilesetsRendererData;
89
90 procedure BuildObjectGroupLayerNode(const LayerNode: TTransformNode;
91 const ALayer: TCastleTiledMapData.TLayer);
92
93 procedure BuildTileLayerNode(const LayerNode: TTransformNode;
94 const ALayer: TCastleTiledMapData.TLayer);
95
96 { Convert Tiled coordinates to CGE.
97 @groupBegin }
98 function ConvY(const TiledCoord: TVector2): TVector2; overload;
99 function ConvY(const X, Y: Single): TVector2; overload;
100 { @groupEnd }
101
102 { The Tiled map is loaded from stream and NOT free'd automatically. }
103 property Map: TCastleTiledMapData read FMap write FMap;
104
105 { Holds the X3D representation of the Tiled map. It is NOT free'd
106 automatically. Usually the X3D representation is added to a scene
107 by Scene.Load(). The scene which will care about freeing. }
108 property MapNode: TTransformNode read FMapNode write FMapNode;
109 public
110 type
111 TLayerIndex = 0..30;
112 TLayers = set of TLayerIndex;
113 const
114 AllLayers = [Low(TLayerIndex)..High(TLayerIndex)];
115 var
116 { Workaround rendering artifacts for tilesets without alpha bleeding.
117 Set before @link(ConvertMap). }
118 SmoothScalingSafeBorder: Boolean;
119
120 { See @link(TCastleTiledMap.ForceTilesetSpacing). }
121 ForceTilesetSpacing : Boolean;
122
123 { Layers to load. }
124 Layers: TLayers;
125
126 constructor Create(const ATiledMap: TCastleTiledMapData);
127 destructor Destroy; override;
128
129 { Constructs RootNode from TCastleTiledMapData data. }
130 procedure ConvertMap;
131
132 property RootNode: TX3DRootNode read FRootNode write FRootNode;
133 end;
134
135 implementation
136
137 uses
138 SysUtils, Math, Generics.Defaults,
139 CastleTransform, CastleColors, CastleRectangles, CastleUtils,
140 CastleRenderOptions, CastleControls, CastleStringUtils,
141 CastleImages, CastleUriUtils;
142
143 { TUnicodeCharEqualityComparer ----------------------------------------------- }
144
145 {$ifndef FPC}
146
147 type
148 { This is necessary to workaround buggy TDictionary on early Delphi versions
149 (Delphi <= 10.2.3 has this bug, Delphi >= 10.4.2 has it fixed). }
150 TTilesetEqualityComparer = class(TCustomComparer<TCastleTiledMapData.TTileset>)
151 function Compare(const Left, Right: TCastleTiledMapData.TTileset): Integer; override;
152 function Equals(const Left, Right: TCastleTiledMapData.TTileset): Boolean; override;
153 function GetHashCode(const Value: TCastleTiledMapData.TTileset): Integer; override;
154 end;
155
156 function TTilesetEqualityComparer.Compare(const Left, Right: TCastleTiledMapData.TTileset): Integer;
157 begin
158 Result := Left.GetHashCode - Right.GetHashCode;
159 end;
160
161 function TTilesetEqualityComparer.Equals(const Left, Right: TCastleTiledMapData.TTileset): Boolean;
162 begin
163 Result := Left = Right;
164 end;
165
166 function TTilesetEqualityComparer.GetHashCode(const Value: TCastleTiledMapData.TTileset): Integer;
167 begin
168 Result := Value.GetHashCode;
169 end;
170
171 {$endif}
172
173 { TCastleTiledMapConverter -------------------------------------------------- }
174
175 constructor TCastleTiledMapConverter.TLayerConversion.Create;
176 begin
177 {$ifndef FPC}
178 { See CastleTextureFontData for explanation at the analogous workaround.
179 This is only necessary for older Delphis (<= 10.2.3),
180 but to ease testing we use it with all Delphi versions. }
181 inherited Create(TTilesetEqualityComparer.Create);
182 {$else}
183 inherited;
184 {$endif}
185 FLayerTimeSensors := TLayerTimeSensors.Create;
186 FLayerAnimations := TLayerAnimations.Create;
187 end;
188
189 destructor TCastleTiledMapConverter.TLayerConversion.Destroy;
190 begin
191 FLayerTimeSensors.Free;
192 FLayerAnimations.Free;
193 inherited;
194 end;
195
196 procedure TCastleTiledMapConverter.ConvertMap;
197 begin
198 PrepareTilesets;
199 ConvertLayers;
200 FreeUnusedTilesetsRendererData;
201 end;
202
203 procedure TCastleTiledMapConverter.FreeUnusedTilesetsRendererData;
204 var
205 Appearance: TAppearanceNode;
206 Tileset: TCastleTiledMapData.TTileset;
207 begin
208 for Tileset in Map.Tilesets do
209 begin
210 Appearance := Tileset.RendererData as TAppearanceNode;
211 FreeIfUnusedAndNil(Appearance);
212 Tileset.RendererData := nil;
213 end;
214 end;
215
216 procedure TCastleTiledMapConverter.PrepareTilesets;
217 var
218 Tileset: TCastleTiledMapData.TTileset;
219
220 { Make a tileset image with added paddings,
221 also modify the Tileset to point to the new tileset image (with larger sizes). }
222 function ForceTilesetImageSpacing(const AURL: String): TCastleImage;
223 var
224 OriginalImage: TCastleImage;
225 Col, Row: Integer;
226 SrcPos, Pos: TVector2Integer;
227 ColumnCount, RowCount: Cardinal;
228
229 function TilePosition(const AImage: TEncodedImage; const AMargin, ASpacing: Cardinal): TVector2Integer;
230 begin
231 Result.X := AMargin + Col * (Tileset.TileWidth + ASpacing);
232 Result.Y := AImage.Height - (AMargin + Row * (Tileset.TileHeight + ASpacing)
233 + Tileset.TileHeight);
234 end;
235
236 procedure Draw(const APos, ASrcPos: TVector2Integer; const AWidth, AHeight: Integer);
237 begin
238 Result.DrawFrom(OriginalImage, APos.X, APos.Y, ASrcPos.X, ASrcPos.Y, AWidth, AHeight, dmOverwrite);
239 end;
240
241 const
242 NewMargin = 1;
243 NewSpacing = 2;
244 begin
245 OriginalImage := LoadImage(AURL);
246 Result := TCastleImageClass(OriginalImage.ClassType).Create;
247
248 try
249 ColumnCount := (OriginalImage.Width - 2 * Tileset.Margin + Tileset.Spacing)
250 div (Tileset.TileWidth + Tileset.Spacing);
251 RowCount := (OriginalImage.Height - 2 * Tileset.Margin + Tileset.Spacing)
252 div (Tileset.TileHeight + Tileset.Spacing);
253
254 Result.SetSize(ColumnCount * (Tileset.TileWidth + NewSpacing) - NewSpacing + 2 * NewMargin,
255 RowCount * (Tileset.TileHeight + NewSpacing) - NewSpacing + 2 * NewMargin);
256
257 for Row := 0 to RowCount - 1 do
258 begin
259 for Col := 0 to ColumnCount - 1 do
260 begin
261 Pos := TilePosition(Result, NewMargin, NewSpacing);
262 SrcPos := TilePosition(OriginalImage, Tileset.Margin, Tileset.Spacing);
263
264 { Draw original tiles -----------------------------------------------}
265 Draw(Pos, SrcPos, Tileset.TileWidth, Tileset.TileHeight);
266
267 { Draw frame -----------------------------------------------}
268
269 { Left }
270 Draw(Pos + Vector2Integer(-1, 0), SrcPos
271 , 1, Tileset.TileHeight);
272 { Right }
273 Draw(Pos + Vector2Integer(Tileset.TileWidth, 0), SrcPos + Vector2Integer(Tileset.TileWidth - 1, 0)
274 , 1, Tileset.TileHeight);
275 { Bottom }
276 Draw(Pos + Vector2Integer(0, -1), SrcPos
277 , Tileset.TileWidth, 1);
278 { Top }
279 Draw(Pos + Vector2Integer(0, Tileset.TileHeight), SrcPos + Vector2Integer(0, Tileset.TileHeight - 1)
280 , Tileset.TileWidth, 1);
281
282 { LeftBottom }
283 Draw(Pos + Vector2Integer(-1, -1), SrcPos
284 , 1, 1);
285 { RightBottom }
286 Draw(Pos + Vector2Integer(Tileset.TileWidth, -1), SrcPos + Vector2Integer(Tileset.TileWidth - 1, 0)
287 , 1, 1);
288 { LeftTop }
289 Draw(Pos + Vector2Integer(-1, Tileset.TileHeight), SrcPos + Vector2Integer(0, Tileset.TileHeight - 1)
290 , 1, 1);
291 { RightTop }
292 Draw(Pos + Vector2Integer(Tileset.TileWidth, Tileset.TileHeight)
293 ,SrcPos + Vector2Integer(Tileset.TileWidth - 1, Tileset.TileHeight - 1), 1, 1);
294
295 end;
296 end;
297
298 WritelnLog('Tiled', 'Added spacing to tileset image "%s", new margin %d, new spacing %d, old size %d x %d -> new size %d x %d', [
299 UriDisplay(AURL),
300 NewMargin,
301 NewSpacing,
302 Tileset.Image.Width,
303 Tileset.Image.Height,
304 Result.Width,
305 Result.Height
306 ]);
307
308 Tileset.Margin := NewMargin;
309 Tileset.Spacing := NewSpacing;
310 Tileset.Image.Width := Result.Width;
311 Tileset.Image.Height := Result.Height;
312 finally
313 FreeAndNil(OriginalImage);
314 end;
315 end;
316
317 var
318 Texture: TImageTextureNode;
319 TexProperties: TTexturePropertiesNode;
320 Appearance: TAppearanceNode;
321 begin
322 for Tileset in Map.Tilesets do
323 begin
324 if Tileset.Image = nil then
325 begin
326 WriteLnWarning('Tileset has no image');
327 Continue;
328 end;
329
330 if (Tileset.TileCount = 0) or (Tileset.Columns = 0) then
331 begin
332 WriteLnWarning('Empty Tileset');
333 Continue;
334 end;
335
336 Texture := TImageTextureNode.Create;
337 if ForceTilesetSpacing then
338 Texture.LoadFromImage(ForceTilesetImageSpacing(Tileset.Image.URL), true, '')
339 else
340 Texture.SetUrl([Tileset.Image.URL]);
341
342 TexProperties := TTexturePropertiesNode.Create;
343 TexProperties.MagnificationFilter := magDefault;
344 TexProperties.MinificationFilter := minDefault;
345 { Do not force "power of 2" size, which may prevent mipmaps.
346 Not resizing is consistent with X3DLoadInternalImage, LoadCastleSpriteSheet,
347 users may use it with pixel-art and don't expect images to be resized. }
348 TexProperties.GuiTexture := true;
349 Texture.TextureProperties := TexProperties;
350
351 Appearance := TAppearanceNode.Create(Tileset.Name, '');
352 Appearance.Texture := Texture;
353 Tileset.RendererData := Appearance;
354 end;
355 end;
356
357 procedure TCastleTiledMapConverter.ConvertLayers;
358 var
359 LayerIndex: Integer;
360 Layer: TCastleTiledMapData.TLayer;
361 LayerNode: TTransformNode;
362 LayerZ: Single;
363 SwitchNode: TSwitchNode;
364 const
365 { Distance between Tiled layers in Z. Layers are rendered as 3D objects
366 and need some distance to avoid Z-fighting.
367
368 This could be avoided when using RenderContext.DepthFunc := dfAlways,
369 we even tried it at one point (TCastleTiledMap.AssumePerfectRenderingOrder),
370 but it had with it's own disadvantages:
371 Rendering with RenderContext.DepthFunc = dfAlways
372 assumes that really *everything*, including other things
373 that could be behind / in front of this Tiled map, are arranged in the TCastleViewport.Items
374 tree in the correct order. That is, things behind the Tiled map must be earlier than
375 the TCastleTiledMap component in the transformation tree. And things in front of Tiled map must
376 be after the TCastleTiledMap component in the transformation tree.
377 And this assumption must be preserved by blending sorting done
378 by @link(TCastleViewport.BlendingSort), if any.
379
380 So we don't use RenderContext.DepthFunc = dfAlways anymore.
381 Instead we apply layer Z distance.
382
383 Note: 1 is too small for examples/tiled/map_viewer/data/maps/desert_with_objects.tmx }
384 LayerZDistanceIncrease: Single = 10;
385 begin
386 LayerZ := 0;
387
388 for LayerIndex := 0 to Map.Layers.Count - 1 do
389 begin
390 Layer := Map.Layers[LayerIndex];
391 if not (
392 Layer.Visible and
393 (
394 (LayerIndex > High(TLayerIndex)) or
395 (LayerIndex in Layers)
396 )
397 ) then
398 Continue;
399
400 LayerNode := TTransformNode.Create;
401
402 // Create an intermediate switch node to enable showing/hiding of the layer via the Exists-property.
403 SwitchNode := TSwitchNode.Create;
404 SwitchNode.AddChildren(LayerNode);
405 SwitchNode.WhichChoice := Iff(Layer.Visible, 0, -1);
406 Layer.SwitchNode := SwitchNode;
407
408 if Layer is TCastleTiledMapData.TObjectGroupLayer then
409 BuildObjectGroupLayerNode(LayerNode, Layer)
410 else
411 { TODO:
412 if Layer is TCastleTiledMapData.TImageLayer then
413 BuildImageLayer(Layer, LayerNode)
414 else }
415 BuildTileLayerNode(LayerNode, Layer);
416
417 MapNode.AddChildren(SwitchNode);
418
419 // flip -Layer.OffsetY, as Tiled Y goes down
420 LayerNode.Translation := Vector3(Layer.OffsetX, -Layer.OffsetY, LayerZ);
421 LayerZ := LayerZ + LayerZDistanceIncrease;
422 end;
423 end;
424
425 procedure TCastleTiledMapConverter.BuildObjectGroupLayerNode(const LayerNode: TTransformNode;
426 const ALayer: TCastleTiledMapData.TLayer);
427 var
428 // Appearance (refers also to TiledObjectMaterial) node of a Tiled obj.
429 TiledObjectAppearance: TAppearanceNode;
430 TiledObjectMaterial: TUnlitMaterialNode;
431 // A Tiled object instance (as saved in TCastleTiledMapData).
432 TiledObject: TCastleTiledMapData.TTiledObject;
433 // Node of a Tiled object.
434 TiledObjectNode: TTransformNode;
435 // Geometry node of a TiledObject primitive.
436 TiledObjectGeometry: TPolyline2DNode;
437 // Shape node of a TiledObject.
438 TiledObjectShape: TShapeNode;
439 // Helper list.
440 AVector2List: TVector2List;
441 I: Cardinal;
442 begin
443 TiledObjectAppearance := nil;
444 TiledObjectMaterial := nil;
445 TiledObjectNode := nil;
446 TiledObjectGeometry := nil;
447 TiledObjectShape := nil;
448 AVector2List := nil;
449
450 AVector2List := TVector2List.Create;
451
452 for TiledObject in (ALayer as TCastleTiledMapData.TObjectGroupLayer).Objects do
453 begin
454 if not TiledObject.Visible then
455 Continue;
456
457 { All Tiled objects of this layer share the same material node. The color
458 depends on the layer color in accordance with handling of Tiled editor. }
459 if not Assigned(TiledObjectAppearance) then
460 begin
461 TiledObjectMaterial := TUnlitMaterialNode.Create;
462 TiledObjectMaterial.EmissiveColor := ALayer.Color;
463 TiledObjectAppearance := TAppearanceNode.Create;
464 TiledObjectAppearance.Material := TiledObjectMaterial;
465 end;
466
467 { Every Tiled object is based on a transform node. }
468 TiledObjectNode := TTransformNode.Create;
469 TiledObjectNode.Translation := Vector3(
470 TiledObject.Position.X,
471 Map.Height * Map.TileHeight - TiledObject.Position.Y, // Tiled Y goes down, CGE Y goes up
472 0
473 );
474
475 { Every primitive is implemented as polyline node. Hint: For better
476 performance rectangle and point could be implemented as rect. node?}
477 TiledObjectGeometry := TPolyline2DNode.CreateWithShape(TiledObjectShape);
478 case TiledObject.Primitive of
479 topPolyline, topPolygon:
480 begin
481 AVector2List.Clear;
482 AVector2List.Assign(TiledObject.Points);
483 for I := 0 to AVector2List.Count-1 do
484 AVector2List.Items[I] := ConvY(AVector2List.Items[I]);
485
486 { Polygon: Add point with index 0 to points list to get a closed polygon }
487 if TiledObject.Primitive = topPolygon then
488 AVector2List.Add(AVector2List.Items[0]);
489
490 TiledObjectGeometry.SetLineSegments(AVector2List);
491 end;
492 topRectangle:
493 begin
494 TiledObjectGeometry.SetLineSegments([
495 ConvY(0.0, 0.0),
496 ConvY(TiledObject.Width, 0.0),
497 ConvY(TiledObject.Width, TiledObject.Height),
498 ConvY(0.0, TiledObject.Height),
499 ConvY(0.0, 0.0)
500 ]);
501 end;
502 topPoint:
503 begin
504 { TODO: Render points a X3D/OpenGL points, not rectangles. }
505 AVector2List.Clear;
506 { Construct a rectangle around position of point. }
507 AVector2List.Add(ConvY(-1, -1));
508 AVector2List.Add(ConvY(-1, 1));
509 AVector2List.Add(ConvY(1, 1));
510 AVector2List.Add(ConvY(1,-1));
511 AVector2List.Add(ConvY(-1, -1));
512 TiledObjectGeometry.SetLineSegments(AVector2List);
513 end;
514 // TODO: handle ellipse
515 topEllipse:
516 begin
517 WritelnWarning('Not supported yet: Ellipse object primitive. Ignored.');
518 end;
519 end;
520 TiledObjectShape.Appearance := TiledObjectAppearance;
521 TiledObjectNode.AddChildren(TiledObjectShape);
522 LayerNode.AddChildren(TiledObjectNode);
523 end;
524 FreeAndNil(AVector2List);
525 end;
526
527 procedure TCastleTiledMapConverter.BuildTileLayerNode(const LayerNode: TTransformNode;
528 const ALayer: TCastleTiledMapData.TLayer);
529
530 function GetTileCoordRect(const TilePosition: TVector2Integer;
531 const Tileset: TCastleTiledMapData.TTileset): TFloatRectangle;
532 begin
533 Result := FloatRectangle(
534 Map.TileRenderPosition(TilePosition) + Vector2(Tileset.TileOffset.X, - Tileset.TileOffset.Y),
535 Tileset.TileWidth,
536 Tileset.TileHeight
537 );
538 end;
539
540 function GetTileTexCoordRect(const Tile: TCastleTiledMapData.TTile; const Tileset: TCastleTiledMapData.TTileset): TFloatRectangle;
541 begin
542 Result := FloatRectangle(
543 (Tile.Id mod Tileset.Columns) * (Tileset.TileWidth + Tileset.Spacing)
544 + Tileset.Margin,
545 (Tile.Id div Tileset.Columns) * (Tileset.TileHeight + Tileset.Spacing)
546 + Tileset.Margin,
547 Tileset.TileWidth,
548 Tileset.TileHeight
549 );
550
551 if SmoothScalingSafeBorder then
552 Result := Result.Grow(-0.51)
553 else
554 { Fixes appearance of seams at certain zoom levels. }
555 Result := Result.Grow(-0.01);
556
557 { fix Result to be in 0..1 range }
558 Result.Left := Result.Left / Tileset.Image.Width;
559 Result.Width := Result.Width / Tileset.Image.Width;
560 Result.Bottom := Result.Bottom / Tileset.Image.Height;
561 Result.Height := Result.Height / Tileset.Image.Height;
562
563 // account that Tiled logic for texture coords assumes Y goes down
564 Result.Bottom := 1 - Result.Bottom - Result.Height;
565 end;
566
567 type
568 { 4 texture coordinates, in order:
569 - left-bottom
570 - right-bottom
571 - right-top
572 - left-top }
573 TQuadTexCoords = array [0..3] of TVector2;
574
575 { Flip rendering of the tile by changing texture coordinates. }
576 procedure ApplyFlips(var TexCoord: TQuadTexCoords;
577 const HorizontalFlip, VerticalFlip, DiagonalFlip: Boolean);
578
579 procedure SwapValues(var V1, V2: TVector2);
580 var
581 Tmp: TVector2;
582 begin
583 Tmp := V1;
584 V1 := V2;
585 V2 := Tmp;
586 end;
587
588 begin
589 { Following https://doc.mapeditor.org/en/latest/reference/global-tile-ids/#gid-tile-flipping :
590 When rendering an orthographic or isometric tile, the order of operations matters.
591 The diagonal flip is done first, followed by the horizontal and vertical flips.
592 The diagonal flip should flip the bottom left and top right corners of the tile,
593 and can be thought of as an x/y axis swap. For hexagonal tiles, the order does not matter. }
594 if DiagonalFlip then
595 SwapValues(TexCoord[0], TexCoord[2]);
596 if HorizontalFlip then
597 begin
598 SwapValues(TexCoord[0], TexCoord[1]);
599 SwapValues(TexCoord[2], TexCoord[3]);
600 end;
601 if VerticalFlip then
602 begin
603 SwapValues(TexCoord[0], TexCoord[3]);
604 SwapValues(TexCoord[1], TexCoord[2]);
605 end;
606 end;
607
608 var
609 LayerConversion: TLayerConversion;
610 Nodes: TTilesetNodes;
611 Tileset: TCastleTiledMapData.TTileset;
612 Geometry: TQuadSetNode;
613 Shape: TShapeNode;
614 Frame: Integer;
615 CoordRect, TexCoordRect: TFloatRectangle;
616 TexCoordArray: TQuadTexCoords;
617 HorizontalFlip, VerticalFlip, DiagonalFlip: Boolean;
618 LayerIndex : Integer;
619 { Render order. }
620 CurrentZ: Single;
621 { animations var.}
622 TimeSensor: TTimeSensorNode;
623
624 function ValidTileId(const TileId : Integer):Boolean;
625 begin
626 Result := Between(TileId, 0, Tileset.Tiles.Count - 1);
627 end;
628
629 procedure CalcTexCoordArray(const TileId:Integer);
630 begin
631 if ValidTileId(TileId) then
632 TexCoordRect := GetTileTexCoordRect(Tileset.Tiles[TileId], Tileset)
633 else
634 begin
635 WritelnWarning('Tiled', 'Invalid frame id %d', [TileId]);
636 // some fallback, to have something defined
637 TexCoordRect := FloatRectangle(0, 0, Tileset.TileWidth, Tileset.TileHeight);
638 end;
639
640 TexCoordArray[0] := Vector2(TexCoordRect.Left , TexCoordRect.Bottom);
641 TexCoordArray[1] := Vector2(TexCoordRect.Right, TexCoordRect.Bottom);
642 TexCoordArray[2] := Vector2(TexCoordRect.Right, TexCoordRect.Top);
643 TexCoordArray[3] := Vector2(TexCoordRect.Left , TexCoordRect.Top);
644 ApplyFlips(TexCoordArray, HorizontalFlip, VerticalFlip, DiagonalFlip);
645 end;
646
647 function CreateTimeSensor(const CycleIntervalMs :Cardinal): TTimeSensorNode;
648 begin
649 Result := TTimeSensorNode.Create(Format('TimeSensor_%d_%d', [LayerIndex,CycleIntervalMs]));
650 Result.CycleInterval := CycleIntervalMs / 1000;
651 { Add TimeSensor to Root node }
652 LayerNode.AddChildren(Result);
653 Result.Loop := true;
654 end;
655
656 function CreateNodes: TTilesetNodes;
657 begin
658 Geometry := TQuadSetNode.CreateWithShape(Shape);
659 Result.Coord := TCoordinateNode.Create;
660 Geometry.Coord := Result.Coord;
661 Result.TexCoord := TTextureCoordinateNode.Create;
662 Geometry.TexCoord := Result.TexCoord;
663 Shape.Appearance := Tileset.RendererData as TAppearanceNode;
664 LayerNode.AddChildren(Shape);
665 end;
666
667 function GetOrCreateTimeSensor(const CycleIntervalMs:Cardinal) :TTimeSensorNode;
668 begin
669 if LayerConversion.LayerTimeSensors.TryGetValue(CycleIntervalMs, Result) then Exit;
670
671 Result := CreateTimeSensor(CycleIntervalMs);
672 LayerConversion.LayerTimeSensors.Add(CycleIntervalMs, Result);
673 end;
674
675 procedure AddToTexCoordInterp(const AnimationNodes: TAnimationNodes; const bCreate: Boolean);
676 var
677 I, StartIndex, Step, FrameCount: SizeInt;
678 Durations: Single;
679 AniFrame: TCastleTiledMapData.TFrame;
680 begin
681 FrameCount := Tileset.Tiles[Frame].Animation.Count;
682
683 { Silence Delphi warnings about uninitialized variables,
684 in this case the warning is really a false alarm -- our bCreate stays constant,
685 so in each case the variables that will be really used are initialized. }
686 {$ifndef FPC}
687 Durations := 0;
688 StartIndex := 0;
689 Step := 0;
690 {$endif}
691
692 if bCreate then
693 Durations := 0
694 else
695 begin
696 Step := AnimationNodes.TexCoordInterp.FdKeyValue.Items.Count div FrameCount;
697 StartIndex := Step;
698 Step := Step + 4;
699 end;
700
701 for I := 0 to FrameCount - 1 do
702 begin
703 AniFrame := Tileset.Tiles[Frame].Animation.Items[I];
704
705 CalcTexCoordArray(AniFrame.TileId);
706
707 if bCreate then
708 begin
709 AnimationNodes.TexCoordInterp.FdKeyValue.Items.AddRange(TexCoordArray);
710 AnimationNodes.TexCoordInterp.FdKey.Items.Add(Durations / AnimationNodes.CycleIntervalMs);
711 Durations := Durations + AniFrame.Duration;
712 end else
713 begin
714 AnimationNodes.TexCoordInterp.FdKeyValue.Items.InsertRange(StartIndex, TexCoordArray);
715 StartIndex := StartIndex + Step;
716 end;
717 end;
718 end;
719
720 function CreateAnimationNodes: TAnimationNodes;
721 var
722 I: integer;
723 begin
724 Result.CoordNodes := CreateNodes;
725 Result.TexCoordInterp := TCoordinateInterpolator2DNode.Create;
726 Result.TexCoordInterp.Interpolation := inStep;
727
728 { Calc CycleInterval. }
729 Result.CycleIntervalMs := 0;
730 for I := 0 to Tileset.Tiles[Frame].Animation.Count - 1 do
731 Result.CycleIntervalMs := Result.CycleIntervalMs + Tileset.Tiles[Frame].Animation.Items[I].Duration;
732
733 { Get TimeSensor. }
734 TimeSensor := GetOrCreateTimeSensor(Result.CycleIntervalMs);
735
736 AddToTexCoordInterp(Result, true);
737 { Add to rootnode. }
738 LayerNode.AddChildren(Result.TexCoordInterp);
739 LayerNode.AddRoute(TimeSensor.EventFraction_changed, Result.TexCoordInterp.EventSet_fraction);
740 LayerNode.AddRoute(Result.TexCoordInterp.EventValue_changed, Result.CoordNodes.TexCoord.FdPoint);
741 end;
742
743 function GetOrCreateNodesForTileset: TTilesetNodes;
744 begin
745 if LayerConversion.TryGetValue(Tileset, Result) then Exit;
746
747 Result := CreateNodes;
748 LayerConversion.Add(Tileset, Result);
749 end;
750
751 function GetOrCreateNodesForAnimation: TAnimationNodes;
752 begin
753 if LayerConversion.LayerAnimations.TryGetValue(Tileset.Tiles[Frame].Animation, Result) then
754 begin
755 AddToTexCoordInterp(Result, false);
756 Exit;
757 end;
758
759 Result := CreateAnimationNodes;
760 LayerConversion.LayerAnimations.Add(Tileset.Tiles[Frame].Animation, Result);
761 end;
762
763 procedure RenderTile(const TilePosition: TVector2Integer);
764 var
765 Coord: TCoordinateNode;
766 TexCoord: TTextureCoordinateNode;
767
768 procedure AddCoordPoints;
769 begin
770 CoordRect := GetTileCoordRect(TilePosition, Tileset);
771 Coord.FdPoint.Items.AddRange([
772 Vector3(CoordRect.Left , CoordRect.Bottom, CurrentZ),
773 Vector3(CoordRect.Right, CoordRect.Bottom, CurrentZ),
774 Vector3(CoordRect.Right, CoordRect.Top , CurrentZ),
775 Vector3(CoordRect.Left , CoordRect.Top , CurrentZ)
776 ]);
777 end;
778
779 procedure AddTexCoordPoints;
780 begin
781 CalcTexCoordArray(Frame);
782 TexCoord.FdPoint.Items.AddRange(TexCoordArray);
783 end;
784
785 function HasAnimation:Boolean;
786 begin
787 Result := Tileset.Tiles[Frame].Animation.Count > 0;
788 end;
789
790 begin
791 if Map.TileRenderData(TilePosition, ALayer,
792 Tileset, Frame, HorizontalFlip, VerticalFlip, DiagonalFlip) then
793 begin
794 { Do not load image when there's no Url (no "source" attribute at <tileset>).
795 This is possible when each <tile> has its own <image> element,
796 we don't support it yet, TCastleTiledMapConverter will later warn and
797 skip such tileset.
798
799 Testcase: Phoenix bugreport,
800 https://discord.com/channels/389676745957310465/1204090530368327690/1247180638520606829 ,
801 Michalis has testcase in private. }
802 if Tileset.Columns = 0 then
803 begin
804 WritelnWarning('Tileset "%s" has zero columns, likely because the tileset does not specify the image with all tiles packed. This is not supported now, skipping the tileset.', [
805 Tileset.Name
806 ]);
807 Exit;
808 end;
809
810 if not ValidTileId(Frame) then
811 begin
812 WritelnWarning('Invalid TileId:%d TilePosition:' + TilePosition.ToString, [Frame]);
813 Exit;
814 end;
815
816 CurrentZ := CurrentZ + 1 / (Map.Width * Map.Height);
817
818 { If not Created then Create and Add to Dictionary. }
819 if HasAnimation then
820 Nodes := GetOrCreateNodesForAnimation.CoordNodes
821 else
822 Nodes := GetOrCreateNodesForTileset;
823
824 Coord := Nodes.Coord;
825 TexCoord := Nodes.TexCoord;
826
827 AddCoordPoints;
828 AddTexCoordPoints;
829 end;
830 end;
831
832 procedure PrepareData;
833 begin
834 CurrentZ := 0;
835 LayerIndex := FMap.Layers.IndexOf(ALayer);
836 end;
837
838 var
839 X, Y: Integer;
840 begin
841 PrepareData;
842 LayerConversion := TLayerConversion.Create;
843 try
844 for Y := Map.Height - 1 downto 0 do
845 for X := 0 to Map.Width - 1 do
846 RenderTile(Vector2Integer(X, Y));
847 finally
848 FreeAndNil(LayerConversion);
849 end;
850 end;
851
852 constructor TCastleTiledMapConverter.Create(const ATiledMap: TCastleTiledMapData);
853 begin
854 inherited Create;
855
856 Layers := AllLayers;
857
858 Map := ATiledMap;
859
860 RootNode := TX3DRootNode.Create;
861 MapNode := TTransformNode.Create;
862 RootNode.AddChildren(MapNode);
863 end;
864
865 destructor TCastleTiledMapConverter.Destroy;
866 begin
867 inherited Destroy;
868 end;
869
870 function TCastleTiledMapConverter.ConvY(const TiledCoord: TVector2): TVector2;
871 begin
872 Result := Vector2(TiledCoord.X, - TiledCoord.Y);
873 end;
874
875 function TCastleTiledMapConverter.ConvY(const X, Y: Single): TVector2;
876 begin
877 Result := ConvY(Vector2(X, Y));
878 end;
879
880 function LoadTiledMap2d(const Stream: TStream; const BaseUrl: String): TX3DRootNode;
881 var
882 TiledMapFromStream: TCastleTiledMapData;
883 TiledMapConverter: TCastleTiledMapConverter;
884 begin
885 { The Tiled converter unit expects a TCastleTiledMapData object instance,
886 hence create one. }
887 TiledMapFromStream := TCastleTiledMapData.Create(Stream, BaseUrl);
888 try
889 TiledMapConverter := TCastleTiledMapConverter.Create(TiledMapFromStream);
890 try
891 TiledMapConverter.ConvertMap;
892 Result := TiledMapConverter.RootNode;
893 finally FreeAndNil(TiledMapConverter) end;
894 finally FreeAndNil(TiledMapFromStream) end;
895 end;
896
897 var
898 ModelFormat: TModelFormat;
899 initialization
900 ModelFormat := TModelFormat.Create;
901 ModelFormat.OnLoad := {$ifdef FPC}@{$endif} LoadTiledMap2d;
902 ModelFormat.MimeTypes.Add('application/x-tiled-map');
903 ModelFormat.FileFilterName := 'Tiled Map (*.tmx)';
904 ModelFormat.Extensions.Add('.tmx');
905 RegisterModelFormat(ModelFormat);
906 end.