|
| 1 | +use std::{ |
| 2 | + io::Read, |
| 3 | + path::{Path, PathBuf}, |
| 4 | +}; |
| 5 | + |
| 6 | +use regex::Regex; |
| 7 | +use serde::Deserialize; |
| 8 | + |
| 9 | +use crate::{Error, ResourceReader}; |
| 10 | + |
| 11 | +/// A World is a list of maps files or regex patterns that define a layout of TMX maps. |
| 12 | +/// You can use the loader to further load the maps defined by the world. |
| 13 | +#[derive(Deserialize, PartialEq, Clone, Debug)] |
| 14 | +pub struct World { |
| 15 | + /// The path first used in a [`ResourceReader`] to load this world. |
| 16 | + #[serde(skip_deserializing)] |
| 17 | + pub source: PathBuf, |
| 18 | + /// The [`WorldMap`]s defined by the world file. |
| 19 | + #[serde(skip_serializing_if = "Vec::is_empty", default)] |
| 20 | + pub maps: Vec<WorldMap>, |
| 21 | + /// Optional regex pattern to load maps. |
| 22 | + #[serde(skip_serializing_if = "Vec::is_empty", default)] |
| 23 | + pub patterns: Vec<WorldPattern>, |
| 24 | +} |
| 25 | + |
| 26 | +impl World { |
| 27 | + /// Utility function to test a single path against all defined patterns. |
| 28 | + /// Returns a parsed [`WorldMap`] on the first matched pattern or an error if no patterns match. |
| 29 | + pub fn match_path(&self, path: impl AsRef<Path>) -> Result<WorldMap, Error> { |
| 30 | + let path_str = path.as_ref().to_str().expect("obtaining valid UTF-8 path"); |
| 31 | + |
| 32 | + for pattern in self.patterns.iter() { |
| 33 | + match pattern.match_path_impl(path_str) { |
| 34 | + Ok(world_map) => return Ok(world_map), |
| 35 | + // We ignore match errors here as the path may be matched by another pattern. |
| 36 | + Err(Error::NoMatchFound { .. }) => continue, |
| 37 | + Err(err) => return Err(err), |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + Err(Error::NoMatchFound { |
| 42 | + path: path_str.to_owned(), |
| 43 | + }) |
| 44 | + } |
| 45 | + |
| 46 | + /// Utility function to test a vec of filenames against all defined patterns. |
| 47 | + /// Returns a vec of results with the parsed [`WorldMap`]s if it matches the pattern. |
| 48 | + pub fn match_paths<P: AsRef<Path>>(&self, paths: &[P]) -> Vec<Result<WorldMap, Error>> { |
| 49 | + paths |
| 50 | + .into_iter() |
| 51 | + .map(|path| self.match_path(path)) |
| 52 | + .collect() |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +/// A WorldMap provides the information for a map in the world and its layout. |
| 57 | +#[derive(Deserialize, PartialEq, Clone, Debug)] |
| 58 | +pub struct WorldMap { |
| 59 | + /// The filename of the tmx map. |
| 60 | + #[serde(rename = "fileName")] |
| 61 | + pub filename: String, |
| 62 | + /// The x position of the map. |
| 63 | + pub x: i32, |
| 64 | + /// The y position of the map. |
| 65 | + pub y: i32, |
| 66 | + /// The optional width of the map. |
| 67 | + pub width: Option<i32>, |
| 68 | + /// The optional height of the map. |
| 69 | + pub height: Option<i32>, |
| 70 | +} |
| 71 | + |
| 72 | +/// A WorldPattern defines a regex pattern to automatically determine which maps to load and how to lay them out. |
| 73 | +#[derive(Deserialize, Clone, Debug)] |
| 74 | +#[serde(rename_all = "camelCase")] |
| 75 | +pub struct WorldPattern { |
| 76 | + /// The regex pattern to match against filenames. |
| 77 | + /// The first two capture groups should be the x integer and y integer positions. |
| 78 | + #[serde(with = "serde_regex")] |
| 79 | + pub regexp: Regex, |
| 80 | + /// The multiplier for the x position. |
| 81 | + pub multiplier_x: i32, |
| 82 | + /// The multiplier for the y position. |
| 83 | + pub multiplier_y: i32, |
| 84 | + /// The offset for the x position. |
| 85 | + pub offset_x: i32, |
| 86 | + /// The offset for the y position. |
| 87 | + pub offset_y: i32, |
| 88 | +} |
| 89 | + |
| 90 | +impl PartialEq for WorldPattern { |
| 91 | + fn eq(&self, other: &Self) -> bool { |
| 92 | + self.multiplier_x == other.multiplier_x |
| 93 | + && self.multiplier_y == other.multiplier_y |
| 94 | + && self.offset_x == other.offset_x |
| 95 | + && self.offset_y == other.offset_y |
| 96 | + && self.regexp.to_string() == other.regexp.to_string() |
| 97 | + } |
| 98 | +} |
| 99 | + |
| 100 | +impl WorldPattern { |
| 101 | + /// Utility function to test a path against this pattern. |
| 102 | + /// Returns a parsed [`WorldMap`] on the first matched pattern or an error if no patterns match. |
| 103 | + pub fn match_path(&self, path: impl AsRef<Path>) -> Result<WorldMap, Error> { |
| 104 | + let path_str = path.as_ref().to_str().expect("obtaining valid UTF-8 path"); |
| 105 | + |
| 106 | + self.match_path_impl(path_str) |
| 107 | + } |
| 108 | + |
| 109 | + pub(crate) fn match_path_impl(&self, path: &str) -> Result<WorldMap, Error> { |
| 110 | + let captures = match self.regexp.captures(path) { |
| 111 | + Some(captures) => captures, |
| 112 | + None => { |
| 113 | + return Err(Error::NoMatchFound { |
| 114 | + path: path.to_owned(), |
| 115 | + }) |
| 116 | + } |
| 117 | + }; |
| 118 | + |
| 119 | + let x = match captures.get(1) { |
| 120 | + Some(x) => x.as_str().parse::<i32>().unwrap(), |
| 121 | + None => { |
| 122 | + return Err(Error::NoMatchFound { |
| 123 | + path: path.to_owned(), |
| 124 | + }) |
| 125 | + } |
| 126 | + }; |
| 127 | + |
| 128 | + let y = match captures.get(2) { |
| 129 | + Some(y) => y.as_str().parse::<i32>().unwrap(), |
| 130 | + None => { |
| 131 | + return Err(Error::NoMatchFound { |
| 132 | + path: path.to_owned(), |
| 133 | + }) |
| 134 | + } |
| 135 | + }; |
| 136 | + |
| 137 | + // Calculate x and y positions based on the multiplier and offset. |
| 138 | + let x = x |
| 139 | + .checked_mul(self.multiplier_x) |
| 140 | + .ok_or(Error::RangeError( |
| 141 | + "Capture x * multiplierX causes overflow".to_string(), |
| 142 | + ))? |
| 143 | + .checked_add(self.offset_x) |
| 144 | + .ok_or(Error::RangeError( |
| 145 | + "Capture x * multiplierX + offsetX causes overflow".to_string(), |
| 146 | + ))?; |
| 147 | + |
| 148 | + let y = y |
| 149 | + .checked_mul(self.multiplier_y) |
| 150 | + .ok_or(Error::RangeError( |
| 151 | + "Capture y * multiplierY causes overflow".to_string(), |
| 152 | + ))? |
| 153 | + .checked_add(self.offset_y) |
| 154 | + .ok_or(Error::RangeError( |
| 155 | + "Capture y * multiplierY + offsetY causes overflow".to_string(), |
| 156 | + ))?; |
| 157 | + |
| 158 | + Ok(WorldMap { |
| 159 | + filename: path.to_owned(), |
| 160 | + x, |
| 161 | + y, |
| 162 | + width: None, |
| 163 | + height: None, |
| 164 | + }) |
| 165 | + } |
| 166 | +} |
| 167 | + |
| 168 | +pub(crate) fn parse_world( |
| 169 | + world_path: &Path, |
| 170 | + reader: &mut impl ResourceReader, |
| 171 | +) -> Result<World, Error> { |
| 172 | + let mut path = reader |
| 173 | + .read_from(&world_path) |
| 174 | + .map_err(|err| Error::ResourceLoadingError { |
| 175 | + path: world_path.to_owned(), |
| 176 | + err: Box::new(err), |
| 177 | + })?; |
| 178 | + |
| 179 | + let mut world_string = String::new(); |
| 180 | + path.read_to_string(&mut world_string) |
| 181 | + .map_err(|err| Error::ResourceLoadingError { |
| 182 | + path: world_path.to_owned(), |
| 183 | + err: Box::new(err), |
| 184 | + })?; |
| 185 | + |
| 186 | + let mut world: World = |
| 187 | + serde_json::from_str(&world_string).map_err(|err| Error::JsonDecodingError(err))?; |
| 188 | + |
| 189 | + world.source = world_path.to_owned(); |
| 190 | + |
| 191 | + Ok(world) |
| 192 | +} |
0 commit comments