bevy_ecs_ldtk 0.5.0

An ECS-friendly ldtk plugin for bevy.
Documentation
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
//! Utility functions used internally by the plugin that have been exposed to the public api.

#[allow(unused_imports)]
use crate::{
    app::LdtkEntity,
    components::{GridCoords, IntGridCell},
};

use crate::{components::TileGridBundle, ldtk::*};
use bevy::prelude::*;
use bevy_ecs_tilemap::{
    map::{TilemapId, TilemapSize},
    tiles::{TilePos, TileStorage},
};

use std::{collections::HashMap, hash::Hash};

/// The `int_grid_csv` field of a [LayerInstance] is a 1-dimensional [Vec<i32>].
/// This function can map the indices of this [Vec] to a corresponding [GridCoords].
///
/// Will return [None] if the resulting [GridCoords] is out of the bounds implied by the width and
/// height.
pub fn int_grid_index_to_grid_coords(
    index: usize,
    layer_width_in_tiles: u32,
    layer_height_in_tiles: u32,
) -> Option<GridCoords> {
    if layer_width_in_tiles * layer_height_in_tiles == 0 {
        // Checking for potential n mod 0 and n / 0 issues
        // Also it just doesn't make sense for either of these to be 0.
        return None;
    }

    let tile_x = index as u32 % layer_width_in_tiles;

    let inverted_y = (index as u32 - tile_x) / layer_width_in_tiles;

    if layer_height_in_tiles > inverted_y {
        // Checking for potential subtraction issues.
        // We don't need to check index >= tile_x because tile_x is defined as index mod n where n
        // is a natural number.
        // This means tile_x == index where index < n, and tile_x < index where index >= n.

        Some(ldtk_grid_coords_to_grid_coords(
            IVec2::new(tile_x as i32, inverted_y as i32),
            layer_height_in_tiles as i32,
        ))
    } else {
        None
    }
}

/// Simple conversion from a list of [EntityDefinition]s to a map using their Uids as the keys.
pub fn create_entity_definition_map(
    entity_definitions: &[EntityDefinition],
) -> HashMap<i32, &EntityDefinition> {
    entity_definitions.iter().map(|e| (e.uid, e)).collect()
}

/// Simple conversion from a list of [LayerDefinition]s to a map using their Uids as the keys.
pub fn create_layer_definition_map(
    layer_definitions: &[LayerDefinition],
) -> HashMap<i32, &LayerDefinition> {
    layer_definitions.iter().map(|l| (l.uid, l)).collect()
}

/// Performs [EntityInstance] to [Transform] conversion
///
/// The `entity_definition_map` should be a map of [EntityDefinition] uids to [EntityDefinition]s.
///
/// Internally, this transform is used to place [EntityInstance]s as children of the level.
pub fn calculate_transform_from_entity_instance(
    entity_instance: &EntityInstance,
    entity_definition_map: &HashMap<i32, &EntityDefinition>,
    level_height: i32,
    z_value: f32,
) -> Transform {
    let entity_definition = entity_definition_map.get(&entity_instance.def_uid).unwrap();

    let def_size = match &entity_instance.tile {
        Some(tile) => IVec2::new(tile.w, tile.h),
        None => IVec2::new(entity_definition.width, entity_definition.height),
    };

    let size = IVec2::new(entity_instance.width, entity_instance.height);

    let translation = ldtk_pixel_coords_to_translation_pivoted(
        entity_instance.px,
        level_height as i32,
        size,
        entity_instance.pivot,
    );
    let scale = size.as_vec2() / def_size.as_vec2();

    Transform::from_translation(translation.extend(z_value)).with_scale(scale.extend(1.))
}

fn ldtk_coord_conversion(coords: IVec2, height: i32) -> IVec2 {
    IVec2::new(coords.x, height - coords.y)
}

fn ldtk_coord_conversion_origin_adjusted(coords: IVec2, height: i32) -> IVec2 {
    IVec2::new(coords.x, height - coords.y - 1)
}

/// Performs LDtk pixel coordinate to translation conversion.
pub fn ldtk_pixel_coords_to_translation(ldtk_coords: IVec2, ldtk_pixel_height: i32) -> Vec2 {
    ldtk_coord_conversion(ldtk_coords, ldtk_pixel_height).as_vec2()
}

/// Performs translation to LDtk pixel coordinate conversion.
pub fn translation_to_ldtk_pixel_coords(translation: Vec2, ldtk_pixel_height: i32) -> IVec2 {
    ldtk_coord_conversion(translation.as_ivec2(), ldtk_pixel_height)
}

/// Performs LDtk grid coordinate to [GridCoords] conversion.
///
/// This conversion is performed so that both the LDtk grid coords and the resulting [GridCoords]
/// refer to the same tile.
/// This is different from them referring to the same position in space, because the tile is
/// referenced by its top-left corner in LDtk, and by its bottom-left corner with [GridCoords].
pub fn ldtk_grid_coords_to_grid_coords(ldtk_coords: IVec2, ldtk_grid_height: i32) -> GridCoords {
    ldtk_coord_conversion_origin_adjusted(ldtk_coords, ldtk_grid_height).into()
}

/// Performs [GridCoords] to LDtk grid coordinate conversion.
///
/// This conversion is performed so that both the [GridCoords] and the resulting LDtk grid coords
/// refer to the same tile.
/// This is different from them referring to the same position in space, because the tile is
/// referenced by its top-left corner in LDtk, and by its bottom-left corner with [GridCoords].
pub fn grid_coords_to_ldtk_grid_coords(grid_coords: GridCoords, ldtk_grid_height: i32) -> IVec2 {
    ldtk_coord_conversion_origin_adjusted(grid_coords.into(), ldtk_grid_height)
}

/// Performs translation to [GridCoords] conversion.
///
/// This is inherently lossy since `GridCoords` space is less detailed than translation space.
///
/// Assumes that the origin of the grid is at [Vec2::ZERO].
pub fn translation_to_grid_coords(translation: Vec2, grid_size: IVec2) -> GridCoords {
    (translation / grid_size.as_vec2()).as_ivec2().into()
}

/// Performs [GridCoords] to translation conversion (relative to the layer), so that the resulting translation is in the
/// the center of the tile.
///
/// `IntGrid`, `AutoTile` and `Tile` layer entities have nonzero translations to adjust for
/// `bevy_ecs_tilemap`'s center-anchored tiles.
/// This function is intended to calculate translations for entities that are children of those
/// layers.
/// If you want to calculate translations for other entities relative to the level instead, see
/// [grid_coords_to_translation].
///
/// Internally, this transform is used to place [IntGridCell]s as children of the level.
pub fn grid_coords_to_translation_relative_to_tile_layer(
    grid_coords: GridCoords,
    tile_size: IVec2,
) -> Vec2 {
    let tile_coords: IVec2 = grid_coords.into();
    let tile_size = tile_size.as_vec2();
    tile_size * tile_coords.as_vec2()
}

/// Performs [GridCoords] to translation conversion, so that the resulting translation is in the
/// the center of the tile.
///
/// See also: [grid_coords_to_translation_relative_to_tile_layer]
pub fn grid_coords_to_translation(grid_coords: GridCoords, tile_size: IVec2) -> Vec2 {
    grid_coords_to_translation_relative_to_tile_layer(grid_coords, tile_size)
        + (tile_size.as_vec2() / 2.)
}

/// Performs LDtk pixel coordinate to [GridCoords] conversion.
///
/// This is inherently lossy since `GridCoords` space is less detailed than ldtk pixel coord space.
pub fn ldtk_pixel_coords_to_grid_coords(
    ldtk_coords: IVec2,
    ldtk_grid_height: i32,
    grid_size: IVec2,
) -> GridCoords {
    ldtk_grid_coords_to_grid_coords(ldtk_coords / grid_size, ldtk_grid_height)
}

/// Performs LDtk grid coordinate to translation conversion, so that the resulting translation is
/// in the center of the tile.
///
/// `IntGrid`, `AutoTile` and `Tile` layer entities have nonzero translations to adjust for
/// `bevy_ecs_tilemap`'s center-anchored tiles.
/// This function is intended to calculate translations for entities that are children of those
/// layers.
/// If you want to calculate translations for other entities relative to the level instead, see
/// [ldtk_grid_coords_to_translation].
pub fn ldtk_grid_coords_to_translation_relative_to_tile_layer(
    ldtk_coords: IVec2,
    ldtk_grid_height: i32,
    grid_size: IVec2,
) -> Vec2 {
    ldtk_pixel_coords_to_translation(ldtk_coords * grid_size, ldtk_grid_height * grid_size.y)
        + Vec2::new(0., -grid_size.y as f32)
}

/// Performs LDtk grid coordinate to translation conversion, so that the resulting translation is
/// in the center of the tile.
///
/// See also: [ldtk_grid_coords_to_translation_relative_to_tile_layer]
pub fn ldtk_grid_coords_to_translation(
    ldtk_coords: IVec2,
    ldtk_grid_height: i32,
    grid_size: IVec2,
) -> Vec2 {
    ldtk_grid_coords_to_translation_relative_to_tile_layer(ldtk_coords, ldtk_grid_height, grid_size)
        + (grid_size.as_vec2() / 2.)
}

/// Performs LDtk pixel coordinate to translation conversion, with "pivot" support.
///
/// In LDtk, the "pivot" of an entity indicates the percentage that an entity's visual is adjusted
/// relative to its pixel coordinates in both directions.
///
/// The resulting translation will indicate the location of the "center" of the entity's visual,
/// after being pivot-adjusted.
pub fn ldtk_pixel_coords_to_translation_pivoted(
    ldtk_coords: IVec2,
    ldtk_pixel_height: i32,
    entity_size: IVec2,
    pivot: Vec2,
) -> Vec2 {
    let pivot_point = ldtk_coord_conversion(ldtk_coords, ldtk_pixel_height).as_vec2();

    let adjusted_pivot = Vec2::new(0.5 - pivot.x, pivot.y - 0.5);

    let offset = entity_size.as_vec2() * adjusted_pivot;

    pivot_point + offset
}

/// Similar to [LayerBuilder::new_batch], except it doesn't consume the [LayerBuilder]
///
/// This allows for more methods to be performed on the [LayerBuilder] before building it.
/// However, the performance cons of using non-batch methods still apply here.
pub(crate) fn set_all_tiles_with_func(
    commands: &mut Commands,
    storage: &mut TileStorage,
    size: TilemapSize,
    tilemap_id: TilemapId,
    mut func: impl FnMut(TilePos) -> Option<TileGridBundle>,
) {
    for x in 0..size.x {
        for y in 0..size.y {
            let tile_pos = TilePos { x, y };
            let tile_entity = func(tile_pos)
                .map(|tile_bundle| commands.spawn(tile_bundle).insert(tilemap_id).id());
            match tile_entity {
                Some(tile_entity) => storage.set(&tile_pos, tile_entity),
                None => storage.remove(&tile_pos),
            }
        }
    }
}

/// Wraps `a` and `b` in an [Option] and tries each [Some]/[None] permutation as inputs to `func`,
/// returning the first non-none result of `func`.
///
/// The permutations are tried in this order:
/// 1. Some, Some
/// 2. None, Some
/// 3. Some, None
/// 4. None, None
///
/// Used for the defaulting functionality of [bevy_ecs_ldtk::app::RegisterLdtkObjects]
pub(crate) fn try_each_optional_permutation<A, B, R>(
    a: A,
    b: B,
    mut func: impl FnMut(Option<A>, Option<B>) -> Option<R>,
) -> Option<R>
where
    A: Clone,
    B: Clone,
{
    func(Some(a.clone()), Some(b.clone()))
        .or_else(|| func(None, Some(b)))
        .or_else(|| func(Some(a), None))
        .or_else(|| func(None, None))
}

/// The "get" function used on [bevy_ecs_ldtk::app::LdtkEntityMap] and
/// [bevy_ecs_ldtk::app::LdtkIntCellMap].
///
/// Due to the defaulting functionality of [bevy_ecs_ldtk::app::RegisterLdtkObjects], a single
/// instance of an LDtk entity or int grid tile may match multiple registrations.
/// This function is responsible for picking the correct registration while spawning these
/// entities/tiles.
pub(crate) fn ldtk_map_get_or_default<'a, A, B, L>(
    a: A,
    b: B,
    default: &'a L,
    map: &'a HashMap<(Option<A>, Option<B>), L>,
) -> &'a L
where
    A: Hash + Eq + Clone,
    B: Hash + Eq + Clone,
{
    try_each_optional_permutation(a, b, |x, y| map.get(&(x, y))).unwrap_or(default)
}

/// Creates a [SpriteSheetBundle] from the entity information available to the
/// [LdtkEntity::bundle_entity] method.
///
/// Used for the `#[sprite_sheet_bundle]` attribute macro for `#[derive(LdtkEntity)]`.
/// See [LdtkEntity#sprite_sheet_bundle] for more info.
pub fn sprite_sheet_bundle_from_entity_info(
    entity_instance: &EntityInstance,
    tileset: Option<&Handle<Image>>,
    tileset_definition: Option<&TilesetDefinition>,
    texture_atlases: &mut Assets<TextureAtlas>,
) -> SpriteSheetBundle {
    match (tileset, &entity_instance.tile, tileset_definition) {
        (Some(tileset), Some(tile), Some(tileset_definition)) => SpriteSheetBundle {
            texture_atlas: texture_atlases.add(TextureAtlas::from_grid(
                tileset.clone(),
                Vec2::new(tile.w as f32, tile.h as f32),
                tileset_definition.c_wid as usize,
                tileset_definition.c_hei as usize,
                Some(Vec2::splat(tileset_definition.spacing as f32)),
                Some(Vec2::splat(tileset_definition.padding as f32)),
            )),
            sprite: TextureAtlasSprite {
                index: (tile.y / (tile.h + tileset_definition.spacing)) as usize
                    * tileset_definition.c_wid as usize
                    + (tile.x / (tile.w + tileset_definition.spacing)) as usize,
                ..Default::default()
            },
            ..Default::default()
        },
        _ => {
            warn!("EntityInstance needs a tile, an associated tileset, and an associated tileset definition to be bundled as a SpriteSheetBundle");
            SpriteSheetBundle::default()
        }
    }
}

/// Creates a [SpriteBundle] from the entity information available to the
/// [LdtkEntity::bundle_entity] method.
///
/// Used for the `#[sprite_bundle]` attribute macro for `#[derive(LdtkEntity)]`.
/// See [LdtkEntity#sprite_bundle] for more info.
pub fn sprite_bundle_from_entity_info(tileset: Option<&Handle<Image>>) -> SpriteBundle {
    let tileset = match tileset {
        Some(tileset) => tileset.clone(),
        None => {
            warn!("EntityInstance needs a tileset to be bundled as a SpriteBundle");
            return SpriteBundle::default();
        }
    };

    SpriteBundle {
        texture: tileset,
        ..Default::default()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_int_grid_index_to_tile_pos() {
        assert_eq!(
            int_grid_index_to_grid_coords(3, 4, 5),
            Some(GridCoords::new(3, 4))
        );

        assert_eq!(
            int_grid_index_to_grid_coords(10, 5, 5),
            Some(GridCoords::new(0, 2))
        );

        assert_eq!(
            int_grid_index_to_grid_coords(49, 10, 5),
            Some(GridCoords::new(9, 0))
        );

        assert_eq!(
            int_grid_index_to_grid_coords(64, 100, 1),
            Some(GridCoords::new(64, 0))
        );

        assert_eq!(
            int_grid_index_to_grid_coords(35, 1, 100),
            Some(GridCoords::new(0, 64))
        );
    }

    #[test]
    fn test_int_grid_index_out_of_range() {
        assert_eq!(int_grid_index_to_grid_coords(3, 0, 5), None);

        assert_eq!(int_grid_index_to_grid_coords(3, 5, 0), None);

        assert_eq!(int_grid_index_to_grid_coords(25, 5, 5), None);
    }

    #[test]
    fn test_calculate_transform_from_entity_instance() {
        let entity_definitions = vec![
            EntityDefinition {
                uid: 0,
                width: 32,
                height: 32,
                ..Default::default()
            },
            EntityDefinition {
                uid: 1,
                width: 64,
                height: 16,
                ..Default::default()
            },
            EntityDefinition {
                uid: 2,
                width: 10,
                height: 25,
                ..Default::default()
            },
        ];
        let entity_definition_map = create_entity_definition_map(&entity_definitions);

        // simple case
        let entity_instance = EntityInstance {
            px: IVec2::new(256, 256),
            def_uid: 0,
            width: 32,
            height: 32,
            pivot: Vec2::new(0., 0.),
            ..Default::default()
        };
        let result = calculate_transform_from_entity_instance(
            &entity_instance,
            &entity_definition_map,
            320,
            0.,
        );
        assert_eq!(result, Transform::from_xyz(272., 48., 0.));

        // difficult case
        let entity_instance = EntityInstance {
            px: IVec2::new(40, 50),
            def_uid: 2,
            width: 30,
            height: 50,
            pivot: Vec2::new(1., 1.),
            ..Default::default()
        };
        let result = calculate_transform_from_entity_instance(
            &entity_instance,
            &entity_definition_map,
            100,
            2.,
        );
        assert_eq!(
            result,
            Transform::from_xyz(25., 75., 2.).with_scale(Vec3::new(3., 2., 1.))
        );
    }

    #[test]
    fn test_calculate_transform_from_entity_instance_with_tile() {
        let entity_definitions = vec![EntityDefinition {
            uid: 0,
            width: 32,
            height: 32,
            ..Default::default()
        }];
        let entity_definition_map = create_entity_definition_map(&entity_definitions);

        let entity_instance = EntityInstance {
            px: IVec2::new(64, 64),
            def_uid: 0,
            width: 64,
            height: 64,
            pivot: Vec2::new(1., 1.),
            tile: Some(TilesetRectangle {
                x: 0,
                y: 0,
                w: 16,
                h: 32,
                ..Default::default()
            }),
            ..Default::default()
        };
        let result = calculate_transform_from_entity_instance(
            &entity_instance,
            &entity_definition_map,
            100,
            2.,
        );
        assert_eq!(
            result,
            Transform::from_xyz(32., 68., 2.).with_scale(Vec3::new(4., 2., 1.))
        );
    }

    #[test]
    fn test_translation_ldtk_pixel_coords_conversion() {
        assert_eq!(
            ldtk_pixel_coords_to_translation(IVec2::new(32, 64), 128),
            Vec2::new(32., 64.)
        );
        assert_eq!(
            ldtk_pixel_coords_to_translation(IVec2::new(0, 0), 100),
            Vec2::new(0., 100.)
        );

        assert_eq!(
            translation_to_ldtk_pixel_coords(Vec2::new(32., 64.), 128),
            IVec2::new(32, 64)
        );
        assert_eq!(
            translation_to_ldtk_pixel_coords(Vec2::new(0., 0.), 100),
            IVec2::new(0, 100)
        );
    }

    #[test]
    fn test_ldtk_grid_coords_to_translation_relative_to_tile_layer() {
        assert_eq!(
            ldtk_grid_coords_to_translation_relative_to_tile_layer(
                IVec2::new(1, 1),
                4,
                IVec2::splat(32)
            ),
            Vec2::new(32., 64.)
        );

        assert_eq!(
            ldtk_grid_coords_to_translation_relative_to_tile_layer(
                IVec2::new(1, 1),
                2,
                IVec2::splat(100)
            ),
            Vec2::new(100., 0.)
        );

        assert_eq!(
            ldtk_grid_coords_to_translation_relative_to_tile_layer(
                IVec2::new(0, 4),
                10,
                IVec2::splat(1)
            ),
            Vec2::new(0., 5.)
        );
    }

    #[test]
    fn test_ldtk_grid_coords_to_translation() {
        assert_eq!(
            ldtk_grid_coords_to_translation(IVec2::new(1, 1), 4, IVec2::splat(32)),
            Vec2::new(48., 80.)
        );

        assert_eq!(
            ldtk_grid_coords_to_translation(IVec2::new(1, 1), 2, IVec2::splat(100)),
            Vec2::new(150., 50.)
        );

        assert_eq!(
            ldtk_grid_coords_to_translation(IVec2::new(0, 4), 10, IVec2::splat(1)),
            Vec2::new(0.5, 5.5)
        );
    }

    #[test]
    fn test_grid_coords_to_translation_relative_to_tile_layer() {
        assert_eq!(
            grid_coords_to_translation_relative_to_tile_layer(
                GridCoords::new(1, 2),
                IVec2::splat(32)
            ),
            Vec2::new(32., 64.)
        );

        assert_eq!(
            grid_coords_to_translation_relative_to_tile_layer(
                GridCoords::new(1, 0),
                IVec2::splat(100)
            ),
            Vec2::new(100., 0.)
        );

        assert_eq!(
            grid_coords_to_translation_relative_to_tile_layer(
                GridCoords::new(0, 5),
                IVec2::splat(1)
            ),
            Vec2::new(0.0, 5.0)
        );
    }

    #[test]
    fn test_grid_coords_to_translation() {
        assert_eq!(
            grid_coords_to_translation(GridCoords::new(1, 2), IVec2::splat(32)),
            Vec2::new(48., 80.)
        );

        assert_eq!(
            grid_coords_to_translation(GridCoords::new(1, 0), IVec2::splat(100)),
            Vec2::new(150., 50.)
        );

        assert_eq!(
            grid_coords_to_translation(GridCoords::new(0, 5), IVec2::splat(1)),
            Vec2::new(0.5, 5.5)
        );
    }

    #[test]
    fn test_ldtk_pixel_coords_to_translation_pivoted() {
        assert_eq!(
            ldtk_pixel_coords_to_translation_pivoted(
                IVec2::new(32, 64),
                128,
                IVec2::splat(32),
                Vec2::ZERO
            ),
            Vec2::new(48., 48.),
        );

        assert_eq!(
            ldtk_pixel_coords_to_translation_pivoted(
                IVec2::new(0, 0),
                10,
                IVec2::splat(1),
                Vec2::new(1., 0.)
            ),
            Vec2::new(-0.5, 9.5),
        );

        assert_eq!(
            ldtk_pixel_coords_to_translation_pivoted(
                IVec2::new(20, 20),
                20,
                IVec2::splat(5),
                Vec2::new(0.5, 0.5)
            ),
            Vec2::new(20., 0.),
        );
    }

    #[test]
    fn test_try_each_optional_permutation() {
        fn test_func(a: Option<i32>, b: Option<i32>) -> Option<i32> {
            match (a, b) {
                (Some(a), Some(_)) if a == 1 => Some(1),
                (Some(_), Some(_)) => None,
                (Some(a), None) if a == 2 => Some(2),
                (Some(_), None) => None,
                (None, Some(b)) if b == 3 => Some(3),
                (None, Some(_)) => None,
                (None, None) => Some(4),
            }
        }

        assert_eq!(try_each_optional_permutation(1, 1, test_func), Some(1));
        assert_eq!(try_each_optional_permutation(2, 1, test_func), Some(2));
        assert_eq!(try_each_optional_permutation(2, 2, test_func), Some(2));
        assert_eq!(try_each_optional_permutation(2, 3, test_func), Some(3));
        assert_eq!(try_each_optional_permutation(3, 3, test_func), Some(3));
        assert_eq!(try_each_optional_permutation(4, 3, test_func), Some(3));
        assert_eq!(try_each_optional_permutation(4, 4, test_func), Some(4));
        assert_eq!(try_each_optional_permutation(5, 5, test_func), Some(4));
    }
}