use bevy::prelude::{Component, Resource}; use ldtk_rust::EntityInstance; use num_traits::AsPrimitive; use serde::de::DeserializeOwned; use serde::Serialize; use crate::get_ldtk_tile_scale; pub trait SerdeClone { fn serde_clone(&self) -> Self; } impl<T> SerdeClone for T where T: Serialize + DeserializeOwned, { fn serde_clone(&self) -> Self { serde_json::from_value(serde_json::to_value(&self).unwrap()).unwrap() } } pub fn px_to_grid<T: AsPrimitive<i64>>(t: T) -> i64 { t.as_() / (get_ldtk_tile_scale() as i64) } pub fn grid_to_px<T: AsPrimitive<f32>>(t: T) -> f32 { t.as_() * get_ldtk_tile_scale() } pub fn entity_to_worldspace(level_height: i64, entity: &EntityInstance) -> (f32, f32) { let centre_align_pixel_x = grid_to_px(entity.grid[0]) - (get_ldtk_tile_scale() / 2.0); let centre_align_pixel_y = grid_to_px(entity.grid[1]) - (get_ldtk_tile_scale() / 2.0); let inverted_pixel_y = level_height as f32 - centre_align_pixel_y - get_ldtk_tile_scale(); let box_aligned_x = centre_align_pixel_x + (entity.width / 2) as f32; let box_aligned_y = inverted_pixel_y - (entity.height / 2) as f32; (box_aligned_x, box_aligned_y) } pub fn entity_centre(level_height: i64, entity: &EntityInstance) -> (f32, f32) { let x = entity.px[0] - (entity.width / 2); let y = (level_height - entity.px[1] - entity.height / 2); (x as f32, y as f32) } #[derive(Component)] pub struct WorldLinked; #[derive(Default, Resource, Clone)] pub struct ActiveLevel { pub map: String, pub dirty: bool, } impl ActiveLevel { pub fn new<T: ToString>(map: T) -> Self { ActiveLevel { map: map.to_string(), dirty: false, } } } #[derive(Debug, Copy, Clone)] pub struct Indexer { width: isize, height: isize, } impl Indexer { pub fn new(width: impl AsPrimitive<isize>, height: impl AsPrimitive<isize>) -> Self { Self { width: width.as_(), height: height.as_(), } } pub fn index(&self, x: impl AsPrimitive<isize>, y: impl AsPrimitive<isize>) -> usize { ((y.as_() * self.width) + x.as_()).as_() } pub fn reverse(&self, index: impl AsPrimitive<isize>) -> (usize, usize) { ( (index.as_() % self.width) as usize, (index.as_() / self.width) as usize, ) } pub fn width(&self) -> isize { self.width } pub fn height(&self) -> isize { self.height } }