forked from StarArawn/bevy_ecs_tilemap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tiled.rs
382 lines (335 loc) · 16.1 KB
/
tiled.rs
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
// How to use this:
// You should copy/paste this into your project and use it much like examples/tiles.rs uses this
// file. When you do so you will need to adjust the code based on whether you're using the
// 'atlas` feature in bevy_ecs_tilemap. The bevy_ecs_tilemap uses this as an example of how to
// use both single image tilesets and image collection tilesets. Since your project won't have
// the 'atlas' feature defined in your Cargo config, the expressions prefixed by the #[cfg(...)]
// macro will not compile in your project as-is. If your project depends on the bevy_ecs_tilemap
// 'atlas' feature then move all of the expressions prefixed by #[cfg(not(feature = "atlas"))].
// Otherwise remove all of the expressions prefixed by #[cfg(feature = "atlas")].
//
// Functional limitations:
// * When the 'atlas' feature is enabled tilesets using a collection of images will be skipped.
// * Only finite tile layers are loaded. Infinite tile layers and object layers will be skipped.
use std::io::Cursor;
use std::path::Path;
use std::sync::Arc;
use bevy::{
asset::{AssetLoader, AssetPath, LoadedAsset},
log,
prelude::{
AddAsset, Added, AssetEvent, Assets, Bundle, Commands, Component, DespawnRecursiveExt,
Entity, EventReader, GlobalTransform, Handle, Image, Plugin, Query, Res, Transform,
},
reflect::TypeUuid,
utils::HashMap,
};
use bevy_ecs_tilemap::prelude::*;
use anyhow::Result;
#[derive(Default)]
pub struct TiledMapPlugin;
impl Plugin for TiledMapPlugin {
fn build(&self, app: &mut bevy::prelude::App) {
app.add_asset::<TiledMap>()
.add_asset_loader(TiledLoader)
.add_system(process_loaded_maps);
}
}
#[derive(TypeUuid)]
#[uuid = "e51081d0-6168-4881-a1c6-4249b2000d7f"]
pub struct TiledMap {
pub map: tiled::Map,
pub tilemap_textures: HashMap<usize, TilemapTexture>,
// The offset into the tileset_images for each tile id within each tileset.
#[cfg(not(feature = "atlas"))]
pub tile_image_offsets: HashMap<(usize, tiled::TileId), u32>,
}
// Stores a list of tiled layers.
#[derive(Component, Default)]
pub struct TiledLayersStorage {
pub storage: HashMap<u32, Entity>,
}
#[derive(Default, Bundle)]
pub struct TiledMapBundle {
pub tiled_map: Handle<TiledMap>,
pub storage: TiledLayersStorage,
pub transform: Transform,
pub global_transform: GlobalTransform,
}
struct BytesResourceReader {
bytes: Arc<[u8]>,
}
impl BytesResourceReader {
fn new(bytes: &[u8]) -> Self {
Self {
bytes: Arc::from(bytes),
}
}
}
impl tiled::ResourceReader for BytesResourceReader {
type Resource = Cursor<Arc<[u8]>>;
type Error = std::io::Error;
fn read_from(&mut self, _path: &Path) -> std::result::Result<Self::Resource, Self::Error> {
// In this case, the path is ignored because the byte data is already provided.
Ok(Cursor::new(self.bytes.clone()))
}
}
pub struct TiledLoader;
impl AssetLoader for TiledLoader {
fn load<'a>(
&'a self,
bytes: &'a [u8],
load_context: &'a mut bevy::asset::LoadContext,
) -> bevy::asset::BoxedFuture<'a, Result<()>> {
Box::pin(async move {
// The load context path is the TMX file itself. If the file is at the root of the
// assets/ directory structure then the tmx_dir will be empty, which is fine.
let tmx_dir = load_context
.path()
.parent()
.expect("The asset load context was empty.");
let mut loader = tiled::Loader::with_cache_and_reader(
tiled::DefaultResourceCache::new(),
BytesResourceReader::new(bytes),
);
let map = loader
.load_tmx_map(load_context.path())
.map_err(|e| anyhow::anyhow!("Could not load TMX map: {e}"))?;
let mut dependencies = Vec::new();
let mut tilemap_textures = HashMap::default();
#[cfg(not(feature = "atlas"))]
let mut tile_image_offsets = HashMap::default();
for (tileset_index, tileset) in map.tilesets().iter().enumerate() {
let tilemap_texture = match &tileset.image {
None => {
#[cfg(feature = "atlas")]
{
log::info!("Skipping image collection tileset '{}' which is incompatible with atlas feature", tileset.name);
continue;
}
#[cfg(not(feature = "atlas"))]
{
let mut tile_images: Vec<Handle<Image>> = Vec::new();
for (tile_id, tile) in tileset.tiles() {
if let Some(img) = &tile.image {
let tile_path = tmx_dir.join(&img.source);
let asset_path = AssetPath::new(tile_path, None);
log::info!("Loading tile image from {asset_path:?} as image ({tileset_index}, {tile_id})");
let texture: Handle<Image> =
load_context.get_handle(asset_path.clone());
tile_image_offsets
.insert((tileset_index, tile_id), tile_images.len() as u32);
tile_images.push(texture.clone());
dependencies.push(asset_path);
}
}
TilemapTexture::Vector(tile_images)
}
}
Some(img) => {
let tile_path = tmx_dir.join(&img.source);
let asset_path = AssetPath::new(tile_path, None);
let texture: Handle<Image> = load_context.get_handle(asset_path.clone());
dependencies.push(asset_path);
TilemapTexture::Single(texture.clone())
}
};
tilemap_textures.insert(tileset_index, tilemap_texture);
}
let asset_map = TiledMap {
map,
tilemap_textures,
#[cfg(not(feature = "atlas"))]
tile_image_offsets,
};
log::info!("Loaded map: {}", load_context.path().display());
let loaded_asset = LoadedAsset::new(asset_map);
load_context.set_default_asset(loaded_asset.with_dependencies(dependencies));
Ok(())
})
}
fn extensions(&self) -> &[&str] {
static EXTENSIONS: &[&str] = &["tmx"];
EXTENSIONS
}
}
pub fn process_loaded_maps(
mut commands: Commands,
mut map_events: EventReader<AssetEvent<TiledMap>>,
maps: Res<Assets<TiledMap>>,
tile_storage_query: Query<(Entity, &TileStorage)>,
mut map_query: Query<(&Handle<TiledMap>, &mut TiledLayersStorage)>,
new_maps: Query<&Handle<TiledMap>, Added<Handle<TiledMap>>>,
) {
let mut changed_maps = Vec::<Handle<TiledMap>>::default();
for event in map_events.iter() {
match event {
AssetEvent::Created { handle } => {
log::info!("Map added!");
changed_maps.push(handle.clone());
}
AssetEvent::Modified { handle } => {
log::info!("Map changed!");
changed_maps.push(handle.clone());
}
AssetEvent::Removed { handle } => {
log::info!("Map removed!");
// if mesh was modified and removed in the same update, ignore the modification
// events are ordered so future modification events are ok
changed_maps.retain(|changed_handle| changed_handle == handle);
}
}
}
// If we have new map entities add them to the changed_maps list.
for new_map_handle in new_maps.iter() {
changed_maps.push(new_map_handle.clone_weak());
}
for changed_map in changed_maps.iter() {
for (map_handle, mut layer_storage) in map_query.iter_mut() {
// only deal with currently changed map
if map_handle != changed_map {
continue;
}
if let Some(tiled_map) = maps.get(map_handle) {
// TODO: Create a RemoveMap component..
for layer_entity in layer_storage.storage.values() {
if let Ok((_, layer_tile_storage)) = tile_storage_query.get(*layer_entity) {
for tile in layer_tile_storage.iter().flatten() {
commands.entity(*tile).despawn_recursive()
}
}
// commands.entity(*layer_entity).despawn_recursive();
}
// The TilemapBundle requires that all tile images come exclusively from a single
// tiled texture or from a Vec of independent per-tile images. Furthermore, all of
// the per-tile images must be the same size. Since Tiled allows tiles of mixed
// tilesets on each layer and allows differently-sized tile images in each tileset,
// this means we need to load each combination of tileset and layer separately.
for (tileset_index, tileset) in tiled_map.map.tilesets().iter().enumerate() {
let Some(tilemap_texture) = tiled_map
.tilemap_textures
.get(&tileset_index) else {
log::warn!("Skipped creating layer with missing tilemap textures.");
continue;
};
let tile_size = TilemapTileSize {
x: tileset.tile_width as f32,
y: tileset.tile_height as f32,
};
let tile_spacing = TilemapSpacing {
x: tileset.spacing as f32,
y: tileset.spacing as f32,
};
// Once materials have been created/added we need to then create the layers.
for (layer_index, layer) in tiled_map.map.layers().enumerate() {
let offset_x = layer.offset_x;
let offset_y = layer.offset_y;
let tiled::LayerType::Tiles(tile_layer) = layer.layer_type() else {
log::info!(
"Skipping layer {} because only tile layers are supported.",
layer.id()
);
continue;
};
let tiled::TileLayer::Finite(layer_data) = tile_layer else {
log::info!(
"Skipping layer {} because only finite layers are supported.",
layer.id()
);
continue;
};
let map_size = TilemapSize {
x: tiled_map.map.width,
y: tiled_map.map.height,
};
let grid_size = TilemapGridSize {
x: tiled_map.map.tile_width as f32,
y: tiled_map.map.tile_height as f32,
};
let map_type = match tiled_map.map.orientation {
tiled::Orientation::Hexagonal => {
TilemapType::Hexagon(HexCoordSystem::Row)
}
tiled::Orientation::Isometric => {
TilemapType::Isometric(IsoCoordSystem::Diamond)
}
tiled::Orientation::Staggered => {
TilemapType::Isometric(IsoCoordSystem::Staggered)
}
tiled::Orientation::Orthogonal => TilemapType::Square,
};
let mut tile_storage = TileStorage::empty(map_size);
let layer_entity = commands.spawn_empty().id();
for x in 0..map_size.x {
for y in 0..map_size.y {
// Transform TMX coords into bevy coords.
let mapped_y = tiled_map.map.height - 1 - y;
let mapped_x = x as i32;
let mapped_y = mapped_y as i32;
let layer_tile = match layer_data.get_tile(mapped_x, mapped_y) {
Some(t) => t,
None => {
continue;
}
};
if tileset_index != layer_tile.tileset_index() {
continue;
}
let layer_tile_data =
match layer_data.get_tile_data(mapped_x, mapped_y) {
Some(d) => d,
None => {
continue;
}
};
let texture_index = match tilemap_texture {
TilemapTexture::Single(_) => layer_tile.id(),
#[cfg(not(feature = "atlas"))]
TilemapTexture::Vector(_) =>
*tiled_map.tile_image_offsets.get(&(tileset_index, layer_tile.id()))
.expect("The offset into to image vector should have been saved during the initial load."),
#[cfg(not(feature = "atlas"))]
_ => unreachable!()
};
let tile_pos = TilePos { x, y };
let tile_entity = commands
.spawn(TileBundle {
position: tile_pos,
tilemap_id: TilemapId(layer_entity),
texture_index: TileTextureIndex(texture_index),
flip: TileFlip {
x: layer_tile_data.flip_h,
y: layer_tile_data.flip_v,
d: layer_tile_data.flip_d,
},
..Default::default()
})
.id();
tile_storage.set(&tile_pos, tile_entity);
}
}
commands.entity(layer_entity).insert(TilemapBundle {
grid_size,
size: map_size,
storage: tile_storage,
texture: tilemap_texture.clone(),
tile_size,
spacing: tile_spacing,
transform: get_tilemap_center_transform(
&map_size,
&grid_size,
&map_type,
layer_index as f32,
) * Transform::from_xyz(offset_x, -offset_y, 0.0),
map_type,
..Default::default()
});
layer_storage
.storage
.insert(layer_index as u32, layer_entity);
}
}
}
}
}
}