-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathraytmx.h
More file actions
4945 lines (4440 loc) · 248 KB
/
raytmx.h
File metadata and controls
4945 lines (4440 loc) · 248 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**********************************************************************************************
* Copyright (c) 2024 Luke Philipsen
*
* Permission to use, copy, modify, and/or distribute this software for
* any purpose with or without fee is hereby granted.
*
* THE SOFTWARE IS PROVIDED “AS IS” AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE
* FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY
* DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
* OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
**********************************************************************************************/
/**********************************************************************************************
* Usage
*
* Do this:
* #define RAYTMX_IMPLEMENTATION
* before you include this file in *one* C or C++ file to create the implementation.
* You can define RAYTMX_DEC with
* #define RAYTMX_DEC static
* or
* #define RAYTMX_DEC extern
* to specify raytmx function declarations as static or extern, respectively.
* The default specifier is extern.
**********************************************************************************************/
#ifndef RAYTMX_H
#define RAYTMX_H
#include <ctype.h> // Required for: isspace().
#include <math.h> // Required for: fabs(), floor(), INFINITY, roundf().
#include <stddef.h> // Required for: NULL.
#include <stdint.h> // Required for: int32_t, uint32_t.
#include <stdlib.h> // Required for: atoi(), strtoul().
#include <string.h> // Required for: memcpy(), memset(), strcpy(), strcpy_s() strlen(), strncpy(), strncpy_s().
#include "raylib.h"
#include "rlgl.h"
#ifndef RAYTMX_DEC
#define RAYTMX_DEC
#endif // RAYTMX_DEC
#ifdef __cplusplus
extern "C" {
#endif // __cpluspus
//----------------------------------------------------------------------------------
// Public types and functions.
//----------------------------------------------------------------------------------
// Function signature of raylib's LoadTexture() as a type. For use with SetLoadTextureTMX().
typedef Texture2D (*LoadTextureCallback)(const char *fileName);
// Bit flags passed to SetTraceLogFlagsTMX() that optionally disable the logging of specific TMX elements.
enum TmxLogFlags {
LOG_SKIP_PROPERTIES = 1, // Skip <properties> and child <property> elements.
LOG_SKIP_LAYERS = 2, // Skip <layer>, <objectgroup>, <imagelayer>, and <group> layers and children thereof.
LOG_SKIP_TILE_LAYERS = 4, // Skip <layer> layers and children thereof.
LOG_SKIP_TILES = 8, // Skip tiles (GIDs) of tile layers (<layer>s).
LOG_SKIP_OBJECT_GROUPS = 16, // Skip <objectgroup> layers and children thereof.
LOG_SKIP_OBJECTS = 32, // Skip objects of object layers (<objectgroup>s).
LOG_SKIP_IMAGE_LAYERS = 64, // Skip <imagelayer> layers and children thereof.
LOG_SKIP_IMAGES = 128, // Skip images of image layers (<imagelayer>s).
LOG_SKIP_WANG_SETS = 256, // Skip <wangsets> and child <wangset> elements.
LOG_SKIP_WANG_TILES = 512 // Skip Wang tiles of Wang sets (<wangset>s).
};
// Identifiers for the possible layer types.
typedef enum {
LAYER_TYPE_TILE_LAYER = 0, // Layer containing a set number of tiles referenced by Global IDs (GIDs).
LAYER_TYPE_OBJECT_GROUP, // Layer containing an arbitrary number of various object types.
LAYER_TYPE_IMAGE_LAYER, // Layer consisting of a single image.
LAYER_TYPE_GROUP // Container layer, with no visuals of its own, that holds other, child layers.
} TmxLayerType;
// Identifiers for the possible property (data) types.
typedef enum {
PROPERTY_TYPE_STRING = 0, // String, or a sequence of characters.
PROPERTY_TYPE_INT, // Integer number.
PROPERTY_TYPE_FLOAT, // Floating-point number.
PROPERTY_TYPE_BOOL, // Boolean, true or false.
PROPERTY_TYPE_COLOR, // Color with red, green, and blue values and a possible alpha value.
PROPERTY_TYPE_FILE, // File name or path to a file as a string.
PROPERTY_TYPE_OBJECT // Object (<object>) within the map as an integer ID.
} TmxPropertyType;
// Identifiers for the possible draw orders applicable to object layers.
typedef enum {
OBJECT_GROUP_DRAW_ORDER_TOP_DOWN = 0, // Drawn in ascending order by Y coordinate.
OBJECT_GROUP_DRAW_ORDER_INDEX // Drawn in the order in which the appear in the document.
} TmxObjectGroupDrawOrder;
// Identifiers for the possible alignments of tiles with an object's bounds.
typedef enum {
OBJECT_ALIGNMENT_UNSPECIFIED = 0, // For orthogonal, behaves like bottom-left. For isometric, like bottom.
OBJECT_ALIGNMENT_TOP_LEFT, // Tiles are snapped to the upper-left bound of objects.
OBJECT_ALIGNMENT_TOP, // Tiles are snapped to the upper-center bound of objects.
OBJECT_ALIGNMENT_TOP_RIGHT, // Tiles are snapped to the upper-right bound of objects.
OBJECT_ALIGNMENT_LEFT, // Tiles are snapped to the left-center bound of objects.
OBJECT_ALIGNMENT_CENTER, // Tiles are snapped to the horizontal and vertical center of objects.
OBJECT_ALIGNMENT_RIGHT, // Tiles are snapped to the right-center bound of objects.
OBJECT_ALIGNMENT_BOTTOM_LEFT, // Tiles are snapped to the lower-left bound of objects.
OBJECT_ALIGNMENT_BOTTOM, // Tiles are snapped to the lower-center bound of objects.
OBJECT_ALIGNMENT_BOTTOM_RIGHT // Tiles are snapped to the lower-right bound of objects.
} TmxObjectAlignment;
// Identifiers for the possible object types.
typedef enum {
OBJECT_TYPE_RECTANGLE = 0, // Four-sided polygon with four right angles and axis-aligned edges.
OBJECT_TYPE_ELLIPSE, // Ellipse, or a circle when the axes are equal.
OBJECT_TYPE_POINT, // Individual (X, Y) position with no dimensions.
OBJECT_TYPE_POLYGON, // Filled polygon formed by an ordered series of points.
OBJECT_TYPE_POLYLINE, // Unfilled polygon formed by an ordered series of points.
OBJECT_TYPE_TEXT, // Text, or the visual representation of a string.
OBJECT_TYPE_TILE // Tile, referenced by a Global ID (GID), from a tileset known to the map.
} TmxObjectType;
// Identifiers for the possible horizontal alignments of text.
typedef enum {
HORIZONTAL_ALIGNMENT_LEFT = 0, // Text is to be snapped to the left bound of its object.
HORIZONTAL_ALIGNMENT_CENTER, // Text is to be centered along the X-axis of its object.
HORIZONTAL_ALIGNMENT_RIGHT, // Text is to be snapped to the right bound of its object.
HORIZONTAL_ALIGNMENT_JUSTIFY // Text is to be evenly spaced, per line, filling the object's width.
} TmxHorizontalAlignment;
// Identifiers for the possible vertical alignments of text.
typedef enum {
VERTICAL_ALIGNMENT_TOP = 0, // Text is to be snapped to the upper bound of its object.
VERTICAL_ALIGNMENT_CENTER, // Text is to be cnetered along the Y-axis of its object.
VERTICAL_ALIGNMENT_BOTTOM // Text is to be snapped to the lower bound of its object.
} TmxVerticalAlignment;
// Identifiers for the possible map orientations.
typedef enum {
ORIENTATION_NONE = 0, // Orientation was not specified. Assumed to be orthogonal.
ORIENTATION_ORTHOGONAL, // Standard top-down view with rectanglular tiles.
ORIENTATION_ISOMETRIC, // Subset top-down view from a 45-degree angle. NOT supported.
ORIENTATION_STAGGERED, // Variation of isometric with staggered axes.
ORIENTATION_HEXAGONAL // Top-down view in which tiles are six-sided and alternative rows/columns are offset.
} TmxOrientation;
// Identifiers for the possible orders in which tiles in a tile layer are rendered/drawn.
typedef enum {
RENDER_ORDER_RIGHT_DOWN = 0, // Tiles are rendered by row, from left to right, then column, from top to bottom.
RENDER_ORDER_RIGHT_UP, // Tiles are rendered by row, from left to right, then column, from bottom to top.
RENDER_ORDER_LEFT_DOWN, // Tiles are rendered by row, from right to left, then column, from top to bottom.
RENDER_ORDER_LEFT_UP // Tiles are rendered by row, from right to left, then column, from bottom to top.
} TmxRenderOrder;
// Model of an <image> element. Defines an image and relevant attributes along with a loaded texture.
typedef struct TmxImage {
char *source; // File name and/or path referencing the image on disk.
Color trans; // [optional] Color that defines is treated as transparent. Not currently implemented.
bool hasTrans; // When true, indicates 'trans' has been set with a color to be treated as transparent.
uint32_t width; // Width of the image in pixels.
uint32_t height; // Height of the image in pixels.
Texture2D texture; // The image as a raylib texture loaded into VRAM, if loading was successful.
} TmxImage;
// Model of a <layer> element when combined with the 'TmxLayer' model. Defines a tile layer with a fixed-size list of
// tile Global IDs (GIDs).
typedef struct TmxTileLayer {
uint32_t width; // Width of the layer in tiles.
uint32_t height; // Height of the layer in tiles.
char *encoding; // [optional] Encoding used to encode tiles. May be NULL, "base64", or "csv".
char *compression; // [optional] Compression used to compress tiles. May be NULL, "gzip", "zlib", or "zstd".
uint32_t *tiles; // Array of tile Global IDs (GIDs) contained by this tile layer.
uint32_t tilesLength; // Length of the 'tiles' array.
} TmxTileLayer;
// Contains the information needed to quickly draw a single line of a <text> element.
typedef struct TmxTextLine {
char *content; // The string to be drawn. This may be the whole content of the parent string or partial.
Font font; // The raylib Font to be used when drawing.
Vector2 position; // Absolute position of this line. This is separate from its object layer's potential offset.
float spacing; // Spacing in pixels to be applied between each character when drawing.
} TmxTextLine;
// Model of a <text> element along with some pre-calculated objects for efficient drawing.
typedef struct TmxText {
char *fontFamily; // Font family (e.g. "sans-serif") to be used to render the text.
uint32_t pixelSize; // Size of the font in pixels.
bool wrap; // When true, indicates word wrapping should be used when appropriate.
Color color; // Color of the text.
bool bold; // When true, indicates the text should be bolded.
bool italic; // When true, indicates the text should be italicized.
bool underline; // When true, indicates the text should be underlined.
bool strikeOut; // When true, indicates the text should be struck/crossed out.
bool kerning; // When true, indicates kerning should be used when drawing.
TmxHorizontalAlignment halign; // Horizontal alignment of the text within its object.
TmxVerticalAlignment valign; // Vertical alignment of the text within its object.
char *content; // The string to be drawn.
TmxTextLine *lines; // Array of pre-calculated lines with all values needed to quickly draw this text.
uint32_t linesLength; // Length of the 'lines' array.
} TmxText;
// Model of a <property> element. Describes a property of the model it's attached to with a name, type, and value.
typedef struct TmxProperty {
TmxPropertyType type; // The specific (data) type of the property indicating which associated value to read.
char *name; // Name of the property.
char *stringValue; // The property's value for string-typed properties.
int32_t intValue; // The property's value for integer-typed properties.
float floatValue; // The property's value for floating point-typed properties.
bool boolValue; // The property's value for boolean-typed properties.
Color colorValue; // The property's value for color-typed properties.
} TmxProperty;
// Model of an <object> element within an <objectgroup> element. Objects are amorphous entities of varying type but all
// are potentially visible with positions and dimensions.
typedef struct TmxObject {
TmxObjectType type; // The specific object type indicating which optional fields have relevant information.
uint32_t id; // Unique ID of the object.
char *name; // Name of the object.
char *typeString; // The type/class of the object. ('type' is a reserved keyword hence 'typeString'.)
double x; // Pixel X coordinate of the object. Separate from its object layer's potential offset.
double y; // Pixel Y coordinate of the object. Separate from its object layer's potential offset.
double width; // Width of the object in pixels.
double height; // Height of the object in pixels.
double rotation; // Rotation of the object in (clockwise) degrees around the object's (X, Y) position.
uint32_t gid; // [semi-optional] Global ID of a tile drawn as the object. Zero if not a tile.
bool visible; // When true, indicates the object will be drawn.
char *templateString; // [optional] File name and/or path referencing an object template on disk applied to
// this object. If NULL, no template is used.
Vector2 *points; // [optional] Array of *relative*, ordered points that define a poly(gon|line).
uint32_t pointsLength; // Length of the 'points' array.
Vector2 *drawPoints; // [optional] Array used as a buffer when drawing. Equal in length to the 'points' array.
TmxText *text; // [optional] Text to be drawn.
TmxProperty *properties; // Array of named, typed properties that apply to this object.
uint32_t propertiesLength; // Length of the 'properties' array.
Rectangle aabb; // Axis-Aligned Bounding Box (AABB).
} TmxObject;
// Model of an <objectgroup> element when combined with the 'TmxLayer' model. Defines an object layer of an arbitrary
// number of objects of varying types.
typedef struct TmxObjectGroup {
// uint32_t width; // Width of the object layer in tiles. Documentation calls it "meaningless."
// uint32_t height; // Height of the object layer in tiles. Documentation calls it "meaningless."
Color color; // [optional] Color used to display objects within the layer.
bool hasColor; // When true, indicates 'color' has been set.
TmxObjectGroupDrawOrder drawOrder; // Indicates the order in which objects in this layer are drawn.
TmxObject *objects; // Array of objects contained by this object layer.
uint32_t objectsLength; // Length of the 'objects' array.
uint32_t *ySortedObjects; // Array of indexes of 'objects' sorted by the objects' Y coordinates.
} TmxObjectGroup;
// Model of an <imagelayer> element when combined with the 'TmxLayer' model. Defines a layer consisting of one image.
typedef struct TmxImageLayer {
bool repeatX; // When true, indicates the image is repeated along the X-axis.
bool repeatY; // When true, indicates the image is repeated along the Y-axis.
TmxImage image; // Sole image of this layer.
bool hasImage; // When true, indicates 'image' has been set. Should always be true.
} TmxImageLayer;
struct TmxLayer; // Forward declaration of the following type. Contains children of the same type.
// Model of multiple layer elements: <layer>, <objectgroup>, <imagelayer>, or <group>. Defines a layer with attributes
// common to all, more-specific layer types. The more-specific attributes
typedef struct TmxLayer {
TmxLayerType type; // The layer type indicating which associated layer ('exact') has mspecific values.
uint32_t id; // Unique integer ID of the layer.
char *name; // Name of the layer.
char *classString; // [optional] Class of the layer. If unused, defaults to an empty string.
bool visible; // When true, indicates the layer and its children will be drawn.
double opacity; // Opacity of the layer and its children where 0.0 means the layer is fully transparent.
Color tintColor; // [optional] Tint color applied to the layer and its children.
bool hasTintColor; // When true, indicates 'tintColor' has been set.
int32_t offsetX; // Horizontal offset of the layer and its children in pixels.
int32_t offsetY; // Vertical offset of the layer and its children in pixels.
double parallaxX; // Horizontal parallax factor. 1.0 means the layers position on the screen changes at the
// same rate as the camera. 0.0 means the layer will not move with the camera.
double parallaxY; // Veritcal parallax factor. 1.0 means the layers position on the screen changes at the
// same rate as the camera. 0.0 means the layer will not move with the camera.
TmxProperty *properties; // Array of named, typed properties that apply to this layer.
uint32_t propertiesLength; // Length of the 'properties' array.
struct TmxLayer *layers; // [optional] Array of child layers, may be NULL. Only used by group layers.
uint32_t layersLength; // Length of the 'layers' array.
union {
TmxTileLayer tileLayer;
TmxObjectGroup objectGroup;
TmxImageLayer imageLayer;
} exact; // Additional information specific to a tile, object, or image layer but not groups.
} TmxLayer;
// Model of a <frame> element. Defines a temporal frame of an animation with the Global ID (GID) of the tile to be
// displayed and the duration thereof.
typedef struct TmxAnimationFrame {
uint32_t gid; // The Global ID (GID) of a tile from the animation's tileset to be drawn for some duration.
float duration; // Duration in milliseconds that the frame should be displayed.
} TmxAnimationFrame;
// Model of an <animation> element. Defines a series of (tile) frames.
typedef struct TmxAnimation {
TmxAnimationFrame *frames; // Array of frames. These frames identify tiles and durations to be displayed.
uint32_t framesLength; // Length of the 'frames' array.
} TmxAnimation;
// Model of a <tile> element within a <tileset> element. Contains information about tiles that are not or cannot be
// implicitly determined from the tileset.
typedef struct TmxTilesetTile {
uint32_t id; // Local ID of the tile within its tileset. Related to but separate from its Global ID.
char *classString; // [optional] Class of the tile. If unused, defaults to an empty string.
int32_t x; // X coordinate, in pixels, of the sub-rectangle within the tileset's image to extract.
int32_t y; // Y coordinate, in pixels, of the sub-rectangle within the tileset's image to extract.
uint32_t width; // Width, in pixels, of the sub-rectangle within the tileset's image to extract.
uint32_t height; // Height, in pixels, of the sub-rectangle within the tileset's image to extract.
TmxImage image; // [optional] Image to be used as the tile for "collection of images" tilesets.
bool hasImage; // When true, indicates 'image' is set.
TmxAnimation animation; // [optional] Animation. Lists GIDs to be drawn temporarily and periodically.
bool hasAnimation; // When true, indicates 'animation' is assigned.
TmxProperty *properties; // Array of named, typed properties that apply to this tileset tile.
uint32_t propertiesLength; // Length of the 'properties' array.
TmxObjectGroup objectGroup; // [optional] 0+ objects representing collision information unique to the tile.
} TmxTilesetTile;
// Model of a <tileset> element. Defines an image, or series of images, from which tiles are drawn along with
// information on how to extract areas from within the image and/or how to align them within an object.
typedef struct TmxTileset {
uint32_t firstGid; // First Global ID (GID) of a tile in this tileset.
uint32_t lastGid; // Last Global ID (GID) of a tile in this tileset.
char *source; // [optional] Source of this tileset, may be NULL. Only for external tilesets.
char *name; // Name of the tileset.
char *classString; // [optional] Class of the tileset. If unused, defaults to an empty string.
uint32_t tileWidth; // Maximum, typically exact, width of the tiles in this tileset in pixels.
uint32_t tileHeight; // Maximum, typically exact, height of the tiles in this tileset in pixels.
uint32_t spacing; // Spacing in pixels between tiles in this tileset.
uint32_t margin; // Margin around the tiles in this tileset.
uint32_t tileCount; // Number of tiles in this tileset.
// Note: 'lastGid' - 'firstGid' is not always 'tileCount'.
uint32_t columns; // Number of tile columsn in this tileset.
TmxObjectAlignment objectAlignment; // Controls the alignment of tiles of this tileset when used as objects.
int32_t tileOffsetX; // Horizontal offset in pixels applied when drawing tiles from this tileset.
int32_t tileOffsetY; // Vertical offset in pixels applied when drawing tiles form this tileset.
TmxImage image; // [optional] Image from which this tilesets tiles are extracted.
bool hasImage; // When true, indicates 'image' is set.
TmxProperty *properties; // Array of named, typed properties that apply to this tileset.
uint32_t propertiesLength; // Length of the 'properties' array.
TmxTilesetTile *tiles; // Array of explicitly-defined tiles within the tileset.
uint32_t tilesLength; // Length of the 'tiles' array.
} TmxTileset;
// Contains the information and objects needed to quickly draw a <tile> in a raylib application.
typedef struct TmxTile {
uint32_t gid; // Global ID (GID) of the tile. Used for lookups. Zero means the tile is unused.
Rectangle sourceRect; // Sub-rectangle within a tileset to extract that is to be drawn.
Texture2D texture; // Texture to be drawn. May be used whole or as a source of a sub-rectangle.
Vector2 offset; // Offset in pixels to be applied to the tile, derived from the tileset.
Vector2 dimensions; // Width and height as drawn, in pixels. May differ from the maps tile width and height.
TmxAnimation animation; // [optional] Animation. Lists GIDs to be drawn temporarily and periodically.
bool hasAnimation; // When true, indicates 'animation' is assigned.
uint32_t frameIndex; // The current animation frame to draw for animations.
float frameTime; // Accumulator for animations. The time, in seconds, the current frame has been drawn.
TmxObjectGroup objectGroup; // [optional] 0+ objects representing collision information unique to the tile.
} TmxTile;
// Model of a <map> element along with some pre-calculated objects for efficient drawing.
typedef struct TmxMap {
char *fileName; // File name of the TMX file with extension.
TmxOrientation orientation; // Map orientation. May be orthogonal, isometric, staggered, or hexagonal.
TmxRenderOrder renderOrder; // Order in which tiles on tile layers are rendered.
uint32_t width; // Width of this map in tiles.
uint32_t height; // Height of htis map in tiles.
uint32_t tileWidth; // Width of a tile in pixels.
uint32_t tileHeight; // Height of a tile in pixels.
int32_t parallaxOriginX; // X coordinate, in pixels, of the parallax origin.
int32_t parallaxOriginY; // Y coordinate, in pixels, of the parallax origin.
Color backgroundColor; // [optional] Background color to be drawn behind the map with its dimensions.
bool hasBackgroundColor; // When true, indicates 'backgroundColor' is set.
TmxProperty *properties; // Array of named, typed properties that apply to this map.
uint32_t propertiesLength; // Length of the 'properties' array.
TmxTileset *tilesets; // Array of tilesets used by the map.
uint32_t tilesetsLength; // Length of the 'tilesets' array.
TmxLayer *layers; // Array of layers and potential child layers that make up this map.
uint32_t layersLength; // Length of the 'layers' array.
TmxTile *gidsToTiles; // Array of pre-calculated tile metadata with values needed to quickly draw a tile given
// its GID. Allocated such that e.g. gidsToTiles[11] gets the data of tile GID eleven.
uint32_t gidsToTilesLength; // Length of the 'gidsToTiles' array.
} TmxMap;
// Load a TMX map from disk. To clean up, use UnloadTMX().
RAYTMX_DEC TmxMap *LoadTMX(const char *fileName);
// Unload a TMX map.
RAYTMX_DEC void UnloadTMX(TmxMap *map);
// Draw all visible layers of a map. 'camera' is required for parallax and may be used for culling. 'viewport' may be
// used for culling and takes priority over 'camera' if passed.
RAYTMX_DEC void DrawTMX(const TmxMap *map, const Camera2D *camera, const Rectangle *viewport, int posX, int posY,
Color tint);
// Draw spcific visible layers of a map. 'camera' is required for parallax and may be used for culling. 'viewport' may
// be used for culling and takes priority over 'camera' if passed. 'layers' is an array of length 'layersLength'.
RAYTMX_DEC void DrawTMXLayers(const TmxMap *map, const Camera2D *camera, const Rectangle *viewport,
const TmxLayer *layers, uint32_t layersLength, int posX, int posY, Color tint);
// Update animated tales based on draw times. Call this once between BeginDrawing() and EndDrawing().
RAYTMX_DEC void AnimateTMX(TmxMap *map);
// Check for collisions between two objects of arbitrary type. Text and tiles are treated as rectangles.
RAYTMX_DEC bool CheckCollisionTMXObjects(TmxObject object1, TmxObject object2);
// Check for collisions between a tile layer, or group layer, and a rectangle. The tiles must have collision information
// created with the Tiled Collision Editor. 'layers' is an array of length 'layersLength'. 'outputObject' is assigned
// with the object collided with, if not NULL.
RAYTMX_DEC bool CheckCollisionTMXTileLayersRec(const TmxMap *map, const TmxLayer *layers, uint32_t layersLength,
Rectangle rec, TmxObject *outputObject);
// Check for collisions between a tile layer, or group layer, and a circle. The tiles must have collision information
// created with the Tiled Collision Editor. 'layers' is an array of length 'layersLength'. 'outputObject' is assigned
// with the object collided with, if not NULL.
RAYTMX_DEC bool CheckCollisionTMXTileLayersCircle(const TmxMap *map, const TmxLayer *layers, uint32_t layersLength,
Vector2 center, float radius, TmxObject *outputObject);
// Check for collisions between a tile layer, or group layer, and a point. The tiles must have collision information
// created with the Tiled Collision Editor. // 'layers' is an array of length 'layersLength'. 'outputObject' is assigned
// with the object collided with, if not NULL.
RAYTMX_DEC bool CheckCollisionTMXTileLayersPoint(const TmxMap *map, const TmxLayer *layers, uint32_t layersLength,
Vector2 point, TmxObject *outputObject);
// Check for collisions between a tile layer, or group layer, and a polygon. The tiles must have collision information
// created with the Tiled Collision Editor. 'layers' is an array of length 'layersLength'. 'outputObject' is assigned
// with the object collided with, if not NULL.
RAYTMX_DEC bool CheckCollisionTMXTileLayersPoly(const TmxMap *map, const TmxLayer *layers, uint32_t layersLength,
Vector2 *points, int pointCount, TmxObject *outputObject);
// Check for collisions between a tile layer, or group layer, and a polygon. The tiles must have collision information
// created with the Tiled Collision Editor. 'layers' is an array of length 'layersLength'. 'outputObject' is assigned
// with the object collided with, if not NULL.
RAYTMX_DEC bool CheckCollisionTMXTileLayersPolyEx(const TmxMap *map, const TmxLayer *layers, uint32_t layersLength,
Vector2 *points, int pointCount, Rectangle aabb, TmxObject *outputObject);
// Check for collisions between an object group and a rectangle. 'outputObject' is assigned with the object collided
// with, if not NULL.
RAYTMX_DEC bool CheckCollisionTMXObjectGroupRec(TmxObjectGroup group, Rectangle rec, TmxObject *outputObject);
// Check for collisiosn between an object group and a circle. 'outputObject' is assigned with the object collided with,
// if not NULL.
RAYTMX_DEC bool CheckCollisionTMXObjectGroupCircle(TmxObjectGroup group, Vector2 center, float radius,
TmxObject *outputObject);
// Check for collisions between an object group and a point. 'outputObject' is assigned with the object collided with,
// if not NULL.
RAYTMX_DEC bool CheckCollisionTMXObjectGroupPoint(TmxObjectGroup group, Vector2 point, TmxObject *outputObject);
// Check for collisions between an object group and a polygon. 'outputObject' is assigned with the object collided with,
// if not NULL.
RAYTMX_DEC bool CheckCollisionTMXObjectGroupPoly(TmxObjectGroup group, Vector2 *points, int pointCount,
TmxObject *outputObject);
// Check for collisions between an object group and a polygon. 'outputObject' is assigned with the object collided with,
// if not NULL.
RAYTMX_DEC bool CheckCollisionTMXObjectGroupPolyEx(TmxObjectGroup group, Vector2 *points, int pointCount,
Rectangle aabb, TmxObject *outputObject);
// Set a custom texture load. If set, used in place of raylib's LoadTexture().
RAYTMX_DEC void SetLoadTextureTMX(LoadTextureCallback callback);
// Log properties of a map. SetTraceLogFlagsTMX() may be used to exclude select properties.
RAYTMX_DEC void TraceLogTMX(int logLevel, const TmxMap *map);
// Set logging options for TraceLogTMX(). Consumes flag defined in the TmxLogFlags enumeration.
RAYTMX_DEC void SetTraceLogFlagsTMX(int logFlags);
#ifdef __cplusplus
}
#endif // __cplusplus
#ifdef RAYTMX_IMPLEMENTATION
#ifndef HOXML_IMPLEMENTATION
#define HOXML_IMPLEMENTATION
#endif
#include "hoxml.h"
//----------------------------------------------------------------------------------
// Private implementation of public types and functions.
//----------------------------------------------------------------------------------
// Thickness, in pixels, that outlines of specific objects are drawn with.
#define TMX_LINE_THICKNESS 3.0f
// Bit flags that GIDs may be masked with in order to indicate transformations for individual tiles.
enum TmxFlipFlags {
FLIP_FLAG_HORIZONTAL = 0x80000000,
FLIP_FLAG_VERTICAL = 0x40000000,
FLIP_FLAG_DIAGONAL = 0x20000000,
FLIP_FLAG_ROTATE_120 = 0x10000000
};
typedef enum {
FORMAT_TMX = 0, // Tilemap with tilesets, layers, etc.
FORMAT_TSX, // External tilesets.
FORMAT_TX // Object templates.
} RaytmxDocumentFormat;
typedef struct RaytmxExternalTileset {
TmxTileset tileset;
bool isSuccess; // 'isSuccess' is true when the external tileset was successfully loaded.
} RaytmxExternalTileset;
typedef struct RaytmxObjectTemplate {
TmxTileset tileset;
TmxObject object;
bool isSuccess, hasTileset; // 'isSuccess' is true when the object template was successfully loaded.
} RaytmxObjectTemplate;
struct RaytmxCachedTextureNode; // Forward declaration.
// Associates a file name with a Texture2D allowing for the reuse of textures in VRAM.
typedef struct RaytmxCachedTextureNode {
char *fileName;
Texture2D texture;
struct RaytmxCachedTextureNode *next;
} RaytmxCachedTextureNode;
struct RaytmxCachedTemplateNode; // Forward declaration.
// Associates a file name with an object template.
typedef struct RaytmxCachedTemplateNode {
char *fileName;
RaytmxObjectTemplate objectTemplate;
struct RaytmxCachedTemplateNode *next;
} RaytmxCachedTemplateNode;
struct RaytmxPropertyNode; // Forward declaration.
typedef struct RaytmxPropertyNode {
TmxProperty property;
struct RaytmxPropertyNode *next;
} RaytmxPropertyNode;
struct RaytmxTilesetNode; // Forward declaration.
typedef struct RaytmxTilesetNode {
TmxTileset tileset;
struct RaytmxTilesetNode *next;
} RaytmxTilesetNode;
struct RaytmxTilesetTileNode; // Forward declaration.
typedef struct RaytmxTilesetTileNode {
TmxTilesetTile tile;
struct RaytmxTilesetTileNode *next;
} RaytmxTilesetTileNode;
struct RaytmxAnimationFrameNode; // Forward declaration.
typedef struct RaytmxAnimationFrameNode {
TmxAnimationFrame frame;
struct RaytmxAnimationFrameNode *next;
} RaytmxAnimationFrameNode;
struct RaytmxLayerNode; // Forward declaration.
typedef struct RaytmxLayerNode {
TmxLayer layer;
uint32_t childrenLength;
struct RaytmxLayerNode *next;
struct RaytmxLayerNode *parent;
struct RaytmxLayerNode *childrenRoot;
struct RaytmxLayerNode *childrenTail;
} RaytmxLayerNode;
struct RaytmxTileLayerTileNode; // Forward declaration.
typedef struct RaytmxTileLayerTileNode {
uint32_t gid;
struct RaytmxTileLayerTileNode *next;
} RaytmxTileLayerTileNode;
struct RaytmxObjectNode; // Forward declaration.
typedef struct RaytmxObjectNode {
TmxObject object;
struct RaytmxObjectNode *next;
} RaytmxObjectNode;
struct RaytmxObjectSortingNode; // Forward declaration.
typedef struct RaytmxObjectSortingNode {
double y;
uint32_t index;
struct RaytmxObjectSortingNode *next;
} RaytmxObjectSortingNode;
struct RaytmxPolyPointNode; // Forward declaration.
typedef struct RaytmxPolyPointNode {
Vector2 point;
struct RaytmxPolyPointNode *next;
} RaytmxPolyPointNode;
struct RaytmxTextLineNode; // Forward declaration.
typedef struct RaytmxTextLineNode {
TmxTextLine line;
struct RaytmxTextLineNode *next;
} RaytmxTextLineNode;
// Intermediate data used internally to parse TMX (map), TSX (tileset), and TX (template) files.
typedef struct RaytmxState {
RaytmxDocumentFormat format;
char documentDirectory[512];
bool isSuccess;
// Variables intended for TMX (map) parsing.
RaytmxCachedTextureNode *texturesRoot;
RaytmxCachedTemplateNode *templatesRoot;
TmxOrientation mapOrientation;
TmxRenderOrder mapRenderOrder;
uint32_t mapWidth;
uint32_t mapHeight;
uint32_t mapTileWidth;
uint32_t mapTileHeight;
uint32_t mapPropertiesLength;
int32_t mapParallaxOriginX;
int32_t mapParallaxOriginY;
Color mapBackgroundColor;
bool mapHasBackgroundColor;
TmxProperty *mapProperties;
// These variables, when not NULL, are assigned to the current element(s) being parsed.
TmxProperty *property;
TmxTileset *tileset;
TmxImage *image;
TmxTilesetTile *tilesetTile;
TmxAnimationFrame *animationFrame;
// TmxWangSet *wangSet; // TODO: Wang sets. Low priority.
// TmxWangColor *wangColor; // TODO: Wang sets. Low priority.
TmxLayer *layer;
TmxTileLayer *tileLayer;
TmxObjectGroup *objectGroup;
TmxImageLayer *imageLayer;
TmxObject *object;
// These variables are linked lists containing various elements where an arbitrary amount are allowed, such as 1+
// <object> elements in an <objectgroup>, that will be copied to arrays of known sizes later on.
RaytmxPropertyNode *propertiesRoot;
RaytmxPropertyNode *propertiesTail;
uint32_t propertiesLength;
uint32_t propertiesDepth;
RaytmxTilesetNode *tilesetsRoot;
RaytmxTilesetNode *tilesetsTail;
uint32_t tilesetsLength;
RaytmxTilesetTileNode *tilesetTilesRoot;
RaytmxTilesetTileNode *tilesetTilesTail;
uint32_t tilesetTilesLength;
RaytmxAnimationFrameNode *animationFramesRoot;
RaytmxAnimationFrameNode *animationFramesTail;
uint32_t animationFramesLength;
RaytmxLayerNode *layersRoot;
RaytmxLayerNode *layersTail;
uint32_t layersLength;
RaytmxLayerNode *groupNode;
RaytmxTileLayerTileNode *layerTilesRoot;
RaytmxTileLayerTileNode *layerTilesTail;
uint32_t layerTilesLength;
RaytmxObjectNode *objectsRoot;
RaytmxObjectNode *objectsTail;
uint32_t objectsLength;
} RaytmxState;
typedef struct RaytmxTransform {
Vector2 position;
Vector2 parallax;
Vector2 cameraOffset;
} RaytmxTransform;
// Forward declarations of functions used by the private implementation.
RaytmxExternalTileset LoadTSX(const char *fileName);
RaytmxObjectTemplate LoadTX(const char *fileName);
void ParseDocument(RaytmxState *state, const char *fileName);
void HandleElementBegin(RaytmxState *state, hoxml_context_t *hoxml);
void HandleAttribute(RaytmxState *state, hoxml_context_t *hoxml);
void HandleElementEnd(RaytmxState *state, hoxml_context_t *hoxml);
void FreeState(RaytmxState *state);
void FreeString(char *str);
void FreeTileset(TmxTileset tileset);
void FreeProperty(TmxProperty property);
void FreeLayer(TmxLayer layer);
void FreeObject(TmxObject object);
bool IterateTileLayer(const TmxMap *map, const TmxTileLayer *layer, Rectangle viewport, RaytmxTransform transform,
uint32_t *rawGid, TmxTile *tile, Rectangle *tileRect);
void DrawTMXLayersInternal(const TmxMap *map, const Camera2D *camera, const Rectangle *viewport, const TmxLayer *layers,
uint32_t layersLength, RaytmxTransform transform, Color tint);
void DrawTMXTileLayer(const TmxMap *map, Rectangle viewport, TmxLayer layer, RaytmxTransform transform, Color tint);
void DrawTMXLayerTile(const TmxMap *map, Rectangle viewport, RaytmxTransform transform, uint32_t rawGid,
Rectangle destRect, Color tint);
void DrawTMXObjectTile(const TmxMap *map, Rectangle viewport, uint32_t rawGid, RaytmxTransform transform, float width,
float height, Color tint);
void DrawTMXObjectGroup(const TmxMap *map, Rectangle viewport, TmxLayer layer, RaytmxTransform transform, Color tint);
void DrawTMXImageLayer(const TmxMap *map, Rectangle viewport, TmxLayer layer, RaytmxTransform transform, Color tint);
bool CheckCollisionTMXTileLayerObject(const TmxMap *map, const TmxLayer *layers, uint32_t layersLength,
TmxObject object, TmxObject *outputObject);
bool CheckCollisionTMXObjectGroupObject(TmxObjectGroup group, TmxObject object, TmxObject *outputObject);
void TraceLogTMXTilesets(int logLevel, TmxOrientation orientation, TmxTileset *tilesets, uint32_t tilesetsLength,
int numSpaces);
void TraceLogTMXProperties(int logLevel, TmxProperty *properties, uint32_t propertiesLength, int numSpaces);
void TraceLogTMXLayers(int logLevel, TmxLayer *layers, uint32_t layersLength, int numSpaces);
void TraceLogTMXObject(int logLevel, TmxObject object, int numSpaces);
void StringCopy(char *destination, const char *source);
TmxProperty *AddProperty(RaytmxState *state);
void AddTileLayerTile(RaytmxState *state, uint32_t gid);
TmxTileset *AddTileset(RaytmxState *state);
TmxTilesetTile *AddTilesetTile(RaytmxState *state);
TmxAnimationFrame *AddAnimationFrame(RaytmxState *state);
TmxLayer *AddGenericLayer(RaytmxState *state, bool isGroup);
TmxObject *AddObject(RaytmxState *state);
void AppendLayerTo(TmxMap *map, RaytmxLayerNode *groupNode, RaytmxLayerNode *layersRoot, uint32_t layersLength);
RaytmxCachedTextureNode *LoadCachedTexture(RaytmxState *state, const char *fileName);
RaytmxCachedTemplateNode *LoadCachedTemplate(RaytmxState *state, const char *fileName);
Color GetColorFromHexString(const char *hex);
uint32_t GetGid(uint32_t rawGid, bool *flipX, bool *flipY, bool *flipDiag, bool *rotateHexag120);
void *MemAllocZero(unsigned int size);
const char *GetDirectoryPath2(const char *filePath);
const char *JoinPath(const char *prefix, const char *suffix);
void StringCopyN(char *destination, const char *source, size_t number);
void StringConcatenate(char *destination, const char *source);
RAYTMX_DEC TmxMap *LoadTMX(const char *fileName)
{
TmxMap *map = (TmxMap *)MemAllocZero(sizeof(TmxMap));
RaytmxState state;
memset(&state, 0, sizeof(RaytmxState));
state.format = FORMAT_TMX;
// Do format-agnostic parsing of the document. The state object will be populated with raytmx's models of the
// equivalent TMX, TSX, and/or TX elements. */
ParseDocument(&state, fileName);
if (!state.isSuccess)
{
UnloadTMX(map);
return NULL;
}
// Copy some top-level map properties.
map->fileName = (char *)MemAllocZero((unsigned int)strlen(fileName) + 1);
StringCopy(map->fileName, GetFileName(fileName));
map->orientation = state.mapOrientation;
map->renderOrder = state.mapRenderOrder;
map->width = state.mapWidth;
map->height = state.mapHeight;
map->tileWidth = state.mapTileWidth;
map->tileHeight = state.mapTileHeight;
map->backgroundColor = state.mapBackgroundColor;
map->parallaxOriginX = state.mapParallaxOriginX;
map->parallaxOriginY = state.mapParallaxOriginY;
map->hasBackgroundColor = state.mapHasBackgroundColor;
uint32_t gidsToTilesLength = 0; // Can also be seen as the last GID.
if (state.tilesetsRoot != NULL) // If there is at least one tileset.
{
// Allocate the array of tilesets and zeroize every index.
TmxTileset *tilesets = (TmxTileset *)MemAllocZero(sizeof(TmxTileset)*state.tilesetsLength);
// Copy the TmxTileset pointers into the array.
RaytmxTilesetNode *tilesetIter = state.tilesetsRoot;
for (uint32_t i = 0; tilesetIter != NULL; i++)
{
TmxTileset tileset = tilesetIter->tileset;
if (tileset.hasImage) // If the tileset has a shared image and implicitly defines tiles.
{
// These tilesets implicitly have X tiles where X = <width in tiles> * <height in tiles>. But even these
// tilesets may have explicitly defined tiles for things like animations, or anything else. We need to
// know the greatest ID of those explicit tiles because they are allowed to have IDs that exceed the
// tileset's tile count and this affects global IDs, even in other tilesets.
uint32_t greatestID = 0;
for (uint32_t i = 0; i < tileset.tilesLength; i++)
if (greatestID < tileset.tiles[i].id) greatestID = tileset.tiles[i].id;
// Determine the last GID, meaning the greatest GID value, from the greatest local ID and tile count.
if (greatestID >= tileset.tileCount) tileset.lastGid = tileset.firstGid + greatestID;
else tileset.lastGid = tileset.firstGid + tileset.tileCount - 1;
}
else if (tileset.tilesLength > 0) // If the tileset is a "collection of images" with explicit tiles.
tileset.lastGid = tileset.firstGid + tileset.tiles[tileset.tilesLength - 1].id - 1;
if (gidsToTilesLength < tileset.lastGid + 1) gidsToTilesLength = tileset.lastGid + 1;
// Note: GIDs start at 1 so the length is the last GID + 1.
tilesets[i] = tileset;
tilesetIter = tilesetIter->next;
}
// Add the tilesets array to the map.
map->tilesets = tilesets;
map->tilesetsLength = state.tilesetsLength;
}
else TraceLog(LOG_WARNING, "RAYTMX: The map does not contain any tilesets");
if (state.layersRoot != NULL) // If there is at least one layer within the map.
{
// Due to the existence of <group> layers, layers can have children of multiple generations. To form the
// resulting tree-like structure, recursion is used.
AppendLayerTo(map, NULL, state.layersRoot, state.layersLength);
}
else TraceLog(LOG_WARNING, "RAYTMX: The map does not contain any layers");
if (gidsToTilesLength > 0)
{
TmxTile *gidsToTiles = (TmxTile *)MemAllocZero(sizeof(TmxTile)*gidsToTilesLength);
for (uint32_t i = 0; i < map->tilesetsLength; i++)
{
TmxTileset *tileset = &(map->tilesets[i]);
if (tileset->hasImage) // If the tileset has a shared image (i.e. not a "collection of images").
{
// First, iterate through the explicit tiles. These are explicitly defined with <tile> elements and are
// used to, among other things, provide animations and specific source rectangles. Note: Their IDs may
// exceed the tileset's tile count.
for (uint32_t j = 0; j < tileset->tilesLength; j++)
{
const TmxTilesetTile tilesetTile = tileset->tiles[j];
const uint32_t gid = tileset->firstGid + tilesetTile.id;
if (tilesetTile.hasAnimation) // If the tile is meta, pointing to a series of other tiles.
{
gidsToTiles[gid].hasAnimation = true;
gidsToTiles[gid].animation = tilesetTile.animation;
// Frames' tile (G)IDs are initially set with local values. Now that all tilesets are known and
// this tileset's first global ID is available, update the ID to be global.
for (uint32_t k = 0; k < gidsToTiles[gid].animation.framesLength; k++)
gidsToTiles[gid].animation.frames[k].gid += tileset->firstGid;
}
if (tilesetTile.x != 0 || tilesetTile.y != 0 || tilesetTile.width != 0 || tilesetTile.height != 0)
{
// This tile directly tells us the area within the tileset's image to use when drawing,
// overriding the implicit dimensions derived from the map's tile width and height.
gidsToTiles[gid].sourceRect.x = (float)tilesetTile.x;
gidsToTiles[gid].sourceRect.y = (float)tilesetTile.y;
gidsToTiles[gid].sourceRect.width = (float)tilesetTile.width;
gidsToTiles[gid].sourceRect.height = (float)tilesetTile.height;
}
gidsToTiles[gid].dimensions.x = (float)tileset->tileWidth;
gidsToTiles[gid].dimensions.y = (float)tileset->tileHeight;
// Tiles may have child object groups. These objects are a form of collision information. The object
// group may be empty or may have objects. A simple assignment covers both.
gidsToTiles[gid].objectGroup = tilesetTile.objectGroup;
gidsToTiles[gid].gid = gid; // Tell the tile its GID.
}
// Second, loop through the implicit tiles. These are inferred from knowing the dimensions of the
// tileset's image, dimensiosn of tiles, and the (right-down) order of tiles within the image.
for (uint32_t id = 0; id < tileset->tileCount; id++)
{
const uint32_t gid = id + tileset->firstGid;
const uint32_t x = id%tileset->columns;
const uint32_t y = id/tileset->columns;
gidsToTiles[gid].gid = gid; // Tell the tile its GID.
// If that source renctangle within the image was NOT explicitly defined.
// Note: Float comparisons like this are typically unreliable but the GIDs-to-tiles array is
// initialized with zeroes making this accurate.
if ((gidsToTiles[gid].sourceRect.x == 0.0f) && (gidsToTiles[gid].sourceRect.y == 0.0f) &&
(gidsToTiles[gid].sourceRect.width == 0.0f) && (gidsToTiles[gid].sourceRect.height == 0.0f))
{
// Calculate the area within the texture to extract from some contextual information.
gidsToTiles[gid].sourceRect.x = (float)(tileset->margin + (x*tileset->tileWidth) +
(x*tileset->spacing));
gidsToTiles[gid].sourceRect.y = (float)(tileset->margin + (y*tileset->tileHeight) +
(y*tileset->spacing));
gidsToTiles[gid].sourceRect.width = (float)tileset->tileWidth;
gidsToTiles[gid].sourceRect.height = (float)tileset->tileHeight;
}
gidsToTiles[gid].texture = tileset->image.texture;
gidsToTiles[gid].offset.x = (float)tileset->tileOffsetX;
gidsToTiles[gid].offset.y = (float)tileset->tileOffsetY;
gidsToTiles[gid].dimensions.x = (float)tileset->tileWidth;
gidsToTiles[gid].dimensions.y = (float)tileset->tileHeight;
}
}
else // If the tileset is a collection of images where each tile has its own image.
{
for (uint32_t j = 0; j < tileset->tilesLength; j++)
{
const TmxTilesetTile tilesetTile = tileset->tiles[j];
if (!tilesetTile.hasImage)
{
TraceLog(LOG_WARNING, "RAYTMX: Skipping tile %d of image collection tileset \"%s\" because "
"it has no image", tilesetTile.id, tileset->name);
continue;
}
const int32_t gid = tileset->firstGid + tilesetTile.id;
gidsToTiles[gid].gid = gid;
gidsToTiles[gid].sourceRect.x = (float)tilesetTile.x; // Defaults to, and probably is, zero.
gidsToTiles[gid].sourceRect.y = (float)tilesetTile.y; // Defaults to, and probably is, zero.
gidsToTiles[gid].sourceRect.width = (tilesetTile.width != tilesetTile.image.width)?
(float)tilesetTile.width : (float)tilesetTile.image.width;
gidsToTiles[gid].sourceRect.height = (tilesetTile.height != tilesetTile.image.height)?
(float)tilesetTile.height : (float)tilesetTile.image.height;
gidsToTiles[gid].dimensions.x = gidsToTiles[gid].sourceRect.width;
gidsToTiles[gid].dimensions.y = gidsToTiles[gid].sourceRect.height;
gidsToTiles[gid].texture = tilesetTile.image.texture;
}
}
}
map->gidsToTiles = gidsToTiles;
map->gidsToTilesLength = gidsToTilesLength;
}
// Free the linked lists and zeroize related values.
FreeState(&state);
return map;
}
RAYTMX_DEC void UnloadTMX(TmxMap *map)
{
if (map == NULL) return;
if (map->fileName != NULL) MemFree(map->fileName);
if (map->properties != NULL)
{
for (uint32_t i = 0; i < map->propertiesLength; i++) FreeProperty(map->properties[i]);
MemFree(map->properties);
}
if (map->tilesets != NULL)
{
for (uint32_t i = 0; i < map->tilesetsLength; i++) FreeTileset(map->tilesets[i]);
MemFree(map->tilesets);
}
if (map->layers != NULL)
{
for (uint32_t i = 0; i < map->layersLength; i++) FreeLayer(map->layers[i]);
MemFree(map->layers);
}
if (map->gidsToTiles != NULL) MemFree(map->gidsToTiles);
MemFree(map);
}
RAYTMX_DEC void DrawTMX(const TmxMap *map, const Camera2D *camera, const Rectangle *viewport, int posX, int posY,
Color tint)
{
if (map == NULL) return;
if (map->hasBackgroundColor)
{
Rectangle backgroundRect;
backgroundRect.x = (float)posX;
backgroundRect.y = (float)posY;
backgroundRect.width = (float)(map->width * map->tileWidth);
backgroundRect.height = (float)(map->height * map->tileHeight);
DrawRectangleRec(backgroundRect, map->backgroundColor);
}
DrawTMXLayers(map, camera, viewport, map->layers, map->layersLength, posX, posY, tint);
}
RAYTMX_DEC void DrawTMXLayers(const TmxMap* map, const Camera2D* camera, const Rectangle* viewport,
const TmxLayer* layers, uint32_t layersLength, int posX, int posY, Color tint)
{
// Pack some position and related information into an object to pass to various functions. At a minimum, this will
// will determine the position each layer is drawn at. With a camera, this will also be used for parallax.
RaytmxTransform transform;
transform.position.x = (float)posX;
transform.position.y = (float)posY;
transform.parallax.x = 1.0f;
transform.parallax.y = 1.0f;
transform.cameraOffset.x = 0.0f;
transform.cameraOffset.y = 0.0f;
if ((map != NULL) && (camera != NULL)) // If the map, with its parallax origin, and a camera are available.
{
// Calculate the camera's distance from the parallax origin. This origin is the reference point for parallax
// scrolling. The amount a parallaxed layer scrolls is proportion to this distance and some constant factor.
transform.cameraOffset.x = camera->target.x - map->parallaxOriginX;
transform.cameraOffset.y = camera->target.y - map->parallaxOriginY;
}
DrawTMXLayersInternal(map, camera, viewport, layers, layersLength, transform, tint);
}
RAYTMX_DEC void AnimateTMX(TmxMap *map)
{
if (map == NULL) return;
const float dt = GetFrameTime(); // Get the time, in seconds, since the last frame.
// Iterate through the tiles, searching for those that are animations.
for (uint32_t gid = 0; gid < map->gidsToTilesLength; gid++)
{
TmxTile *tile = &map->gidsToTiles[gid]; // A pointer is used in case the frame time needs to be reassigned.
// If the GID maps to a valid tile, that tile is an animation, and the bounds check passes.
if (tile->gid > 0 && tile->hasAnimation && tile->frameIndex < tile->animation.framesLength)
{
tile->frameTime += dt;
// If the current frame has been displayed for its whole duration, or longer.
if (tile->frameTime > tile->animation.frames[tile->frameIndex].duration)
{
tile->frameTime -= tile->animation.frames[tile->frameIndex].duration;
// Increment the frame index to display the next one...
tile->frameIndex += 1;