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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
//! Map rendering for the editor viewport using bevy_ecs_tilemap
//!
//! This module uses GPU-accelerated tilemap rendering via bevy_ecs_tilemap,
//! matching the approach used in bevy_map_runtime for consistent rendering
//! between editor and game.
use bevy::prelude::*;
use bevy_ecs_tilemap::prelude::*;
use bevy_map_core::{LayerData, OCCUPIED_CELL};
use std::collections::HashMap;
use uuid::Uuid;
use crate::project::Project;
use crate::tools::ViewportInputState;
use crate::ui::{EditorTool, Selection, TilesetTextureCache, ToolMode};
use crate::EditorState;
/// Plugin for map rendering
pub struct MapRenderPlugin;
impl Plugin for MapRenderPlugin {
fn build(&self, app: &mut App) {
app.add_plugins(TilemapPlugin)
.init_resource::<RenderState>()
.init_resource::<SelectionRenderState>()
.init_resource::<TerrainPreviewCache>()
.init_resource::<BrushPreviewCache>()
.init_resource::<EntityRenderState>()
.init_resource::<CollisionOverlayCache>()
.add_systems(Update, sync_level_rendering)
.add_systems(Update, sync_layer_visibility)
.add_systems(Update, sync_grid_rendering)
.add_systems(Update, sync_collision_rendering)
.add_systems(Update, sync_selection_preview)
.add_systems(Update, sync_tile_selection_highlights)
.add_systems(Update, sync_terrain_preview)
.add_systems(Update, sync_brush_preview)
.add_systems(Update, sync_entity_rendering)
.add_systems(Update, update_camera_from_editor_state);
}
}
/// Tracks the current render state for bevy_ecs_tilemap-based rendering
#[derive(Resource, Default)]
pub struct RenderState {
/// Currently rendered level ID
pub rendered_level: Option<Uuid>,
/// Tilemap entities: (level_id, layer_index, image_index) -> tilemap entity
pub tilemap_entities: HashMap<(Uuid, usize, usize), Entity>,
/// TileStorage for each tilemap (needed for tile updates)
pub tile_storages: HashMap<(Uuid, usize, usize), TileStorage>,
/// Grid line entities
pub grid_entities: Vec<Entity>,
/// Whether we need to rebuild the map
pub needs_rebuild: bool,
/// Last known layer visibility states for change detection
pub layer_visibility: HashMap<(Uuid, usize), bool>,
/// Last known grid visibility state
pub last_grid_visible: bool,
/// Last rendered level dimensions for grid
pub last_grid_dimensions: Option<(u32, u32, u32)>, // (width, height, tile_size)
/// Multi-cell tile sprites: (level_id, layer_index, x, y) -> sprite entity
/// These are rendered as separate Sprites instead of TileBundle to span multiple cells
pub multi_cell_sprites: HashMap<(Uuid, usize, u32, u32), Entity>,
}
impl RenderState {
/// Mark the viewport as needing a rebuild
pub fn mark_dirty(&mut self) {
self.needs_rebuild = true;
}
/// Set the current level being rendered
pub fn set_level(&mut self, level_id: Uuid) {
if self.rendered_level != Some(level_id) {
self.rendered_level = Some(level_id);
self.needs_rebuild = true;
}
}
}
/// Marker component for editor tilemaps
#[derive(Component)]
pub struct EditorTilemap {
pub level_id: Uuid,
pub layer_index: usize,
pub image_index: usize,
}
/// Marker component for the grid overlay
#[derive(Component)]
pub struct GridLine;
/// Marker component for the selection rectangle preview
#[derive(Component)]
pub struct SelectionPreview;
/// Marker component for collision shape overlays
#[derive(Component)]
pub struct CollisionOverlay;
/// Marker component for multi-cell tile sprites
#[derive(Component)]
pub struct MultiCellTileSprite {
pub level_id: Uuid,
pub layer_index: usize,
pub x: u32,
pub y: u32,
}
/// Cache for collision overlay entities (for efficient updates)
#[derive(Resource, Default)]
pub struct CollisionOverlayCache {
/// Collision overlay entities
pub entities: Vec<Entity>,
/// Last known show_collisions state
pub last_visible: bool,
/// Last known level ID
pub last_level: Option<Uuid>,
}
/// System to sync level rendering with the project data
fn sync_level_rendering(
mut commands: Commands,
mut render_state: ResMut<RenderState>,
editor_state: Res<EditorState>,
project: Res<Project>,
tileset_cache: Res<TilesetTextureCache>,
tilemap_query: Query<Entity, With<EditorTilemap>>,
asset_server: Res<AssetServer>,
) {
let current_level_id = editor_state.selected_level;
// Check if we need to switch levels
if render_state.rendered_level != current_level_id {
// Despawn all tile entities from storages first (safe - entity may not exist)
for storage in render_state.tile_storages.values() {
for tile_entity in storage.iter().flatten() {
let _ = commands.get_entity(*tile_entity).map(|mut e| e.despawn());
}
}
// Despawn all tilemap entities (safe - entity may not exist)
for entity in tilemap_query.iter() {
let _ = commands.get_entity(entity).map(|mut e| e.despawn());
}
// Despawn multi-cell tile sprites (safe - entity may not exist)
for entity in render_state.multi_cell_sprites.values() {
let _ = commands.get_entity(*entity).map(|mut e| e.despawn());
}
render_state.tilemap_entities.clear();
render_state.tile_storages.clear();
render_state.multi_cell_sprites.clear();
render_state.layer_visibility.clear();
render_state.rendered_level = current_level_id;
render_state.needs_rebuild = true;
}
// Get the current level
let Some(level_id) = current_level_id else {
return;
};
// Use O(1) lookup instead of iter().find()
let Some(level) = project.get_level(level_id) else {
return;
};
// Rebuild if needed
if render_state.needs_rebuild {
// Despawn all tile entities from storages first (safe - entity may not exist)
for storage in render_state.tile_storages.values() {
for tile_entity in storage.iter().flatten() {
let _ = commands.get_entity(*tile_entity).map(|mut e| e.despawn());
}
}
// Despawn all tilemap entities (safe - entity may not exist)
for entity in tilemap_query.iter() {
let _ = commands.get_entity(entity).map(|mut e| e.despawn());
}
// Despawn multi-cell tile sprites (safe - entity may not exist)
for entity in render_state.multi_cell_sprites.values() {
let _ = commands.get_entity(*entity).map(|mut e| e.despawn());
}
render_state.tilemap_entities.clear();
render_state.tile_storages.clear();
render_state.multi_cell_sprites.clear();
spawn_level_tilemaps(
&mut commands,
&mut render_state,
level,
&project,
&tileset_cache,
&asset_server,
);
render_state.needs_rebuild = false;
}
}
/// System to sync layer visibility
fn sync_layer_visibility(
editor_state: Res<EditorState>,
project: Res<Project>,
mut render_state: ResMut<RenderState>,
mut tilemap_query: Query<(&EditorTilemap, &mut Visibility), Without<MultiCellTileSprite>>,
mut multi_cell_query: Query<(&MultiCellTileSprite, &mut Visibility), Without<EditorTilemap>>,
) {
let Some(level_id) = editor_state.selected_level else {
return;
};
// Use O(1) lookup
let Some(level) = project.get_level(level_id) else {
return;
};
// Check for layer visibility changes and update tilemaps
for (layer_index, layer) in level.layers.iter().enumerate() {
let key = (level_id, layer_index);
let old_vis = render_state.layer_visibility.get(&key).copied();
if old_vis != Some(layer.visible) {
render_state.layer_visibility.insert(key, layer.visible);
let new_visibility = if layer.visible {
Visibility::Inherited
} else {
Visibility::Hidden
};
// Update visibility of all tilemaps for this layer
for (editor_tilemap, mut visibility) in tilemap_query.iter_mut() {
if editor_tilemap.level_id == level_id && editor_tilemap.layer_index == layer_index
{
*visibility = new_visibility;
}
}
// Update visibility of multi-cell tile sprites for this layer
for (multi_cell_sprite, mut visibility) in multi_cell_query.iter_mut() {
if multi_cell_sprite.level_id == level_id
&& multi_cell_sprite.layer_index == layer_index
{
*visibility = new_visibility;
}
}
}
}
}
/// Spawn tilemaps for a level using bevy_ecs_tilemap
fn spawn_level_tilemaps(
commands: &mut Commands,
render_state: &mut RenderState,
level: &bevy_map_core::Level,
project: &Project,
tileset_cache: &TilesetTextureCache,
asset_server: &AssetServer,
) {
for (layer_index, layer) in level.layers.iter().enumerate() {
// Skip non-tile layers
let LayerData::Tiles {
tileset_id, tiles, ..
} = &layer.data
else {
continue;
};
// Get tileset info (O(1) lookup)
let Some(tileset) = project.get_tileset(*tileset_id) else {
continue;
};
let tile_size = tileset.tile_size;
let tile_size_f32 = tile_size as f32;
// Group tiles by image (for multi-image tilesets)
// bevy_ecs_tilemap uses a single texture per tilemap, so we need separate tilemaps per image
// Also track which tiles are multi-cell (they'll be rendered as Sprites instead)
let mut tiles_by_image: HashMap<usize, Vec<(u32, u32, u32)>> = HashMap::new();
let mut multi_cell_tiles: Vec<(u32, u32, u32, u32, u32, usize)> = Vec::new(); // (x, y, virtual_idx, grid_w, grid_h, image_index)
for y in 0..level.height {
for x in 0..level.width {
let index = (y * level.width + x) as usize;
if let Some(Some(virtual_tile_index)) = tiles.get(index) {
// Skip OCCUPIED_CELL sentinel values (used for multi-cell tiles)
if *virtual_tile_index == OCCUPIED_CELL {
continue;
}
// Check if this is a multi-cell tile
let (grid_width, grid_height) = tileset.get_tile_grid_size(*virtual_tile_index);
if grid_width > 1 || grid_height > 1 {
// Multi-cell tile - will be rendered as Sprite
if let Some((image_index, _)) =
tileset.virtual_to_local(*virtual_tile_index)
{
multi_cell_tiles.push((
x,
y,
*virtual_tile_index,
grid_width,
grid_height,
image_index,
));
}
} else {
// Regular 1x1 tile - use TileBundle
if let Some((image_index, local_tile_index)) =
tileset.virtual_to_local(*virtual_tile_index)
{
tiles_by_image.entry(image_index).or_default().push((
x,
y,
local_tile_index,
));
}
}
}
}
}
// Spawn a tilemap for each image used in this layer (for regular 1x1 tiles)
for (image_index, image_tiles) in tiles_by_image {
// Get texture handle for this image
let texture_handle = if let Some(image) = tileset.images.get(image_index) {
if let Some((handle, _, _, _)) = tileset_cache.loaded.get(&image.id) {
handle.clone()
} else {
asset_server.load(crate::to_asset_path(&image.path))
}
} else if let Some(path) = tileset.primary_path() {
asset_server.load(crate::to_asset_path(path))
} else {
continue;
};
let map_size = TilemapSize {
x: level.width,
y: level.height,
};
let tilemap_tile_size = TilemapTileSize {
x: tile_size_f32,
y: tile_size_f32,
};
let grid_size: TilemapGridSize = tilemap_tile_size.into();
let mut tile_storage = TileStorage::empty(map_size);
let tilemap_entity = commands.spawn_empty().id();
// Spawn tiles for this image
for (x, y, local_tile_index) in &image_tiles {
let tile_pos = TilePos { x: *x, y: *y };
let tile_entity = commands
.spawn(TileBundle {
position: tile_pos,
tilemap_id: TilemapId(tilemap_entity),
texture_index: TileTextureIndex(*local_tile_index),
..default()
})
.id();
tile_storage.set(&tile_pos, tile_entity);
}
// Z-offset: layer_index * 0.1 + image_index * 0.01
// This ensures proper ordering: all images in layer 0 render before layer 1
let layer_z = layer_index as f32 * 0.1 + image_index as f32 * 0.01;
// Insert TilemapBundle first (which includes Visibility internally)
// Use BottomLeft anchor so tiles at (0,0) start at world origin
commands.entity(tilemap_entity).insert((
TilemapBundle {
grid_size,
map_type: TilemapType::Square,
size: map_size,
storage: tile_storage.clone(),
texture: TilemapTexture::Single(texture_handle),
tile_size: tilemap_tile_size,
transform: Transform::from_xyz(0.0, 0.0, layer_z),
anchor: TilemapAnchor::BottomLeft,
visibility: if layer.visible {
Visibility::Inherited
} else {
Visibility::Hidden
},
..default()
},
EditorTilemap {
level_id: level.id,
layer_index,
image_index,
},
));
// Store references for later updates
let key = (level.id, layer_index, image_index);
render_state.tilemap_entities.insert(key, tilemap_entity);
render_state.tile_storages.insert(key, tile_storage);
}
// Spawn multi-cell tiles as Sprites
for (x, y, virtual_tile_index, grid_width, grid_height, image_index) in multi_cell_tiles {
// Get texture handle and image info for this tile
let Some(image) = tileset.images.get(image_index) else {
continue;
};
let texture_handle =
if let Some((handle, _, _, _)) = tileset_cache.loaded.get(&image.id) {
handle.clone()
} else {
// Image not loaded yet, skip for now (will be rendered on rebuild)
continue;
};
// Calculate local tile position in the tileset image
let (_, local_tile_index) = tileset.virtual_to_local(virtual_tile_index).unwrap();
let tile_col = local_tile_index % image.columns;
let tile_row = local_tile_index / image.columns;
// Source rect in texture coordinates (pixels)
// Note: In Bevy textures, Y=0 is at top, but we need to flip for correct sampling
let src_x = (tile_col * tile_size) as f32;
let src_y = (tile_row * tile_size) as f32;
let src_width = (grid_width * tile_size) as f32;
let src_height = (grid_height * tile_size) as f32;
// Create a rect for the source region
let rect = bevy::math::Rect::new(src_x, src_y, src_x + src_width, src_y + src_height);
// Get origin point (defaults to center if not set)
let props = tileset
.get_tile_properties(virtual_tile_index)
.cloned()
.unwrap_or_default();
let (origin_x, origin_y) = props.get_origin(src_width as u32, src_height as u32);
// World position: place sprite so origin aligns with grid cell corner
// For center origin (size/2): sprite center at grid + size/2 (standard behavior)
// For top-left origin (0): sprite center at grid + 0 (tile shifts left/down)
let world_x = x as f32 * tile_size_f32 + origin_x as f32;
let world_y = y as f32 * tile_size_f32 + origin_y as f32;
// Z-offset slightly above regular tiles in same layer
let layer_z = layer_index as f32 * 0.1 + image_index as f32 * 0.01 + 0.001;
let sprite_entity = commands
.spawn((
Sprite {
image: texture_handle,
rect: Some(rect),
custom_size: Some(Vec2::new(src_width, src_height)),
..default()
},
Transform::from_xyz(world_x, world_y, layer_z),
Visibility::Inherited,
MultiCellTileSprite {
level_id: level.id,
layer_index,
x,
y,
},
))
.id();
// Store reference for updates
render_state
.multi_cell_sprites
.insert((level.id, layer_index, x, y), sprite_entity);
}
// Store layer visibility
render_state
.layer_visibility
.insert((level.id, layer_index), layer.visible);
}
}
/// Update a single tile in the rendered tilemap
///
/// This function updates both the visual representation and the TileStorage.
/// Call this when painting tiles to avoid full rebuilds.
pub fn update_tile(
commands: &mut Commands,
render_state: &mut RenderState,
project: &Project,
tileset_cache: &TilesetTextureCache,
level_id: Uuid,
layer_index: usize,
x: u32,
y: u32,
new_tile_index: Option<u32>,
) {
// Get the level and layer to find the tileset (O(1) lookups)
let Some(level) = project.get_level(level_id) else {
return;
};
let Some(layer) = level.layers.get(layer_index) else {
return;
};
let LayerData::Tiles { tileset_id, .. } = &layer.data else {
return;
};
let Some(tileset) = project.get_tileset(*tileset_id) else {
return;
};
let tile_size = tileset.tile_size;
let tile_size_f32 = tile_size as f32;
let tile_pos = TilePos { x, y };
// Skip rendering OCCUPIED_CELL sentinel values (used for multi-cell tiles)
// Treat them as empty cells
let effective_tile_index = new_tile_index.filter(|&idx| idx != OCCUPIED_CELL);
// Only remove existing multi-cell sprite if we're placing a real tile here
// (not for OCCUPIED_CELL or None, which shouldn't affect other tiles)
if effective_tile_index.is_some() {
let multi_cell_key = (level_id, layer_index, x, y);
if let Some(entity) = render_state.multi_cell_sprites.remove(&multi_cell_key) {
let _ = commands.get_entity(entity).map(|mut e| e.despawn());
}
}
if let Some(tile_idx) = effective_tile_index {
// Check if this is a multi-cell tile
let (grid_width, grid_height) = tileset.get_tile_grid_size(tile_idx);
if grid_width > 1 || grid_height > 1 {
// Multi-cell tile - render as Sprite
// Note: Only remove sprite at exact same position (already handled above at lines 507-511)
// Overlapping tiles are preserved - no cleanup needed here
if let Some((image_index, local_idx)) = tileset.virtual_to_local(tile_idx) {
// Remove from regular tilemap storage if it was there
for ((lid, li, _), storage) in render_state.tile_storages.iter_mut() {
if *lid == level_id && *li == layer_index {
if let Some(entity) = storage.get(&tile_pos) {
let _ = commands.get_entity(entity).map(|mut e| e.despawn());
storage.remove(&tile_pos);
}
}
}
// Get texture handle
if let Some(image) = tileset.images.get(image_index) {
if let Some((texture_handle, _, _, _)) = tileset_cache.loaded.get(&image.id) {
// Calculate tile position in tileset image
let tile_col = local_idx % image.columns;
let tile_row = local_idx / image.columns;
// Source rect
let src_x = (tile_col * tile_size) as f32;
let src_y = (tile_row * tile_size) as f32;
let src_width = (grid_width * tile_size) as f32;
let src_height = (grid_height * tile_size) as f32;
let rect = bevy::math::Rect::new(
src_x,
src_y,
src_x + src_width,
src_y + src_height,
);
// Get origin point (defaults to center if not set)
let props = tileset
.get_tile_properties(tile_idx)
.cloned()
.unwrap_or_default();
let (origin_x, origin_y) =
props.get_origin(src_width as u32, src_height as u32);
// World position: place sprite so origin aligns with grid cell corner
let world_x = x as f32 * tile_size_f32 + origin_x as f32;
let world_y = y as f32 * tile_size_f32 + origin_y as f32;
let layer_z = layer_index as f32 * 0.1 + image_index as f32 * 0.01 + 0.001;
let sprite_entity = commands
.spawn((
Sprite {
image: texture_handle.clone(),
rect: Some(rect),
custom_size: Some(Vec2::new(src_width, src_height)),
..default()
},
Transform::from_xyz(world_x, world_y, layer_z),
Visibility::Inherited,
MultiCellTileSprite {
level_id,
layer_index,
x,
y,
},
))
.id();
render_state
.multi_cell_sprites
.insert((level_id, layer_index, x, y), sprite_entity);
}
}
}
} else {
// Regular 1x1 tile - use TileBundle
if let Some((image_index, local_idx)) = tileset.virtual_to_local(tile_idx) {
let key = (level_id, layer_index, image_index);
// First, remove the tile from any other image's storage at this position
// (in case we're changing which image the tile uses)
for ((lid, li, img_idx), storage) in render_state.tile_storages.iter_mut() {
if *lid == level_id && *li == layer_index && *img_idx != image_index {
if let Some(old_entity) = storage.get(&tile_pos) {
let _ = commands.get_entity(old_entity).map(|mut e| e.despawn());
storage.remove(&tile_pos);
}
}
}
// Create tilemap on-demand if it doesn't exist
if !render_state.tile_storages.contains_key(&key) {
// Get texture handle from cache
let texture_handle = tileset.images.get(image_index).and_then(|image| {
tileset_cache
.loaded
.get(&image.id)
.map(|(handle, _, _, _)| handle.clone())
});
if let Some(texture_handle) = texture_handle {
let map_size = TilemapSize {
x: level.width,
y: level.height,
};
let tilemap_tile_size = TilemapTileSize {
x: tile_size_f32,
y: tile_size_f32,
};
let grid_size: TilemapGridSize = tilemap_tile_size.into();
let tile_storage = TileStorage::empty(map_size);
let tilemap_entity = commands.spawn_empty().id();
let layer_z = layer_index as f32 * 0.1 + image_index as f32 * 0.01;
let layer_visible = layer.visible;
commands.entity(tilemap_entity).insert((
TilemapBundle {
grid_size,
map_type: TilemapType::Square,
size: map_size,
storage: tile_storage.clone(),
texture: TilemapTexture::Single(texture_handle),
tile_size: tilemap_tile_size,
transform: Transform::from_xyz(0.0, 0.0, layer_z),
anchor: TilemapAnchor::BottomLeft,
visibility: if layer_visible {
Visibility::Inherited
} else {
Visibility::Hidden
},
..default()
},
EditorTilemap {
level_id,
layer_index,
image_index,
},
));
render_state.tilemap_entities.insert(key, tilemap_entity);
render_state.tile_storages.insert(key, tile_storage);
}
}
// Now update the correct tilemap
if let Some(storage) = render_state.tile_storages.get_mut(&key) {
let tilemap_entity = render_state.tilemap_entities[&key];
// Remove old tile if exists
if let Some(old_entity) = storage.get(&tile_pos) {
let _ = commands.get_entity(old_entity).map(|mut e| e.despawn());
}
// Spawn new tile
let new_tile = commands
.spawn(TileBundle {
position: tile_pos,
tilemap_id: TilemapId(tilemap_entity),
texture_index: TileTextureIndex(local_idx),
..default()
})
.id();
storage.set(&tile_pos, new_tile);
}
}
}
} else {
// Erase: remove tile from all image tilemaps for this layer
for ((lid, li, _), storage) in render_state.tile_storages.iter_mut() {
if *lid == level_id && *li == layer_index {
if let Some(entity) = storage.get(&tile_pos) {
let _ = commands.get_entity(entity).map(|mut e| e.despawn());
storage.remove(&tile_pos);
}
}
}
}
}
/// System to render grid overlay (sprite-based, on top of tilemaps)
fn sync_grid_rendering(
mut commands: Commands,
mut render_state: ResMut<RenderState>,
editor_state: Res<EditorState>,
project: Res<Project>,
) {
let show_grid = editor_state.show_grid;
// Get current level info
let level_info = editor_state.selected_level.and_then(|level_id| {
project
.levels
.iter()
.find(|l| l.id == level_id)
.map(|level| {
// Get tile size from first tile layer's tileset, or default
let tile_size = level
.layers
.iter()
.find_map(|layer| {
if let LayerData::Tiles { tileset_id, .. } = &layer.data {
project
.tilesets
.iter()
.find(|t| t.id == *tileset_id)
.map(|t| t.tile_size)
} else {
None
}
})
.unwrap_or(32);
(level.width, level.height, tile_size)
})
});
// Check if we need to update grid
let needs_update = show_grid != render_state.last_grid_visible
|| (show_grid && level_info != render_state.last_grid_dimensions);
if !needs_update {
return;
}
// Despawn existing grid
for entity in render_state.grid_entities.drain(..) {
let _ = commands.get_entity(entity).map(|mut e| e.despawn());
}
render_state.last_grid_visible = show_grid;
render_state.last_grid_dimensions = level_info;
if !show_grid {
return;
}
let Some((width, height, tile_size)) = level_info else {
return;
};
let tile_size_f32 = tile_size as f32;
let grid_color = Color::srgba(0.5, 0.5, 0.5, 0.5);
let line_thickness = 1.0;
let grid_width = width as f32 * tile_size_f32;
let grid_height = height as f32 * tile_size_f32;
// Spawn vertical lines
for x in 0..=width {
let world_x = x as f32 * tile_size_f32;
let center_y = grid_height / 2.0;
let entity = commands
.spawn((
Sprite {
color: grid_color,
custom_size: Some(Vec2::new(line_thickness, grid_height)),
..default()
},
Transform::from_xyz(world_x, center_y, 100.0),
GridLine,
))
.id();
render_state.grid_entities.push(entity);
}
// Spawn horizontal lines
for y in 0..=height {
let world_y = y as f32 * tile_size_f32;
let center_x = grid_width / 2.0;
let entity = commands
.spawn((
Sprite {
color: grid_color,
custom_size: Some(Vec2::new(grid_width, line_thickness)),
..default()
},
Transform::from_xyz(center_x, world_y, 100.0),
GridLine,
))
.id();
render_state.grid_entities.push(entity);
}
}
/// System to render collision shape overlays on tiles
fn sync_collision_rendering(
mut commands: Commands,
mut cache: ResMut<CollisionOverlayCache>,
editor_state: Res<EditorState>,
project: Res<Project>,
) {
let show_collisions = editor_state.show_collisions;
let current_level = editor_state.selected_level;
// Check if we need to update
let needs_update = show_collisions != cache.last_visible || current_level != cache.last_level;
if !needs_update && !show_collisions {
return;
}
// Despawn existing collision overlays
for entity in cache.entities.drain(..) {
let _ = commands.get_entity(entity).map(|mut e| e.despawn());
}
cache.last_visible = show_collisions;
cache.last_level = current_level;
if !show_collisions {
return;
}
let Some(level_id) = current_level else {
return;
};
// Use O(1) lookup instead of iter().find()
let Some(level) = project.get_level(level_id) else {
return;
};
let collision_color = Color::srgba(0.0, 0.6, 1.0, 0.3);
// Iterate through tile layers
for (layer_idx, layer) in level.layers.iter().enumerate() {
if !layer.visible {
continue;
}
if let bevy_map_core::LayerData::Tiles {
tileset_id, tiles, ..
} = &layer.data
{
// Get the tileset (O(1) lookup)
let Some(tileset) = project.get_tileset(*tileset_id) else {
continue;
};
let tile_size = tileset.tile_size as f32;
// Iterate through tiles
for y in 0..level.height {
for x in 0..level.width {
let idx = (y * level.width + x) as usize;
if let Some(&Some(tile_index)) = tiles.get(idx) {
// Check if this tile has collision
if let Some(props) = tileset.get_tile_properties(tile_index) {
if props.collision.has_collision() {
// Spawn collision overlay sprite(s)
spawn_collision_overlay(
&mut commands,
&mut cache,
&props.collision.shape,
x,
y,
tile_size,
layer_idx,
collision_color,
);
}
}
}
}
}
}
}
}
/// Spawn collision overlay sprite(s) for a single tile
fn spawn_collision_overlay(
commands: &mut Commands,
cache: &mut CollisionOverlayCache,
shape: &bevy_map_core::CollisionShape,
tile_x: u32,
tile_y: u32,
tile_size: f32,
layer_idx: usize,
color: Color,
) {
// Calculate world position (tiles are positioned from bottom-left)
let base_x = tile_x as f32 * tile_size;
let base_y = tile_y as f32 * tile_size;
let z = 101.0 + layer_idx as f32 * 0.01; // Just above grid (100.0)
match shape {
bevy_map_core::CollisionShape::None => {}
bevy_map_core::CollisionShape::Full => {
// Full tile collision - single sprite covering the tile
let entity = commands
.spawn((
Sprite {
color,
custom_size: Some(Vec2::new(tile_size, tile_size)),
..default()
},
Transform::from_xyz(base_x + tile_size / 2.0, base_y + tile_size / 2.0, z),
CollisionOverlay,
))
.id();
cache.entities.push(entity);
}
bevy_map_core::CollisionShape::Rectangle { offset, size } => {
// Rectangle at offset with size (both normalized 0-1)
// Flip Y: editor uses Y-down (top=0), Bevy uses Y-up (bottom=0)
let width = size[0] * tile_size;
let height = size[1] * tile_size;
let center_x = base_x + (offset[0] + size[0] / 2.0) * tile_size;
let center_y = base_y + (1.0 - offset[1] - size[1] / 2.0) * tile_size;
let entity = commands
.spawn((
Sprite {
color,
custom_size: Some(Vec2::new(width, height)),
..default()
},
Transform::from_xyz(center_x, center_y, z),
CollisionOverlay,
))
.id();
cache.entities.push(entity);
}
bevy_map_core::CollisionShape::Circle { offset, radius } => {
// Circle - approximate with a square sprite for now
// Could use a circle texture or shader in the future
// Flip Y: editor uses Y-down (top=0), Bevy uses Y-up (bottom=0)
let diameter = radius * 2.0 * tile_size;
let center_x = base_x + offset[0] * tile_size;
let center_y = base_y + (1.0 - offset[1]) * tile_size;
let entity = commands
.spawn((
Sprite {
color,
custom_size: Some(Vec2::new(diameter, diameter)),
..default()
},
Transform::from_xyz(center_x, center_y, z),
CollisionOverlay,
))
.id();
cache.entities.push(entity);
}
bevy_map_core::CollisionShape::Polygon { points } => {
// Polygon - draw lines connecting vertices
if points.len() < 2 {
return;
}
let line_thickness = 2.0;
let line_color = Color::srgba(0.0, 0.6, 1.0, 0.6); // Slightly more opaque for lines
for i in 0..points.len() {
let p1 = &points[i];
let p2 = &points[(i + 1) % points.len()];
// Convert normalized coords to world coords
// Flip Y: editor uses Y-down (top=0), Bevy uses Y-up (bottom=0)
let x1 = base_x + p1[0] * tile_size;
let y1 = base_y + (1.0 - p1[1]) * tile_size;
let x2 = base_x + p2[0] * tile_size;
let y2 = base_y + (1.0 - p2[1]) * tile_size;
// Calculate line center, length, and angle
let center_x = (x1 + x2) / 2.0;
let center_y = (y1 + y2) / 2.0;
let dx = x2 - x1;
let dy = y2 - y1;
let length = (dx * dx + dy * dy).sqrt();
let angle = dy.atan2(dx);
let entity = commands
.spawn((
Sprite {
color: line_color,
custom_size: Some(Vec2::new(length, line_thickness)),
..default()
},
Transform::from_xyz(center_x, center_y, z)
.with_rotation(Quat::from_rotation_z(angle)),
CollisionOverlay,
))
.id();
cache.entities.push(entity);
}
}
}
}
/// System to update camera based on editor state
fn update_camera_from_editor_state(
editor_state: Res<EditorState>,
mut camera_query: Query<&mut Transform, With<Camera2d>>,
mut projection_query: Query<&mut Projection, With<Camera2d>>,
) {
// Update camera position
for mut transform in camera_query.iter_mut() {
transform.translation.x = editor_state.camera_offset.x;
transform.translation.y = editor_state.camera_offset.y;
}
// Update zoom via projection
for mut projection in projection_query.iter_mut() {
if let Projection::Orthographic(ref mut ortho) = *projection {
ortho.scale = 1.0 / editor_state.zoom;
}
}
}
/// System to render the selection rectangle preview
fn sync_selection_preview(
mut commands: Commands,
editor_state: Res<EditorState>,
input_state: Option<Res<ViewportInputState>>,
project: Res<Project>,
existing_preview: Query<Entity, With<SelectionPreview>>,
) {
// Always despawn existing preview first
for entity in existing_preview.iter() {
let _ = commands.get_entity(entity).map(|mut e| e.despawn());
}
// If ViewportInputState doesn't exist, skip
let Some(input_state) = input_state else {
return;
};
// Only show preview when actively drawing in Rectangle mode
let is_rectangle_mode =
editor_state.tool_mode == ToolMode::Rectangle && editor_state.current_tool.supports_modes();
if !is_rectangle_mode || !input_state.is_drawing_rect {
return;
}
let Some((start_x, start_y)) = input_state.rect_start_tile else {
return;
};
let Some(current_pos) = input_state.last_world_pos else {
return;
};
// Get tile size
let tile_size = get_tile_size(&editor_state, &project);
// Calculate end tile position
let end_x = (current_pos.x / tile_size).floor() as i32;
let end_y = (current_pos.y / tile_size).floor() as i32;
// Normalize bounds
let min_x = start_x.min(end_x);
let max_x = start_x.max(end_x);
let min_y = start_y.min(end_y);
let max_y = start_y.max(end_y);
// Calculate world coordinates for the rectangle
let world_min_x = min_x as f32 * tile_size;
let world_max_x = (max_x + 1) as f32 * tile_size;
let world_min_y = min_y as f32 * tile_size;
let world_max_y = (max_y + 1) as f32 * tile_size;
let width = world_max_x - world_min_x;
let height = world_max_y - world_min_y;
let center_x = world_min_x + width / 2.0;
let center_y = world_min_y + height / 2.0;
// Choose color based on whether we're filling or erasing
let color = if editor_state.selected_tile.is_some() {
Color::srgba(0.2, 0.4, 0.8, 0.4) // Blue for fill
} else {
Color::srgba(0.8, 0.2, 0.2, 0.4) // Red for erase
};
// Spawn the preview rectangle
commands.spawn((
Sprite {
color,
custom_size: Some(Vec2::new(width, height)),
..default()
},
Transform::from_xyz(center_x, center_y, 200.0), // High Z to render on top
SelectionPreview,
));
}
/// Get the tile size for the current level/layer/tileset (for preview rendering)
fn get_tile_size(editor_state: &EditorState, project: &Project) -> f32 {
let level_id = editor_state.selected_level;
let layer_idx = editor_state.selected_layer;
// Use O(1) lookup for level
let level = level_id.and_then(|id| project.get_level(id));
let layer_tileset_id = level.and_then(|l| {
layer_idx
.and_then(|idx| l.layers.get(idx))
.and_then(|layer| {
if let LayerData::Tiles { tileset_id, .. } = &layer.data {
Some(*tileset_id)
} else {
None
}
})
});
// Use O(1) lookup for tileset
layer_tileset_id
.or(editor_state.selected_tileset)
.and_then(|id| project.get_tileset(id))
.map(|t| t.tile_size as f32)
.unwrap_or(32.0)
}
/// Resource tracking the current selection highlight state for change detection
#[derive(Resource, Default)]
pub struct SelectionRenderState {
/// Set of currently highlighted tiles (level_id, layer_idx, x, y)
pub highlighted_tiles: std::collections::HashSet<(Uuid, usize, u32, u32)>,
/// 4 border entities for the bounding rectangle (top, right, bottom, left)
pub border_entities: Option<[Entity; 4]>,
/// Current move offset being applied to highlights
pub current_move_offset: Option<(i32, i32)>,
/// Cached bounding box (min_x, max_x, min_y, max_y) in tile coordinates
pub cached_bounds: Option<(i32, i32, i32, i32)>,
}
/// Resource for caching terrain preview entities to avoid respawning every frame
#[derive(Resource, Default)]
pub struct TerrainPreviewCache {
/// Current preview tiles being displayed: (x, y) -> tile_id
pub current_tiles: HashMap<(i32, i32), u32>,
/// Entities for each preview tile (position -> list of entities for tile+highlight+borders)
pub tile_entities: HashMap<(i32, i32), Vec<Entity>>,
/// Whether preview was active last frame
pub was_active: bool,
}
/// Resource for caching brush preview entities
#[derive(Resource, Default)]
pub struct BrushPreviewCache {
/// Sprite entity for the preview tile
pub sprite_entity: Option<Entity>,
/// Border entities for the preview
pub border_entities: Vec<Entity>,
/// Last rendered position
pub last_position: Option<(i32, i32)>,
/// Last rendered tile
pub last_tile: Option<u32>,
/// Last tileset
pub last_tileset: Option<Uuid>,
}
/// Marker component for brush preview sprites
#[derive(Component)]
pub struct BrushPreviewSprite;
/// Marker component for tile selection highlight sprites
#[derive(Component)]
pub struct TileSelectionHighlight;
/// System to render tile selection highlights with a calm bounding box outline
fn sync_tile_selection_highlights(
mut commands: Commands,
editor_state: Res<EditorState>,
project: Res<Project>,
mut selection_state: ResMut<SelectionRenderState>,
time: Res<Time>,
mut sprite_query: Query<(&mut Sprite, &mut Transform), With<TileSelectionHighlight>>,
) {
let current_selection = &editor_state.tile_selection.tiles;
// Helper to clear all highlight entities
let clear_highlights = |commands: &mut Commands, state: &mut SelectionRenderState| {
if let Some(entities) = state.border_entities.take() {
for entity in entities {
let _ = commands.get_entity(entity).map(|mut e| e.despawn());
}
}
state.highlighted_tiles.clear();
state.current_move_offset = None;
state.cached_bounds = None;
};
// Hide tile selection when Entity tool is active (tile selection is irrelevant for entities)
if editor_state.current_tool == EditorTool::Entity {
clear_highlights(&mut commands, &mut selection_state);
return;
}
// If no tile selection, clear any existing highlights and return early
if current_selection.is_empty() {
clear_highlights(&mut commands, &mut selection_state);
return;
}
let tile_size = get_tile_size(&editor_state, &project);
let current_offset = editor_state.tile_move_offset;
let (offset_x, offset_y) = current_offset.unwrap_or((0, 0));
let elapsed_time = time.elapsed_secs();
// Calm cyan animation - slow alpha pulse (2 second cycle)
let alpha = 0.85 + 0.15 * (elapsed_time * std::f32::consts::PI).sin();
let color = Color::srgba(0.0, 0.8, 1.0, alpha);
// Calculate bounding box of all selected tiles
let mut min_x = i32::MAX;
let mut max_x = i32::MIN;
let mut min_y = i32::MAX;
let mut max_y = i32::MIN;
for (level_id, _, x, y) in current_selection.iter() {
// Only consider tiles from the currently selected level
if Some(*level_id) != editor_state.selected_level {
continue;
}
min_x = min_x.min(*x as i32);
max_x = max_x.max(*x as i32);
min_y = min_y.min(*y as i32);
max_y = max_y.max(*y as i32);
}
// If no valid tiles found for current level, clear highlights
if min_x == i32::MAX {
clear_highlights(&mut commands, &mut selection_state);
return;
}
let new_bounds = (min_x, max_x, min_y, max_y);
let bounds_changed = selection_state.cached_bounds != Some(new_bounds);
let offset_changed = selection_state.current_move_offset != current_offset;
// Update colors on all existing sprites for animation
for (mut sprite, _) in sprite_query.iter_mut() {
sprite.color = color;
}
// If bounds or offset changed, we need to update or recreate the border sprites
if bounds_changed || offset_changed {
// Calculate world coordinates for bounding box (apply move offset)
let world_min_x = (min_x + offset_x) as f32 * tile_size;
let world_max_x = ((max_x + 1) + offset_x) as f32 * tile_size;
let world_min_y = (min_y + offset_y) as f32 * tile_size;
let world_max_y = ((max_y + 1) + offset_y) as f32 * tile_size;
let width = world_max_x - world_min_x;
let height = world_max_y - world_min_y;
let center_x = world_min_x + width / 2.0;
let center_y = world_min_y + height / 2.0;
let border_thickness = 2.0;
if let Some(entities) = &selection_state.border_entities {
// Update existing border positions
// Top border
if let Ok((_, mut transform)) = sprite_query.get_mut(entities[0]) {
transform.translation.x = center_x;
transform.translation.y = world_max_y - border_thickness / 2.0;
}
// Right border
if let Ok((_, mut transform)) = sprite_query.get_mut(entities[1]) {
transform.translation.x = world_max_x - border_thickness / 2.0;
transform.translation.y = center_y;
}
// Bottom border
if let Ok((_, mut transform)) = sprite_query.get_mut(entities[2]) {
transform.translation.x = center_x;
transform.translation.y = world_min_y + border_thickness / 2.0;
}
// Left border
if let Ok((_, mut transform)) = sprite_query.get_mut(entities[3]) {
transform.translation.x = world_min_x + border_thickness / 2.0;
transform.translation.y = center_y;
}
// Also update sizes if bounds changed
if bounds_changed {
if let Ok((mut sprite, _)) = sprite_query.get_mut(entities[0]) {
sprite.custom_size = Some(Vec2::new(width, border_thickness));
}
if let Ok((mut sprite, _)) = sprite_query.get_mut(entities[1]) {
sprite.custom_size = Some(Vec2::new(border_thickness, height));
}
if let Ok((mut sprite, _)) = sprite_query.get_mut(entities[2]) {
sprite.custom_size = Some(Vec2::new(width, border_thickness));
}
if let Ok((mut sprite, _)) = sprite_query.get_mut(entities[3]) {
sprite.custom_size = Some(Vec2::new(border_thickness, height));
}
}
} else {
// Create new border sprites (4 total for the entire bounding box)
let top = commands
.spawn((
Sprite {
color,
custom_size: Some(Vec2::new(width, border_thickness)),
..default()
},
Transform::from_xyz(center_x, world_max_y - border_thickness / 2.0, 150.0),
TileSelectionHighlight,
))
.id();
let right = commands
.spawn((
Sprite {
color,
custom_size: Some(Vec2::new(border_thickness, height)),
..default()
},
Transform::from_xyz(world_max_x - border_thickness / 2.0, center_y, 150.0),
TileSelectionHighlight,
))
.id();
let bottom = commands
.spawn((
Sprite {
color,
custom_size: Some(Vec2::new(width, border_thickness)),
..default()
},
Transform::from_xyz(center_x, world_min_y + border_thickness / 2.0, 150.0),
TileSelectionHighlight,
))
.id();
let left = commands
.spawn((
Sprite {
color,
custom_size: Some(Vec2::new(border_thickness, height)),
..default()
},
Transform::from_xyz(world_min_x + border_thickness / 2.0, center_y, 150.0),
TileSelectionHighlight,
))
.id();
selection_state.border_entities = Some([top, right, bottom, left]);
}
selection_state.cached_bounds = Some(new_bounds);
selection_state.current_move_offset = current_offset;
}
// Update tracked tile set
selection_state.highlighted_tiles = current_selection.clone();
}
/// Mark the viewport as needing a rebuild when tiles change
pub fn mark_viewport_dirty(render_state: &mut RenderState) {
render_state.mark_dirty();
}
/// Marker component for terrain preview highlight sprites
#[derive(Component)]
pub struct TerrainPreviewHighlight;
/// System to render terrain preview highlights (blue overlay showing affected tiles)
/// Uses incremental updates - only spawns/despawns when preview data changes
fn sync_terrain_preview(
mut commands: Commands,
editor_state: Res<EditorState>,
project: Res<Project>,
tileset_cache: Res<TilesetTextureCache>,
mut texture_atlas_layouts: ResMut<Assets<TextureAtlasLayout>>,
mut preview_cache: ResMut<TerrainPreviewCache>,
) {
// Build the new tiles map from editor state
let new_tiles: HashMap<(i32, i32), u32> = if editor_state.terrain_preview.active {
editor_state
.terrain_preview
.preview_tiles
.iter()
.map(|&((x, y), tile_id)| ((x, y), tile_id))
.collect()
} else {
HashMap::new()
};
// Check if anything changed
if new_tiles == preview_cache.current_tiles
&& editor_state.terrain_preview.active == preview_cache.was_active
{
return; // No change, skip all work
}
// Find tiles to remove (in cache but not in new)
let to_remove: Vec<(i32, i32)> = preview_cache
.current_tiles
.keys()
.filter(|pos| !new_tiles.contains_key(pos))
.copied()
.collect();
// Find tiles to add (in new but not in cache, or tile_id changed)
let to_add: Vec<((i32, i32), u32)> = new_tiles
.iter()
.filter(|(pos, tile_id)| preview_cache.current_tiles.get(pos) != Some(tile_id))
.map(|(&pos, &tile_id)| (pos, tile_id))
.collect();
// Remove old entities
for pos in to_remove {
if let Some(entities) = preview_cache.tile_entities.remove(&pos) {
for entity in entities {
let _ = commands.get_entity(entity).map(|mut e| e.despawn());
}
}
preview_cache.current_tiles.remove(&pos);
}
// Get tileset info for spawning new entities (O(1) lookup)
let tileset_info = editor_state
.terrain_preview
.tileset_id
.and_then(|tileset_id| project.get_tileset(tileset_id));
let Some(tileset) = tileset_info else {
// No tileset, clear everything remaining
for (_, entities) in preview_cache.tile_entities.drain() {
for entity in entities {
let _ = commands.get_entity(entity).map(|mut e| e.despawn());
}
}
preview_cache.current_tiles.clear();
preview_cache.was_active = editor_state.terrain_preview.active;
return;
};
let tile_size = tileset.tile_size as f32;
let preview_tile_color = Color::srgba(1.0, 1.0, 1.0, 0.6);
let highlight_color = Color::srgba(0.2, 0.5, 1.0, 0.2);
let border_color = Color::srgba(0.2, 0.5, 1.0, 0.8);
let border_thickness = 2.0;
// Add new entities
for ((x, y), tile_id) in to_add {
// Remove old entities if updating
if let Some(entities) = preview_cache.tile_entities.remove(&(x, y)) {
for entity in entities {
let _ = commands.get_entity(entity).map(|mut e| e.despawn());
}
}
let world_x = x as f32 * tile_size + tile_size / 2.0;
let world_y = y as f32 * tile_size + tile_size / 2.0;
let mut entities = Vec::new();
// Spawn tile sprite
if let Some((image_index, local_tile_index)) = tileset.virtual_to_local(tile_id) {
if let Some(image) = tileset.images.get(image_index) {
if let Some((texture_handle, _, img_width, img_height)) =
tileset_cache.loaded.get(&image.id)
{
let columns = (*img_width as u32) / tileset.tile_size;
let rows = (*img_height as u32) / tileset.tile_size;
if columns > 0 && rows > 0 {
let layout = TextureAtlasLayout::from_grid(
UVec2::new(tileset.tile_size, tileset.tile_size),
columns,
rows,
None,
None,
);
let atlas_layout_handle = texture_atlas_layouts.add(layout);
let entity = commands
.spawn((
Sprite {
color: preview_tile_color,
image: texture_handle.clone(),
texture_atlas: Some(TextureAtlas {
layout: atlas_layout_handle,
index: local_tile_index as usize,
}),
..default()
},
Transform::from_xyz(world_x, world_y, 179.0),
TerrainPreviewHighlight,
))
.id();
entities.push(entity);
}
}
}
}
// Blue highlight overlay
let entity = commands
.spawn((
Sprite {
color: highlight_color,
custom_size: Some(Vec2::new(tile_size, tile_size)),
..default()
},
Transform::from_xyz(world_x, world_y, 180.0),
TerrainPreviewHighlight,
))
.id();
entities.push(entity);
// Top border
let entity = commands
.spawn((
Sprite {
color: border_color,
custom_size: Some(Vec2::new(tile_size, border_thickness)),
..default()
},
Transform::from_xyz(
world_x,
world_y + tile_size / 2.0 - border_thickness / 2.0,
181.0,
),
TerrainPreviewHighlight,
))
.id();
entities.push(entity);
// Bottom border
let entity = commands
.spawn((
Sprite {
color: border_color,
custom_size: Some(Vec2::new(tile_size, border_thickness)),
..default()
},
Transform::from_xyz(
world_x,
world_y - tile_size / 2.0 + border_thickness / 2.0,
181.0,
),
TerrainPreviewHighlight,
))
.id();
entities.push(entity);
// Left border
let entity = commands
.spawn((
Sprite {
color: border_color,
custom_size: Some(Vec2::new(border_thickness, tile_size)),
..default()
},
Transform::from_xyz(
world_x - tile_size / 2.0 + border_thickness / 2.0,
world_y,
181.0,
),
TerrainPreviewHighlight,
))
.id();
entities.push(entity);
// Right border
let entity = commands
.spawn((
Sprite {
color: border_color,
custom_size: Some(Vec2::new(border_thickness, tile_size)),
..default()
},
Transform::from_xyz(
world_x + tile_size / 2.0 - border_thickness / 2.0,
world_y,
181.0,
),
TerrainPreviewHighlight,
))
.id();
entities.push(entity);
// Store in cache
preview_cache.current_tiles.insert((x, y), tile_id);
preview_cache.tile_entities.insert((x, y), entities);
}
preview_cache.was_active = editor_state.terrain_preview.active;
}
/// System to render brush preview when Paint tool is active
fn sync_brush_preview(
mut commands: Commands,
editor_state: Res<EditorState>,
project: Res<Project>,
tileset_cache: Res<TilesetTextureCache>,
mut preview_cache: ResMut<BrushPreviewCache>,
mut texture_atlas_layouts: ResMut<Assets<TextureAtlasLayout>>,
) {
// Helper to clear preview
fn clear_preview(commands: &mut Commands, cache: &mut BrushPreviewCache) {
if let Some(entity) = cache.sprite_entity.take() {
let _ = commands.get_entity(entity).map(|mut e| e.despawn());
}
for entity in cache.border_entities.drain(..) {
let _ = commands.get_entity(entity).map(|mut e| e.despawn());
}
cache.last_position = None;
cache.last_tile = None;
cache.last_tileset = None;
}
// Only show preview when Paint tool is active and not in terrain mode
let show_preview = editor_state.current_tool == EditorTool::Paint
&& !editor_state.terrain_paint_state.is_terrain_mode
&& editor_state.brush_preview.active
&& editor_state.brush_preview.position.is_some()
&& editor_state.selected_tile.is_some()
&& editor_state.selected_tileset.is_some();
if !show_preview {
clear_preview(&mut commands, &mut preview_cache);
return;
}
let position = editor_state.brush_preview.position.unwrap();
let tile_id = editor_state.selected_tile.unwrap();
let tileset_id = editor_state.selected_tileset.unwrap();
// Check if we need to update
let needs_update = preview_cache.last_position != Some(position)
|| preview_cache.last_tile != Some(tile_id)
|| preview_cache.last_tileset != Some(tileset_id);
if !needs_update {
return;
}
// Clear old preview
clear_preview(&mut commands, &mut preview_cache);
// Get tileset (O(1) lookup)
let Some(tileset) = project.get_tileset(tileset_id) else {
return;
};
let tile_size = tileset.tile_size as f32;
let (grid_width, grid_height) = tileset.get_tile_grid_size(tile_id);
let preview_color = Color::srgba(1.0, 1.0, 1.0, 0.6);
let border_color = Color::srgba(0.2, 0.8, 0.2, 0.8); // Green for brush
// Calculate world position using origin (consistent with tile placement)
let total_width = grid_width as f32 * tile_size;
let total_height = grid_height as f32 * tile_size;
let props = tileset
.get_tile_properties(tile_id)
.cloned()
.unwrap_or_default();
let (origin_x, origin_y) = props.get_origin(total_width as u32, total_height as u32);
let world_x = position.0 as f32 * tile_size + origin_x as f32;
let world_y = position.1 as f32 * tile_size + origin_y as f32;
// Spawn tile sprite (try to use texture, fall back to colored rectangle)
let mut sprite_created = false;
if let Some((image_index, local_tile_index)) = tileset.virtual_to_local(tile_id) {
if let Some(image) = tileset.images.get(image_index) {
if let Some((texture_handle, _, img_width, img_height)) =
tileset_cache.loaded.get(&image.id)
{
let columns = (*img_width as u32) / tileset.tile_size;
let rows = (*img_height as u32) / tileset.tile_size;
if columns > 0 && rows > 0 {
if grid_width > 1 || grid_height > 1 {
// Multi-cell tile: use Sprite with rect for the full region
let tile_col = local_tile_index % image.columns;
let tile_row = local_tile_index / image.columns;
let src_x = (tile_col * tileset.tile_size) as f32;
let src_y = (tile_row * tileset.tile_size) as f32;
let src_width = total_width;
let src_height = total_height;
let rect = bevy::math::Rect::new(
src_x,
src_y,
src_x + src_width,
src_y + src_height,
);
let entity = commands
.spawn((
Sprite {
color: preview_color,
image: texture_handle.clone(),
rect: Some(rect),
custom_size: Some(Vec2::new(src_width, src_height)),
..default()
},
Transform::from_xyz(world_x, world_y, 179.0),
BrushPreviewSprite,
))
.id();
preview_cache.sprite_entity = Some(entity);
sprite_created = true;
} else {
// Single tile: use TextureAtlas
let layout = TextureAtlasLayout::from_grid(
UVec2::new(tileset.tile_size, tileset.tile_size),
columns,
rows,
None,
None,
);
let atlas_layout_handle = texture_atlas_layouts.add(layout);
let entity = commands
.spawn((
Sprite {
color: preview_color,
image: texture_handle.clone(),
texture_atlas: Some(TextureAtlas {
layout: atlas_layout_handle,
index: local_tile_index as usize,
}),
..default()
},
Transform::from_xyz(world_x, world_y, 179.0),
BrushPreviewSprite,
))
.id();
preview_cache.sprite_entity = Some(entity);
sprite_created = true;
}
}
}
}
}
// Fallback: show a semi-transparent highlight if texture not available
if !sprite_created {
let highlight_color = Color::srgba(0.2, 0.8, 0.2, 0.3);
let entity = commands
.spawn((
Sprite {
color: highlight_color,
custom_size: Some(Vec2::new(total_width, total_height)),
..default()
},
Transform::from_xyz(world_x, world_y, 179.0),
BrushPreviewSprite,
))
.id();
preview_cache.sprite_entity = Some(entity);
}
// Draw border around preview area
let border_thickness = 2.0;
let half_width = total_width / 2.0;
let half_height = total_height / 2.0;
// Top border
let entity = commands
.spawn((
Sprite {
color: border_color,
custom_size: Some(Vec2::new(total_width, border_thickness)),
..default()
},
Transform::from_xyz(
world_x,
world_y + half_height - border_thickness / 2.0,
181.0,
),
BrushPreviewSprite,
))
.id();
preview_cache.border_entities.push(entity);
// Bottom border
let entity = commands
.spawn((
Sprite {
color: border_color,
custom_size: Some(Vec2::new(total_width, border_thickness)),
..default()
},
Transform::from_xyz(
world_x,
world_y - half_height + border_thickness / 2.0,
181.0,
),
BrushPreviewSprite,
))
.id();
preview_cache.border_entities.push(entity);
// Left border
let entity = commands
.spawn((
Sprite {
color: border_color,
custom_size: Some(Vec2::new(border_thickness, total_height)),
..default()
},
Transform::from_xyz(
world_x - half_width + border_thickness / 2.0,
world_y,
181.0,
),
BrushPreviewSprite,
))
.id();
preview_cache.border_entities.push(entity);
// Right border
let entity = commands
.spawn((
Sprite {
color: border_color,
custom_size: Some(Vec2::new(border_thickness, total_height)),
..default()
},
Transform::from_xyz(
world_x + half_width - border_thickness / 2.0,
world_y,
181.0,
),
BrushPreviewSprite,
))
.id();
preview_cache.border_entities.push(entity);
// Update cache
preview_cache.last_position = Some(position);
preview_cache.last_tile = Some(tile_id);
preview_cache.last_tileset = Some(tileset_id);
}
/// Marker component for entity sprites in the editor
#[derive(Component)]
pub struct EditorEntitySprite {
pub level_id: Uuid,
pub entity_id: Uuid,
}
/// Tracks entity render state
#[derive(Resource, Default)]
pub struct EntityRenderState {
/// Spawned entity sprites: (level_id, entity_id) -> sprite entity
pub entity_sprites: HashMap<(Uuid, Uuid), Entity>,
/// Selection highlight entity (if any)
pub selection_highlight: Option<Entity>,
/// Last rendered level for change detection (despawn on level change only)
pub last_level: Option<Uuid>,
/// Last rendered layer for visibility toggle (no despawn needed)
pub last_layer: Option<usize>,
}
/// System to render entities on the canvas as colored rectangles
fn sync_entity_rendering(
mut commands: Commands,
editor_state: Res<EditorState>,
project: Res<Project>,
mut entity_render_state: ResMut<EntityRenderState>,
) {
let current_level_id = editor_state.selected_level;
let current_layer_idx = editor_state.selected_layer;
// Only despawn all entities when LEVEL changes (not layer)
// Layer changes use visibility toggling for performance
if entity_render_state.last_level != current_level_id {
for (_, sprite_entity) in entity_render_state.entity_sprites.drain() {
let _ = commands.get_entity(sprite_entity).map(|mut e| e.despawn());
}
if let Some(highlight_entity) = entity_render_state.selection_highlight.take() {
let _ = commands
.get_entity(highlight_entity)
.map(|mut e| e.despawn());
}
entity_render_state.last_level = current_level_id;
}
entity_render_state.last_layer = current_layer_idx;
let Some(level_id) = current_level_id else {
return;
};
// Use O(1) lookup
let Some(level) = project.get_level(level_id) else {
return;
};
// Get entity IDs for the selected Object layer (only show entities on the current layer)
let layer_entity_ids: std::collections::HashSet<Uuid> = current_layer_idx
.and_then(|idx| level.layers.get(idx))
.and_then(|layer| match &layer.data {
LayerData::Objects { entities } => Some(entities.iter().copied().collect()),
_ => None,
})
.unwrap_or_default();
// Build set of ALL entity IDs in the level (for existence check)
let all_entity_ids: std::collections::HashSet<_> =
level.entities.iter().map(|e| (level_id, e.id)).collect();
// Remove sprites for entities that no longer exist in the level
let to_remove: Vec<_> = entity_render_state
.entity_sprites
.keys()
.filter(|key| !all_entity_ids.contains(key))
.copied()
.collect();
for key in to_remove {
if let Some(sprite_entity) = entity_render_state.entity_sprites.remove(&key) {
let _ = commands.get_entity(sprite_entity).map(|mut e| e.despawn());
}
}
// Spawn or update sprites for ALL entities in the level
// Toggle visibility based on whether entity is in current layer
for entity in &level.entities {
let key = (level_id, entity.id);
let x = entity.position[0];
let y = entity.position[1];
// Determine visibility: only visible if entity is in current layer
let is_visible = layer_entity_ids.contains(&entity.id);
let visibility = if is_visible {
Visibility::Inherited
} else {
Visibility::Hidden
};
// Get color and marker size from schema type definition
let type_def = project.schema.get_type(&entity.type_name);
let color = type_def
.map(|td| parse_hex_color(&td.color))
.unwrap_or(Color::srgba(0.4, 0.8, 0.4, 0.8)); // Default green
let entity_size = type_def.and_then(|td| td.marker_size).unwrap_or(16) as f32;
if let Some(&sprite_entity) = entity_render_state.entity_sprites.get(&key) {
// Update position, color, and visibility of existing sprite
if let Ok(mut entity_commands) = commands.get_entity(sprite_entity) {
entity_commands.insert((
Transform::from_xyz(x, y, 50.0),
Sprite {
color,
custom_size: Some(Vec2::new(entity_size, entity_size)),
..default()
},
visibility,
));
}
} else {
// Spawn new sprite with visibility
let sprite_entity = commands
.spawn((
Sprite {
color,
custom_size: Some(Vec2::new(entity_size, entity_size)),
..default()
},
Transform::from_xyz(x, y, 50.0),
visibility,
EditorEntitySprite {
level_id,
entity_id: entity.id,
},
))
.id();
entity_render_state
.entity_sprites
.insert(key, sprite_entity);
}
}
// Handle selection highlight
if let Some(highlight_entity) = entity_render_state.selection_highlight.take() {
let _ = commands
.get_entity(highlight_entity)
.map(|mut e| e.despawn());
}
// Draw selection highlight around selected entity
if let Selection::Entity(sel_level_id, sel_entity_id) = &editor_state.selection {
if *sel_level_id == level_id {
if let Some(entity) = level.entities.iter().find(|e| e.id == *sel_entity_id) {
// Get marker size from schema for the selected entity
let sel_entity_size = project
.schema
.get_type(&entity.type_name)
.and_then(|td| td.marker_size)
.unwrap_or(16) as f32;
let highlight_entity = commands
.spawn((
Sprite {
color: Color::srgba(1.0, 1.0, 0.0, 0.5), // Yellow highlight
custom_size: Some(Vec2::new(
sel_entity_size + 8.0,
sel_entity_size + 8.0,
)),
..default()
},
Transform::from_xyz(entity.position[0], entity.position[1], 49.0),
))
.id();
entity_render_state.selection_highlight = Some(highlight_entity);
}
}
}
}
/// Parse a hex color string like "#FF0000" or "FF0000" into Color
fn parse_hex_color(color_str: &str) -> Color {
let hex = color_str.trim_start_matches('#');
if hex.len() >= 6 {
if let (Ok(r), Ok(g), Ok(b)) = (
u8::from_str_radix(&hex[0..2], 16),
u8::from_str_radix(&hex[2..4], 16),
u8::from_str_radix(&hex[4..6], 16),
) {
return Color::srgba(r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0, 0.8);
}
}
// Default fallback color (green)
Color::srgba(0.4, 0.8, 0.4, 0.8)
}