Skip to content
Snippets Groups Projects
Verified Commit 06a94039 authored by Louis's avatar Louis :fire:
Browse files

Make Bevy optional

parent 0d2b6cc1
No related branches found
No related tags found
No related merge requests found
This diff is collapsed.
[package] [package]
name = "micro_ldtk" name = "micro_ldtk"
version = "0.11.0" version = "0.12.0"
edition = "2021" edition = "2021"
authors = [ authors = [
...@@ -27,21 +27,22 @@ ldtk_1_1_2 = ["_supports_ldtk"] ...@@ -27,21 +27,22 @@ ldtk_1_1_2 = ["_supports_ldtk"]
ldtk_1_1_1 = ["_supports_ldtk"] ldtk_1_1_1 = ["_supports_ldtk"]
ldtk_1_1_0 = ["_supports_ldtk"] ldtk_1_1_0 = ["_supports_ldtk"]
ldtk_1_0_0 = ["_supports_ldtk"] ldtk_1_0_0 = ["_supports_ldtk"]
autotile = ["micro_autotile"] autotile = ["dep:micro_autotile"]
bevy = ["dep:bevy"]
_supports_intgridgroup = [] _supports_intgridgroup = []
_supports_ldtk = [] _supports_ldtk = []
_optional_tile_list = [] _optional_tile_list = []
no_panic = [] no_panic = []
[dependencies] [dependencies]
bevy = { version = "0.14", default-features = false, features = ["bevy_render", "bevy_sprite", "bevy_asset", "serialize"] } bevy = { optional = true, version = "0.14", default-features = false, features = ["bevy_render", "bevy_sprite", "bevy_asset", "serialize"] }
anyhow = "1.0" anyhow = "1.0"
thiserror = "1.0" thiserror = "2.0"
log = "0.4" log = "0.4"
serde = "1.0" serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0" serde_json = "1.0"
num-traits = "0.2" num-traits = "0.2"
quadtree_rs = "0.1" quadtree_rs = "0.1"
micro_autotile = { version = "0.1", optional = true } micro_autotile = { version = "0.2", optional = true }
...@@ -19,10 +19,6 @@ mod data_1_4_0; ...@@ -19,10 +19,6 @@ mod data_1_4_0;
#[cfg(any(feature = "ldtk_1_5_3"))] #[cfg(any(feature = "ldtk_1_5_3"))]
mod data_1_5_3; mod data_1_5_3;
use bevy::asset::io::Reader;
use bevy::asset::{AssetLoader, AsyncReadExt, LoadContext, UntypedAssetId, VisitAssetDependencies};
use bevy::prelude::{Asset, Handle};
use bevy::reflect::TypePath;
use crate::ldtk; use crate::ldtk;
#[cfg(feature = "ldtk_1_0_0")] #[cfg(feature = "ldtk_1_0_0")]
...@@ -89,37 +85,134 @@ impl<'a> LdtkFromBytes<'a> for Project {} ...@@ -89,37 +85,134 @@ impl<'a> LdtkFromBytes<'a> for Project {}
impl_from_bytes!(Level); impl_from_bytes!(Level);
impl_from_bytes!(Project); impl_from_bytes!(Project);
impl TypePath for Project { #[cfg(feature = "bevy")]
fn type_path() -> &'static str { mod _bevy_impl {
"micro_ldtk::ldtk::Project" use super::*;
use bevy::asset::io::Reader;
use bevy::asset::{AssetLoader, AsyncReadExt, LoadContext, UntypedAssetId, VisitAssetDependencies};
use bevy::prelude::{Asset, Handle};
use bevy::reflect::TypePath;
impl TypePath for Project {
fn type_path() -> &'static str {
"micro_ldtk::ldtk::Project"
}
fn short_type_path() -> &'static str {
"Project"
}
} }
fn short_type_path() -> &'static str { impl VisitAssetDependencies for Project {
"Project" fn visit_dependencies(&self, _visit: &mut impl FnMut(UntypedAssetId)) {}
} }
}
impl VisitAssetDependencies for Project { impl Asset for Project {}
fn visit_dependencies(&self, _visit: &mut impl FnMut(UntypedAssetId)) {}
}
impl Asset for Project {} impl TypePath for Level {
fn type_path() -> &'static str {
"micro_ld0tk::ldtk::Level"
}
impl TypePath for Level { fn short_type_path() -> &'static str {
fn type_path() -> &'static str { "Level"
"micro_ld0tk::ldtk::Level" }
} }
fn short_type_path() -> &'static str { impl VisitAssetDependencies for Level {
"Level" fn visit_dependencies(&self, _visit: &mut impl FnMut(UntypedAssetId)) {}
} }
}
impl VisitAssetDependencies for Level { impl Asset for Level {}
fn visit_dependencies(&self, _visit: &mut impl FnMut(UntypedAssetId)) {}
#[derive(Asset, TypePath)]
pub struct LevelSet(pub Vec<Handle<Level>>);
#[derive(Default)]
pub struct LdtkLoader;
impl AssetLoader for LdtkLoader {
type Asset = Project;
type Settings = ();
type Error = LdtkLoadError;
async fn load<'a>(
&'a self,
reader: &'a mut Reader<'_>,
_settings: &'a Self::Settings,
load_context: &'a mut LoadContext<'_>,
) -> Result<Self::Asset, Self::Error> {
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes).await?;
let project = Project::from_bytes(bytes.as_slice())?;
let levels = project
.levels
.iter()
.flat_map(|level| {
log::debug!(
"Checking if level is external: {} [{}]",
level.identifier,
level.external_rel_path.is_some()
);
level
.external_rel_path
.as_ref()
.map(|path| (level.identifier.clone(), path))
})
.collect::<Vec<(String, &String)>>();
let parent_path = load_context.path().parent().map(|pp| pp.to_path_buf());
let mut level_set = Vec::with_capacity(levels.len());
for (_, path) in levels {
level_set.push(match &parent_path {
Some(parent) => load_context.load::<Level>(parent.join(path)),
None => load_context.load::<Level>(path),
});
}
load_context.add_labeled_asset(
format!("{}ExternalLevels", project.iid),
LevelSet(level_set),
);
Ok(project)
}
fn extensions(&self) -> &[&str] {
&["ldtk"]
}
}
#[derive(Default)]
pub struct LdtkLevelLoader;
impl AssetLoader for LdtkLevelLoader {
type Asset = Level;
type Settings = ();
type Error = LdtkLoadError;
async fn load<'a>(
&'a self,
reader: &'a mut Reader<'_>,
_settings: &'a Self::Settings,
_load_context: &'a mut LoadContext<'_>,
) -> Result<Self::Asset, Self::Error> {
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes).await?;
let level = Level::from_bytes(bytes.as_slice())?;
Ok(level)
}
fn extensions(&self) -> &[&str] {
&["ldtkl"]
}
}
} }
impl Asset for Level {} #[cfg(feature = "bevy")]
pub use _bevy_impl::{LdtkLoader, LdtkLevelLoader, LevelSet};
impl Project { impl Project {
pub fn get_all_levels(&self) -> Vec<&Level> { pub fn get_all_levels(&self) -> Vec<&Level> {
...@@ -173,88 +266,6 @@ pub enum LdtkLoadError { ...@@ -173,88 +266,6 @@ pub enum LdtkLoadError {
pub type LdtkProject = Project; pub type LdtkProject = Project;
#[derive(Asset, TypePath)]
pub(crate) struct LevelSet(pub Vec<Handle<Level>>);
#[derive(Default)]
pub struct LdtkLoader;
impl AssetLoader for LdtkLoader {
type Asset = Project;
type Settings = ();
type Error = LdtkLoadError;
async fn load<'a>(
&'a self,
reader: &'a mut Reader<'_>,
_settings: &'a Self::Settings,
load_context: &'a mut LoadContext<'_>,
) -> Result<Self::Asset, Self::Error> {
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes).await?;
let project = Project::from_bytes(bytes.as_slice())?;
let levels = project
.levels
.iter()
.flat_map(|level| {
log::debug!(
"Checking if level is external: {} [{}]",
level.identifier,
level.external_rel_path.is_some()
);
level
.external_rel_path
.as_ref()
.map(|path| (level.identifier.clone(), path))
})
.collect::<Vec<(String, &String)>>();
let parent_path = load_context.path().parent().map(|pp| pp.to_path_buf());
let mut level_set = Vec::with_capacity(levels.len());
for (_, path) in levels {
level_set.push(match &parent_path {
Some(parent) => load_context.load::<Level>(parent.join(path)),
None => load_context.load::<Level>(path),
});
}
load_context.add_labeled_asset(
format!("{}ExternalLevels", project.iid),
LevelSet(level_set),
);
Ok(project)
}
fn extensions(&self) -> &[&str] {
&["ldtk"]
}
}
#[derive(Default)]
pub struct LdtkLevelLoader;
impl AssetLoader for LdtkLevelLoader {
type Asset = Level;
type Settings = ();
type Error = LdtkLoadError;
async fn load<'a>(
&'a self,
reader: &'a mut Reader<'_>,
_settings: &'a Self::Settings,
_load_context: &'a mut LoadContext<'_>,
) -> Result<Self::Asset, Self::Error> {
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes).await?;
let level = Level::from_bytes(bytes.as_slice())?;
Ok(level)
}
fn extensions(&self) -> &[&str] {
&["ldtkl"]
}
}
#[cfg(feature = "autotile")] #[cfg(feature = "autotile")]
mod autotile_support { mod autotile_support {
...@@ -268,7 +279,7 @@ mod autotile_support { ...@@ -268,7 +279,7 @@ mod autotile_support {
rule.tile_rects_ids rule.tile_rects_ids
.iter() .iter()
.flatten() .flatten()
.map(|val| *val as usize) .map(|val| *val as i32)
.collect(), .collect(),
) )
} }
...@@ -287,36 +298,21 @@ mod autotile_support { ...@@ -287,36 +298,21 @@ mod autotile_support {
1 => Some(AutoTileRule { 1 => Some(AutoTileRule {
chance: rule.chance as f32, chance: rule.chance as f32,
output: create_output(rule), output: create_output(rule),
matcher: TileMatcher::single_match(TileStatus::from_ldtk_value( matcher: TileMatcher::single(TileStatus::from(
rule.pattern[0], rule.pattern[0],
)), )),
}), }),
3 => { _ => {
if rule.pattern.len() == 9 { TileMatcher::try_from(rule.pattern.as_slice())
let matcher = TileMatcher([ .ok().map(|matcher| {
TileStatus::from_ldtk_value(rule.pattern[0]), AutoTileRule {
TileStatus::from_ldtk_value(rule.pattern[1]),
TileStatus::from_ldtk_value(rule.pattern[2]),
TileStatus::from_ldtk_value(rule.pattern[3]),
TileStatus::from_ldtk_value(rule.pattern[4]),
TileStatus::from_ldtk_value(rule.pattern[5]),
TileStatus::from_ldtk_value(rule.pattern[6]),
TileStatus::from_ldtk_value(rule.pattern[7]),
TileStatus::from_ldtk_value(rule.pattern[8]),
]);
let rule = AutoTileRule {
chance: rule.chance as f32,
matcher, matcher,
output: create_output(rule), chance: rule.chance as f32,
}; output: create_output(rule),
}
})
Some(rule)
} else {
None
}
} }
_ => None,
}) })
.collect(); .collect();
......
#[cfg(feature = "_supports_ldtk")] #[cfg(all(feature = "_supports_ldtk", feature = "bevy"))]
mod assets; mod assets;
#[cfg(feature = "bevy")]
mod camera; mod camera;
#[cfg(feature = "bevy")]
mod map_query; mod map_query;
#[cfg(feature = "bevy")]
mod pregen; mod pregen;
mod system; mod system;
...@@ -23,6 +26,7 @@ pub fn set_ldtk_tile_scale_f32(scale: f32) { ...@@ -23,6 +26,7 @@ pub fn set_ldtk_tile_scale_f32(scale: f32) {
} }
} }
#[cfg(feature = "bevy")]
mod __plugin { mod __plugin {
use bevy::ecs::query::QueryFilter; use bevy::ecs::query::QueryFilter;
use std::marker::PhantomData; use std::marker::PhantomData;
...@@ -85,13 +89,19 @@ mod __plugin { ...@@ -85,13 +89,19 @@ mod __plugin {
} }
use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::atomic::{AtomicU32, Ordering};
#[cfg(feature = "bevy")]
pub use __plugin::{MicroLDTKCameraPlugin, MicroLDTKPlugin}; pub use __plugin::{MicroLDTKCameraPlugin, MicroLDTKPlugin};
#[cfg(feature = "bevy")]
pub use assets::{LevelIndex, TileMetadata, TilesetIndex}; pub use assets::{LevelIndex, TileMetadata, TilesetIndex};
#[cfg(feature = "bevy")]
pub use camera::CameraBounder; pub use camera::CameraBounder;
pub use ldtk::{LdtkLoader, LdtkProject}; pub use ldtk::{LdtkProject, Level, AutoLayerRuleGroup};
#[cfg(feature = "bevy")]
pub use ldtk::LdtkLoader;
#[cfg(feature = "bevy")]
pub use map_query::{CameraBounds, InstanceRef, MapQuery}; pub use map_query::{CameraBounds, InstanceRef, MapQuery};
#[cfg(feature = "autotile")] #[cfg(feature = "autotile")]
pub use micro_autotile as autotile; pub use micro_autotile as autotile;
#[cfg(feature = "bevy")]
pub use pregen::{write_layer_to_texture, write_map_to_texture, Rasterise}; pub use pregen::{write_layer_to_texture, write_map_to_texture, Rasterise};
pub use system::*; pub use system::*;
#[cfg(feature = "bevy")]
mod locator; mod locator;
#[cfg(feature = "bevy")]
mod types; mod types;
mod utils; mod utils;
#[cfg(feature = "bevy")]
pub use locator::*; pub use locator::*;
#[cfg(feature = "bevy")]
pub use types::*; pub use types::*;
pub use utils::*; pub use utils::*;
...@@ -3,7 +3,9 @@ use std::fmt::{Debug, Formatter}; ...@@ -3,7 +3,9 @@ use std::fmt::{Debug, Formatter};
use std::ops::{Deref, DerefMut, Index}; use std::ops::{Deref, DerefMut, Index};
use std::path::Path; use std::path::Path;
#[cfg(feature = "bevy")]
use bevy::math::{IVec2, Rect, UVec2, Vec2}; use bevy::math::{IVec2, Rect, UVec2, Vec2};
#[cfg(feature = "bevy")]
use bevy::prelude::Event; use bevy::prelude::Event;
use num_traits::AsPrimitive; use num_traits::AsPrimitive;
use quadtree_rs::area::AreaBuilder; use quadtree_rs::area::AreaBuilder;
...@@ -14,9 +16,12 @@ use serde_json::{Map, Number, Value}; ...@@ -14,9 +16,12 @@ use serde_json::{Map, Number, Value};
use crate::ldtk::{EntityInstance, FieldInstance, LayerInstance, Level, TileInstance}; use crate::ldtk::{EntityInstance, FieldInstance, LayerInstance, Level, TileInstance};
use crate::system::Indexer; use crate::system::Indexer;
use crate::{get_ldtk_tile_scale, px_to_grid, MapQuery}; use crate::{get_ldtk_tile_scale, px_to_grid};
#[cfg(feature = "bevy")]
use crate::MapQuery;
#[derive(Default, Clone, Debug, Ord, PartialOrd, PartialEq, Eq, Event)] #[derive(Default, Clone, Debug, Ord, PartialOrd, PartialEq, Eq)]
#[cfg_attr(feature = "bevy", derive(Event))]
pub struct LevelDataUpdated(pub String); pub struct LevelDataUpdated(pub String);
pub struct TileRef<'a> { pub struct TileRef<'a> {
...@@ -88,11 +93,13 @@ where ...@@ -88,11 +93,13 @@ where
Self(value.0.as_(), value.1.as_()) Self(value.0.as_(), value.1.as_())
} }
} }
#[cfg(feature = "bevy")]
impl From<UVec2> for SpatialIndex { impl From<UVec2> for SpatialIndex {
fn from(value: UVec2) -> Self { fn from(value: UVec2) -> Self {
Self(value.x as i64, value.y as i64) Self(value.x as i64, value.y as i64)
} }
} }
#[cfg(feature = "bevy")]
impl From<IVec2> for SpatialIndex { impl From<IVec2> for SpatialIndex {
fn from(value: IVec2) -> Self { fn from(value: IVec2) -> Self {
Self(value.x as i64, value.y as i64) Self(value.x as i64, value.y as i64)
......
#[cfg(feature = "bevy")]
use bevy::prelude::{Component, IVec2, Resource}; use bevy::prelude::{Component, IVec2, Resource};
use num_traits::AsPrimitive; use num_traits::AsPrimitive;
...@@ -18,10 +19,11 @@ pub fn entity_centre(level_height: i64, entity: &EntityInstance) -> (f32, f32) { ...@@ -18,10 +19,11 @@ pub fn entity_centre(level_height: i64, entity: &EntityInstance) -> (f32, f32) {
(x as f32, y as f32) (x as f32, y as f32)
} }
#[derive(Component)] #[cfg_attr(feature="bevy", derive(Component))]
pub struct WorldLinked; pub struct WorldLinked;
#[derive(Default, Resource, Clone, Debug)] #[derive(Default, Clone, Debug)]
#[cfg_attr(feature="bevy", derive(Resource))]
pub struct ActiveLevel { pub struct ActiveLevel {
pub map: String, pub map: String,
pub dirty: bool, pub dirty: bool,
...@@ -87,6 +89,7 @@ impl Indexer { ...@@ -87,6 +89,7 @@ impl Indexer {
x >= 0 && x < self.width && y >= 0 && y < self.height x >= 0 && x < self.width && y >= 0 && y < self.height
} }
#[cfg(feature = "bevy")]
/// Perform a transformation to flip a grid point (top down coordinates) into a render /// Perform a transformation to flip a grid point (top down coordinates) into a render
/// point (bottom up coordinates) /// point (bottom up coordinates)
pub fn flip_y(&self, point: IVec2) -> IVec2 { pub fn flip_y(&self, point: IVec2) -> IVec2 {
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment