From 83140aed33824bc70b49bc7a8aa5f69d146b64cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BB=B7=E6=96=87=20=E6=A5=8A?= Date: Mon, 16 Nov 2026 03:37:48 +0800 Subject: [PATCH 1/6] Add road strip model and preserve legacy spline output --- src/road_maker.rs | 265 +++++++++++------- src/road_maker/compat_tests.rs | 220 +++++++++++++++ src/road_maker/legacy_reference.rs | 415 +++++++++++++++++++++++++++++ src/road_maker/migration.rs | 113 ++++++++ src/road_maker/strips.rs | 269 +++++++++++++++++++ src/ui_roads.rs | 10 +- 6 files changed, 1193 insertions(+), 99 deletions(-) create mode 100644 src/road_maker/compat_tests.rs create mode 100644 src/road_maker/legacy_reference.rs create mode 100644 src/road_maker/migration.rs create mode 100644 src/road_maker/strips.rs diff --git a/src/road_maker.rs b/src/road_maker.rs index 4243ae1..ef5474f 100644 --- a/src/road_maker.rs +++ b/src/road_maker.rs @@ -16,6 +16,12 @@ use std::fmt::Write as _; use std::path::{Path, PathBuf}; use serde::{Deserialize, Serialize}; +mod strips; +mod migration; +pub use strips::{Direction, Strip}; +#[cfg(test)] +#[allow(dead_code)] +mod legacy_reference; /// How a painted line along the road looks. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] @@ -186,6 +192,10 @@ pub fn arrow_polygon(at: (f32, f32), back: bool) -> Vec<(f32, f32)> { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(default)] pub struct RoadSpec { + /// Canonical cross section, in physical left-to-right order. + pub strips: Vec, + /// None only while importing old parameters or initializing a new road. + pub left_hand: Option, pub name: String, /// Lanes the way the road is drawn, and against it (0: one-way). pub lanes_fwd: u8, @@ -221,7 +231,7 @@ pub struct RoadSpec { impl Default for RoadSpec { fn default() -> Self { - RoadSpec { name: String::new(), lanes_fwd: 1, lanes_back: 1, lane_width: 3.5, median: 0.0, median_raised: false, footway: 3.0, footway_right: None, kerb: 0.15, pocket: 0.0, roadway_tex: PathBuf::new(), footway_tex: PathBuf::new(), median_tex: PathBuf::new(), marked: false, markings: Vec::new(), hand: None } + RoadSpec { strips: Vec::new(), left_hand: None, name: String::new(), lanes_fwd: 1, lanes_back: 1, lane_width: 3.5, median: 0.0, median_raised: false, footway: 3.0, footway_right: None, kerb: 0.15, pocket: 0.0, roadway_tex: PathBuf::new(), footway_tex: PathBuf::new(), median_tex: PathBuf::new(), marked: false, markings: Vec::new(), hand: None } } } @@ -246,65 +256,104 @@ pub fn presets() -> Vec<(&'static str, RoadSpec)> { } impl RoadSpec { - pub fn roadway_width(&self) -> f32 { - (self.lanes_fwd + self.lanes_back) as f32 * self.lane_width + self.median_width() + + /// Only the old-parameter import boundary may synthesize strips. + fn effective_strips(&self) -> std::borrow::Cow<'_, [Strip]> { + if self.left_hand.is_none() && self.strips.is_empty() { + std::borrow::Cow::Owned(migration::from_legacy(self, false)) + } else { std::borrow::Cow::Borrowed(&self.strips) } + } + + pub fn rebuild_strips(&mut self, left_hand: bool) { + self.strips = migration::from_legacy(self, left_hand); + self.left_hand = Some(left_hand); + } + + pub fn normalised(&self, fallback: bool) -> Self { + let mut s = self.clone(); + if s.left_hand.is_none() && s.strips.is_empty() { s.rebuild_strips(fallback); } + s.left_hand = Some(s.left_hand.unwrap_or(fallback)); + s + } + + /// Materialize legacy controls from the canonical model for compatibility output. + fn projection(&self) -> Self { + let mut s = self.clone(); + let strips = self.effective_strips(); + s.strips = strips.to_vec(); + let left_dir = if self.left_hand.unwrap_or(false) { Direction::Fwd } else { Direction::Back }; + s.lanes_back = 0; + s.lanes_fwd = 0; + s.median = 0.0; + s.median_raised = false; + s.median_tex.clear(); + s.pocket = 0.0; + s.footway = 0.0; + s.footway_right = Some(0.0); + for (i, strip) in strips.iter().enumerate() { + match strip { + Strip::Lane { dir, width, .. } => { + if *dir == left_dir { s.lanes_back += 1; } else { s.lanes_fwd += 1; } + s.lane_width = *width; + } + Strip::Median { width, raised, tex } => { + s.median += width; + s.median_raised = *raised; + s.median_tex = tex.clone(); + } + Strip::Footway { width, tex } => { + if i == 0 { s.footway = *width; } else { s.footway_right = Some(*width); } + s.footway_tex = tex.clone(); + } + Strip::BusBay { width } => s.pocket = *width, + } + } + s + } + + pub fn validate(&self) -> Result<(), String> { + strips::validate(&self.effective_strips(), self.left_hand.unwrap_or(false)) } + fn bay_tex_name(&self) -> String { + let ext = self.roadway_tex.extension().unwrap_or_default().to_string_lossy(); + format!("{}_bay.{ext}", self.file_stem()) + } + pub fn roadway_width(&self) -> f32 { strips::roadway_width(&self.effective_strips()) } + /// The middle strip's width (none on a one-way road). pub fn median_width(&self) -> f32 { - if self.lanes_fwd > 0 && self.lanes_back > 0 { self.median } else { 0.0 } + self.effective_strips().iter().filter_map(|s| if let Strip::Median { width, .. } = s { Some(*width) } else { None }).sum() } pub fn footway_left(&self) -> f32 { - self.footway + match self.effective_strips().first() { Some(Strip::Footway { width, .. }) => *width, _ => 0.0 } } pub fn footway_right(&self) -> f32 { - self.footway_right.unwrap_or(self.footway) + match self.effective_strips().last() { Some(Strip::Footway { width, .. }) => *width, _ => 0.0 } } - pub fn total_width(&self) -> f32 { - self.roadway_width() + self.pocket + self.footway_left() + self.footway_right() - } + pub fn total_width(&self) -> f32 { self.effective_strips().iter().map(Strip::width).sum() } /// Where the two ways meet across the roadway (m from its middle): off the middle when one /// way has more lanes than the other. pub fn centerline(&self) -> f32 { - (self.lanes_back as f32 - self.lanes_fwd as f32) * self.lane_width / 2.0 + let (lo, hi) = self.median_edges(); + (lo + hi) / 2.0 } /// The middle strip's left and right edges (m from the roadway's middle), about the centreline. pub fn median_edges(&self) -> (f32, f32) { - let (c, mid) = (self.centerline(), self.median_width()); - (c - mid / 2.0, c + mid / 2.0) + strips::median_edges(&self.effective_strips(), self.left_hand.unwrap_or(false)) } /// Where a place across the roadway (m from its middle) lies in the roadway texture (0..1). - pub fn roadway_u(&self, x: f32) -> f32 { - let rw = self.roadway_width(); - let (xl, mid) = (-rw / 2.0, self.median_width()); - if mid > 0.0 && !self.median_tex.as_os_str().is_empty() { - let lanes_w = (rw - mid).max(0.1); - let (ml, mr) = self.median_edges(); - let u_mid = (ml - xl) / lanes_w; - if x <= ml { - (x - xl) / lanes_w - } else if x >= mr { - u_mid + (x - mr) / lanes_w - } else { - u_mid - } - } else { - (x - xl) / rw.max(0.1) - } - } + pub fn roadway_u(&self, x: f32) -> f32 { strips::roadway_u(&self.effective_strips(), x) } /// How wide the roadway texture lies across the road (m): the roadway, less a middle strip /// of its own, which has its own texture. - pub fn canvas_width(&self) -> f32 { - let own = self.median_width() > 0.0 && !self.median_tex.as_os_str().is_empty(); - (self.roadway_width() - if own { self.median_width() } else { 0.0 }).max(0.5) - } + pub fn canvas_width(&self) -> f32 { strips::canvas_width(&self.effective_strips()) } /// How far along the road the painted roadway texture runs before it repeats (m): about /// ten, a whole number of the first dashed line's periods so its dashes go on unbroken. @@ -336,34 +385,32 @@ impl RoadSpec { /// The markings a road like this usually has: edge lines, the middle (double yellow, or /// white edge lines of the strip), dashed lines between lanes of one way. pub fn standard_markings(&self) -> Vec { - let (rw, mid, lw) = (self.roadway_width(), self.median_width(), self.lane_width); - let two_way = self.lanes_fwd > 0 && self.lanes_back > 0; - let line = |x: f32, style: MarkStyle, color: [u8; 3]| Marking { x, style, color, ..Default::default() }; - let mut v = Vec::new(); - let edge = if self.pocket > 0.0 { MarkStyle::Dashed } else { MarkStyle::Solid }; - let offset = self.centerline(); - v.push(line(-rw / 2.0 + 0.2, MarkStyle::Solid, WHITE)); - v.push(line(rw / 2.0 - 0.2, edge, WHITE)); - if two_way { - let gap = mid / 2.0; - if mid <= 0.0 { - v.push(line(offset, MarkStyle::Double, YELLOW)); - } else { - v.push(line(offset - gap - 0.2, MarkStyle::Solid, WHITE)); - v.push(line(offset + gap + 0.2, MarkStyle::Solid, WHITE)); - } - for i in 1..self.lanes_back { - v.push(line(offset - gap - i as f32 * lw, MarkStyle::Dashed, WHITE)); - } - for i in 1..self.lanes_fwd { - v.push(line(offset + gap + i as f32 * lw, MarkStyle::Dashed, WHITE)); - } - } else { - for i in 1..(self.lanes_fwd + self.lanes_back) { - v.push(line(-rw / 2.0 + i as f32 * lw, MarkStyle::Dashed, WHITE)); + let strips = self.effective_strips(); + let positions = strips::positions(&strips); + let rw = self.roadway_width(); + let line = |x, style, color| Marking { x, style, color, ..Default::default() }; + let mut out = vec![line(-rw / 2.0 + 0.2, MarkStyle::Solid, WHITE), + line(rw / 2.0 - 0.2, if strips.iter().any(|s| matches!(s, Strip::BusBay { .. })) { + MarkStyle::Dashed + } else { MarkStyle::Solid }, WHITE)]; + let lanes: Vec<_> = strips.iter().zip(&positions).filter_map(|(s, pos)| { + if let Strip::Lane { dir, .. } = s { Some((*dir, *pos)) } else { None } + }).collect(); + for pair in lanes.windows(2) { + let ((dir_a, (_, hi)), (dir_b, (lo, _))) = (pair[0], pair[1]); + if dir_a != dir_b { + if hi == lo { out.push(line(hi, MarkStyle::Double, YELLOW)); } + else { + out.push(line(hi - 0.2, MarkStyle::Solid, WHITE)); + out.push(line(lo + 0.2, MarkStyle::Solid, WHITE)); + } + } else if hi == lo { out.push(line(hi, MarkStyle::Dashed, WHITE)); } + else { + out.push(line(hi - 0.2, MarkStyle::Solid, WHITE)); + out.push(line(lo + 0.2, MarkStyle::Solid, WHITE)); } } - v + out } /// The roadway texture with the markings painted on: the texture's picture stretched @@ -411,6 +458,11 @@ impl RoadSpec { /// The `.sli` text (OMSI's own keywords; `\n`, turned into CR LF when written). pub fn sli(&self, left_hand: bool) -> String { + let s = self.normalised(left_hand).projection(); + s.compatible_sli(s.left_hand.unwrap()) + } + + fn compatible_sli(&self, left_hand: bool) -> String { let rw = self.roadway_width(); let (xl, xr) = (-rw / 2.0, rw / 2.0); let (fl, fr) = (self.footway_left(), self.footway_right()); @@ -460,6 +512,8 @@ impl RoadSpec { let _ = write!(s, "[texture]\n{}\n\n", name(&self.median_tex)); median_ix = next; } + let bay_ix = if own_median { next + 1 } else { next }; + if pw > 0.0 { let _ = write!(s, "[texture]\n{}\n\n", self.bay_tex_name()); } let profile = |s: &mut String, tex: u32, a: (f32, f32, f32, f32), b: (f32, f32, f32, f32)| { let _ = write!(s, "[profile]\n{tex}\n\n"); for p in [a, b] { @@ -501,37 +555,18 @@ impl RoadSpec { } } if pw > 0.0 { - // the pocket: the roadway's own asphalt at the roadway's scale (u 1 is the roadway's - // width), centred on the middle of its first lane; squeezed into a sliver of the - // texture it would be a smear of one column across the whole bay - let lanes = (self.lanes_fwd + self.lanes_back).max(1) as f32; - let span = pw / rw.max(0.1); - let u0 = (0.5 / lanes - span / 2.0).clamp(0.0, (1.0 - span).max(0.0)); - profile(&mut s, 0, (xr, road_h, u0, rv), (xr2, road_h, u0 + span, rv)); - } - // Left-hand traffic reverses the vehicle paths on the same cross-section. - let forward = u8::from(left_hand); - let backward = u8::from(!left_hand); - let mid_gap = mid / 2.0; - let offset = self.centerline(); - let one_way = self.lanes_back == 0 || self.lanes_fwd == 0; - if fl > 0.0 { - let _ = write!(s, "[path]\n1\n{}\n{}\n{}\n2\n\n", num(xl - fl / 2.0), num(side_h), num(fl * 0.4)); - } - for i in 0..self.lanes_back { - let x = if one_way { xl + (i as f32 + 0.5) * self.lane_width } else { offset - mid_gap - (self.lanes_back - i) as f32 * self.lane_width + self.lane_width / 2.0 }; - let _ = write!(s, "[path]\n0\n{}\n{}\n{}\n{backward}\n\n", num(x), num(road_h), num(self.lane_width * 0.9)); - } - for i in 0..self.lanes_fwd { - let x = if one_way { xl + (i as f32 + 0.5) * self.lane_width } else { offset + mid_gap + (i as f32 + 0.5) * self.lane_width }; - let _ = write!(s, "[path]\n0\n{}\n{}\n{}\n{forward}\n\n", num(x), num(road_h), num(self.lane_width * 0.9)); - } - if pw > 0.0 { - // The pocket follows the direction of the forward lane group. - let _ = write!(s, "[path]\n0\n{}\n{}\n{}\n{forward}\n\n", num(xr + pw / 2.0), num(road_h), num(pw * 0.9)); - } - if fr > 0.0 { - let _ = write!(s, "[path]\n1\n{}\n{}\n{}\n2\n\n", num(xr2 + fr / 2.0), num(side_h), num(fr * 0.4)); + // The bay has an unmarked asphalt copy and uses its full texture width. + profile(&mut s, bay_ix, (xr, road_h, 0.0, rv), (xr2, road_h, 1.0, rv)); + } + for (strip, (lo, hi)) in self.strips.iter().zip(strips::positions(&self.strips)) { + let (kind, direction, scale) = match strip { + Strip::Lane { dir, .. } => (0, dir.path_direction(), 0.9), + Strip::BusBay { .. } => (0, u8::from(left_hand), 0.9), + Strip::Footway { .. } => (1, 2, 0.4), + Strip::Median { .. } => continue, + }; + let _ = write!(s, "[path]\n{kind}\n{}\n{}\n{}\n{direction}\n\n", + num((lo + hi) / 2.0), num(strip.height(self.kerb)), num(strip.width() * scale)); } s } @@ -545,7 +580,13 @@ impl RoadSpec { /// Write it into the content folder with its textures; returns its relative path /// (`Splines\openMapper\.sli`). pub fn write_with_traffic(&self, content: &Path, left_hand: bool) -> anyhow::Result { - anyhow::ensure!(self.lanes_fwd + self.lanes_back > 0, "a road needs a lane"); + let spec = self.normalised(left_hand); + spec.validate().map_err(anyhow::Error::msg)?; + spec.write_normalised(content) + } + + fn write_normalised(&self, content: &Path) -> anyhow::Result { + let left_hand = self.left_hand.unwrap(); anyhow::ensure!(self.roadway_tex.is_file(), "the roadway texture is missing"); let dir = content.join("Splines").join("openMapper"); let tex_dir = dir.join("texture"); @@ -563,6 +604,18 @@ impl RoadSpec { } } } + if self.strips.iter().any(|s| matches!(s, Strip::BusBay { .. })) { + let destination = tex_dir.join(self.bay_tex_name()); + if self.roadway_tex != destination { std::fs::copy(&self.roadway_tex, &destination)?; } + for ext in ["cfg", "surf"] { + let source = PathBuf::from(format!("{}.{ext}", self.roadway_tex.display())); + let target = PathBuf::from(format!("{}.{ext}", destination.display())); + if source.is_file() && source != target { std::fs::copy(&source, &target)?; } + let source = self.roadway_tex.with_extension(ext); + let target = destination.with_extension(ext); + if source.is_file() && source != target { std::fs::copy(&source, &target)?; } + } + } let stem = self.file_stem(); if self.marked { let img = self.painted_roadway().ok_or_else(|| anyhow::anyhow!("the roadway texture could not be read"))?; @@ -584,8 +637,16 @@ impl RoadSpec { /// The spec a road type was made with here, if it was. pub fn of(sli: &Path) -> Option { + Self::of_with_traffic(sli, false) + } + + pub fn of_with_traffic(sli: &Path, map_left_hand: bool) -> Option { let json = sli.with_extension("road.json"); - let mut spec: RoadSpec = serde_json::from_str(&std::fs::read_to_string(json).ok()?).ok()?; + let raw: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(json).ok()?).ok()?; + let mut spec: RoadSpec = serde_json::from_value(raw.clone()).ok()?; + let left_hand = migration::infer_traffic(&spec, sli, spec.left_hand, map_left_hand); + if raw.get("strips").is_none() { spec.rebuild_strips(left_hand); } + spec.left_hand = Some(left_hand); if let Ok(img) = image::open(sli.with_extension("marks.png")) { let img = img.to_rgba8(); if (img.width(), img.height()) == (HAND_W, HAND_H) { @@ -715,7 +776,12 @@ mod tests { let (rht_geometry, rht_blocks) = rht_text.split_once("[path]").unwrap(); let (lht_geometry, lht_blocks) = lht_text.split_once("[path]").unwrap(); println!("{name} RHT:\n[path]{rht_blocks}{name} LHT:\n[path]{lht_blocks}"); - assert_eq!(lht_json, rht_json); + let rht_json: serde_json::Value = serde_json::from_slice(&rht_json).unwrap(); + let lht_json: serde_json::Value = serde_json::from_slice(&lht_json).unwrap(); + assert_eq!(rht_json["left_hand"], false); + assert_eq!(lht_json["left_hand"], true); + assert!(rht_json["strips"].is_array()); + assert!(lht_json["strips"].is_array()); assert_eq!(lht_geometry, rht_geometry); assert_eq!(rht_paths.iter().map(|path| path.direction).collect::>(), directions); assert_eq!(lht_paths.len(), rht_paths.len()); @@ -754,7 +820,7 @@ mod tests { assert!((half - 7.0).abs() < 1e-6); assert!(s.profiles.iter().any(|p| p.points.iter().any(|q| (q.x - half).abs() < 1e-3))); assert!(content.join("Splines/openMapper/texture/asph.png").is_file()); - assert_eq!(RoadSpec::of(&path).unwrap(), spec); + assert_eq!(RoadSpec::of(&path).unwrap(), spec.normalised(false)); let _ = std::fs::remove_dir_all(dir); } @@ -784,7 +850,7 @@ mod tests { assert_eq!(walks.len(), 1); assert!(walks[0].start[0] > 0.0); assert!(content.join("Splines/openMapper/texture/g.png").is_file()); - assert_eq!(RoadSpec::of(&content.join("Splines/openMapper/Avenue.sli")).unwrap(), spec); + assert_eq!(RoadSpec::of(&content.join("Splines/openMapper/Avenue.sli")).unwrap(), spec.normalised(false)); // an old spec file (before these fields) still reads let old: RoadSpec = serde_json::from_str("{\"name\":\"x\",\"lanes_fwd\":1,\"lanes_back\":1}").unwrap(); assert_eq!(old.footway_right(), old.footway); @@ -846,7 +912,7 @@ mod tests { let right = s.profiles.iter().flat_map(|p| p.points.iter()).map(|q| q.x).fold(f32::MIN, f32::max); assert!((right - 8.5).abs() < 1e-3, "{right}"); // the spec reads back, and an old file without a pocket has none - assert_eq!(RoadSpec::of(&content.join("Splines/openMapper/Bay.sli")).unwrap(), spec); + assert_eq!(RoadSpec::of(&content.join("Splines/openMapper/Bay.sli")).unwrap(), spec.normalised(false)); let old: RoadSpec = serde_json::from_str("{\"name\":\"x\"}").unwrap(); assert_eq!(old.pocket, 0.0); let _ = std::fs::remove_dir_all(dir); @@ -875,7 +941,7 @@ mod tests { assert!(content.join("Splines/openMapper/texture/Lined_lines.bmp").is_file()); let s = omsi_scenery::Spline::load(&content.join("Splines/openMapper/Lined.sli")).unwrap(); assert!(s.textures[0].file.eq_ignore_ascii_case("Lined_lines.bmp"), "{}", s.textures[0].file); - assert_eq!(RoadSpec::of(&content.join("Splines/openMapper/Lined.sli")).unwrap(), spec); + assert_eq!(RoadSpec::of(&content.join("Splines/openMapper/Lined.sli")).unwrap(), spec.normalised(false)); // a dashed line's dashes come a whole number to the texture let d = Marking { style: MarkStyle::Dashed, dash: 3.0, gap: 6.0, ..Default::default() }; let spec2 = RoadSpec { markings: vec![d.clone()], ..spec.clone() }; @@ -935,3 +1001,6 @@ mod tests { let _ = std::fs::remove_dir_all(dir); } } + +#[cfg(test)] +mod compat_tests; diff --git a/src/road_maker/compat_tests.rs b/src/road_maker/compat_tests.rs new file mode 100644 index 0000000..1f16907 --- /dev/null +++ b/src/road_maker/compat_tests.rs @@ -0,0 +1,220 @@ +use super::legacy_reference::LegacyRoadSpec; +use super::*; + +fn legacy(spec: &RoadSpec) -> LegacyRoadSpec { + serde_json::from_value(serde_json::to_value(spec).unwrap()).unwrap() +} + +fn assert_compatible(old: &str, new: &str, bay_name: Option<&str>) { + if let Some(name) = bay_name { + let texture = format!("[texture]\n{name}\n\n"); + assert_eq!(new.matches(&texture).count(), 1); + let mut stripped = new.replacen(&texture, "", 1); + let old_start = old.rfind("[profile]\n").unwrap(); + let old_end = old.find("[path]\n").unwrap(); + let new_start = stripped.rfind("[profile]\n").unwrap(); + let new_end = stripped.find("[path]\n").unwrap(); + let profile = &stripped[new_start..new_end]; + let texture_index = old.matches("[texture]\n").count(); + assert!(profile.starts_with(&format!("[profile]\n{texture_index}\n\n"))); + let points: Vec<_> = profile.split("[profilepnt]\n").skip(1).collect(); + assert_eq!(points.len(), 2); + assert_eq!(points[0].lines().nth(2), Some("0.000")); + assert_eq!(points[1].lines().nth(2), Some("1.000")); + // Only the bay material and u coordinates may differ: its x/y/v also match. + let old_points: Vec<_> = old[old_start..old_end] + .split("[profilepnt]\n") + .skip(1) + .collect(); + for (a, b) in points.iter().zip(old_points) { + for field in [0, 1, 3] { + assert_eq!(a.lines().nth(field), b.lines().nth(field)); + } + } + stripped.replace_range(new_start..new_end, &old[old_start..old_end]); + assert_eq!(stripped, old); + } else { + assert_eq!(new, old); + } +} + +#[test] +fn all_presets_match_the_frozen_integration_writer_in_both_traffic_sides() { + let mut cases: Vec<_> = presets().into_iter().map(|(_, s)| s).collect(); + cases.extend([ + RoadSpec { + lanes_fwd: 2, + lanes_back: 2, + lane_width: 3.25, + median: 4.0, + median_raised: true, + footway: 0.0, + footway_right: Some(2.0), + ..Default::default() + }, + RoadSpec { + lanes_fwd: 2, + lanes_back: 3, + lane_width: 3.0, + median: 2.0, + median_raised: true, + footway: 2.0, + ..Default::default() + }, + RoadSpec { + lanes_fwd: 2, + lanes_back: 2, + lane_width: 3.25, + median: 1.0, + footway: 2.5, + ..Default::default() + }, + RoadSpec { + lanes_fwd: 0, + lanes_back: 3, + footway_right: Some(0.0), + ..Default::default() + }, + RoadSpec { + pocket: 3.0, + footway: 2.0, + ..Default::default() + }, + ]); + for (i, mut spec) in cases.into_iter().enumerate() { + spec.name = format!("case_{i}"); + for textured in [false, true] { + spec.roadway_tex = "asphalt.png".into(); + spec.footway_tex = if textured { + "side.png".into() + } else { + PathBuf::new() + }; + spec.median_tex = if textured { + "grass.png".into() + } else { + PathBuf::new() + }; + for marked in [false, true] { + spec.marked = marked; + spec.markings = if marked { + legacy(&spec).standard_markings() + } else { + Vec::new() + }; + for left_hand in [false, true] { + let old = legacy(&spec).sli(left_hand); + let new = spec.sli(left_hand); + let bay_name = spec.bay_tex_name(); + assert_compatible(&old, &new, (spec.pocket > 0.0).then_some(bay_name.as_str())); + } + } + } + } +} + +#[test] +fn old_roads_keep_their_traffic_side_when_opened_in_the_opposite_map() { + let root = std::env::temp_dir().join(format!("om-strips-migrate-{}", std::process::id())); + std::fs::create_dir_all(&root).unwrap(); + let texture = root.join("asphalt.png"); + image::RgbaImage::from_pixel(2, 2, image::Rgba([80, 80, 80, 255])) + .save(&texture) + .unwrap(); + for left_hand in [false, true] { + for (back, fwd) in [(1, 2), (0, 2), (2, 0)] { + let spec = RoadSpec { + name: format!("old_{left_hand}_{back}_{fwd}"), + lanes_back: back, + lanes_fwd: fwd, + roadway_tex: texture.clone(), + ..Default::default() + }; + let old = legacy(&spec); + let original = old.sli(left_hand); + let sli = root.join(format!("{}.sli", spec.file_stem())); + std::fs::write(&sli, &original).unwrap(); + std::fs::write( + sli.with_extension("road.json"), + serde_json::to_vec(&old).unwrap(), + ) + .unwrap(); + let migrated = RoadSpec::of_with_traffic(&sli, !left_hand).unwrap(); + assert_eq!(migrated.left_hand, Some(left_hand)); + assert_eq!(migrated.sli(!left_hand), original); + migrated.write_with_traffic(&root, !left_hand).unwrap(); + let saved = root + .join("Splines/openMapper") + .join(sli.file_name().unwrap()); + let text = omsi_cfg::vfs::read_text(&saved) + .unwrap() + .replace("\r\n", "\n"); + assert_eq!(text, original); + let json: serde_json::Value = + serde_json::from_slice(&std::fs::read(saved.with_extension("road.json")).unwrap()) + .unwrap(); + assert_eq!(json["left_hand"], left_hand); + assert!(json["strips"].is_array()); + assert_eq!( + RoadSpec::of_with_traffic(&saved, !left_hand) + .unwrap() + .sli(!left_hand), + original + ); + } + } + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn traffic_inference_prefers_json_and_falls_back_only_without_usable_paths() { + let root = std::env::temp_dir().join(format!("om-strips-infer-{}", std::process::id())); + std::fs::create_dir_all(&root).unwrap(); + let path = root.join("old.sli"); + let spec = RoadSpec::default(); + assert!(migration::infer_traffic(&spec, &path, None, true)); + assert!(!migration::infer_traffic(&spec, &path, Some(false), true)); + std::fs::write(&path, legacy(&spec).sli(false)).unwrap(); + assert!(migration::infer_traffic(&spec, &path, Some(true), false)); + std::fs::write(&path, "[path]\n0\n0\n0.1\n3\n2\n").unwrap(); + assert!(migration::infer_traffic(&spec, &path, None, true)); + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn bay_texture_copies_original_asphalt_and_sidecars_when_marked() { + let root = std::env::temp_dir().join(format!("om-strips-bay-{}", std::process::id())); + std::fs::create_dir_all(&root).unwrap(); + let texture = root.join("asphalt.png"); + image::RgbaImage::from_pixel(2, 2, image::Rgba([80, 80, 80, 255])) + .save(&texture) + .unwrap(); + std::fs::write(root.join("asphalt.png.cfg"), b"texture settings").unwrap(); + std::fs::write(root.join("asphalt.surf"), b"surface settings").unwrap(); + let mut spec = RoadSpec { + name: "Bus road".into(), + pocket: 3.0, + roadway_tex: texture.clone(), + marked: true, + ..Default::default() + }; + spec.markings = spec.standard_markings(); + spec.write(&root).unwrap(); + let folder = root.join("Splines/openMapper/texture"); + assert_eq!( + std::fs::read(folder.join("Bus_road_bay.png")).unwrap(), + std::fs::read(&texture).unwrap() + ); + assert_eq!( + std::fs::read(folder.join("Bus_road_bay.png.cfg")).unwrap(), + b"texture settings" + ); + assert_eq!( + std::fs::read(folder.join("Bus_road_bay.surf")).unwrap(), + b"surface settings" + ); + let sli = omsi_scenery::Spline::load(&root.join("Splines/openMapper/Bus_road.sli")).unwrap(); + assert_eq!(sli.textures[0].file, "Bus_road_lines.bmp"); + assert_eq!(sli.textures.last().unwrap().file, "Bus_road_bay.png"); + std::fs::remove_dir_all(root).unwrap(); +} diff --git a/src/road_maker/legacy_reference.rs b/src/road_maker/legacy_reference.rs new file mode 100644 index 0000000..abf6ee3 --- /dev/null +++ b/src/road_maker/legacy_reference.rs @@ -0,0 +1,415 @@ +// Frozen from integration 4f33c9f; test oracle only. +use super::*; +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct LegacyRoadSpec { + pub name: String, + /// Lanes the way the road is drawn, and against it (0: one-way). + pub lanes_fwd: u8, + pub lanes_back: u8, + pub lane_width: f32, + /// A strip between the two ways (m, 0: none). + pub median: f32, + /// The strip stands as high as the footways, with a kerb along it (else it lies level with + /// the roadway). + pub median_raised: bool, + /// Footway each side (m, 0: none) and the kerb's height. The footway on the right is the + /// same unless `footway_right` says otherwise. + pub footway: f32, + pub footway_right: Option, + pub kerb: f32, + /// A bus pocket: a lane (m, 0: none) beside the roadway on the right, between it and the + /// footway, for buses to stop in. A road type made with one is what the Roads tool's bus + /// pocket tool lays where a bay is wanted. + pub pocket: f32, + /// Texture files (found in the installation or the content folder). + pub roadway_tex: PathBuf, + pub footway_tex: PathBuf, + /// The middle strip's own texture (grass, paving); the roadway's runs on under it if none. + pub median_tex: PathBuf, + /// The lines are painted by the maker (`markings`) onto the roadway texture, which should + /// be plain asphalt, instead of being the ones the texture has. + pub marked: bool, + pub markings: Vec, + /// What is drawn over them by hand (kept beside the road as `.marks.png`). + #[serde(skip)] + pub hand: Option>, +} + +impl Default for LegacyRoadSpec { + fn default() -> Self { + LegacyRoadSpec { name: String::new(), lanes_fwd: 1, lanes_back: 1, lane_width: 3.5, median: 0.0, median_raised: false, footway: 3.0, footway_right: None, kerb: 0.15, pocket: 0.0, roadway_tex: PathBuf::new(), footway_tex: PathBuf::new(), median_tex: PathBuf::new(), marked: false, markings: Vec::new(), hand: None } + } +} + +fn num(v: f32) -> String { + format!("{v:.3}") +} + +/// A ready-made start for the road maker: (name, what it is made of). +pub fn presets() -> Vec<(&'static str, LegacyRoadSpec)> { + use crate::i18n::tr; + let base = LegacyRoadSpec::default(); + vec![ + (tr("Quiet street", "Тихая улица"), LegacyRoadSpec { lane_width: 3.0, footway: 2.0, ..base.clone() }), + (tr("Street with a footway on one side", "Улица с тротуаром с одной стороны"), LegacyRoadSpec { lane_width: 3.0, footway: 0.0, footway_right: Some(2.0), ..base.clone() }), + (tr("Main road", "Главная дорога"), LegacyRoadSpec { lanes_fwd: 2, lanes_back: 2, lane_width: 3.25, footway: 3.0, ..base.clone() }), + (tr("Avenue with a green strip", "Проспект с газоном"), LegacyRoadSpec { lanes_fwd: 2, lanes_back: 2, lane_width: 3.25, median: 4.0, median_raised: true, footway: 3.5, ..base.clone() }), + (tr("One-way street", "Улица с односторонним движением"), LegacyRoadSpec { lanes_fwd: 2, lanes_back: 0, lane_width: 3.0, footway: 2.5, ..base.clone() }), + (tr("Street with a bus pocket", "Улица с автобусным карманом"), LegacyRoadSpec { lane_width: 3.0, footway: 2.5, pocket: 3.0, ..base.clone() }), + (tr("Country road", "Просёлочная дорога"), LegacyRoadSpec { lane_width: 3.0, footway: 0.0, kerb: 0.0, ..base.clone() }), + (tr("Service road", "Служебный проезд"), LegacyRoadSpec { lanes_fwd: 1, lanes_back: 0, lane_width: 3.5, footway: 0.0, kerb: 0.0, ..base }), + ] +} + +impl LegacyRoadSpec { + pub fn roadway_width(&self) -> f32 { + (self.lanes_fwd + self.lanes_back) as f32 * self.lane_width + self.median_width() + } + + /// The middle strip's width (none on a one-way road). + pub fn median_width(&self) -> f32 { + if self.lanes_fwd > 0 && self.lanes_back > 0 { self.median } else { 0.0 } + } + + pub fn footway_left(&self) -> f32 { + self.footway + } + + pub fn footway_right(&self) -> f32 { + self.footway_right.unwrap_or(self.footway) + } + + pub fn total_width(&self) -> f32 { + self.roadway_width() + self.pocket + self.footway_left() + self.footway_right() + } + + /// Where the two ways meet across the roadway (m from its middle): off the middle when one + /// way has more lanes than the other. + pub fn centerline(&self) -> f32 { + (self.lanes_back as f32 - self.lanes_fwd as f32) * self.lane_width / 2.0 + } + + /// The middle strip's left and right edges (m from the roadway's middle), about the centreline. + pub fn median_edges(&self) -> (f32, f32) { + let (c, mid) = (self.centerline(), self.median_width()); + (c - mid / 2.0, c + mid / 2.0) + } + + /// Where a place across the roadway (m from its middle) lies in the roadway texture (0..1). + pub fn roadway_u(&self, x: f32) -> f32 { + let rw = self.roadway_width(); + let (xl, mid) = (-rw / 2.0, self.median_width()); + if mid > 0.0 && !self.median_tex.as_os_str().is_empty() { + let lanes_w = (rw - mid).max(0.1); + let (ml, mr) = self.median_edges(); + let u_mid = (ml - xl) / lanes_w; + if x <= ml { + (x - xl) / lanes_w + } else if x >= mr { + u_mid + (x - mr) / lanes_w + } else { + u_mid + } + } else { + (x - xl) / rw.max(0.1) + } + } + + /// How wide the roadway texture lies across the road (m): the roadway, less a middle strip + /// of its own, which has its own texture. + pub fn canvas_width(&self) -> f32 { + let own = self.median_width() > 0.0 && !self.median_tex.as_os_str().is_empty(); + (self.roadway_width() - if own { self.median_width() } else { 0.0 }).max(0.5) + } + + /// How far along the road the painted roadway texture runs before it repeats (m): about + /// ten, a whole number of the first dashed line's periods so its dashes go on unbroken. + pub fn mark_period(&self) -> f32 { + let first = self.markings.iter().filter(|m| matches!(m.style, MarkStyle::Dashed | MarkStyle::SolidDashed)).map(|m| (m.dash + m.gap).max(0.5)).next().unwrap_or(10.0); + (first * (10.0 / first).round().max(1.0)).clamp(2.0, 40.0) + } + + /// A dashed line's period as painted: the texture's length holds a whole number of them. + pub fn dash_period(&self, m: &Marking) -> f32 { + let l = self.mark_period(); + l / (l / (m.dash + m.gap).max(0.5)).round().max(1.0) + } + + /// The v scale of the roadway's profiles: 0.1 (ten metres to the texture), or the painted + /// texture's own length. + fn roadway_v(&self) -> f32 { + if self.marked { 1.0 / self.mark_period() } else { 0.1 } + } + + fn roadway_tex_name(&self) -> String { + if self.marked { + format!("{}_lines.bmp", self.file_stem()) + } else { + self.roadway_tex.file_name().map(|f| f.to_string_lossy().to_string()).unwrap_or_default() + } + } + + /// The markings a road like this usually has: edge lines, the middle (double yellow, or + /// white edge lines of the strip), dashed lines between lanes of one way. + pub fn standard_markings(&self) -> Vec { + let (rw, mid, lw) = (self.roadway_width(), self.median_width(), self.lane_width); + let two_way = self.lanes_fwd > 0 && self.lanes_back > 0; + let line = |x: f32, style: MarkStyle, color: [u8; 3]| Marking { x, style, color, ..Default::default() }; + let mut v = Vec::new(); + let edge = if self.pocket > 0.0 { MarkStyle::Dashed } else { MarkStyle::Solid }; + let offset = self.centerline(); + v.push(line(-rw / 2.0 + 0.2, MarkStyle::Solid, WHITE)); + v.push(line(rw / 2.0 - 0.2, edge, WHITE)); + if two_way { + let gap = mid / 2.0; + if mid <= 0.0 { + v.push(line(offset, MarkStyle::Double, YELLOW)); + } else { + v.push(line(offset - gap - 0.2, MarkStyle::Solid, WHITE)); + v.push(line(offset + gap + 0.2, MarkStyle::Solid, WHITE)); + } + for i in 1..self.lanes_back { + v.push(line(offset - gap - i as f32 * lw, MarkStyle::Dashed, WHITE)); + } + for i in 1..self.lanes_fwd { + v.push(line(offset + gap + i as f32 * lw, MarkStyle::Dashed, WHITE)); + } + } else { + for i in 1..(self.lanes_fwd + self.lanes_back) { + v.push(line(-rw / 2.0 + i as f32 * lw, MarkStyle::Dashed, WHITE)); + } + } + v + } + + /// The roadway texture with the markings painted on: the texture's picture stretched + /// across the roadway as it is laid (u across, v along `mark_period` metres), lines drawn + /// with soft edges. + pub fn painted_roadway(&self) -> Option { + let img = omsi_texture::decode_file(&self.roadway_tex).ok()?; + let src = image::RgbaImage::from_raw(img.width as u32, img.height as u32, img.rgba.clone())?; + let (w, h) = (1024usize, 512usize); + let mut buf = image::imageops::resize(&src, w as u32, h as u32, image::imageops::FilterType::Triangle); + let len = self.mark_period(); + for m in &self.markings { + let period = self.dash_period(m); + for (x, dashed) in m.lines_at() { + let (a, b) = (self.roadway_u(x - m.width / 2.0) * w as f32, self.roadway_u(x + m.width / 2.0) * w as f32); + let (lo, hi) = (a.min(b), a.max(b)); + for px in (lo.floor().max(0.0) as usize)..(hi.ceil().max(0.0) as usize).min(w) { + let cover = (hi.min(px as f32 + 1.0) - lo.max(px as f32)).clamp(0.0, 1.0); + if cover <= 0.0 { + continue; + } + for py in 0..h { + if dashed && ((py as f32 + 0.5) / h as f32 * len) % period >= m.dash.min(period) { + continue; + } + let p = buf.get_pixel_mut(px as u32, py as u32); + for c in 0..3 { + p.0[c] = (p.0[c] as f32 + (m.color[c] as f32 - p.0[c] as f32) * cover * 0.96) as u8; + } + } + } + } + } + if let Some(h) = &self.hand { + h.over(&mut buf); + } + Some(buf) + } + + /// The file name it is saved as. + pub fn file_stem(&self) -> String { + let s: String = self.name.trim().chars().map(|c| if c.is_alphanumeric() || c == '-' || c == '_' { c } else { '_' }).collect(); + if s.is_empty() { "road".into() } else { s } + } + + /// The `.sli` text (OMSI's own keywords; `\n`, turned into CR LF when written). + pub fn sli(&self, left_hand: bool) -> String { + let rw = self.roadway_width(); + let (xl, xr) = (-rw / 2.0, rw / 2.0); + let (fl, fr) = (self.footway_left(), self.footway_right()); + let pw = self.pocket.max(0.0); + // (the right footway and its kerb start past the pocket) + let xr2 = xr + pw; + let road_h = 0.10f32; + let side_h = road_h + self.kerb; + let mid = self.median_width(); + let own_median = mid > 0.0 && !self.median_tex.as_os_str().as_encoded_bytes().is_empty(); + let raised = mid > 0.0 && self.median_raised; + let rv = self.roadway_v(); + let mut s = format!("File created with openMapper\n\n[friendlyname]\n{}\n\n", self.name.trim()); + // the ground and the wheels: footways high, the roadway low + let height = |s: &mut String, a: f32, b: f32, h: f32| { + let _ = write!(s, "[heightprofile]\n{}\n{}\n{}\n{}\n\n", num(a), num(b), num(h), num(h)); + }; + if fl > 0.0 { + height(&mut s, xl - fl, xl, side_h); + } + let (ml, mr) = self.median_edges(); + if raised { + height(&mut s, xl, ml, road_h); + height(&mut s, ml, mr, side_h); + height(&mut s, mr, xr, road_h); + } else { + height(&mut s, xl, xr, road_h); + } + if pw > 0.0 { + height(&mut s, xr, xr2, road_h); + } + if fr > 0.0 { + height(&mut s, xr2, xr2 + fr, side_h); + } + let name = |p: &Path| p.file_name().map(|f| f.to_string_lossy().to_string()).unwrap_or_default(); + let _ = write!(s, "[texture]\n{}\n\n", self.roadway_tex_name()); + let side_tex = (fl > 0.0 || fr > 0.0 || raised) && !self.footway_tex.as_os_str().is_empty(); + let mut next = 1u32; + let mut side_ix = 0; + if side_tex { + let _ = write!(s, "[texture]\n{}\n\n", name(&self.footway_tex)); + side_ix = next; + next += 1; + } + let mut median_ix = 0; + if own_median { + let _ = write!(s, "[texture]\n{}\n\n", name(&self.median_tex)); + median_ix = next; + } + let profile = |s: &mut String, tex: u32, a: (f32, f32, f32, f32), b: (f32, f32, f32, f32)| { + let _ = write!(s, "[profile]\n{tex}\n\n"); + for p in [a, b] { + let _ = write!(s, "[profilepnt]\n{}\n{}\n{}\n{}\n\n", num(p.0), num(p.1), num(p.2), num(p.3)); + } + }; + // the roadway: one texture across it, u 0 at its left edge and 1 at its right (as the + // stock lane textures are painted); a strip of its own texture in the middle takes its + // own place, the roadway's u running across the lanes either side of it + if own_median { + let lanes_w = rw - mid; + let u_mid = ((ml - xl) / lanes_w).clamp(0.0, 1.0); + let y = |on: bool| if on { side_h } else { road_h }; + profile(&mut s, 0, (xl, road_h, 0.0, rv), (ml, road_h, u_mid, rv)); + profile(&mut s, 0, (mr, road_h, u_mid, rv), (xr, road_h, 1.0, rv)); + if raised && side_tex { + profile(&mut s, side_ix, (ml, road_h, 0.995, 0.2), (ml, y(true), 0.953, 0.2)); + profile(&mut s, side_ix, (mr, y(true), 0.953, 0.2), (mr, road_h, 0.995, 0.2)); + } + profile(&mut s, median_ix, (ml, y(raised), 0.0, mid), (mr, y(raised), 1.0, mid)); + } else { + profile(&mut s, 0, (xl, road_h, 0.0, rv), (xr, road_h, 1.0, rv)); + if raised && side_tex { + profile(&mut s, side_ix, (ml, road_h, 0.995, 0.2), (ml, side_h, 0.953, 0.2)); + profile(&mut s, side_ix, (ml, side_h, 0.953, 0.2), (mr, side_h, 0.187, 0.2)); + profile(&mut s, side_ix, (mr, side_h, 0.953, 0.2), (mr, road_h, 0.995, 0.2)); + } + } + if side_tex { + // kerb face and footway top, on the stock footway texture's kerb and pavement parts + let t = side_ix; + if fl > 0.0 { + profile(&mut s, t, (xl - fl, side_h, 0.187, 0.2), (xl, side_h, 0.953, 0.2)); + profile(&mut s, t, (xl, side_h, 0.953, 0.2), (xl, road_h, 0.995, 0.2)); + } + if fr > 0.0 { + profile(&mut s, t, (xr2, road_h, 0.995, 0.2), (xr2, side_h, 0.953, 0.2)); + profile(&mut s, t, (xr2, side_h, 0.953, 0.2), (xr2 + fr, side_h, 0.187, 0.2)); + } + } + if pw > 0.0 { + // the pocket: the roadway's own asphalt at the roadway's scale (u 1 is the roadway's + // width), centred on the middle of its first lane; squeezed into a sliver of the + // texture it would be a smear of one column across the whole bay + let lanes = (self.lanes_fwd + self.lanes_back).max(1) as f32; + let span = pw / rw.max(0.1); + let u0 = (0.5 / lanes - span / 2.0).clamp(0.0, (1.0 - span).max(0.0)); + profile(&mut s, 0, (xr, road_h, u0, rv), (xr2, road_h, u0 + span, rv)); + } + // Left-hand traffic reverses the vehicle paths on the same cross-section. + let forward = u8::from(left_hand); + let backward = u8::from(!left_hand); + let mid_gap = mid / 2.0; + let offset = self.centerline(); + let one_way = self.lanes_back == 0 || self.lanes_fwd == 0; + if fl > 0.0 { + let _ = write!(s, "[path]\n1\n{}\n{}\n{}\n2\n\n", num(xl - fl / 2.0), num(side_h), num(fl * 0.4)); + } + for i in 0..self.lanes_back { + let x = if one_way { xl + (i as f32 + 0.5) * self.lane_width } else { offset - mid_gap - (self.lanes_back - i) as f32 * self.lane_width + self.lane_width / 2.0 }; + let _ = write!(s, "[path]\n0\n{}\n{}\n{}\n{backward}\n\n", num(x), num(road_h), num(self.lane_width * 0.9)); + } + for i in 0..self.lanes_fwd { + let x = if one_way { xl + (i as f32 + 0.5) * self.lane_width } else { offset + mid_gap + (i as f32 + 0.5) * self.lane_width }; + let _ = write!(s, "[path]\n0\n{}\n{}\n{}\n{forward}\n\n", num(x), num(road_h), num(self.lane_width * 0.9)); + } + if pw > 0.0 { + // The pocket follows the direction of the forward lane group. + let _ = write!(s, "[path]\n0\n{}\n{}\n{}\n{forward}\n\n", num(xr + pw / 2.0), num(road_h), num(pw * 0.9)); + } + if fr > 0.0 { + let _ = write!(s, "[path]\n1\n{}\n{}\n{}\n2\n\n", num(xr2 + fr / 2.0), num(side_h), num(fr * 0.4)); + } + s + } + + /// Write a right-hand road for tests that build spline fixtures. + #[cfg(test)] + pub fn write(&self, content: &Path) -> anyhow::Result { + self.write_with_traffic(content, false) + } + + /// Write it into the content folder with its textures; returns its relative path + /// (`Splines\openMapper\.sli`). + pub fn write_with_traffic(&self, content: &Path, left_hand: bool) -> anyhow::Result { + anyhow::ensure!(self.lanes_fwd + self.lanes_back > 0, "a road needs a lane"); + anyhow::ensure!(self.roadway_tex.is_file(), "the roadway texture is missing"); + let dir = content.join("Splines").join("openMapper"); + let tex_dir = dir.join("texture"); + std::fs::create_dir_all(&tex_dir)?; + for t in [&self.roadway_tex, &self.footway_tex, &self.median_tex].into_iter().filter(|t| t.is_file()) { + let name = t.file_name().unwrap(); + if t.parent() != Some(tex_dir.as_path()) { + std::fs::copy(t, tex_dir.join(name))?; + // (its settings and surface sound go with it) + for ext in ["cfg", "surf"] { + let side = PathBuf::from(format!("{}.{ext}", t.display())); + if side.is_file() { + std::fs::copy(&side, tex_dir.join(format!("{}.{ext}", name.to_string_lossy())))?; + } + } + } + } + let stem = self.file_stem(); + if self.marked { + let img = self.painted_roadway().ok_or_else(|| anyhow::anyhow!("the roadway texture could not be read"))?; + image::DynamicImage::ImageRgba8(img).to_rgb8().save(tex_dir.join(self.roadway_tex_name()))?; + } + let path = dir.join(format!("{stem}.sli")); + crate::doc::safe::write_atomic(&path, &omsi_cfg::encode_text(&self.sli(left_hand).replace('\n', "\r\n")))?; + // (the spec beside it, so the road can be opened in the maker again) + crate::doc::safe::write_atomic(&dir.join(format!("{stem}.road.json")), serde_json::to_string_pretty(self)?.as_bytes())?; + let marks = dir.join(format!("{stem}.marks.png")); + match self.hand.as_ref().filter(|h| self.marked && !h.is_empty()) { + Some(h) => h.img.save(&marks)?, + None => { + let _ = std::fs::remove_file(&marks); + } + } + Ok(format!("Splines\\openMapper\\{stem}.sli")) + } + + /// The spec a road type was made with here, if it was. + pub fn of(sli: &Path) -> Option { + let json = sli.with_extension("road.json"); + let mut spec: LegacyRoadSpec = serde_json::from_str(&std::fs::read_to_string(json).ok()?).ok()?; + if let Ok(img) = image::open(sli.with_extension("marks.png")) { + let img = img.to_rgba8(); + if (img.width(), img.height()) == (HAND_W, HAND_H) { + spec.hand = Some(std::sync::Arc::new(Hand { img })); + } + } + Some(spec) + } +} + diff --git a/src/road_maker/migration.rs b/src/road_maker/migration.rs new file mode 100644 index 0000000..24c6762 --- /dev/null +++ b/src/road_maker/migration.rs @@ -0,0 +1,113 @@ +//! Compatibility at the old parameter-model boundary. + +use super::{ + RoadSpec, + strips::{Direction, Strip}, +}; +use std::path::Path; + +pub fn from_legacy(spec: &RoadSpec, left_hand: bool) -> Vec { + let mut strips = Vec::new(); + if spec.footway > 0.0 { + strips.push(Strip::Footway { + width: spec.footway, + tex: spec.footway_tex.clone(), + }); + } + let left_dir = if left_hand { + Direction::Fwd + } else { + Direction::Back + }; + let right_dir = if left_hand { + Direction::Back + } else { + Direction::Fwd + }; + strips.extend((0..spec.lanes_back).map(|_| Strip::Lane { + dir: left_dir, + width: spec.lane_width, + bus_only: false, + })); + if spec.lanes_back > 0 && spec.lanes_fwd > 0 && spec.median > 0.0 { + strips.push(Strip::Median { + width: spec.median, + raised: spec.median_raised, + tex: spec.median_tex.clone(), + }); + } + strips.extend((0..spec.lanes_fwd).map(|_| Strip::Lane { + dir: right_dir, + width: spec.lane_width, + bus_only: false, + })); + if spec.pocket > 0.0 { + strips.push(Strip::BusBay { width: spec.pocket }); + } + let right = spec.footway_right.unwrap_or(spec.footway); + if right > 0.0 { + strips.push(Strip::Footway { + width: right, + tex: spec.footway_tex.clone(), + }); + } + strips +} + +/// The original maker appends its pocket after all through lanes. Take only the +/// declared through-lane count before sorting so that the pocket cannot vote. +pub fn infer_traffic(spec: &RoadSpec, sli: &Path, saved: Option, fallback: bool) -> bool { + log::info!( + "road traffic inference: sli={}, saved={saved:?}, lanes_back={}, lanes_fwd={}, pocket={}, map_left_hand={fallback}", + sli.display(), + spec.lanes_back, + spec.lanes_fwd, + spec.pocket + ); + if let Some(left_hand) = saved { + log::info!("road traffic inference: source=json, left_hand={left_hand}"); + return left_hand; + } + let count = usize::from(spec.lanes_back) + usize::from(spec.lanes_fwd); + match omsi_scenery::Spline::load(sli) { + Ok(spline) => { + let mut lanes: Vec<_> = spline + .paths + .iter() + .filter(|p| p.kind == 0) + .take(count) + .collect(); + log::info!( + "road traffic inference: through paths (x, direction)={:?}", + lanes + .iter() + .map(|p| (p.start[0], p.direction)) + .collect::>() + ); + if count > 0 && lanes.len() == count && lanes.iter().all(|p| p.start[0].is_finite()) { + lanes.sort_by(|a, b| a.start[0].total_cmp(&b.start[0])); + let direction = lanes[0].direction; + if direction == 0 || direction == 1 { + let left_hand = if spec.lanes_back > 0 { + direction == 0 + } else { + direction == 1 + }; + log::info!( + "road traffic inference: source=sli, leftmost_direction={direction}, left_hand={left_hand}" + ); + return left_hand; + } + } + } + Err(error) => log::warn!( + "road traffic inference: cannot read {}: {error}", + sli.display() + ), + } + log::warn!( + "road traffic inference: cannot determine traffic side for {}; using map_left_hand={fallback}", + sli.display() + ); + fallback +} diff --git a/src/road_maker/strips.rs b/src/road_maker/strips.rs new file mode 100644 index 0000000..58f9fb2 --- /dev/null +++ b/src/road_maker/strips.rs @@ -0,0 +1,269 @@ +//! Ordered road cross sections. Coordinates are relative to the through roadway. + +use serde::{Deserialize, Serialize}; +use std::path::PathBuf; + +/// Actual OMSI travel direction, independent of traffic handedness. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum Direction { + Fwd, + Back, +} + +impl Direction { + pub fn path_direction(self) -> u8 { + match self { + Self::Fwd => 0, + Self::Back => 1, + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub enum Strip { + Lane { + dir: Direction, + width: f32, + bus_only: bool, + }, + Median { + width: f32, + raised: bool, + tex: PathBuf, + }, + Footway { + width: f32, + tex: PathBuf, + }, + BusBay { + width: f32, + }, +} + +impl Strip { + pub fn width(&self) -> f32 { + match self { + Self::Lane { width, .. } + | Self::Median { width, .. } + | Self::Footway { width, .. } + | Self::BusBay { width } => *width, + } + } + + pub fn height(&self, kerb: f32) -> f32 { + match self { + Self::Footway { .. } | Self::Median { raised: true, .. } => 0.10 + kerb, + _ => 0.10, + } + } + + pub fn is_roadway(&self) -> bool { + matches!(self, Self::Lane { .. } | Self::Median { .. }) + } +} + +/// Validate before writing any files; an invalid editor state remains editable. +pub fn validate(strips: &[Strip], left_hand: bool) -> Result<(), String> { + let first = strips + .iter() + .position(|s| matches!(s, Strip::Lane { .. })) + .ok_or_else(|| "道路至少需要一條 Lane".to_string())?; + let last = strips + .iter() + .rposition(|s| matches!(s, Strip::Lane { .. })) + .unwrap(); + for (i, strip) in strips.iter().enumerate() { + let w = strip.width(); + if !w.is_finite() || w < 0.0 || (w == 0.0 && !matches!(strip, Strip::Median { .. })) { + return Err(format!("積木 {} 的寬度無效", i + 1)); + } + match strip { + Strip::Footway { .. } if i != 0 && i + 1 != strips.len() => { + return Err("Footway 只能位於道路兩端".into()); + } + Strip::BusBay { .. } if i.checked_add(1) != Some(first) && i != last + 1 => { + return Err("BusBay 只能緊貼車道段外緣,各側最多一個".into()); + } + Strip::Median { .. } if i < first || i > last => { + return Err("Median 必須位於車道段內".into()); + } + _ => {} + } + if (first..=last).contains(&i) && !strip.is_roadway() { + return Err("車道段內只能包含 Lane 和 Median".into()); + } + } + let left_dir = if left_hand { + Direction::Fwd + } else { + Direction::Back + }; + let mut reached_right = false; + for strip in strips { + if let Strip::Lane { dir, .. } = strip { + if *dir != left_dir { + reached_right = true; + } else if reached_right { + return Err("車道方向排列不符合此道路的行駛側設定".into()); + } + } + } + Ok(()) +} + +/// Each strip's left and right edges, accumulated from its actual width. +pub fn positions(strips: &[Strip]) -> Vec<(f32, f32)> { + let roadway: f32 = strips + .iter() + .filter(|s| s.is_roadway()) + .map(Strip::width) + .sum(); + let before: f32 = strips + .iter() + .take_while(|s| !s.is_roadway()) + .map(Strip::width) + .sum(); + let mut x = -roadway / 2.0 - before; + strips + .iter() + .map(|s| { + let start = x; + x += s.width(); + (start, x) + }) + .collect() +} + +pub fn roadway_width(strips: &[Strip]) -> f32 { + strips + .iter() + .filter(|s| s.is_roadway()) + .map(Strip::width) + .sum() +} + +pub fn canvas_width(strips: &[Strip]) -> f32 { + strips + .iter() + .filter(|s| s.is_roadway()) + .map(|s| match s { + Strip::Median { tex, .. } if !tex.as_os_str().is_empty() => 0.0, + _ => s.width(), + }) + .sum::() + .max(0.5) +} + +pub fn roadway_u(strips: &[Strip], x: f32) -> f32 { + let mut used = x + roadway_width(strips) / 2.0; + let mut removed = 0.0; + for (strip, (lo, _)) in strips.iter().zip(positions(strips)) { + if let Strip::Median { width, tex, .. } = strip { + if !tex.as_os_str().is_empty() { + used -= (x - lo).clamp(0.0, *width); + removed += width; + } + } + } + used / (roadway_width(strips) - removed).max(0.1) +} + +/// Boundaries of the divider between the two directional lane groups. +pub fn median_edges(strips: &[Strip], left_hand: bool) -> (f32, f32) { + let left_dir = if left_hand { + Direction::Fwd + } else { + Direction::Back + }; + let mut left_end = -roadway_width(strips) / 2.0; + let mut right_start = roadway_width(strips) / 2.0; + for (strip, (lo, hi)) in strips.iter().zip(positions(strips)) { + if let Strip::Lane { dir, .. } = strip { + if *dir == left_dir { + left_end = hi; + } else { + right_start = lo; + break; + } + } + } + (left_end, right_start) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn lane(dir: Direction, width: f32) -> Strip { + Strip::Lane { + dir, + width, + bus_only: false, + } + } + + #[test] + fn widths_and_origin_exclude_bays_and_footways() { + let strips = vec![ + Strip::Footway { + width: 2.0, + tex: "side.png".into(), + }, + Strip::BusBay { width: 3.0 }, + lane(Direction::Back, 3.0), + Strip::Median { + width: 2.0, + raised: true, + tex: "grass.png".into(), + }, + lane(Direction::Fwd, 4.0), + Strip::BusBay { width: 2.5 }, + ]; + assert_eq!(roadway_width(&strips), 9.0); + assert_eq!(canvas_width(&strips), 7.0); + assert_eq!( + positions(&strips), + vec![ + (-9.5, -7.5), + (-7.5, -4.5), + (-4.5, -1.5), + (-1.5, 0.5), + (0.5, 4.5), + (4.5, 7.0) + ] + ); + assert_eq!(median_edges(&strips, false), (-1.5, 0.5)); + assert_eq!(roadway_u(&strips, -4.5), 0.0); + assert_eq!(roadway_u(&strips, 4.5), 1.0); + assert_eq!(roadway_u(&strips, -1.5), roadway_u(&strips, 0.5)); + assert!(validate(&strips, false).is_ok()); + assert!(validate(&strips, true).is_err()); + } + + #[test] + fn rejects_nonfinite_widths_and_disallowed_orderings() { + let foot = Strip::Footway { + width: 2.0, + tex: PathBuf::new(), + }; + let median = Strip::Median { + width: 2.0, + raised: false, + tex: PathBuf::new(), + }; + for strips in [ + vec![], + vec![lane(Direction::Fwd, f32::NAN)], + vec![median, lane(Direction::Fwd, 3.0)], + vec![lane(Direction::Back, 3.0), foot, lane(Direction::Fwd, 3.0)], + vec![lane(Direction::Fwd, 3.0), lane(Direction::Back, 3.0)], + vec![ + Strip::BusBay { width: 3.0 }, + Strip::BusBay { width: 3.0 }, + lane(Direction::Fwd, 3.0), + ], + ] { + assert!(validate(&strips, false).is_err(), "{strips:?}"); + } + } +} diff --git a/src/ui_roads.rs b/src/ui_roads.rs index 7f00bb3..ce0b973 100644 --- a/src/ui_roads.rs +++ b/src/ui_roads.rs @@ -358,7 +358,7 @@ impl RoadTypes { ed.set_tool(crate::editor::Tool::Roads); } let path = roots.resolve(&rel); - if let Some(spec) = RoadSpec::of(&path) { + if let Some(spec) = RoadSpec::of_with_traffic(&path, left_hand) { if ui.button(icons::labelled(Icon::Settings, tr("Change it in the road maker", "Изменить в конструкторе"))).clicked() { self.maker = Some(spec); } @@ -440,6 +440,12 @@ impl RoadTypes { fn maker_ui(ui: &mut egui::Ui, s: &mut RoadSpec, textures: &mut Option>, search: &mut [String; 3], roots: &Roots, tex: &mut TexCache, canvas: &mut bool, left_hand: bool) { ui.label(RichText::new(tr("Road maker", "Конструктор дороги")).strong().color(Color32::WHITE)); + let map_left_hand = left_hand; + let left_hand = s.left_hand.unwrap_or(map_left_hand); + if left_hand != map_left_hand { + ui.colored_label(Color32::YELLOW, if left_hand { "此道路是為靠左行駛建立的" } else { "此道路是為靠右行駛建立的" }); + } + ui.horizontal(|ui| { ui.label(tr("Start from", "Взять за основу")); egui::ComboBox::from_id_salt("road preset").selected_text(tr("a ready-made road…", "готовую дорогу…")).show_ui(ui, |ui| { @@ -497,6 +503,7 @@ impl RoadTypes { ui.add(egui::Slider::new(&mut s.pocket, 0.0..=4.0).suffix(" m")).on_hover_text(tr("A lane for buses to stop in, right of the roadway, before the footway. Lay a road type made so where a bay is wanted with the Bus pocket tool of the Roads tool", "Полоса для остановки автобусов справа от проезжей части, перед тротуаром. Дорогой такого типа делают карман инструментом «Автобусный карман» в «Дорогах»")); ui.end_row(); }); + s.rebuild_strips(left_hand); preview(ui, s, tex, left_hand); let list = textures.get_or_insert_with(|| spline_textures(roots)); let has_median = s.median_width() > 0.0; @@ -534,6 +541,7 @@ impl RoadTypes { } }); } + s.rebuild_strips(left_hand); egui::CollapsingHeader::new(RichText::new(tr("Road markings", "Дорожная разметка")).strong().color(Color32::WHITE)).id_salt("road markings").default_open(s.marked).show(ui, |ui| { ui.checkbox(&mut s.marked, tr("Paint my own markings", "Нарисовать свою разметку")).on_hover_text(tr("The maker paints the lines onto the roadway texture: pick a plain asphalt texture, or its own lines show too", "Конструктор рисует линии на текстуре проезжей части: берите гладкий асфальт, иначе проступят и его собственные линии")); if !s.marked { From 6f3be511c329b49dd452a00e3c44d141e5f32ffa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BB=B7=E6=96=87=20=E6=A5=8A?= Date: Mon, 16 Nov 2026 03:47:46 +0800 Subject: [PATCH 2/6] Add advanced road strip editing and derived bus lane paths --- src/road_maker.rs | 102 ++++++++++++++-- src/road_maker/free_layout.rs | 147 +++++++++++++++++++++++ src/road_maker/layout_tests.rs | 126 ++++++++++++++++++++ src/ui_roads.rs | 208 +++++---------------------------- src/ui_roads/strip_panel.rs | 130 +++++++++++++++++++++ src/ui_roads/strip_preview.rs | 160 +++++++++++++++++++++++++ 6 files changed, 681 insertions(+), 192 deletions(-) create mode 100644 src/road_maker/free_layout.rs create mode 100644 src/road_maker/layout_tests.rs create mode 100644 src/ui_roads/strip_panel.rs create mode 100644 src/ui_roads/strip_preview.rs diff --git a/src/road_maker.rs b/src/road_maker.rs index ef5474f..af1652d 100644 --- a/src/road_maker.rs +++ b/src/road_maker.rs @@ -18,6 +18,7 @@ use std::path::{Path, PathBuf}; use serde::{Deserialize, Serialize}; mod strips; mod migration; +mod free_layout; pub use strips::{Direction, Strip}; #[cfg(test)] #[allow(dead_code)] @@ -194,6 +195,12 @@ pub fn arrow_polygon(at: (f32, f32), back: bool) -> Vec<(f32, f32)> { pub struct RoadSpec { /// Canonical cross section, in physical left-to-right order. pub strips: Vec, + /// Derived at export; never trusted from an edited sidecar. + pub bus_paths: Vec, + #[serde(skip)] + pub advanced: bool, + #[serde(skip)] + pub mode_error: Option, /// None only while importing old parameters or initializing a new road. pub left_hand: Option, pub name: String, @@ -231,7 +238,7 @@ pub struct RoadSpec { impl Default for RoadSpec { fn default() -> Self { - RoadSpec { strips: Vec::new(), left_hand: None, name: String::new(), lanes_fwd: 1, lanes_back: 1, lane_width: 3.5, median: 0.0, median_raised: false, footway: 3.0, footway_right: None, kerb: 0.15, pocket: 0.0, roadway_tex: PathBuf::new(), footway_tex: PathBuf::new(), median_tex: PathBuf::new(), marked: false, markings: Vec::new(), hand: None } + RoadSpec { bus_paths: Vec::new(), advanced: false, mode_error: None, strips: Vec::new(), left_hand: None, name: String::new(), lanes_fwd: 1, lanes_back: 1, lane_width: 3.5, median: 0.0, median_raised: false, footway: 3.0, footway_right: None, kerb: 0.15, pocket: 0.0, roadway_tex: PathBuf::new(), footway_tex: PathBuf::new(), median_tex: PathBuf::new(), marked: false, markings: Vec::new(), hand: None } } } @@ -256,6 +263,8 @@ pub fn presets() -> Vec<(&'static str, RoadSpec)> { } impl RoadSpec { + const LEGACY_FIELDS: [&'static str; 9] = ["lanes_fwd", "lanes_back", "lane_width", "median", "median_raised", "footway", "footway_right", "pocket", "median_tex"]; + /// Only the old-parameter import boundary may synthesize strips. fn effective_strips(&self) -> std::borrow::Cow<'_, [Strip]> { @@ -311,6 +320,54 @@ impl RoadSpec { s } + pub fn strip_positions(&self) -> Vec<(f32, f32)> { strips::positions(&self.effective_strips()) } + + pub fn bus_path_indices(&self) -> Vec { + let mut path = 0; + let mut result = Vec::new(); + for strip in &self.strips { + if matches!(strip, Strip::Median { .. }) { continue; } + if matches!(strip, Strip::Lane { bus_only: true, .. }) { result.push(path); } + path += 1; + } + result + } + + pub fn simple_mode_issues(&self) -> Vec { + let mut issues = Vec::new(); + if let Err(error) = self.validate() { issues.push(error); } + let strips = self.effective_strips(); + let lanes: Vec<_> = strips.iter().filter_map(|s| if let Strip::Lane { width, .. } = s { Some(*width) } else { None }).collect(); + if lanes.windows(2).any(|p| p[0] != p[1]) { issues.push("車道寬度不一致".into()); } + if strips.iter().any(|s| matches!(s, Strip::Lane { bus_only: true, .. })) { issues.push("含公車專用車道".into()); } + let medians: Vec<_> = strips.iter().enumerate().filter(|(_, s)| matches!(s, Strip::Median { .. })).collect(); + if medians.len() > 1 { issues.push("含多個分隔島".into()); } + for (i, _) in medians { + let left = strips[..i].iter().rev().find_map(|s| if let Strip::Lane { dir, .. } = s { Some(*dir) } else { None }); + let right = strips[i+1..].iter().find_map(|s| if let Strip::Lane { dir, .. } = s { Some(*dir) } else { None }); + if left.is_none() || right.is_none() || left == right { issues.push("分隔島不在兩向車道交界".into()); } + } + let first_lane = strips.iter().position(|s| matches!(s, Strip::Lane { .. })).unwrap_or(0); + if strips[..first_lane].iter().any(|s| matches!(s, Strip::BusBay { .. })) { issues.push("左側含 BusBay".into()); } + let textures: Vec<_> = strips.iter().filter_map(|s| if let Strip::Footway { tex, .. } = s { Some(tex) } else { None }).collect(); + if textures.windows(2).any(|p| p[0] != p[1]) { issues.push("兩側人行道使用不同材質".into()); } + issues + } + + pub fn use_simple_mode(&mut self) -> Result<(), Vec> { + let issues = self.simple_mode_issues(); + if !issues.is_empty() { return Err(issues); } + *self = self.projection(); + self.advanced = false; + self.mode_error = None; + Ok(()) + } + + pub fn unequal_lane_widths(&self) -> bool { + let widths: Vec<_> = self.strips.iter().filter_map(|s| if let Strip::Lane { width, .. } = s { Some(*width) } else { None }).collect(); + widths.windows(2).any(|p| p[0] != p[1]) + } + pub fn validate(&self) -> Result<(), String> { strips::validate(&self.effective_strips(), self.left_hand.unwrap_or(false)) } @@ -458,8 +515,12 @@ impl RoadSpec { /// The `.sli` text (OMSI's own keywords; `\n`, turned into CR LF when written). pub fn sli(&self, left_hand: bool) -> String { - let s = self.normalised(left_hand).projection(); - s.compatible_sli(s.left_hand.unwrap()) + let s = self.normalised(left_hand); + if s.validate().is_err() { return String::new(); } + if s.simple_mode_issues().is_empty() { + let projected = s.projection(); + projected.compatible_sli(projected.left_hand.unwrap()) + } else { free_layout::emit(&s) } } fn compatible_sli(&self, left_hand: bool) -> String { @@ -580,7 +641,8 @@ impl RoadSpec { /// Write it into the content folder with its textures; returns its relative path /// (`Splines\openMapper\.sli`). pub fn write_with_traffic(&self, content: &Path, left_hand: bool) -> anyhow::Result { - let spec = self.normalised(left_hand); + let mut spec = self.normalised(left_hand); + spec.bus_paths = spec.bus_path_indices(); spec.validate().map_err(anyhow::Error::msg)?; spec.write_normalised(content) } @@ -591,7 +653,10 @@ impl RoadSpec { let dir = content.join("Splines").join("openMapper"); let tex_dir = dir.join("texture"); std::fs::create_dir_all(&tex_dir)?; - for t in [&self.roadway_tex, &self.footway_tex, &self.median_tex].into_iter().filter(|t| t.is_file()) { + let strip_textures = self.strips.iter().filter_map(|strip| match strip { + Strip::Footway { tex, .. } | Strip::Median { tex, .. } => Some(tex), _ => None, + }); + for t in [&self.roadway_tex, &self.footway_tex, &self.median_tex].into_iter().chain(strip_textures).filter(|t| t.is_file()) { let name = t.file_name().unwrap(); if t.parent() != Some(tex_dir.as_path()) { std::fs::copy(t, tex_dir.join(name))?; @@ -624,7 +689,15 @@ impl RoadSpec { let path = dir.join(format!("{stem}.sli")); crate::doc::safe::write_atomic(&path, &omsi_cfg::encode_text(&self.sli(left_hand).replace('\n', "\r\n")))?; // (the spec beside it, so the road can be opened in the maker again) - crate::doc::safe::write_atomic(&dir.join(format!("{stem}.road.json")), serde_json::to_string_pretty(self)?.as_bytes())?; + let mut saved = serde_json::to_value(self)?; + if self.simple_mode_issues().is_empty() { + let projected = serde_json::to_value(self.projection())?; + for field in Self::LEGACY_FIELDS { saved[field] = projected[field].clone(); } + saved["footway_tex"] = projected["footway_tex"].clone(); + } else { + for field in Self::LEGACY_FIELDS { saved.as_object_mut().unwrap().remove(field); } + } + crate::doc::safe::write_atomic(&dir.join(format!("{stem}.road.json")), serde_json::to_string_pretty(&saved)?.as_bytes())?; let marks = dir.join(format!("{stem}.marks.png")); match self.hand.as_ref().filter(|h| self.marked && !h.is_empty()) { Some(h) => h.img.save(&marks)?, @@ -653,6 +726,12 @@ impl RoadSpec { spec.hand = Some(std::sync::Arc::new(Hand { img })); } } + spec.bus_paths = spec.bus_path_indices(); + spec.advanced = !spec.simple_mode_issues().is_empty(); + if !spec.advanced { + // Controls are a projection; the saved strips remain authoritative. + spec = spec.projection(); + } Some(spec) } } @@ -820,7 +899,7 @@ mod tests { assert!((half - 7.0).abs() < 1e-6); assert!(s.profiles.iter().any(|p| p.points.iter().any(|q| (q.x - half).abs() < 1e-3))); assert!(content.join("Splines/openMapper/texture/asph.png").is_file()); - assert_eq!(RoadSpec::of(&path).unwrap(), spec.normalised(false)); + assert_eq!(RoadSpec::of(&path).unwrap(), spec.normalised(false).projection()); let _ = std::fs::remove_dir_all(dir); } @@ -850,7 +929,7 @@ mod tests { assert_eq!(walks.len(), 1); assert!(walks[0].start[0] > 0.0); assert!(content.join("Splines/openMapper/texture/g.png").is_file()); - assert_eq!(RoadSpec::of(&content.join("Splines/openMapper/Avenue.sli")).unwrap(), spec.normalised(false)); + assert_eq!(RoadSpec::of(&content.join("Splines/openMapper/Avenue.sli")).unwrap(), spec.normalised(false).projection()); // an old spec file (before these fields) still reads let old: RoadSpec = serde_json::from_str("{\"name\":\"x\",\"lanes_fwd\":1,\"lanes_back\":1}").unwrap(); assert_eq!(old.footway_right(), old.footway); @@ -912,7 +991,7 @@ mod tests { let right = s.profiles.iter().flat_map(|p| p.points.iter()).map(|q| q.x).fold(f32::MIN, f32::max); assert!((right - 8.5).abs() < 1e-3, "{right}"); // the spec reads back, and an old file without a pocket has none - assert_eq!(RoadSpec::of(&content.join("Splines/openMapper/Bay.sli")).unwrap(), spec.normalised(false)); + assert_eq!(RoadSpec::of(&content.join("Splines/openMapper/Bay.sli")).unwrap(), spec.normalised(false).projection()); let old: RoadSpec = serde_json::from_str("{\"name\":\"x\"}").unwrap(); assert_eq!(old.pocket, 0.0); let _ = std::fs::remove_dir_all(dir); @@ -941,7 +1020,7 @@ mod tests { assert!(content.join("Splines/openMapper/texture/Lined_lines.bmp").is_file()); let s = omsi_scenery::Spline::load(&content.join("Splines/openMapper/Lined.sli")).unwrap(); assert!(s.textures[0].file.eq_ignore_ascii_case("Lined_lines.bmp"), "{}", s.textures[0].file); - assert_eq!(RoadSpec::of(&content.join("Splines/openMapper/Lined.sli")).unwrap(), spec.normalised(false)); + assert_eq!(RoadSpec::of(&content.join("Splines/openMapper/Lined.sli")).unwrap(), spec.normalised(false).projection()); // a dashed line's dashes come a whole number to the texture let d = Marking { style: MarkStyle::Dashed, dash: 3.0, gap: 6.0, ..Default::default() }; let spec2 = RoadSpec { markings: vec![d.clone()], ..spec.clone() }; @@ -1004,3 +1083,6 @@ mod tests { #[cfg(test)] mod compat_tests; + +#[cfg(test)] +mod layout_tests; diff --git a/src/road_maker/free_layout.rs b/src/road_maker/free_layout.rs new file mode 100644 index 0000000..0f4f34c --- /dev/null +++ b/src/road_maker/free_layout.rs @@ -0,0 +1,147 @@ +//! Emission for layouts not representable by the original quick parameters. +use super::*; + +pub(super) fn emit(spec: &RoadSpec) -> String { + let strips = &spec.strips; + let positions = strips::positions(strips); + let mut text = format!( + "File created with openMapper\n\n[friendlyname]\n{}\n\n", + spec.name.trim() + ); + for (strip, (lo, hi)) in strips.iter().zip(&positions) { + let h = strip.height(spec.kerb); + let _ = write!( + text, + "[heightprofile]\n{}\n{}\n{}\n{}\n\n", + num(*lo), + num(*hi), + num(h), + num(h) + ); + } + let mut textures = vec![spec.roadway_tex_name()]; + let mut texture_index = |path: &Path| -> usize { + if path.as_os_str().is_empty() { + return 0; + } + let name = path + .file_name() + .unwrap_or_default() + .to_string_lossy() + .into_owned(); + if let Some(index) = textures.iter().position(|s| s == &name) { + index + } else { + textures.push(name); + textures.len() - 1 + } + }; + let side_index = texture_index(&spec.footway_tex); + let mut indices = Vec::new(); + for strip in strips { + indices.push(match strip { + Strip::Footway { tex, .. } | Strip::Median { tex, .. } => texture_index(tex), + _ => 0, + }); + } + let bay_index = textures.len(); + if strips.iter().any(|s| matches!(s, Strip::BusBay { .. })) { + textures.push(spec.bay_tex_name()); + } + for name in textures { + let _ = write!(text, "[texture]\n{name}\n\n"); + } + let profile = |s: &mut String, index, a: (f32, f32, f32, f32), b: (f32, f32, f32, f32)| { + let _ = write!(s, "[profile]\n{index}\n\n"); + for (x, h, u, v) in [a, b] { + let _ = write!( + s, + "[profilepnt]\n{}\n{}\n{}\n{}\n\n", + num(x), + num(h), + num(u), + num(v) + ); + } + }; + for (i, (strip, (lo, hi))) in strips.iter().zip(&positions).enumerate() { + let h = strip.height(spec.kerb); + let (index, u0, u1, v) = match strip { + Strip::Lane { .. } => ( + 0, + spec.roadway_u(*lo), + spec.roadway_u(*hi), + spec.roadway_v(), + ), + Strip::BusBay { .. } => (bay_index, 0.0, 1.0, spec.roadway_v()), + Strip::Footway { .. } if i == 0 => (indices[i], 0.187, 0.953, 0.2), + Strip::Footway { .. } => (indices[i], 0.953, 0.187, 0.2), + Strip::Median { width, tex, .. } if !tex.as_os_str().is_empty() => { + (indices[i], 0.0, 1.0, *width) + } + Strip::Median { raised: true, .. } if side_index != 0 => { + (side_index, 0.953, 0.187, 0.2) + } + Strip::Median { .. } => ( + 0, + spec.roadway_u(*lo), + spec.roadway_u(*hi), + spec.roadway_v(), + ), + }; + profile(&mut text, index, (*lo, h, u0, v), (*hi, h, u1, v)); + if let Some(next) = strips.get(i + 1) { + let next_h = next.height(spec.kerb); + if h != next_h { + let index = if matches!(strip, Strip::Footway { .. }) { + indices[i] + } else if matches!(next, Strip::Footway { .. }) { + indices[i + 1] + } else { + side_index + }; + let (u0, u1) = if h < next_h { + (0.995, 0.953) + } else { + (0.953, 0.995) + }; + profile(&mut text, index, (*hi, h, u0, 0.2), (*hi, next_h, u1, 0.2)); + } + } + } + for (i, (strip, (lo, hi))) in strips.iter().zip(&positions).enumerate() { + let (kind, direction, scale) = match strip { + Strip::Lane { dir, .. } => (0, dir.path_direction(), 0.9), + Strip::Footway { .. } => (1, 2, 0.4), + Strip::BusBay { .. } => { + let adjacent = if strips[..i].iter().any(|s| matches!(s, Strip::Lane { .. })) { + strips[..i].iter().rev().find_map(|s| { + if let Strip::Lane { dir, .. } = s { + Some(*dir) + } else { + None + } + }) + } else { + strips[i + 1..].iter().find_map(|s| { + if let Strip::Lane { dir, .. } = s { + Some(*dir) + } else { + None + } + }) + }; + (0, adjacent.unwrap().path_direction(), 0.9) + } + Strip::Median { .. } => continue, + }; + let _ = write!( + text, + "[path]\n{kind}\n{}\n{}\n{}\n{direction}\n\n", + num((lo + hi) / 2.0), + num(strip.height(spec.kerb)), + num(strip.width() * scale) + ); + } + text +} diff --git a/src/road_maker/layout_tests.rs b/src/road_maker/layout_tests.rs new file mode 100644 index 0000000..747817a --- /dev/null +++ b/src/road_maker/layout_tests.rs @@ -0,0 +1,126 @@ +use super::*; + +fn lane(dir: Direction, width: f32, bus_only: bool) -> Strip { + Strip::Lane { + dir, + width, + bus_only, + } +} +fn spec() -> RoadSpec { + RoadSpec { + left_hand: Some(false), + strips: vec![ + Strip::Footway { + width: 2.0, + tex: PathBuf::new(), + }, + Strip::BusBay { width: 3.0 }, + lane(Direction::Back, 3.0, true), + Strip::Median { + width: 2.0, + raised: true, + tex: PathBuf::new(), + }, + lane(Direction::Fwd, 4.0, false), + lane(Direction::Fwd, 3.5, true), + Strip::BusBay { width: 2.5 }, + Strip::Footway { + width: 1.0, + tex: PathBuf::new(), + }, + ], + ..Default::default() + } +} + +#[test] +fn unequal_lanes_and_two_bays_emit_actual_paths_and_share_one_bay_texture() { + let root = std::env::temp_dir().join(format!("om-layout-{}", std::process::id())); + std::fs::create_dir_all(&root).unwrap(); + let tex = root.join("asphalt.png"); + image::RgbaImage::from_pixel(2, 2, image::Rgba([80, 80, 80, 255])) + .save(&tex) + .unwrap(); + let mut road = spec(); + road.roadway_tex = tex; + road.name = "Layout".into(); + road.write(&root).unwrap(); + let path = root.join("Splines/openMapper/Layout.sli"); + let spline = omsi_scenery::Spline::load(&path).unwrap(); + let actual: Vec<_> = spline + .paths + .iter() + .map(|p| (p.kind, p.start[0], p.width, p.direction)) + .collect(); + assert_eq!( + actual, + vec![ + (1, -10.25, 0.8, 2), + (0, -7.75, 2.7, 1), + (0, -4.75, 2.7, 1), + (0, 0.75, 3.6, 0), + (0, 4.5, 3.15, 0), + (0, 7.5, 2.25, 0), + (1, 9.25, 0.4, 2) + ] + ); + assert_eq!( + spline + .textures + .iter() + .filter(|t| t.file == "Layout_bay.png") + .count(), + 1 + ); + let json: serde_json::Value = + serde_json::from_slice(&std::fs::read(path.with_extension("road.json")).unwrap()).unwrap(); + assert_eq!(json["bus_paths"], serde_json::json!([2, 4])); + assert!(json.get("lane_width").is_none()); + let loaded = RoadSpec::of(&path).unwrap(); + assert!(loaded.advanced); + assert_eq!(loaded.strips, road.strips); + assert_eq!(loaded.sli(false), road.sli(false)); + assert!( + road.standard_markings() + .iter() + .any(|m| m.x == 2.75 && m.style == MarkStyle::Dashed) + ); + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn switching_to_simple_mode_rejects_lossy_settings_and_projects_representable_roads() { + let mut road = spec(); + road.advanced = true; + let before = road.strips.clone(); + let reasons = road.use_simple_mode().unwrap_err(); + assert!(reasons.iter().any(|r| r.contains("寬度"))); + assert!(reasons.iter().any(|r| r.contains("公車"))); + assert!(reasons.iter().any(|r| r.contains("左側"))); + assert_eq!(road.strips, before); + assert!(road.advanced); + let mut road = RoadSpec { + lanes_back: 2, + lanes_fwd: 1, + pocket: 3.0, + ..Default::default() + } + .normalised(true); + road.advanced = true; + road.lanes_back = 99; // stale controls must never override the strips + road.use_simple_mode().unwrap(); + assert_eq!(road.lanes_back, 2); + assert_eq!(road.lanes_fwd, 1); + assert_eq!(road.pocket, 3.0); + assert!(!road.advanced); +} + +#[test] +fn invalid_layout_is_rejected_before_creating_output_files() { + let root = std::env::temp_dir().join(format!("om-invalid-layout-{}", std::process::id())); + let mut road = spec(); + road.strips.swap(2, 4); + assert!(road.write(&root).is_err()); + assert!(!root.exists()); +} diff --git a/src/ui_roads.rs b/src/ui_roads.rs index ce0b973..2952119 100644 --- a/src/ui_roads.rs +++ b/src/ui_roads.rs @@ -2,6 +2,8 @@ //! of new road types (lanes, widths, footways, textures), written as ordinary OMSI splines. use std::path::{Path, PathBuf}; +mod strip_panel; +mod strip_preview; use egui::{Color32, Pos2, RichText, Sense, Stroke, Vec2}; @@ -65,122 +67,8 @@ fn file_name(p: &Path) -> String { /// The road seen from above, a stretch of it running up the picture: footways and kerbs, the /// roadway with its lane lines (dashed between lanes of one way, solid at the middle), the /// middle strip, the pocket, and arrows for the ways the lanes go. -fn plan(ui: &mut egui::Ui, s: &RoadSpec, tex: &mut TexCache, left_hand: bool) { - let (rect, _) = ui.allocate_exact_size(Vec2::new(ui.available_width(), 170.0), Sense::hover()); - let p = ui.painter_at(rect); - p.rect_filled(rect, 3.0, Color32::from_rgb(28, 30, 33)); - let total = s.total_width().max(1.0); - let k = ((rect.width() - 30.0) / total).min((rect.height() - 20.0) / 14.0); - let rw = s.roadway_width(); - let centre = rect.center().x + (s.footway_left() - s.footway_right() - s.pocket) / 2.0 * k; - let x = |m: f32| centre + m * k; - let (top, bottom) = (rect.top() + 6.0, rect.bottom() - 18.0); - let ctx = ui.ctx().clone(); - let (road_t, foot_t) = (tex.get(&ctx, &s.roadway_tex), tex.get(&ctx, &s.footway_tex)); - let med_t = tex.get(&ctx, &s.median_tex); - // a band across the road from `a` to `b` m, painted with a picture over the u range - // `u` (v running along the road, `per_m` of it to the metre) - let strip = |a: f32, b: f32, col: Color32, pic: Option, u: (f32, f32), per_m: f32| { - let v = (bottom - top) / k * per_m; - quad(&p, pic, [Pos2::new(x(a), top), Pos2::new(x(b), top), Pos2::new(x(b), bottom), Pos2::new(x(a), bottom)], [Pos2::new(u.0, v), Pos2::new(u.1, v), Pos2::new(u.1, 0.0), Pos2::new(u.0, 0.0)], col); - }; - let walk = Color32::from_rgb(150, 150, 145); - strip(-rw / 2.0 - s.footway_left(), -rw / 2.0, walk, foot_t, (0.187, 0.953), 0.2); - strip(rw / 2.0 + s.pocket, rw / 2.0 + s.pocket + s.footway_right(), walk, foot_t, (0.953, 0.187), 0.2); - strip(-rw / 2.0, rw / 2.0, Color32::from_rgb(70, 72, 76), road_t, (0.0, 1.0), 0.1); - if s.pocket > 0.0 { - let u = 0.5 / (s.lanes_fwd + s.lanes_back).max(1) as f32; - strip(rw / 2.0, rw / 2.0 + s.pocket, Color32::from_rgb(86, 90, 104), road_t, (u - 0.01, u + 0.01), 0.1); - } - // kerbs - let kerb = |m: f32| { - if s.kerb > 0.0 { - p.line_segment([Pos2::new(x(m), top), Pos2::new(x(m), bottom)], Stroke::new(2.0, Color32::from_gray(205))); - } - }; - if s.footway_left() > 0.0 { - kerb(-rw / 2.0); - } - if s.footway_right() > 0.0 { - kerb(rw / 2.0 + s.pocket); - } - let mid = s.median_width(); - let two_way = s.lanes_fwd > 0 && s.lanes_back > 0; - if mid > 0.0 { - let col = if s.median_tex.as_os_str().is_empty() { Color32::from_rgb(90, 92, 96) } else { Color32::from_rgb(86, 128, 74) }; - let (ml, mr) = s.median_edges(); - strip(ml, mr, col, med_t, (0.0, 1.0), 0.2); - } - let dash = |m: f32, col: Color32, solid: bool| { - let mut y = bottom; - while y > top { - let y2 = if solid { top } else { (y - 1.5 * k).max(top) }; - p.line_segment([Pos2::new(x(m), y), Pos2::new(x(m), y2)], Stroke::new(1.5, col)); - if solid { - break; - } - y -= 3.0 * k; - } - }; - let white = Color32::from_gray(225); - let yellow = Color32::from_rgb(232, 190, 60); - let gap = if two_way { mid / 2.0 } else { 0.0 }; - let arrow = |m: f32, up: bool, col: Color32| { - // (drawn, not written: a lane's arrow must show whatever fonts there are) - let dir = if up { -1.0 } else { 1.0 }; - for y in [bottom - 22.0, top + 40.0] { - p.add(egui::Shape::convex_polygon(vec![Pos2::new(x(m), y + dir * 8.0), Pos2::new(x(m) - 5.0, y - dir * 6.0), Pos2::new(x(m) + 5.0, y - dir * 6.0)], col, Stroke::NONE)); - } - }; - let lanes = |first: f32, n: u8, up: bool| { - for i in 0..n { - let l = first + i as f32 * s.lane_width; - arrow(l + s.lane_width / 2.0, up, Color32::from_rgb(if up { 232 } else { 110 }, if up { 170 } else { 180 }, if up { 60 } else { 240 })); - if i > 0 && !s.marked { - dash(l, white, false); - } - } - }; - let offset = s.centerline(); - if two_way { - lanes(offset - gap - s.lanes_back as f32 * s.lane_width, s.lanes_back, left_hand); - lanes(offset + gap, s.lanes_fwd, !left_hand); - if mid <= 0.0 && !s.marked { - dash(offset - 0.1, yellow, true); - dash(offset + 0.1, yellow, true); - } - } else { - lanes(-rw / 2.0, s.lanes_fwd + s.lanes_back, (s.lanes_fwd > 0) != left_hand); - } - if s.marked { - // the painted lines, as the texture will have them (dashes at their real length) - for m in &s.markings { - let col = Color32::from_rgb(m.color[0], m.color[1], m.color[2]); - let period = s.dash_period(m); - for (lx, dashed) in m.lines_at() { - let mut y = bottom; - while y > top { - let y2 = if dashed { (y - m.dash.min(period) * k).max(top) } else { top }; - p.line_segment([Pos2::new(x(lx), y), Pos2::new(x(lx), y2)], Stroke::new((m.width * k).max(1.0), col)); - if !dashed { - break; - } - y -= period * k; - } - } - } - } else if s.pocket > 0.0 { - dash(rw / 2.0, white, false); - } - if s.pocket > 0.0 { - arrow(rw / 2.0 + s.pocket / 2.0, !left_hand, Color32::from_rgb(120, 200, 150)); - p.text(Pos2::new(x(rw / 2.0 + s.pocket / 2.0), (top + bottom) / 2.0), egui::Align2::CENTER_CENTER, "BUS", egui::FontId::proportional(11.0), Color32::from_rgb(120, 200, 150)); - } - // 5 m scale - let sy = rect.bottom() - 9.0; - p.line_segment([Pos2::new(rect.left() + 10.0, sy), Pos2::new(rect.left() + 10.0 + 5.0 * k, sy)], Stroke::new(2.0, Color32::from_gray(170))); - p.text(Pos2::new(rect.left() + 16.0 + 5.0 * k, sy), egui::Align2::LEFT_CENTER, "5 m", egui::FontId::proportional(11.0), Color32::from_gray(170)); - p.text(Pos2::new(rect.right() - 8.0, sy), egui::Align2::RIGHT_CENTER, format!("{:.1} m", total), egui::FontId::proportional(11.0), Color32::from_gray(170)); +fn plan(ui: &mut egui::Ui, s: &RoadSpec, tex: &mut TexCache, _left_hand: bool) { + strip_preview::draw(ui, s, tex, true); } /// The spline seen from above or across it (the choice is kept while the maker is open). @@ -197,69 +85,7 @@ fn preview(ui: &mut egui::Ui, s: &RoadSpec, tex: &mut TexCache, left_hand: bool) /// The road's cross-section, drawn as one looks along it. fn section(ui: &mut egui::Ui, s: &RoadSpec, tex: &mut TexCache) { - let (rect, _) = ui.allocate_exact_size(Vec2::new(ui.available_width(), 100.0), Sense::hover()); - let p = ui.painter_at(rect); - p.rect_filled(rect, 3.0, Color32::from_rgb(28, 30, 33)); - let total = s.total_width().max(1.0); - let k = (rect.width() - 20.0) / total; - let rw = s.roadway_width(); - // (the road's middle is the origin; the footways and the pocket make the picture lean to - // the wider side) - let centre = rect.center().x + (s.footway_left() - s.footway_right() - s.pocket) / 2.0 * k; - let x = |m: f32| centre + m * k; - let base = rect.bottom() - 26.0; - let lift = (s.kerb * k * 4.0).min(16.0); - let ctx = ui.ctx().clone(); - let (road_t, foot_t, med_t) = (tex.get(&ctx, &s.roadway_tex), tex.get(&ctx, &s.footway_tex), tex.get(&ctx, &s.median_tex)); - // a surface's top seen end on, painted with its picture over the u range `u` - let band = |a: f32, b: f32, y0: f32, col: Color32, pic: Option, u: (f32, f32)| { - quad(&p, pic, [Pos2::new(x(a), y0), Pos2::new(x(b), y0), Pos2::new(x(b), base), Pos2::new(x(a), base)], [Pos2::new(u.0, 0.0), Pos2::new(u.1, 0.0), Pos2::new(u.1, 0.4), Pos2::new(u.0, 0.4)], col); - }; - // footways - let walk = Color32::from_rgb(150, 150, 145); - if s.footway_left() > 0.0 { - band(-rw / 2.0 - s.footway_left(), -rw / 2.0, base - lift - 8.0, walk, foot_t, (0.187, 0.953)); - } - if s.footway_right() > 0.0 { - band(rw / 2.0 + s.pocket, rw / 2.0 + s.pocket + s.footway_right(), base - lift - 8.0, walk, foot_t, (0.953, 0.187)); - } - // the roadway, lanes, the middle - band(-rw / 2.0, rw / 2.0, base - 8.0, Color32::from_rgb(70, 72, 76), road_t, (0.0, 1.0)); - if s.pocket > 0.0 { - let u = 0.5 / (s.lanes_fwd + s.lanes_back).max(1) as f32; - band(rw / 2.0, rw / 2.0 + s.pocket, base - 8.0, Color32::from_rgb(86, 90, 104), road_t, (u - 0.01, u + 0.01)); - } - let two_way = s.lanes_fwd > 0 && s.lanes_back > 0; - let mid = s.median_width(); - if mid > 0.0 { - let own = !s.median_tex.as_os_str().is_empty(); - let col = if own { Color32::from_rgb(86, 128, 74) } else { Color32::from_rgb(90, 92, 96) }; - let up = if s.median_raised { lift } else { 0.0 }; - let (ml, mr) = s.median_edges(); - band(ml, mr, base - 8.0 - up, col, if own { med_t } else { road_t }, (0.0, 1.0)); - } - let gap = if two_way { mid / 2.0 } else { 0.0 }; - let lane = |left: f32, fwd: bool| { - let c = x(left + s.lane_width / 2.0); - let y = base - 18.0; - let col = if fwd { Color32::from_rgb(232, 170, 60) } else { Color32::from_rgb(110, 180, 240) }; - p.text(Pos2::new(c, y), egui::Align2::CENTER_CENTER, if fwd { Icon::Up.ch() } else { Icon::Down.ch() }, Icon::font(14.0), col); - p.line_segment([Pos2::new(x(left), base - 8.0), Pos2::new(x(left), base)], Stroke::new(1.0, Color32::from_gray(200))); - }; - let offset = s.centerline(); - if two_way { - for i in 0..s.lanes_back { - lane(offset - gap - (s.lanes_back - i) as f32 * s.lane_width, false); - } - for i in 0..s.lanes_fwd { - lane(offset + gap + i as f32 * s.lane_width, true); - } - } else { - for i in 0..(s.lanes_fwd + s.lanes_back) { - lane(-rw / 2.0 + i as f32 * s.lane_width, s.lanes_fwd > 0); - } - } - p.text(Pos2::new(rect.center().x, rect.bottom() - 10.0), egui::Align2::CENTER_CENTER, format!("{:.1} m · {} {:.1} m", total, tr("roadway", "проезжая часть"), rw), egui::FontId::proportional(11.0), Color32::from_gray(170)); + strip_preview::draw(ui, s, tex, false); } impl RoadTypes { @@ -446,6 +272,19 @@ impl RoadTypes { ui.colored_label(Color32::YELLOW, if left_hand { "此道路是為靠左行駛建立的" } else { "此道路是為靠右行駛建立的" }); } + if s.left_hand.is_none() { s.rebuild_strips(left_hand); } + let mut advanced = s.advanced; + if ui.checkbox(&mut advanced, "進階:積木模式").changed() { + if advanced { s.advanced = true; s.mode_error = None; } + else if let Err(issues) = s.use_simple_mode() { + s.mode_error = Some(format!("此道路含簡單模式無法表示的設定:{}", issues.join("、"))); + } + } + if let Some(error) = &s.mode_error { ui.colored_label(Color32::YELLOW, error); } + if s.advanced { + let list = textures.get_or_insert_with(|| spline_textures(roots)); + strip_panel::panel(ui, s, list); + } else { ui.horizontal(|ui| { ui.label(tr("Start from", "Взять за основу")); egui::ComboBox::from_id_salt("road preset").selected_text(tr("a ready-made road…", "готовую дорогу…")).show_ui(ui, |ui| { @@ -503,12 +342,17 @@ impl RoadTypes { ui.add(egui::Slider::new(&mut s.pocket, 0.0..=4.0).suffix(" m")).on_hover_text(tr("A lane for buses to stop in, right of the roadway, before the footway. Lay a road type made so where a bay is wanted with the Bus pocket tool of the Roads tool", "Полоса для остановки автобусов справа от проезжей части, перед тротуаром. Дорогой такого типа делают карман инструментом «Автобусный карман» в «Дорогах»")); ui.end_row(); }); - s.rebuild_strips(left_hand); + } + if !s.advanced { s.rebuild_strips(left_hand); } + if let Err(error) = s.validate() { ui.colored_label(Color32::RED, error); } + if !s.marked && s.unequal_lane_widths() { + ui.colored_label(Color32::YELLOW, "內建多車道貼圖的線會和車道對不上"); + } preview(ui, s, tex, left_hand); let list = textures.get_or_insert_with(|| spline_textures(roots)); let has_median = s.median_width() > 0.0; for (i, (label, hint)) in [(tr("Roadway texture", "Текстура проезжей части"), "asph"), (tr("Footway texture", "Текстура тротуара"), "side"), (tr("Middle strip texture", "Текстура разделителя"), "gras")].into_iter().enumerate() { - if i == 2 && !has_median { + if (s.advanced && i > 0) || (i == 2 && !has_median) { continue; } let cur = match i { 0 => &mut s.roadway_tex, 1 => &mut s.footway_tex, _ => &mut s.median_tex }; @@ -541,7 +385,7 @@ impl RoadTypes { } }); } - s.rebuild_strips(left_hand); + if !s.advanced { s.rebuild_strips(left_hand); } egui::CollapsingHeader::new(RichText::new(tr("Road markings", "Дорожная разметка")).strong().color(Color32::WHITE)).id_salt("road markings").default_open(s.marked).show(ui, |ui| { ui.checkbox(&mut s.marked, tr("Paint my own markings", "Нарисовать свою разметку")).on_hover_text(tr("The maker paints the lines onto the roadway texture: pick a plain asphalt texture, or its own lines show too", "Конструктор рисует линии на текстуре проезжей части: берите гладкий асфальт, иначе проступят и его собственные линии")); if !s.marked { diff --git a/src/ui_roads/strip_panel.rs b/src/ui_roads/strip_panel.rs new file mode 100644 index 0000000..f108500 --- /dev/null +++ b/src/ui_roads/strip_panel.rs @@ -0,0 +1,130 @@ +use super::*; +use crate::road_maker::{Direction, Strip}; + +pub(super) fn panel(ui: &mut egui::Ui, s: &mut RoadSpec, textures: &[PathBuf]) { + ui.horizontal(|ui| { + ui.label("名稱"); + ui.text_edit_singleline(&mut s.name); + ui.label("緣石高度"); + ui.add(egui::Slider::new(&mut s.kerb, 0.0..=0.3).suffix(" m")); + }); + ui.label("積木依道路左至右排列"); + let count = s.strips.len(); + let mut remove = None; + let mut swap = None; + for (i, strip) in s.strips.iter_mut().enumerate() { + ui.push_id(("strip", i), |ui| { + ui.group(|ui| { + ui.horizontal(|ui| { + ui.label(format!("{}", i + 1)); + ui.strong(match strip { + Strip::Lane { .. } => "Lane 車道", + Strip::Median { .. } => "Median 分隔島", + Strip::Footway { .. } => "Footway 人行道", + Strip::BusBay { .. } => "BusBay 巴士灣", + }); + if ui.add_enabled(i > 0, egui::Button::new("上移")).clicked() { + swap = Some((i, i - 1)); + } + if ui + .add_enabled(i + 1 < count, egui::Button::new("下移")) + .clicked() + { + swap = Some((i, i + 1)); + } + if ui.button("刪除").clicked() { + remove = Some(i); + } + }); + ui.horizontal(|ui| { + ui.label("寬度"); + match strip { + Strip::Lane { + dir, + width, + bus_only, + } => { + ui.add(egui::Slider::new(width, 2.5..=5.0).suffix(" m")); + ui.selectable_value(dir, Direction::Fwd, "順向 ↑"); + ui.selectable_value(dir, Direction::Back, "逆向 ↓"); + ui.checkbox(bus_only, "公車專用"); + } + Strip::Median { width, raised, .. } => { + ui.add(egui::Slider::new(width, 0.0..=12.0).suffix(" m")); + ui.checkbox(raised, "抬高"); + } + Strip::Footway { width, .. } => { + ui.add(egui::Slider::new(width, 0.1..=8.0).suffix(" m")); + } + Strip::BusBay { width } => { + ui.add(egui::Slider::new(width, 0.1..=4.0).suffix(" m")); + } + } + }); + if let Strip::Median { tex, .. } | Strip::Footway { tex, .. } = strip { + ui.horizontal(|ui| { + ui.label("材質"); + egui::ComboBox::from_id_salt("material") + .selected_text(if tex.as_os_str().is_empty() { + "使用車道材質".into() + } else { + file_name(tex) + }) + .show_ui(ui, |ui| { + if ui + .selectable_label(tex.as_os_str().is_empty(), "使用車道材質") + .clicked() + { + tex.clear(); + } + for path in textures { + if ui.selectable_label(tex == path, file_name(path)).clicked() { + *tex = path.clone(); + } + } + }); + if ui.button("選擇檔案…").clicked() { + if let Some(path) = rfd::FileDialog::new() + .add_filter("材質", &["png", "jpg", "bmp", "tga", "dds"]) + .pick_file() + { + *tex = path; + } + } + }); + } + }); + }); + } + if let Some(i) = remove { + s.strips.remove(i); + } else if let Some((a, b)) = swap { + s.strips.swap(a, b); + } + ui.horizontal(|ui| { + ui.label("新增"); + if ui.button("Lane").clicked() { + s.strips.push(Strip::Lane { + dir: Direction::Fwd, + width: 3.5, + bus_only: false, + }); + } + if ui.button("Median").clicked() { + s.strips.push(Strip::Median { + width: 2.0, + raised: true, + tex: s.median_tex.clone(), + }); + } + if ui.button("Footway").clicked() { + s.strips.push(Strip::Footway { + width: 2.0, + tex: s.footway_tex.clone(), + }); + } + if ui.button("BusBay").clicked() { + s.strips.push(Strip::BusBay { width: 3.0 }); + } + }); +} diff --git a/src/ui_roads/strip_preview.rs b/src/ui_roads/strip_preview.rs new file mode 100644 index 0000000..d9b8b2f --- /dev/null +++ b/src/ui_roads/strip_preview.rs @@ -0,0 +1,160 @@ +use super::*; +use crate::road_maker::{Direction, Strip}; + +pub(super) fn draw(ui: &mut egui::Ui, s: &RoadSpec, tex: &mut TexCache, top: bool) { + let (rect, _) = ui.allocate_exact_size( + Vec2::new(ui.available_width(), if top { 170.0 } else { 100.0 }), + Sense::hover(), + ); + let painter = ui.painter_at(rect); + painter.rect_filled(rect, 3.0, Color32::from_rgb(28, 30, 33)); + let positions = s.strip_positions(); + let lo = positions.first().map_or(0.0, |p| p.0); + let hi = positions.last().map_or(1.0, |p| p.1); + let scale = (rect.width() - 30.0) / (hi - lo).max(1.0); + let x = |m: f32| rect.center().x + (m - (lo + hi) / 2.0) * scale; + let bottom = rect.bottom() - 24.0; + for (i, (strip, &(a, b))) in s.strips.iter().zip(&positions).enumerate() { + let bus = matches!( + strip, + Strip::Lane { bus_only: true, .. } | Strip::BusBay { .. } + ); + let (color, path) = match strip { + Strip::Lane { .. } | Strip::BusBay { .. } => ( + if bus { + Color32::from_rgb(40, 160, 180) + } else { + Color32::from_rgb(100, 105, 115) + }, + &s.roadway_tex, + ), + Strip::Footway { tex, .. } => (Color32::from_gray(175), tex), + Strip::Median { tex, .. } => (Color32::from_rgb(100, 145, 90), tex), + }; + let pic = tex.get(ui.ctx(), path); + let y = if top { + rect.top() + 8.0 + } else { + bottom - 9.0 - ((strip.height(s.kerb) - 0.10) * scale * 4.0).min(18.0) + }; + let (u0, u1) = if matches!(strip, Strip::Lane { .. }) { + (s.roadway_u(a), s.roadway_u(b)) + } else { + (0.0, 1.0) + }; + quad( + &painter, + pic, + [ + Pos2::new(x(a), y), + Pos2::new(x(b), y), + Pos2::new(x(b), bottom), + Pos2::new(x(a), bottom), + ], + [ + Pos2::new(u0, 0.0), + Pos2::new(u1, 0.0), + Pos2::new(u1, 1.0), + Pos2::new(u0, 1.0), + ], + color, + ); + if bus { + painter.rect_filled( + egui::Rect::from_min_max(Pos2::new(x(a), y), Pos2::new(x(b), bottom)), + 0.0, + Color32::from_rgba_unmultiplied(0, 200, 230, 75), + ); + } + let direction = match strip { + Strip::Lane { dir, .. } => Some(*dir), + Strip::BusBay { .. } => s.strips[..i] + .iter() + .rev() + .chain(s.strips[i + 1..].iter()) + .find_map(|p| { + if let Strip::Lane { dir, .. } = p { + Some(*dir) + } else { + None + } + }), + _ => None, + }; + if let Some(dir) = direction { + let middle = x((a + b) / 2.0); + let cy = if top { (y + bottom) / 2.0 } else { y - 11.0 }; + let sign = if dir == Direction::Fwd { -1.0 } else { 1.0 }; + painter.add(egui::Shape::convex_polygon( + vec![ + Pos2::new(middle, cy + sign * 8.0), + Pos2::new(middle - 5.0, cy - sign * 5.0), + Pos2::new(middle + 5.0, cy - sign * 5.0), + ], + Color32::WHITE, + Stroke::NONE, + )); + if bus { + painter.text( + Pos2::new(middle, cy + 22.0), + egui::Align2::CENTER_CENTER, + "BUS", + egui::FontId::proportional(11.0), + Color32::WHITE, + ); + } + } + if i + 1 < s.strips.len() && strip.height(s.kerb) != s.strips[i + 1].height(s.kerb) { + let end = if top { + y + } else { + bottom - 9.0 - ((s.strips[i + 1].height(s.kerb) - 0.10) * scale * 4.0).min(18.0) + }; + painter.line_segment( + [Pos2::new(x(b), end), Pos2::new(x(b), bottom)], + Stroke::new(2.0, Color32::LIGHT_GRAY), + ); + } + } + if top { + let markings = if s.marked { + s.markings.clone() + } else { + s.standard_markings() + }; + for m in markings { + for (position, dashed) in m.lines_at() { + let mut y = rect.top() + 8.0; + while y < bottom { + let end = if dashed { + (y + m.dash * scale).min(bottom) + } else { + bottom + }; + painter.line_segment( + [Pos2::new(x(position), y), Pos2::new(x(position), end)], + Stroke::new( + (m.width * scale).max(1.0), + Color32::from_rgb(m.color[0], m.color[1], m.color[2]), + ), + ); + if !dashed { + break; + } + y += s.dash_period(&m) * scale; + } + } + } + } + painter.text( + Pos2::new(rect.center().x, rect.bottom() - 9.0), + egui::Align2::CENTER_CENTER, + format!( + "{:.1} m · roadway {:.1} m", + s.total_width(), + s.roadway_width() + ), + egui::FontId::proportional(11.0), + Color32::LIGHT_GRAY, + ); +} From 8a1d5934debb3e3b28b2cee6a83b6fb8b15f56d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BB=B7=E6=96=87=20=E6=A5=8A?= Date: Mon, 16 Nov 2026 04:22:57 +0800 Subject: [PATCH 3/6] Apply maker bus lane and bay rules to new and retyped splines --- src/clipboard.rs | 2 + src/doc/mod.rs | 1 + src/ed_cjunction.rs | 2 + src/editor.rs | 31 +++--- src/editor/bus_lane_tests.rs | 174 ++++++++++++++++++++++++++++++ src/parallel.rs | 1 + src/reshape.rs | 2 + src/road_maker.rs | 16 ++- src/road_maker/bus_rules.rs | 168 +++++++++++++++++++++++++++++ src/road_maker/bus_rules/tests.rs | 104 ++++++++++++++++++ 10 files changed, 483 insertions(+), 18 deletions(-) create mode 100644 src/editor/bus_lane_tests.rs create mode 100644 src/road_maker/bus_rules.rs create mode 100644 src/road_maker/bus_rules/tests.rs diff --git a/src/clipboard.rs b/src/clipboard.rs index 8e01b96..d68587e 100644 --- a/src/clipboard.rs +++ b/src/clipboard.rs @@ -229,6 +229,8 @@ pub fn paste(doc: &mut Document, clip: &Clip, at: DVec3) -> Vec { t.touch_content(); out.push(Sel::Spline(k, ids[&c.s.id])); } + let made: Vec<_> = out.iter().filter_map(|s| if let Sel::Spline(k, id) = s { Some((*k, *id)) } else { None }).collect(); + crate::road_maker::bus_rules::apply_for_splines(doc, &made, "clipboard::paste"); // what hangs on them, in order (a parent comes before what hangs on it) for a in &clip.attached { let Some(pid) = a.parent_id else { continue }; diff --git a/src/doc/mod.rs b/src/doc/mod.rs index 3d1835f..bab7dda 100644 --- a/src/doc/mod.rs +++ b/src/doc/mod.rs @@ -722,6 +722,7 @@ impl Document { } } } + crate::road_maker::bus_rules::apply_for_splines(self, &[(k, new)], "doc::split_spline"); Some(new) } diff --git a/src/ed_cjunction.rs b/src/ed_cjunction.rs index 455537e..9910213 100644 --- a/src/ed_cjunction.rs +++ b/src/ed_cjunction.rs @@ -217,6 +217,8 @@ fn lay_connector(doc: &mut Document, at: (TileKey, i64, bool), file: &str, from: }); t.touch_content(); } + let made: Vec<_> = ordered.iter().zip(&ids).map(|((s, _), id)| (tile_of(s.start), *id)).collect(); + crate::road_maker::bus_rules::apply_for_splines(doc, &made, "ed_cjunction::lay_connector"); // the road's end takes the link if let Some(t) = doc.tiles.get_mut(&at.0) { if let Some(s) = t.tile.splines.iter_mut().find(|s| s.id == at.1) { diff --git a/src/editor.rs b/src/editor.rs index 32766d9..2394167 100644 --- a/src/editor.rs +++ b/src/editor.rs @@ -4597,6 +4597,7 @@ impl Editor { t.touch_content(); made.push((k, ids[i])); } + crate::road_maker::bus_rules::apply_for_splines(doc, &made, "editor::lay_road"); // link the ends to what they meet (whether it is still there with that end free: a // one-sided link would point at nothing) let link = |doc: &mut Document, at: Option<(TileKey, i64, bool)>, mine: i64| -> bool { @@ -6588,6 +6589,7 @@ impl Editor { let t = doc.tiles.get_mut(&nk).unwrap(); t.tile.splines.push(q); t.touch_content(); + crate::road_maker::bus_rules::apply_for_splines(doc, &[(nk, nid)], "editor::continue_spline"); self.finish_step(); self.select(Some(Sel::Spline(nk, nid))); true @@ -7470,6 +7472,7 @@ impl Editor { let t = doc.tiles.get_mut(&k).unwrap(); t.tile.splines.push(sp); t.touch_content(); + crate::road_maker::bus_rules::apply_for_splines(doc, &[(k, ids[i])], "editor::connect_path_points"); } } let (next, prev) = if ids.is_empty() { (to.1, from.1) } else { (ids[0], *ids.last().unwrap()) }; @@ -8251,20 +8254,11 @@ impl Editor { /// Give every selected spline another type. pub fn retype_splines(&mut self, file: &str) { - let sels = self.selection(); + let splines: Vec<_> = self.selection().into_iter().filter_map(|s| if let Sel::Spline(k, id) = s { Some((k, id)) } else { None }).collect(); let Some(doc) = self.doc.as_mut() else { return }; self.history.begin(tr("Change road type", "Смена типа дороги")); - for s in &sels { - if let Sel::Spline(k, id) = *s { - self.history.touch_tile(doc, k); - if let Some(t) = doc.tiles.get_mut(&k) { - if let Some(sp) = t.tile.splines.iter_mut().find(|x| x.id == id) { - sp.file = file.to_string(); - } - t.touch_content(); - } - } - } + for &(key, _) in &splines { self.history.touch_tile(doc, key); } + crate::road_maker::bus_rules::retype(doc, &splines, file, "editor::retype_splines"); self.history.commit(); } @@ -9611,17 +9605,16 @@ impl Editor { continue; } self.history.touch_tile(doc, k); - let t = doc.tiles.get_mut(&k).unwrap(); if splines { - for s in t.tile.splines.iter_mut().filter(|s| !s.deleted && s.file.eq_ignore_ascii_case(from)) { - s.file = to.to_string(); - } + let instances: Vec<_> = doc.tiles[&k].tile.splines.iter().filter(|s| !s.deleted && s.file.eq_ignore_ascii_case(from)).map(|s| (k, s.id)).collect(); + crate::road_maker::bus_rules::retype(doc, &instances, to, "editor::replace_everywhere"); } else { + let t = doc.tiles.get_mut(&k).unwrap(); for o in t.tile.objects.iter_mut().chain(t.tile.attach_objects.iter_mut()).filter(|o| o.file.eq_ignore_ascii_case(from)) { o.file = to.to_string(); } } - t.touch_content(); + doc.tiles.get_mut(&k).unwrap().touch_content(); n += here; } self.history.commit(); @@ -10896,6 +10889,7 @@ fn join_arms(doc: &mut Document, a: &crate::junction::Arm, b: &crate::junction:: t.touch_content(); ids.push((k, id)); } + crate::road_maker::bus_rules::apply_for_splines(doc, &ids, "editor::join_arms"); // link the chain: a's end -> new pieces -> b's end let set = |doc: &mut Document, k: TileKey, id: i64, at_end: bool, other: i64| { if let Some(t) = doc.tiles.get_mut(&k) { @@ -17048,3 +17042,6 @@ mod tests { assert!((o.rot[0] - 270.0).abs() < 1e-4); } } + +#[cfg(test)] +mod bus_lane_tests; diff --git a/src/editor/bus_lane_tests.rs b/src/editor/bus_lane_tests.rs new file mode 100644 index 0000000..3afd56b --- /dev/null +++ b/src/editor/bus_lane_tests.rs @@ -0,0 +1,174 @@ +use super::*; +use crate::road_maker::{RoadSpec, Strip}; +use crate::selection::tests::flat_map; + +struct Fixture { + root: std::path::PathBuf, + bus: String, + plain: String, + assets: Assets, + editor: Editor, +} +impl Fixture { + fn new(tag: &str) -> Self { + let root = std::env::temp_dir().join(format!("om-bus-rules-{tag}-{}", std::process::id())); + std::fs::create_dir_all(&root).unwrap(); + let tex = root.join("asphalt.png"); + image::RgbaImage::from_pixel(4, 4, image::Rgba([80, 80, 80, 255])) + .save(&tex) + .unwrap(); + let plain_spec = RoadSpec { + name: "Plain road".into(), + roadway_tex: tex, + ..Default::default() + }; + let plain = plain_spec.write(&root).unwrap(); + let mut spec = plain_spec.normalised(false); + spec.name = "Bus road".into(); + if let Strip::Lane { bus_only, .. } = &mut spec.strips[2] { + *bus_only = true; + } + spec.strips.insert(3, Strip::BusBay { width: 3.0 }); + let bus = spec.write(&root).unwrap(); + let mut doc = flat_map(1); + doc.dir = root.join("maps/Rules"); + let mut editor = Editor::default(); + editor.content_dir = Some(root.clone()); + editor.open(doc); + editor.auto_junctions = false; + Self { + assets: Assets::new(root.join("omsi"), root.clone()), + root, + bus, + plain, + editor, + } + } + fn lay(&mut self) -> Vec<(TileKey, i64)> { + let start = Anchor { + pos: DVec3::new(100.0, 50.0, 0.0), + ..Default::default() + }; + let pieces = vec![Seg { + start: start.pos.truncate(), + heading: 0.0, + length: 80.0, + radius: 0.0, + }]; + self.editor.history.begin("test road"); + let doc = self.editor.doc.as_ref().unwrap(); + self.editor.history.touch_tile(doc, (0, 0)); + self.editor.history.touch_global(doc); + let made = self + .editor + .lay_road( + &mut self.assets, + &self.bus, + &pieces, + 0.0, + 0.0, + start, + None, + 5.0, + ) + .unwrap(); + self.editor.history.commit(); + made + } +} +impl Drop for Fixture { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.root); + } +} +fn assert_rules(doc: &Document, instances: &[(TileKey, i64)]) { + for &(key, id) in instances { + let s = doc.spline(key, id).unwrap(); + for index in [2, 3] { + for kind in ["bus", "no_cars"] { + assert_eq!( + s.rules + .iter() + .filter(|r| r.path_index == index && r.kind == kind && !r.kill) + .count(), + 1, + "{id}: {:?}", + s.rules + ); + } + } + } +} + +#[test] +fn laying_a_made_road_applies_bus_lane_and_bus_bay_rules_and_undoes_them() { + let mut f = Fixture::new("lay"); + let made = f.lay(); + assert_rules(f.editor.doc.as_ref().unwrap(), &made); + let path = omsi_cfg::resolve_path(&f.root, &f.bus); + let json: serde_json::Value = + serde_json::from_slice(&std::fs::read(path.with_extension("road.json")).unwrap()).unwrap(); + assert_eq!(json["bus_paths"], serde_json::json!([2])); + assert_eq!(json["bay_paths"], serde_json::json!([3])); + f.editor.undo(); + assert!(made.iter().all(|&(k, id)| { + f.editor + .doc + .as_ref() + .unwrap() + .spline(k, id) + .is_none_or(|s| s.deleted) + })); +} + +#[test] +fn split_paste_parallel_and_reshape_fill_missing_rules_without_duplicates() { + let mut f = Fixture::new("copies"); + let made = f.lay(); + let doc = f.editor.doc.as_mut().unwrap(); + doc.tiles.get_mut(&(0, 0)).unwrap().tile.splines[0] + .rules + .clear(); + let new = doc.split_spline(made[0].0, made[0].1, 30.0).unwrap(); + assert_rules(doc, &[((0, 0), new)]); + let copied = crate::parallel::copy(doc, &made, 10.0).unwrap(); + assert_rules(doc, &copied); + let clip = crate::clipboard::copy(doc, &[Sel::Spline(made[0].0, made[0].1)], |_| false); + let pasted = crate::clipboard::paste(doc, &clip, DVec3::new(140.0, 50.0, 0.0)); + let pasted: Vec<_> = pasted + .into_iter() + .filter_map(|s| { + if let Sel::Spline(k, id) = s { + Some((k, id)) + } else { + None + } + }) + .collect(); + assert_rules(doc, &pasted); + let plan = reshape::Plan { + pieces: vec![reshape::Piece { + key: made[0].0, + id: made[0].1, + segs: vec![Seg { + start: DVec2::new(100.0, 50.0), + heading: 0.0, + length: 120.0, + radius: 0.0, + }], + z0: 0.0, + z1: 0.0, + g0: None, + g1: None, + }], + }; + reshape::apply(doc, &plan); + let made: Vec<_> = doc.tiles[&(0, 0)] + .tile + .splines + .iter() + .filter(|s| !s.deleted) + .map(|s| ((0, 0), s.id)) + .collect(); + assert_rules(doc, &made); +} diff --git a/src/parallel.rs b/src/parallel.rs index aa7b45c..9cce7e2 100644 --- a/src/parallel.rs +++ b/src/parallel.rs @@ -94,6 +94,7 @@ pub fn copy(doc: &mut Document, splines: &[(TileKey, i64)], d: f64) -> Result = ids.iter().map(|id| (p.key, *id)).collect(); + crate::road_maker::bus_rules::apply_for_splines(doc, &made, "reshape::apply"); // the spline after it now follows the last piece if last != old.id && old.next_id != 0 { if let Some((nk, _)) = doc.find_spline(old.next_id) { diff --git a/src/road_maker.rs b/src/road_maker.rs index af1652d..109790e 100644 --- a/src/road_maker.rs +++ b/src/road_maker.rs @@ -19,6 +19,7 @@ use serde::{Deserialize, Serialize}; mod strips; mod migration; mod free_layout; +pub mod bus_rules; pub use strips::{Direction, Strip}; #[cfg(test)] #[allow(dead_code)] @@ -197,6 +198,7 @@ pub struct RoadSpec { pub strips: Vec, /// Derived at export; never trusted from an edited sidecar. pub bus_paths: Vec, + pub bay_paths: Vec, #[serde(skip)] pub advanced: bool, #[serde(skip)] @@ -238,7 +240,7 @@ pub struct RoadSpec { impl Default for RoadSpec { fn default() -> Self { - RoadSpec { bus_paths: Vec::new(), advanced: false, mode_error: None, strips: Vec::new(), left_hand: None, name: String::new(), lanes_fwd: 1, lanes_back: 1, lane_width: 3.5, median: 0.0, median_raised: false, footway: 3.0, footway_right: None, kerb: 0.15, pocket: 0.0, roadway_tex: PathBuf::new(), footway_tex: PathBuf::new(), median_tex: PathBuf::new(), marked: false, markings: Vec::new(), hand: None } + RoadSpec { bay_paths: Vec::new(), bus_paths: Vec::new(), advanced: false, mode_error: None, strips: Vec::new(), left_hand: None, name: String::new(), lanes_fwd: 1, lanes_back: 1, lane_width: 3.5, median: 0.0, median_raised: false, footway: 3.0, footway_right: None, kerb: 0.15, pocket: 0.0, roadway_tex: PathBuf::new(), footway_tex: PathBuf::new(), median_tex: PathBuf::new(), marked: false, markings: Vec::new(), hand: None } } } @@ -282,6 +284,8 @@ impl RoadSpec { let mut s = self.clone(); if s.left_hand.is_none() && s.strips.is_empty() { s.rebuild_strips(fallback); } s.left_hand = Some(s.left_hand.unwrap_or(fallback)); + s.bus_paths = s.bus_path_indices(); + s.bay_paths = s.bay_path_indices(); s } @@ -333,6 +337,11 @@ impl RoadSpec { result } + pub fn bay_path_indices(&self) -> Vec { + self.strips.iter().filter(|s| !matches!(s, Strip::Median { .. })).enumerate() + .filter_map(|(i, s)| matches!(s, Strip::BusBay { .. }).then_some(i)).collect() + } + pub fn simple_mode_issues(&self) -> Vec { let mut issues = Vec::new(); if let Err(error) = self.validate() { issues.push(error); } @@ -369,6 +378,9 @@ impl RoadSpec { } pub fn validate(&self) -> Result<(), String> { + if self.name.to_lowercase().contains("_bay_") || self.file_stem().to_lowercase().contains("_bay_") { + return Err("名稱不能包含 _bay_(保留給巴士停車灣工具產生的道路類型)".into()); + } strips::validate(&self.effective_strips(), self.left_hand.unwrap_or(false)) } @@ -643,6 +655,7 @@ impl RoadSpec { pub fn write_with_traffic(&self, content: &Path, left_hand: bool) -> anyhow::Result { let mut spec = self.normalised(left_hand); spec.bus_paths = spec.bus_path_indices(); + spec.bay_paths = spec.bay_path_indices(); spec.validate().map_err(anyhow::Error::msg)?; spec.write_normalised(content) } @@ -727,6 +740,7 @@ impl RoadSpec { } } spec.bus_paths = spec.bus_path_indices(); + spec.bay_paths = spec.bay_path_indices(); spec.advanced = !spec.simple_mode_issues().is_empty(); if !spec.advanced { // Controls are a projection; the saved strips remain authoritative. diff --git a/src/road_maker/bus_rules.rs b/src/road_maker/bus_rules.rs new file mode 100644 index 0000000..e1c36a9 --- /dev/null +++ b/src/road_maker/bus_rules.rs @@ -0,0 +1,168 @@ +//! Rules live on map instances; road files only describe which paths need them. +use super::RoadSpec; +use crate::doc::{Document, TileKey}; +use omsi_map::MapSpline; + +pub fn paths_for(doc: &Document, file: &str) -> Vec { + // Made roads live in the map's content installation. A source map can also + // refer to a made road beside the installation it was read from. + for map in std::iter::once(doc.dir.as_path()).chain(doc.source.as_deref()) { + let Some(root) = map.parent().and_then(|p| p.parent()) else { + continue; + }; + let sli = omsi_cfg::resolve_path(root, file); + if sli.with_extension("road.json").is_file() { + return RoadSpec::of_with_traffic(&sli, doc.global.left_hand_traffic) + .map(|s| { + let mut paths = s.bus_paths; + paths.extend(s.bay_paths); + paths.sort_unstable(); + paths.dedup(); + paths + }) + .unwrap_or_default(); + } + } + Vec::new() +} + +fn log_rule(caller: &str, phase: &str, spline: &MapSpline, path: i32, kind: &str) { + log::info!( + "bus lane rules: caller={caller} phase={phase} spline_id={} file={:?} path_index={path} kind={kind} rules={:?}", + spline.id, + spline.file, + spline.rules + ); +} + +fn add(spline: &mut MapSpline, paths: &[usize], caller: &str) -> bool { + let mut changed = false; + for &path in paths { + let Ok(path_index) = i32::try_from(path) else { + continue; + }; + for kind in ["bus", "no_cars"] { + if spline + .rules + .iter() + .any(|r| r.path_index == path_index && r.kind == kind && !r.kill) + { + continue; + } + log_rule(caller, "before-add", spline, path_index, kind); + spline.rules.push(omsi_map::MapRule { + path_index, + kind: kind.into(), + ..Default::default() + }); + log_rule(caller, "after-add", spline, path_index, kind); + changed = true; + } + } + changed +} + +/// Idempotent and never renumbers existing rules. +pub fn apply_bus_lane_rules(doc: &mut Document, splines: &[(TileKey, i64)], bus_paths: &[usize]) { + apply_logged(doc, splines, bus_paths, "apply_bus_lane_rules"); +} + +pub fn apply_logged(doc: &mut Document, splines: &[(TileKey, i64)], paths: &[usize], caller: &str) { + for &(key, id) in splines { + let Some(tile) = doc.tiles.get_mut(&key) else { + continue; + }; + let Some(spline) = tile + .tile + .splines + .iter_mut() + .find(|s| s.id == id && !s.deleted) + else { + continue; + }; + if add(spline, paths, caller) { + tile.touch_content(); + } + } +} + +/// Called after insertion, while the caller's history step is still open. +pub fn apply_for_splines(doc: &mut Document, splines: &[(TileKey, i64)], caller: &str) { + let mut by_file = std::collections::BTreeMap::>::new(); + for &(key, id) in splines { + if let Some(s) = doc.spline(key, id) { + by_file.entry(s.file.clone()).or_default().push((key, id)); + } + } + for (file, instances) in by_file { + let paths = paths_for(doc, &file); + if !paths.is_empty() { + apply_logged(doc, &instances, &paths, caller); + } + } +} + +/// Only a complete live bus/no_cars pair on the old declared indices is removed. +pub fn remove_old(doc: &mut Document, key: TileKey, id: i64, paths: &[usize], caller: &str) { + let Some(tile) = doc.tiles.get_mut(&key) else { + return; + }; + let Some(spline) = tile + .tile + .splines + .iter_mut() + .find(|s| s.id == id && !s.deleted) + else { + return; + }; + let mut changed = false; + for &path in paths { + let Ok(index) = i32::try_from(path) else { + continue; + }; + if !["bus", "no_cars"].iter().all(|kind| { + spline + .rules + .iter() + .any(|r| r.path_index == index && r.kind == *kind && !r.kill) + }) { + continue; + } + for kind in ["bus", "no_cars"] { + log_rule(caller, "before-remove", spline, index, kind); + spline + .rules + .retain(|r| !(r.path_index == index && r.kind == kind && !r.kill)); + log_rule(caller, "after-remove", spline, index, kind); + } + changed = true; + } + if changed { + tile.touch_content(); + } +} + +pub fn retype(doc: &mut Document, splines: &[(TileKey, i64)], file: &str, caller: &str) { + for &(key, id) in splines { + let Some(old) = doc.spline(key, id).map(|s| s.file.clone()) else { + continue; + }; + let paths = paths_for(doc, &old); + remove_old(doc, key, id, &paths, caller); + if let Some(tile) = doc.tiles.get_mut(&key) { + if let Some(s) = tile + .tile + .splines + .iter_mut() + .find(|s| s.id == id && !s.deleted) + { + s.file = file.into(); + } + tile.touch_content(); + } + } + apply_for_splines(doc, splines, caller); +} + +#[cfg(test)] +mod tests; diff --git a/src/road_maker/bus_rules/tests.rs b/src/road_maker/bus_rules/tests.rs new file mode 100644 index 0000000..fcfad50 --- /dev/null +++ b/src/road_maker/bus_rules/tests.rs @@ -0,0 +1,104 @@ +use super::*; +use crate::selection::tests::{add_spline, flat_map}; + +fn rule(path_index: i32, kind: &str) -> omsi_map::MapRule { + omsi_map::MapRule { + path_index, + kind: kind.into(), + ..Default::default() + } +} + +#[test] +fn application_is_idempotent_and_preserves_indices_and_other_rules() { + let mut doc = flat_map(1); + add_spline(&mut doc, (0, 0), 1, 0.0, 0.0, 0.0, 80.0, 0, 0); + let mut killed = rule(1, "no_cars"); + killed.kill = true; + doc.tiles.get_mut(&(0, 0)).unwrap().tile.splines[0].rules = + vec![rule(1, "bus"), killed.clone(), rule(9, "speedlimit")]; + apply_bus_lane_rules(&mut doc, &[((0, 0), 1)], &[1, 3]); + let first = doc.spline((0, 0), 1).unwrap().rules.clone(); + apply_bus_lane_rules(&mut doc, &[((0, 0), 1)], &[1, 3]); + assert_eq!(doc.spline((0, 0), 1).unwrap().rules, first); + assert_eq!(first.len(), 6); + assert_eq!(first[1], killed); + assert_eq!(first[2], rule(9, "speedlimit")); + for index in [1, 3] { + for kind in ["bus", "no_cars"] { + assert_eq!( + first + .iter() + .filter(|r| r.path_index == index && r.kind == kind && !r.kill) + .count(), + 1 + ); + } + } +} + +#[test] +fn cleanup_removes_only_complete_live_pairs_on_declared_paths() { + let mut doc = flat_map(1); + add_spline(&mut doc, (0, 0), 1, 0.0, 0.0, 0.0, 80.0, 0, 0); + let speed = omsi_map::MapRule { + value: 30.0, + ..rule(1, "speedlimit") + }; + let untouched = vec![ + speed.clone(), + rule(2, "bus"), + rule(3, "no_cars"), + rule(8, "bus"), + rule(8, "no_cars"), + ]; + let mut rules = vec![rule(1, "bus"), rule(1, "no_cars")]; + rules.extend(untouched.clone()); + doc.tiles.get_mut(&(0, 0)).unwrap().tile.splines[0].rules = rules; + remove_old(&mut doc, (0, 0), 1, &[1, 2, 3], "test::cleanup"); + assert_eq!(doc.spline((0, 0), 1).unwrap().rules, untouched); +} + +#[test] +fn reserved_names_are_rejected_before_any_output_is_created() { + for name in ["Main_bay_road", "Main_BaY_road", "Main bay road"] { + let root = std::env::temp_dir().join(format!("om-reserved-name-{}", std::process::id())); + let spec = RoadSpec { + name: name.into(), + ..Default::default() + }; + assert_eq!( + spec.validate().unwrap_err(), + "名稱不能包含 _bay_(保留給巴士停車灣工具產生的道路類型)" + ); + assert!(spec.write(&root).is_err()); + assert!(!root.exists()); + } + assert!( + RoadSpec { + name: "BusBay Road".into(), + ..Default::default() + } + .validate() + .is_ok() + ); +} + +#[test] +fn retyping_without_old_metadata_preserves_all_existing_rules() { + let mut doc = flat_map(1); + add_spline(&mut doc, (0, 0), 1, 0.0, 0.0, 0.0, 80.0, 0, 0); + let original = vec![rule(1, "bus"), rule(1, "no_cars"), rule(1, "speedlimit")]; + doc.tiles.get_mut(&(0, 0)).unwrap().tile.splines[0].rules = original.clone(); + retype( + &mut doc, + &[((0, 0), 1)], + "Splines\\missing_new.sli", + "test::missing_metadata", + ); + assert_eq!(doc.spline((0, 0), 1).unwrap().rules, original); + assert_eq!( + doc.spline((0, 0), 1).unwrap().file, + "Splines\\missing_new.sli" + ); +} From 3b3264afff1492efb79a347d02bfa4abd85f07c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BB=B7=E6=96=87=20=E6=A5=8A?= Date: Mon, 16 Nov 2026 04:26:59 +0800 Subject: [PATCH 4/6] Test maker bus roads through bay generation and type changes --- src/editor/bus_lane_tests.rs | 158 +++++++++++++++++++++++++++++++++ src/road_maker/compat_tests.rs | 45 ++++++++++ 2 files changed, 203 insertions(+) diff --git a/src/editor/bus_lane_tests.rs b/src/editor/bus_lane_tests.rs index 3afd56b..5722612 100644 --- a/src/editor/bus_lane_tests.rs +++ b/src/editor/bus_lane_tests.rs @@ -172,3 +172,161 @@ fn split_paste_parallel_and_reshape_fill_missing_rules_without_duplicates() { .collect(); assert_rules(doc, &made); } + +#[test] +fn retyping_bus_to_plain_and_back_preserves_manual_speed_limits() { + let mut f = Fixture::new("retype"); + let made = f.lay(); + let speed = omsi_map::MapRule { + path_index: 2, + kind: "speedlimit".into(), + value: 30.0, + ..Default::default() + }; + for &(k, id) in &made { + f.editor + .doc + .as_mut() + .unwrap() + .tiles + .get_mut(&k) + .unwrap() + .tile + .splines + .iter_mut() + .find(|s| s.id == id) + .unwrap() + .rules + .push(speed.clone()); + } + f.editor + .set_selection(made.iter().map(|&(k, id)| Sel::Spline(k, id)).collect()); + f.editor.retype_splines(&f.plain); + for &(k, id) in &made { + let s = f.editor.doc.as_ref().unwrap().spline(k, id).unwrap(); + assert_eq!(s.file, f.plain); + assert_eq!(s.rules, [speed.clone()]); + } + assert_eq!( + f.editor.replace_everywhere(&f.plain, &f.bus, true), + made.len() + ); + assert_rules(f.editor.doc.as_ref().unwrap(), &made); + for &(k, id) in &made { + let s = f.editor.doc.as_ref().unwrap().spline(k, id).unwrap(); + assert_eq!( + s.rules + .iter() + .filter(|r| r.kind == "speedlimit") + .collect::>(), + vec![&speed] + ); + assert_eq!(s.rules.len(), 5); + } + f.editor.undo(); + for &(k, id) in &made { + assert_eq!( + f.editor.doc.as_ref().unwrap().spline(k, id).unwrap().rules, + [speed.clone()] + ); + } + f.editor.undo(); + assert_rules(f.editor.doc.as_ref().unwrap(), &made); +} + +/// Exercise the actual Roads-tool flow, including cutting, type generation, +/// bay rule insertion and both taper junctions. The old pocket_type is untouched. +#[test] +fn pocket_tool_preserves_maker_bus_paths_and_bays_on_one_and_both_sides() { + for left_bay in [true, false] { + for both in [false, true] { + let mut f = Fixture::new(&format!("pocket-{left_bay}-{both}")); + if left_bay { + let path = omsi_cfg::resolve_path(&f.root, &f.plain); + let mut road = RoadSpec::of(&path).unwrap(); + road.name = "Left shoulder".into(); + road.strips.insert(1, Strip::BusBay { width: 3.0 }); + f.bus = road.write(&f.root).unwrap(); + } + let source_path = omsi_cfg::resolve_path(&f.root, &f.bus); + let source = RoadSpec::of(&source_path).unwrap(); + let mut original_indices = source.bus_paths.clone(); + original_indices.extend(&source.bay_paths); + original_indices.sort_unstable(); + let main = f.assets.spline_wait(&f.bus, 5000).unwrap(); + f.lay(); + f.editor.pocket_both_sides = both; + f.editor.pocket_width = 3.0; + f.editor.pocket_len = 12.0; + f.editor.cursor = Some(DVec3::new(100.0, 90.0, 0.0)); + f.editor.pocket_click(&mut f.assets); + let doc = f.editor.doc.as_ref().unwrap(); + let bays: Vec<_> = doc + .tiles + .values() + .flat_map(|t| &t.tile.splines) + .filter(|s| !s.deleted && s.file.to_lowercase().contains("_bay_")) + .collect(); + assert!( + !bays.is_empty(), + "left_bay={left_bay}, both={both}: tool produced no bay" + ); + assert_eq!( + doc.tiles + .values() + .flat_map(|t| &t.tile.objects) + .filter(|o| o.file.contains("junction_")) + .count(), + 2, + "both taper junctions are produced" + ); + for spline in bays { + let bay = f.assets.spline_wait(&spline.file, 5000).unwrap(); + let added = crate::pocket::bay_path_indices(&main, &bay); + let first = main.def.paths.len(); + assert_eq!(added, first..first + if both { 2 } else { 1 }); + for (i, (before, after)) in main.def.paths.iter().zip(&bay.def.paths).enumerate() { + assert_eq!(before.kind, after.kind, "original path {i}"); + // Widening moves the outside footways. Existing vehicle paths + // retain their original position as well as their index. + if before.kind == 0 { assert_eq!(before.start, after.start, "original vehicle path {i}"); } + assert_eq!(before.direction, after.direction, "original path {i}"); + assert_eq!(before.width, after.width, "original path {i}"); + } + for i in added.clone() { + assert_eq!(bay.def.paths[i].kind, 0); + } + let expected: Vec<_> = original_indices.iter().copied().chain(added).collect(); + for &index in &expected { + assert_eq!(bay.def.paths[index].kind, 0); + for kind in ["bus", "no_cars"] { + assert_eq!( + spline + .rules + .iter() + .filter(|r| r.path_index == index as i32 + && r.kind == kind + && !r.kill) + .count(), + 1, + "left_bay={left_bay} both={both} path={index} kind={kind} rules={:?}", + spline.rules + ); + } + } + assert_eq!( + spline.rules.len(), + expected.len() * 2, + "no rules drift to other paths" + ); + println!( + "pocket compatibility: left_bay={left_bay}, both={both}, original_bus_paths={:?}, original_bay_paths={:?}, new_bay_paths={first}..{}, rules={:?}", + source.bus_paths, + source.bay_paths, + bay.def.paths.len(), + spline.rules + ); + } + } + } +} diff --git a/src/road_maker/compat_tests.rs b/src/road_maker/compat_tests.rs index 1f16907..8b411ea 100644 --- a/src/road_maker/compat_tests.rs +++ b/src/road_maker/compat_tests.rs @@ -218,3 +218,48 @@ fn bay_texture_copies_original_asphalt_and_sidecars_when_marked() { assert_eq!(sli.textures.last().unwrap().file, "Bus_road_bay.png"); std::fs::remove_dir_all(root).unwrap(); } + +#[test] +fn legacy_pocket_files_migrate_resave_and_match_explicit_bus_bay_blocks() { + let root = std::env::temp_dir().join(format!("om-bay-legacy-{}", std::process::id())); + std::fs::create_dir_all(&root).unwrap(); + let texture = root.join("asphalt.png"); + image::RgbaImage::from_pixel(4, 4, image::Rgba([80, 80, 80, 255])) + .save(&texture) + .unwrap(); + for left_hand in [false, true] { + let spec = RoadSpec { + name: format!("Legacy pocket {left_hand}"), + lanes_back: 2, + lanes_fwd: 1, + pocket: 3.0, + roadway_tex: texture.clone(), + ..Default::default() + }; + let old = legacy(&spec); + let sli = root.join(format!("{}.sli", spec.file_stem())); + std::fs::write(&sli, old.sli(left_hand)).unwrap(); + std::fs::write( + sli.with_extension("road.json"), + serde_json::to_vec(&old).unwrap(), + ) + .unwrap(); + let migrated = RoadSpec::of_with_traffic(&sli, !left_hand).unwrap(); + assert_eq!(migrated.bay_paths, [4]); + assert!(migrated.bus_paths.is_empty()); + assert_eq!( + migrated.sli(!left_hand), + spec.normalised(left_hand).sli(!left_hand) + ); + let rel = migrated.write_with_traffic(&root, !left_hand).unwrap(); + let output = omsi_cfg::vfs::read_text(&omsi_cfg::resolve_path(&root, &rel)) + .unwrap() + .replace("\r\n", "\n"); + assert_compatible(&old.sli(left_hand), &output, Some(&spec.bay_tex_name())); + let read = + RoadSpec::of_with_traffic(&omsi_cfg::resolve_path(&root, &rel), !left_hand).unwrap(); + assert_eq!(read.left_hand, Some(left_hand)); + assert_eq!(read.bay_paths, [4]); + } + std::fs::remove_dir_all(root).unwrap(); +} From 74e74733bd7ef60e8d960aa18dcf8f7a899b8a20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BB=B7=E6=96=87=20=E6=A5=8A?= Date: Mon, 16 Nov 2026 04:51:36 +0800 Subject: [PATCH 5/6] Fix road maker textures, rule migration, and bulk rule application --- locales/zh-tw.tsv | 45 +++++++- src/check.rs | 1 + src/collab/mod.rs | 1 + src/doc/autosave.rs | 2 + src/doc/mod.rs | 5 + src/doc/save.rs | 1 + src/doc/tests.rs | 1 + src/editor.rs | 8 ++ src/editor/bus_lane_tests.rs | 23 +++++ src/editor/bus_rule_batch.rs | 71 +++++++++++++ src/i18n.rs | 137 +++++++++++++++++++++++-- src/lanes_edit.rs | 15 ++- src/lanes_edit/review_tests.rs | 120 ++++++++++++++++++++++ src/mcp/tests.rs | 1 + src/road_maker.rs | 87 +++++++++++----- src/road_maker/bus_rules.rs | 47 +++++++-- src/road_maker/bus_rules/batch.rs | 29 ++++++ src/road_maker/bus_rules/tests.rs | 2 +- src/road_maker/free_layout.rs | 30 +++++- src/road_maker/layout_tests.rs | 6 +- src/road_maker/review_tests.rs | 164 ++++++++++++++++++++++++++++++ src/road_maker/strips.rs | 14 +-- src/selection.rs | 1 + src/ui_roads.rs | 41 +++++++- src/ui_roads/strip_panel.rs | 106 ++++++++++++++----- src/ui_roads/strip_preview.rs | 14 ++- 26 files changed, 874 insertions(+), 98 deletions(-) create mode 100644 src/editor/bus_rule_batch.rs create mode 100644 src/lanes_edit/review_tests.rs create mode 100644 src/road_maker/bus_rules/batch.rs create mode 100644 src/road_maker/review_tests.rs diff --git a/locales/zh-tw.tsv b/locales/zh-tw.tsv index e608621..bad8a5d 100644 --- a/locales/zh-tw.tsv +++ b/locales/zh-tw.tsv @@ -2646,7 +2646,7 @@ Another crossing file 另一個路口檔案 Crossing paths of the picked object… 所選路口物件的路徑… Crossing paths 路口路徑 The paths of a crossing or junction object, its blocking and its traffic light program, edited in a copy of the object - the original is left as it is 路口或交叉物件的行車路線、讓路/互斥規則及紅綠燈燈號階段,在物件的副本中編輯,原始檔案維持不變 -Footway 行人路 +Footway 人行道 Street 行車線 Against 逆向 Both ways 雙向 @@ -2839,3 +2839,46 @@ Click a 2nd reference point on the object, or Esc to finish 點擊物件上的 Aligned angle! (Ctrl+Z to undo) 已對齊角度!(Ctrl+Z 復原) Vertex snap complete 頂點吸附完成 Align vertex angle 對齊頂點角度 +Kerb height 緣石高度 +Strips run from left to right 積木依道路左至右排列 +Lane 車道 +Median 分隔帶 +BusBay 巴士停車灣 +Forward ↑ 順向 ↑ +Backward ↓ 逆向 ↓ +bus only 公車專用 +Use roadway texture 使用車道材質 +Choose file… 選擇檔案… +Default footway texture 預設人行道材質 +Advanced: strip mode 進階:積木模式 +This road was made for left-hand traffic 此道路是為靠左行駛建立的 +This road was made for right-hand traffic 此道路是為靠右行駛建立的 +This road contains settings that simple mode cannot represent 此道路含簡單模式無法表示的設定 +Built-in multi-lane texture markings may not align with these lanes 內建多車道貼圖的線會和車道對不上 +Lane widths differ 車道寬度不一致 +Contains bus-only lanes 含公車專用車道 +Contains multiple medians 含多個分隔帶 +Median is not between opposite directions 分隔帶不在兩向車道交界 +Contains a left BusBay 左側含巴士停車灣 +Footway textures differ 兩側人行道使用不同材質 +Names must not contain _bay_ (reserved for the bus bay tool) 名稱不能包含 _bay_(保留給巴士停車灣工具產生的道路類型) +A road needs at least one Lane 道路至少需要一條車道 +Strip {} has an invalid width 積木 {} 的寬度無效 +Footways must be at the outer ends 人行道只能位於道路兩端 +BusBays must border the roadway, at most one per side 巴士停車灣只能緊貼車道段外緣,各側最多一個 +Medians must be inside the roadway 分隔帶必須位於車道段內 +The roadway may contain only Lanes and Medians 車道段內只能包含車道和分隔帶 +Lane directions do not match this road’s traffic side 車道方向排列不符合此道路的行駛側設定 +Reset bay texture 重設灣貼圖 +Bay texture reset 已重設灣貼圖 +Could not reset bay texture 無法重設灣貼圖 +The roadway texture is missing 找不到車道材質 +The roadway texture could not be read 無法讀取車道材質 +Apply bus lane rules to all existing roads 套用公車道規則到所有既有道路 +Road types and spline counts to update 將套用的道路類型與 spline 數量 +Rules added 新增規則數量 +Roads changed; review the preview again 道路已變更,請重新檢查預覽 +No roads need bus lane rules 沒有可套用公車道規則的道路 +BUS 公車 +No footway texture 未設定人行道材質 +Road metadata not found 找不到道路製作器資料檔 diff --git a/src/check.rs b/src/check.rs index e0ad253..6a3a9c7 100644 --- a/src/check.rs +++ b/src/check.rs @@ -1382,6 +1382,7 @@ mod tests { fn doc_with(tiles: &[TileKey]) -> Document { let mut doc = Document { + content_root: None, global: Default::default(), tiles: Default::default(), order: Vec::new(), diff --git a/src/collab/mod.rs b/src/collab/mod.rs index fa1f87d..0494a73 100644 --- a/src/collab/mod.rs +++ b/src/collab/mod.rs @@ -449,6 +449,7 @@ fn guest_doc(roots: &Roots, w: &Welcome) -> Result { /// An empty document to fill. fn placeholder() -> Document { Document { + content_root: None, global: Default::default(), tiles: Default::default(), order: Vec::new(), diff --git a/src/doc/autosave.rs b/src/doc/autosave.rs index 7d26eb5..f6160bf 100644 --- a/src/doc/autosave.rs +++ b/src/doc/autosave.rs @@ -90,6 +90,7 @@ pub struct Snapshot { /// Copy what an autosave of the map writes. pub fn snapshot(doc: &Document) -> Snapshot { let copy = Document { + content_root: doc.content_root.clone(), global: doc.global.clone(), tiles: doc.tiles.iter().filter(|(_, t)| t.dirty).map(|(k, t)| (*k, t.clone())).collect(), order: doc.order.clone(), @@ -327,6 +328,7 @@ mod tests { let content = std::env::temp_dir().join(format!("openmapper-test-autosave-{}", std::process::id())); let _ = std::fs::remove_dir_all(&content); let mut doc = Document { + content_root: None, global: Default::default(), tiles: Default::default(), order: Vec::new(), diff --git a/src/doc/mod.rs b/src/doc/mod.rs index bab7dda..119c1bb 100644 --- a/src/doc/mod.rs +++ b/src/doc/mod.rs @@ -190,6 +190,8 @@ pub enum Sel { /// The map. pub struct Document { + /// Active editor content root, independent of the map save location. + pub content_root: Option, pub global: GlobalCfg, pub tiles: BTreeMap, /// The `[map]` list in file order: entry points and repeaters name tiles by their place @@ -241,6 +243,7 @@ impl Document { omsi_map::set_world_coordinates(false); omsi_map::set_tile_size(omsi_map::TILE_SIZE); let mut doc = Document { + content_root: Some(roots.content.clone()), global, tiles: BTreeMap::new(), order: Vec::new(), @@ -336,6 +339,7 @@ impl Document { progress(1.0); crate::render::profile::log_time(&format!("read {} tiles", tiles.len()), started); Ok(Document { + content_root: Some(roots.content.clone()), global, tiles, order, @@ -388,6 +392,7 @@ impl Document { /// and chrono patches, which take room and are not looked at. pub fn for_reading(&self) -> Document { Document { + content_root: self.content_root.clone(), global: self.global.clone(), tiles: self.tiles.iter().map(|(k, t)| (*k, TileDoc { tile: t.tile.clone(), terrain: t.terrain.clone(), masks: Vec::new(), chrono: Vec::new(), water: t.water, terrain_rev: t.terrain_rev, mask_rev: t.mask_rev, content_rev: t.content_rev, dirty: t.dirty })).collect(), order: self.order.clone(), diff --git a/src/doc/save.rs b/src/doc/save.rs index 9fb692a..c75aba5 100644 --- a/src/doc/save.rs +++ b/src/doc/save.rs @@ -81,6 +81,7 @@ pub(crate) fn prepare_save(doc: &Document) -> SaveJob { source: doc.source.clone(), }; let copy = Document { + content_root: doc.content_root.clone(), global: doc.global.clone(), tiles: doc .tiles diff --git a/src/doc/tests.rs b/src/doc/tests.rs index 336cbf5..b645981 100644 --- a/src/doc/tests.rs +++ b/src/doc/tests.rs @@ -28,6 +28,7 @@ pub(crate) fn sample_map(roots: &Roots) -> Document { GroundTex { texture: "Texture\\sand.bmp".into(), detail_texture: "Texture\\noise_low.bmp".into(), params: [8.0, 16.0, 4.0] }, ]; let mut doc = Document { + content_root: None, global, tiles: Default::default(), order: Vec::new(), diff --git a/src/editor.rs b/src/editor.rs index 2394167..ddcad17 100644 --- a/src/editor.rs +++ b/src/editor.rs @@ -1576,6 +1576,7 @@ impl Editor { self.paint_layer = if doc.global.ground_textures.len() > 1 { 1 } else { 0 }; self.session_first_id = doc.global.next_id_code; let mut doc = doc; + if self.content_dir.is_some() { doc.content_root = self.content_dir.clone(); } doc.groups = crate::mapgroups::load(&doc.dir); if let Some(content) = self.content_dir.as_deref() { doc.signal_sets.reload(&doc.dir, content); @@ -4597,6 +4598,7 @@ impl Editor { t.touch_content(); made.push((k, ids[i])); } + if self.content_dir.is_some() { doc.content_root = self.content_dir.clone(); } crate::road_maker::bus_rules::apply_for_splines(doc, &made, "editor::lay_road"); // link the ends to what they meet (whether it is still there with that end free: a // one-sided link would point at nothing) @@ -6589,6 +6591,7 @@ impl Editor { let t = doc.tiles.get_mut(&nk).unwrap(); t.tile.splines.push(q); t.touch_content(); + if self.content_dir.is_some() { doc.content_root = self.content_dir.clone(); } crate::road_maker::bus_rules::apply_for_splines(doc, &[(nk, nid)], "editor::continue_spline"); self.finish_step(); self.select(Some(Sel::Spline(nk, nid))); @@ -7472,6 +7475,7 @@ impl Editor { let t = doc.tiles.get_mut(&k).unwrap(); t.tile.splines.push(sp); t.touch_content(); + if self.content_dir.is_some() { doc.content_root = self.content_dir.clone(); } crate::road_maker::bus_rules::apply_for_splines(doc, &[(k, ids[i])], "editor::connect_path_points"); } } @@ -8258,6 +8262,7 @@ impl Editor { let Some(doc) = self.doc.as_mut() else { return }; self.history.begin(tr("Change road type", "Смена типа дороги")); for &(key, _) in &splines { self.history.touch_tile(doc, key); } + if self.content_dir.is_some() { doc.content_root = self.content_dir.clone(); } crate::road_maker::bus_rules::retype(doc, &splines, file, "editor::retype_splines"); self.history.commit(); } @@ -9607,6 +9612,7 @@ impl Editor { self.history.touch_tile(doc, k); if splines { let instances: Vec<_> = doc.tiles[&k].tile.splines.iter().filter(|s| !s.deleted && s.file.eq_ignore_ascii_case(from)).map(|s| (k, s.id)).collect(); + if self.content_dir.is_some() { doc.content_root = self.content_dir.clone(); } crate::road_maker::bus_rules::retype(doc, &instances, to, "editor::replace_everywhere"); } else { let t = doc.tiles.get_mut(&k).unwrap(); @@ -17045,3 +17051,5 @@ mod tests { #[cfg(test)] mod bus_lane_tests; + +mod bus_rule_batch; diff --git a/src/editor/bus_lane_tests.rs b/src/editor/bus_lane_tests.rs index 5722612..a282eb0 100644 --- a/src/editor/bus_lane_tests.rs +++ b/src/editor/bus_lane_tests.rs @@ -330,3 +330,26 @@ fn pocket_tool_preserves_maker_bus_paths_and_bays_on_one_and_both_sides() { } } } + +#[test] +fn batch_bus_rules_preview_is_read_only_counts_additions_and_undoes_in_one_step() { + let mut f=Fixture::new("batch"); let made=f.lay(); + let doc=f.editor.doc.as_mut().unwrap(); + let copies=crate::parallel::copy(doc,&made,10.0).unwrap(); + let instances:Vec<_>=made.into_iter().chain(copies).collect(); + for &(k,id) in &instances { doc.tiles.get_mut(&k).unwrap().tile.splines.iter_mut().find(|s|s.id==id).unwrap().rules.clear(); } + let mut deleted=doc.spline(instances[0].0,instances[0].1).unwrap().clone(); deleted.id=999; deleted.deleted=true; + let mut plain=deleted.clone(); plain.id=998; plain.deleted=false; plain.file=f.plain.clone(); + doc.tiles.get_mut(&(0,0)).unwrap().tile.splines.extend([deleted,plain]); + let groups=f.editor.preview_all_bus_rules(); assert_eq!(groups.len(),1); assert_eq!(groups[0].splines.len(),2); + assert!(instances.iter().all(|&(k,id)|f.editor.doc.as_ref().unwrap().spline(k,id).unwrap().rules.is_empty())); + assert_eq!(f.editor.apply_all_bus_rules(&groups).unwrap(),8); + assert_rules(f.editor.doc.as_ref().unwrap(),&instances); + f.editor.undo(); + assert!(instances.iter().all(|&(k,id)|f.editor.doc.as_ref().unwrap().spline(k,id).unwrap().rules.is_empty())); + assert_eq!(f.editor.apply_all_bus_rules(&groups).unwrap(),8); + assert_eq!(f.editor.apply_all_bus_rules(&groups).unwrap(),0); + assert!(f.editor.doc.as_ref().unwrap().spline((0,0),998).unwrap().rules.is_empty()); + f.editor.doc.as_mut().unwrap().tiles.get_mut(&(0,0)).unwrap().tile.splines.iter_mut().find(|s|s.id==instances[0].1).unwrap().file=f.plain.clone(); + assert!(f.editor.apply_all_bus_rules(&groups).is_err()); +} diff --git a/src/editor/bus_rule_batch.rs b/src/editor/bus_rule_batch.rs new file mode 100644 index 0000000..88e561f --- /dev/null +++ b/src/editor/bus_rule_batch.rs @@ -0,0 +1,71 @@ +use super::*; +use crate::road_maker::bus_rules::{self, batch::Group}; + +impl Editor { + pub fn preview_all_bus_rules(&self) -> Vec { + self.doc + .as_ref() + .map(|doc| bus_rules::batch::preview(doc, self.content_dir.as_deref())) + .unwrap_or_default() + } + + /// Only called after the user confirms the displayed groups. Opening a map + /// never invokes this operation. Refuse an outdated confirmation preview. + pub fn apply_all_bus_rules(&mut self, preview: &[Group]) -> Result { + if self.preview_all_bus_rules() != preview { + return Err(tr( + "Roads changed; review the preview again", + "Дороги изменились; проверьте список ещё раз", + ) + .into()); + } + let Some(doc) = self.doc.as_mut() else { + return Ok(0); + }; + if preview.is_empty() { + return Ok(0); + } + let needs_rules = preview.iter().any(|group| { + group.splines.iter().any(|&(k, id)| { + doc.spline(k, id).is_some_and(|s| { + group.paths.iter().any(|&p| { + ["bus", "no_cars"].iter().any(|kind| { + !s.rules + .iter() + .any(|r| r.path_index == p as i32 && r.kind == *kind && !r.kill) + }) + }) + }) + }) + }); + if !needs_rules { + return Ok(0); + } + if self.content_dir.is_some() { + doc.content_root = self.content_dir.clone(); + } + self.history.begin(tr( + "Apply bus lane rules to all existing roads", + "Применить правила автобусных полос ко всем существующим дорогам", + )); + let mut added = 0; + for group in preview { + for &(key, _) in &group.splines { + self.history.touch_tile(doc, key); + } + let count = |doc: &Document| { + group + .splines + .iter() + .filter_map(|&(k, id)| doc.spline(k, id)) + .map(|s| s.rules.len()) + .sum::() + }; + let before = count(doc); + bus_rules::apply_for_splines(doc, &group.splines, "editor::apply_all_bus_rules"); + added += count(doc) - before; + } + self.history.commit(); + Ok(added) + } +} diff --git a/src/i18n.rs b/src/i18n.rs index 9d093c6..30de516 100644 --- a/src/i18n.rs +++ b/src/i18n.rs @@ -304,16 +304,132 @@ mod tests { /// save overwrites the file, and things are picked with 選取, never with 挑. (The words /// these replace are listed: a translation that brings one back is caught here.) #[test] - fn the_hong_kong_table_uses_hong_kong_road_words() { + fn traditional_chinese_preserves_existing_terms_and_requested_road_maker_terms() { let t = table(Lang::ZhTw); assert!(t.len() > 2000, "{} texts", t.len()); - let taiwan = ["車道", "拖曳", "相位", "時相", "樣條", "號誌燈", "公車", "既有", "封鎖", "挑", "人行道", "方向燈", "坡度", "寬度", "轉燈階段", "保持路口淨空"]; + // The road maker explicitly uses the requested Taiwan terminology. + // Check these entries exactly while retaining the older Hong Kong vocabulary elsewhere. + let maker_terms = [ + ("Footway", "人行道"), + ("Kerb height", "緣石高度"), + ("Strips run from left to right", "積木依道路左至右排列"), + ("Lane", "車道"), + ("Median", "分隔帶"), + ("BusBay", "巴士停車灣"), + ("Forward ↑", "順向 ↑"), + ("Backward ↓", "逆向 ↓"), + ("bus only", "公車專用"), + ("Use roadway texture", "使用車道材質"), + ("Choose file…", "選擇檔案…"), + ("Default footway texture", "預設人行道材質"), + ("Advanced: strip mode", "進階:積木模式"), + ( + "This road was made for left-hand traffic", + "此道路是為靠左行駛建立的", + ), + ( + "This road was made for right-hand traffic", + "此道路是為靠右行駛建立的", + ), + ( + "This road contains settings that simple mode cannot represent", + "此道路含簡單模式無法表示的設定", + ), + ( + "Built-in multi-lane texture markings may not align with these lanes", + "內建多車道貼圖的線會和車道對不上", + ), + ("Lane widths differ", "車道寬度不一致"), + ("Contains bus-only lanes", "含公車專用車道"), + ("Contains multiple medians", "含多個分隔帶"), + ( + "Median is not between opposite directions", + "分隔帶不在兩向車道交界", + ), + ("Contains a left BusBay", "左側含巴士停車灣"), + ("Footway textures differ", "兩側人行道使用不同材質"), + ( + "Names must not contain _bay_ (reserved for the bus bay tool)", + "名稱不能包含 _bay_(保留給巴士停車灣工具產生的道路類型)", + ), + ("A road needs at least one Lane", "道路至少需要一條車道"), + ("Strip {} has an invalid width", "積木 {} 的寬度無效"), + ( + "Footways must be at the outer ends", + "人行道只能位於道路兩端", + ), + ( + "BusBays must border the roadway, at most one per side", + "巴士停車灣只能緊貼車道段外緣,各側最多一個", + ), + ( + "Medians must be inside the roadway", + "分隔帶必須位於車道段內", + ), + ( + "The roadway may contain only Lanes and Medians", + "車道段內只能包含車道和分隔帶", + ), + ( + "Lane directions do not match this road’s traffic side", + "車道方向排列不符合此道路的行駛側設定", + ), + ("Reset bay texture", "重設灣貼圖"), + ("Bay texture reset", "已重設灣貼圖"), + ("Could not reset bay texture", "無法重設灣貼圖"), + ("The roadway texture is missing", "找不到車道材質"), + ("The roadway texture could not be read", "無法讀取車道材質"), + ( + "Apply bus lane rules to all existing roads", + "套用公車道規則到所有既有道路", + ), + ( + "Road types and spline counts to update", + "將套用的道路類型與 spline 數量", + ), + ("Rules added", "新增規則數量"), + ( + "Roads changed; review the preview again", + "道路已變更,請重新檢查預覽", + ), + ("No roads need bus lane rules", "沒有可套用公車道規則的道路"), + ("BUS", "公車"), + ("No footway texture", "未設定人行道材質"), + ("Road metadata not found", "找不到道路製作器資料檔"), + ]; + for &(en, expected) in &maker_terms { + assert_eq!(t.get(en).copied(), Some(expected), "{en}"); + } + let taiwan = [ + "車道", + "拖曳", + "相位", + "時相", + "樣條", + "號誌燈", + "公車", + "既有", + "封鎖", + "挑", + "人行道", + "方向燈", + "坡度", + "寬度", + "轉燈階段", + "保持路口淨空", + ]; for (en, tr) in t.iter() { + if maker_terms.iter().any(|(key, _)| key == en) { + continue; + } for w in taiwan { // (行車道 is the roadway as a whole - a carriageway - and Hong Kong's own word; // 車道 alone, a lane, is not) let hay = tr.replace("行車道", ""); - assert!(!hay.contains(w), "{en:?} says {tr:?}: {w} is not Hong Kong's word"); + assert!( + !hay.contains(w), + "{en:?} says {tr:?}: {w} is not Hong Kong's word" + ); } } assert_eq!(t.get("Fit").copied(), Some("置中縮放")); @@ -324,11 +440,20 @@ mod tests { assert_eq!(t.get("Turn signal").copied(), Some("指揮燈")); assert_eq!(t.get("Width").copied(), Some("闊度")); assert_eq!(t.get("Slope").copied(), Some("斜度")); - assert_eq!(t.get("Footway").copied(), Some("行人路")); + assert_eq!(t.get("Footway").copied(), Some("人行道")); assert_eq!(t.get("Request loops").copied(), Some("車輛感應線圈")); - assert!(t.get("Pick a crossing object of the map").is_some_and(|s| s.contains("選取")), "{:?}", t.get("Pick a crossing object of the map")); + assert!( + t.get("Pick a crossing object of the map") + .is_some_and(|s| s.contains("選取")), + "{:?}", + t.get("Pick a crossing object of the map") + ); // (the railway's signals keep their own word: they are not traffic lights) - assert!(t.get("Signal routes").is_some_and(|s| s.contains("號誌")), "{:?}", t.get("Signal routes")); + assert!( + t.get("Signal routes").is_some_and(|s| s.contains("號誌")), + "{:?}", + t.get("Signal routes") + ); } #[test] diff --git a/src/lanes_edit.rs b/src/lanes_edit.rs index 0f5785c..eec1176 100644 --- a/src/lanes_edit.rs +++ b/src/lanes_edit.rs @@ -148,7 +148,7 @@ pub fn detach(doc: &mut Document, assets: &mut Assets, pieces: &[(TileKey, i64)] continue; } let mut made: Vec<(TileKey, MapSpline)> = Vec::new(); - for p in &model.def.paths { + for (path_index, p) in model.def.paths.iter().enumerate() { let file = if p.kind == 1 { walk } else { car }; let (x, z) = (p.start[0] as f64, p.start[2] as f64); // (the lane's own direction, turned round on a mirrored road) @@ -167,8 +167,12 @@ pub fn detach(doc: &mut Document, assets: &mut Assets, pieces: &[(TileKey, i64)] }; for &reverse in ways { let new_id = doc.new_id(); - if let Some(m) = lane_spline(&s, *k, x, z, reverse, file, new_id) { - made.push(m); + if let Some((key, mut lane)) = lane_spline(&s, *k, x, z, reverse, file, new_id) { + lane.rules = s.rules.iter().filter(|r| !r.kill && r.path_index == path_index as i32).map(|rule| { + log::info!("detach rule: source_spline_id={} source_path_index={path_index} new_spline_id={new_id} kind={} value={}", s.id, rule.kind, rule.value); + omsi_map::MapRule { path_index: 0, ..rule.clone() } + }).collect(); + made.push((key, lane)); } } } @@ -181,7 +185,7 @@ pub fn detach(doc: &mut Document, assets: &mut Assets, pieces: &[(TileKey, i64)] if let Some(t) = doc.tiles.get_mut(k) { if let Some(sp) = t.tile.splines.iter_mut().find(|q| q.id == *id) { sp.file = copy.clone(); - // (the rules were for the lanes by number: they no longer apply) + // Rules now live on the corresponding detached AI path splines. sp.rules.clear(); } t.touch_content(); @@ -234,3 +238,6 @@ mod tests { assert!((b.end_point() - c.offset_point(0.0, 2.0, 0.0)).truncate().length() < 0.01, "{:?}", b.end_point()); } } + +#[cfg(test)] +mod review_tests; diff --git a/src/lanes_edit/review_tests.rs b/src/lanes_edit/review_tests.rs new file mode 100644 index 0000000..e23c4bb --- /dev/null +++ b/src/lanes_edit/review_tests.rs @@ -0,0 +1,120 @@ +use super::*; +use crate::road_maker::{RoadSpec, Strip}; + +#[test] +fn detaching_transfers_all_live_rule_kinds_to_each_resulting_ai_path() { + let root = std::env::temp_dir().join(format!("om-detach-rules-{}", std::process::id())); + std::fs::create_dir_all(&root).unwrap(); + let tex = root.join("asphalt.png"); + image::RgbaImage::from_pixel(4, 4, image::Rgba([80, 80, 80, 255])) + .save(&tex) + .unwrap(); + let mut road = RoadSpec { + name: "Detachable road".into(), + roadway_tex: tex, + ..Default::default() + } + .normalised(false); + if let Strip::Lane { bus_only, .. } = &mut road.strips[2] { + *bus_only = true; + } + road.strips.insert(3, Strip::BusBay { width: 3.0 }); + let file = road.write(&root).unwrap(); + // An additional bidirectional vehicle path must split into two AI splines. + let path = omsi_cfg::resolve_path(&root, &file); + let mut text = omsi_cfg::vfs::read_text(&path).unwrap(); + text.push_str("\n[path]\n0\n0\n0.1\n3\n2\n\n"); + std::fs::write(&path, omsi_cfg::encode_text(&text)).unwrap(); + for (file, kind) in [("car.sli", 0), ("walk.sli", 1)] { + std::fs::write(root.join(file), format!("[path]\n{kind}\n0\n0\n3\n0\n\n")).unwrap(); + } + let mut assets = Assets::new(root.join("omsi"), root.clone()); + let source = assets.spline_wait(&file, 5000).unwrap(); + assets.spline_wait("car.sli", 5000).unwrap(); + assets.spline_wait("walk.sli", 5000).unwrap(); + let mut doc = crate::selection::tests::flat_map(1); + doc.global.next_id_code = 10; + let mut rules = Vec::new(); + for (p, _) in source.def.paths.iter().enumerate() { + for (i, kind) in [ + "bus", + "no_cars", + "speedlimit", + "trafficdensity", + "priority", + "trucks", + ] + .iter() + .enumerate() + { + rules.push(omsi_map::MapRule { + path_index: p as i32, + kind: (*kind).into(), + value: (p * 10 + i) as f64, + extra: 7.0, + ..Default::default() + }); + } + rules.push(omsi_map::MapRule { + path_index: p as i32, + kind: "killed".into(), + kill: true, + ..Default::default() + }); + } + doc.tiles + .get_mut(&(0, 0)) + .unwrap() + .tile + .splines + .push(MapSpline { + file: file.clone(), + id: 1, + pos: [100.0, 100.0, 0.0], + length: 60.0, + rules: rules.clone(), + ..Default::default() + }); + let free = std::collections::HashMap::from([(file.to_lowercase(), "without_paths.sli".into())]); + assert_eq!( + detach( + &mut doc, + &mut assets, + &[((0, 0), 1)], + &free, + "car.sli", + "walk.sli" + ), + 1 + ); + assert!(doc.spline((0, 0), 1).unwrap().rules.is_empty()); + for (p, path) in source.def.paths.iter().enumerate() { + let expected: Vec<_> = rules + .iter() + .filter(|r| r.path_index == p as i32 && !r.kill) + .map(|r| omsi_map::MapRule { + path_index: 0, + ..r.clone() + }) + .collect(); + let lanes: Vec<_> = doc.tiles[&(0, 0)] + .tile + .splines + .iter() + .filter(|s| s.id != 1 && (s.pos[0] - 100.0 - f64::from(path.start[0])).abs() < 1e-3) + .collect(); + assert_eq!( + lanes.len(), + if path.direction == 2 { 2 } else { 1 }, + "source path {p}" + ); + for lane in lanes { + assert_eq!( + lane.rules, expected, + "source path {p}, new spline {}", + lane.id + ); + } + } + std::fs::remove_dir_all(root).unwrap(); +} diff --git a/src/mcp/tests.rs b/src/mcp/tests.rs index e353d54..57c3bc5 100644 --- a/src/mcp/tests.rs +++ b/src/mcp/tests.rs @@ -10,6 +10,7 @@ fn server(allow_edit: bool) -> Server { let nowhere = std::env::temp_dir().join("openmapper-mcp-no-omsi"); let roots = crate::install::Roots { omsi: nowhere.clone(), content: nowhere }; let mut doc = Document { + content_root: None, global: Default::default(), tiles: Default::default(), order: Vec::new(), diff --git a/src/road_maker.rs b/src/road_maker.rs index 109790e..61322d9 100644 --- a/src/road_maker.rs +++ b/src/road_maker.rs @@ -316,7 +316,7 @@ impl RoadSpec { } Strip::Footway { width, tex } => { if i == 0 { s.footway = *width; } else { s.footway_right = Some(*width); } - s.footway_tex = tex.clone(); + if !tex.as_os_str().is_empty() { s.footway_tex = tex.clone(); } } Strip::BusBay { width } => s.pocket = *width, } @@ -347,19 +347,19 @@ impl RoadSpec { if let Err(error) = self.validate() { issues.push(error); } let strips = self.effective_strips(); let lanes: Vec<_> = strips.iter().filter_map(|s| if let Strip::Lane { width, .. } = s { Some(*width) } else { None }).collect(); - if lanes.windows(2).any(|p| p[0] != p[1]) { issues.push("車道寬度不一致".into()); } - if strips.iter().any(|s| matches!(s, Strip::Lane { bus_only: true, .. })) { issues.push("含公車專用車道".into()); } + if lanes.windows(2).any(|p| p[0] != p[1]) { issues.push(crate::i18n::tr("Lane widths differ", "Разная ширина полос").into()); } + if strips.iter().any(|s| matches!(s, Strip::Lane { bus_only: true, .. })) { issues.push(crate::i18n::tr("Contains bus-only lanes", "Есть полосы только для автобусов").into()); } let medians: Vec<_> = strips.iter().enumerate().filter(|(_, s)| matches!(s, Strip::Median { .. })).collect(); - if medians.len() > 1 { issues.push("含多個分隔島".into()); } + if medians.len() > 1 { issues.push(crate::i18n::tr("Contains multiple medians", "Несколько разделительных полос").into()); } for (i, _) in medians { let left = strips[..i].iter().rev().find_map(|s| if let Strip::Lane { dir, .. } = s { Some(*dir) } else { None }); let right = strips[i+1..].iter().find_map(|s| if let Strip::Lane { dir, .. } = s { Some(*dir) } else { None }); - if left.is_none() || right.is_none() || left == right { issues.push("分隔島不在兩向車道交界".into()); } + if left.is_none() || right.is_none() || left == right { issues.push(crate::i18n::tr("Median is not between opposite directions", "Разделительная полоса не между встречными направлениями").into()); } } let first_lane = strips.iter().position(|s| matches!(s, Strip::Lane { .. })).unwrap_or(0); - if strips[..first_lane].iter().any(|s| matches!(s, Strip::BusBay { .. })) { issues.push("左側含 BusBay".into()); } - let textures: Vec<_> = strips.iter().filter_map(|s| if let Strip::Footway { tex, .. } = s { Some(tex) } else { None }).collect(); - if textures.windows(2).any(|p| p[0] != p[1]) { issues.push("兩側人行道使用不同材質".into()); } + if strips[..first_lane].iter().any(|s| matches!(s, Strip::BusBay { .. })) { issues.push(crate::i18n::tr("Contains a left BusBay", "Есть левый автобусный карман").into()); } + let textures: Vec<_> = strips.iter().filter_map(|s| if let Strip::Footway { tex, .. } = s { Some(if tex.as_os_str().is_empty() { &self.footway_tex } else { tex }) } else { None }).collect(); + if textures.windows(2).any(|p| p[0] != p[1]) { issues.push(crate::i18n::tr("Footway textures differ", "Разные текстуры тротуаров").into()); } issues } @@ -379,7 +379,7 @@ impl RoadSpec { pub fn validate(&self) -> Result<(), String> { if self.name.to_lowercase().contains("_bay_") || self.file_stem().to_lowercase().contains("_bay_") { - return Err("名稱不能包含 _bay_(保留給巴士停車灣工具產生的道路類型)".into()); + return Err(crate::i18n::tr("Names must not contain _bay_ (reserved for the bus bay tool)", "Имя не должно содержать _bay_ (зарезервировано для инструмента автобусных карманов)").into()); } strips::validate(&self.effective_strips(), self.left_hand.unwrap_or(false)) } @@ -458,10 +458,12 @@ impl RoadSpec { let positions = strips::positions(&strips); let rw = self.roadway_width(); let line = |x, style, color| Marking { x, style, color, ..Default::default() }; - let mut out = vec![line(-rw / 2.0 + 0.2, MarkStyle::Solid, WHITE), - line(rw / 2.0 - 0.2, if strips.iter().any(|s| matches!(s, Strip::BusBay { .. })) { - MarkStyle::Dashed - } else { MarkStyle::Solid }, WHITE)]; + let first = strips.iter().position(Strip::is_roadway).unwrap_or(0); + let last = strips.iter().rposition(Strip::is_roadway).unwrap_or(0); + let edge = |bay| if bay { MarkStyle::Dashed } else { MarkStyle::Solid }; + let left_bay = strips[..first].iter().any(|s| matches!(s, Strip::BusBay { .. })); + let right_bay = strips.get(last + 1..).unwrap_or_default().iter().any(|s| matches!(s, Strip::BusBay { .. })); + let mut out = vec![line(-rw / 2.0 + 0.2, edge(left_bay), WHITE), line(rw / 2.0 - 0.2, edge(right_bay), WHITE)]; let lanes: Vec<_> = strips.iter().zip(&positions).filter_map(|(s, pos)| { if let Strip::Lane { dir, .. } = s { Some((*dir, *pos)) } else { None } }).collect(); @@ -660,9 +662,44 @@ impl RoadSpec { spec.write_normalised(content) } + pub fn reset_bay_texture(&self, content: &Path) -> anyhow::Result<()> { + self.validate().map_err(anyhow::Error::msg)?; + self.copy_bay_texture(content, true) + } + + fn copy_bay_texture(&self, content: &Path, reset: bool) -> anyhow::Result<()> { + if !self.effective_strips().iter().any(|s| matches!(s, Strip::BusBay { .. })) { return Ok(()); } + let dir = content.join("Splines/openMapper/texture"); + std::fs::create_dir_all(&dir)?; + let destination = dir.join(self.bay_tex_name()); + let copy = |source: &Path, target: &Path| -> anyhow::Result<()> { + if target.exists() && !reset { + log::info!("保留既有灣貼圖: {}", target.display()); + } else if source.is_file() && source != target { + if reset { std::fs::copy(source, target)?; } + else { + use std::io::Write; + match std::fs::OpenOptions::new().write(true).create_new(true).open(target) { + Ok(mut file) => file.write_all(&std::fs::read(source)?)?, + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => log::info!("保留既有灣貼圖: {}", target.display()), + Err(e) => return Err(e.into()), + } + } + } + Ok(()) + }; + anyhow::ensure!(self.roadway_tex.is_file(), crate::i18n::tr("The roadway texture is missing", "Отсутствует текстура проезжей части")); + copy(&self.roadway_tex, &destination)?; + for ext in ["cfg", "surf"] { + copy(&PathBuf::from(format!("{}.{ext}", self.roadway_tex.display())), &PathBuf::from(format!("{}.{ext}", destination.display())))?; + copy(&self.roadway_tex.with_extension(ext), &destination.with_extension(ext))?; + } + Ok(()) + } + fn write_normalised(&self, content: &Path) -> anyhow::Result { let left_hand = self.left_hand.unwrap(); - anyhow::ensure!(self.roadway_tex.is_file(), "the roadway texture is missing"); + anyhow::ensure!(self.roadway_tex.is_file(), crate::i18n::tr("The roadway texture is missing", "Отсутствует текстура проезжей части")); let dir = content.join("Splines").join("openMapper"); let tex_dir = dir.join("texture"); std::fs::create_dir_all(&tex_dir)?; @@ -671,6 +708,10 @@ impl RoadSpec { }); for t in [&self.roadway_tex, &self.footway_tex, &self.median_tex].into_iter().chain(strip_textures).filter(|t| t.is_file()) { let name = t.file_name().unwrap(); + if self.strips.iter().any(|s| matches!(s, Strip::BusBay { .. })) && name == std::ffi::OsStr::new(&self.bay_tex_name()) { + // The independent bay file is managed exclusively by copy_bay_texture. + continue; + } if t.parent() != Some(tex_dir.as_path()) { std::fs::copy(t, tex_dir.join(name))?; // (its settings and surface sound go with it) @@ -682,21 +723,10 @@ impl RoadSpec { } } } - if self.strips.iter().any(|s| matches!(s, Strip::BusBay { .. })) { - let destination = tex_dir.join(self.bay_tex_name()); - if self.roadway_tex != destination { std::fs::copy(&self.roadway_tex, &destination)?; } - for ext in ["cfg", "surf"] { - let source = PathBuf::from(format!("{}.{ext}", self.roadway_tex.display())); - let target = PathBuf::from(format!("{}.{ext}", destination.display())); - if source.is_file() && source != target { std::fs::copy(&source, &target)?; } - let source = self.roadway_tex.with_extension(ext); - let target = destination.with_extension(ext); - if source.is_file() && source != target { std::fs::copy(&source, &target)?; } - } - } + self.copy_bay_texture(content, false)?; let stem = self.file_stem(); if self.marked { - let img = self.painted_roadway().ok_or_else(|| anyhow::anyhow!("the roadway texture could not be read"))?; + let img = self.painted_roadway().ok_or_else(|| anyhow::anyhow!(crate::i18n::tr("The roadway texture could not be read", "Не удалось прочитать текстуру проезжей части")))?; image::DynamicImage::ImageRgba8(img).to_rgb8().save(tex_dir.join(self.roadway_tex_name()))?; } let path = dir.join(format!("{stem}.sli")); @@ -1100,3 +1130,6 @@ mod compat_tests; #[cfg(test)] mod layout_tests; + +#[cfg(test)] +mod review_tests; diff --git a/src/road_maker/bus_rules.rs b/src/road_maker/bus_rules.rs index e1c36a9..81bc7cc 100644 --- a/src/road_maker/bus_rules.rs +++ b/src/road_maker/bus_rules.rs @@ -3,15 +3,29 @@ use super::RoadSpec; use crate::doc::{Document, TileKey}; use omsi_map::MapSpline; -pub fn paths_for(doc: &Document, file: &str) -> Vec { - // Made roads live in the map's content installation. A source map can also - // refer to a made road beside the installation it was read from. +pub fn paths_for(doc: &Document, file: &str, content: Option<&std::path::Path>) -> Vec { + let mut roots: Vec = content + .or(doc.content_root.as_deref()) + .map(|p| p.to_path_buf()) + .into_iter() + .collect(); for map in std::iter::once(doc.dir.as_path()).chain(doc.source.as_deref()) { - let Some(root) = map.parent().and_then(|p| p.parent()) else { - continue; - }; - let sli = omsi_cfg::resolve_path(root, file); - if sli.with_extension("road.json").is_file() { + if let Some(root) = map.parent().and_then(|p| p.parent()) { + if !roots.iter().any(|p| p == root) { + roots.push(root.to_path_buf()); + } + } + } + let mut searched = Vec::new(); + for root in roots { + let sli = omsi_cfg::resolve_path(&root, file); + let json = sli.with_extension("road.json"); + searched.push(if json.is_absolute() { + json.clone() + } else { + std::env::current_dir().unwrap_or_default().join(&json) + }); + if json.is_file() { return RoadSpec::of_with_traffic(&sli, doc.global.left_hand_traffic) .map(|s| { let mut paths = s.bus_paths; @@ -23,6 +37,17 @@ pub fn paths_for(doc: &Document, file: &str) -> Vec { .unwrap_or_default(); } } + let normalized = file.replace('\\', "/").to_lowercase(); + if normalized.starts_with("splines/openmapper/") || normalized.contains("/splines/openmapper/") + { + log::warn!( + "{}: file={file:?}, searched={searched:?}", + crate::i18n::tr( + "Road metadata not found", + "Не найдены данные конструктора дороги" + ) + ); + } Vec::new() } @@ -95,7 +120,7 @@ pub fn apply_for_splines(doc: &mut Document, splines: &[(TileKey, i64)], caller: } } for (file, instances) in by_file { - let paths = paths_for(doc, &file); + let paths = paths_for(doc, &file, doc.content_root.as_deref()); if !paths.is_empty() { apply_logged(doc, &instances, &paths, caller); } @@ -147,7 +172,7 @@ pub fn retype(doc: &mut Document, splines: &[(TileKey, i64)], file: &str, caller let Some(old) = doc.spline(key, id).map(|s| s.file.clone()) else { continue; }; - let paths = paths_for(doc, &old); + let paths = paths_for(doc, &old, doc.content_root.as_deref()); remove_old(doc, key, id, &paths, caller); if let Some(tile) = doc.tiles.get_mut(&key) { if let Some(s) = tile @@ -166,3 +191,5 @@ pub fn retype(doc: &mut Document, splines: &[(TileKey, i64)], file: &str, caller #[cfg(test)] mod tests; + +pub mod batch; diff --git a/src/road_maker/bus_rules/batch.rs b/src/road_maker/bus_rules/batch.rs new file mode 100644 index 0000000..c047e5c --- /dev/null +++ b/src/road_maker/bus_rules/batch.rs @@ -0,0 +1,29 @@ +use super::*; +use std::collections::BTreeMap; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Group { + pub file: String, + pub splines: Vec<(TileKey, i64)>, + pub paths: Vec, +} + +pub fn preview(doc: &Document, content: Option<&std::path::Path>) -> Vec { + let mut groups = BTreeMap::>::new(); + for (&key, tile) in &doc.tiles { + for s in tile.tile.splines.iter().filter(|s| !s.deleted) { + groups.entry(s.file.clone()).or_default().push((key, s.id)); + } + } + groups + .into_iter() + .filter_map(|(file, splines)| { + let paths = paths_for(doc, &file, content); + (!paths.is_empty()).then_some(Group { + file, + splines, + paths, + }) + }) + .collect() +} diff --git a/src/road_maker/bus_rules/tests.rs b/src/road_maker/bus_rules/tests.rs index fcfad50..62f71c7 100644 --- a/src/road_maker/bus_rules/tests.rs +++ b/src/road_maker/bus_rules/tests.rs @@ -69,7 +69,7 @@ fn reserved_names_are_rejected_before_any_output_is_created() { }; assert_eq!( spec.validate().unwrap_err(), - "名稱不能包含 _bay_(保留給巴士停車灣工具產生的道路類型)" + crate::i18n::tr("Names must not contain _bay_ (reserved for the bus bay tool)", "Имя не должно содержать _bay_ (зарезервировано для инструмента автобусных карманов)") ); assert!(spec.write(&root).is_err()); assert!(!root.exists()); diff --git a/src/road_maker/free_layout.rs b/src/road_maker/free_layout.rs index 0f4f34c..5fb7cf5 100644 --- a/src/road_maker/free_layout.rs +++ b/src/road_maker/free_layout.rs @@ -40,7 +40,12 @@ pub(super) fn emit(spec: &RoadSpec) -> String { let mut indices = Vec::new(); for strip in strips { indices.push(match strip { - Strip::Footway { tex, .. } | Strip::Median { tex, .. } => texture_index(tex), + Strip::Footway { tex, .. } => texture_index(if tex.as_os_str().is_empty() { + &spec.footway_tex + } else { + tex + }), + Strip::Median { tex, .. } => texture_index(tex), _ => 0, }); } @@ -79,7 +84,7 @@ pub(super) fn emit(spec: &RoadSpec) -> String { Strip::Median { width, tex, .. } if !tex.as_os_str().is_empty() => { (indices[i], 0.0, 1.0, *width) } - Strip::Median { raised: true, .. } if side_index != 0 => { + Strip::Median { raised: true, .. } if !spec.footway_tex.as_os_str().is_empty() => { (side_index, 0.953, 0.187, 0.2) } Strip::Median { .. } => ( @@ -89,7 +94,15 @@ pub(super) fn emit(spec: &RoadSpec) -> String { spec.roadway_v(), ), }; - profile(&mut text, index, (*lo, h, u0, v), (*hi, h, u1, v)); + let footway_has_texture = |i: usize| match &strips[i] { + Strip::Footway { tex, .. } => { + !tex.as_os_str().is_empty() || !spec.footway_tex.as_os_str().is_empty() + } + _ => false, + }; + if !matches!(strip, Strip::Footway { .. }) || footway_has_texture(i) { + profile(&mut text, index, (*lo, h, u0, v), (*hi, h, u1, v)); + } if let Some(next) = strips.get(i + 1) { let next_h = next.height(spec.kerb); if h != next_h { @@ -105,7 +118,16 @@ pub(super) fn emit(spec: &RoadSpec) -> String { } else { (0.953, 0.995) }; - profile(&mut text, index, (*hi, h, u0, 0.2), (*hi, next_h, u1, 0.2)); + let available = if matches!(strip, Strip::Footway { .. }) { + footway_has_texture(i) + } else if matches!(next, Strip::Footway { .. }) { + footway_has_texture(i + 1) + } else { + !spec.footway_tex.as_os_str().is_empty() + }; + if available { + profile(&mut text, index, (*hi, h, u0, 0.2), (*hi, next_h, u1, 0.2)); + } } } } diff --git a/src/road_maker/layout_tests.rs b/src/road_maker/layout_tests.rs index 747817a..0f619ec 100644 --- a/src/road_maker/layout_tests.rs +++ b/src/road_maker/layout_tests.rs @@ -95,9 +95,9 @@ fn switching_to_simple_mode_rejects_lossy_settings_and_projects_representable_ro road.advanced = true; let before = road.strips.clone(); let reasons = road.use_simple_mode().unwrap_err(); - assert!(reasons.iter().any(|r| r.contains("寬度"))); - assert!(reasons.iter().any(|r| r.contains("公車"))); - assert!(reasons.iter().any(|r| r.contains("左側"))); + assert!(reasons.iter().any(|r| r == crate::i18n::tr("Lane widths differ", "Разная ширина полос"))); + assert!(reasons.iter().any(|r| r == crate::i18n::tr("Contains bus-only lanes", "Есть полосы только для автобусов"))); + assert!(reasons.iter().any(|r| r == crate::i18n::tr("Contains a left BusBay", "Есть левый автобусный карман"))); assert_eq!(road.strips, before); assert!(road.advanced); let mut road = RoadSpec { diff --git a/src/road_maker/review_tests.rs b/src/road_maker/review_tests.rs new file mode 100644 index 0000000..91f409c --- /dev/null +++ b/src/road_maker/review_tests.rs @@ -0,0 +1,164 @@ +use super::*; + +fn fixture(tag: &str) -> (PathBuf, RoadSpec) { + let root = std::env::temp_dir().join(format!("om-review-{tag}-{}", std::process::id())); + std::fs::create_dir_all(&root).unwrap(); + let tex = root.join("asphalt.png"); + image::RgbaImage::from_pixel(4, 4, image::Rgba([80, 80, 80, 255])) + .save(&tex) + .unwrap(); + ( + root, + RoadSpec { + name: "Review road".into(), + roadway_tex: tex, + ..Default::default() + } + .normalised(false), + ) +} + +#[test] +fn saving_preserves_custom_bay_pixels_and_sidecars_until_explicit_reset() { + let (root, mut road) = fixture("pixels"); + road.strips.insert(3, Strip::BusBay { width: 3.0 }); + std::fs::write(root.join("asphalt.png.cfg"), b"original cfg").unwrap(); + std::fs::write(root.join("asphalt.surf"), b"original surf").unwrap(); + road.write(&root).unwrap(); + let folder = root.join("Splines/openMapper/texture"); + let bay = folder.join("Review_road_bay.png"); + image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 0, 127, 255])) + .save(&bay) + .unwrap(); + std::fs::write(folder.join("Review_road_bay.png.cfg"), b"custom cfg").unwrap(); + std::fs::write(folder.join("Review_road_bay.surf"), b"custom surf").unwrap(); + road.write(&root).unwrap(); + assert_eq!( + image::open(&bay).unwrap().to_rgba8().get_pixel(0, 0).0, + [255, 0, 127, 255] + ); + assert_eq!( + std::fs::read(folder.join("Review_road_bay.png.cfg")).unwrap(), + b"custom cfg" + ); + assert_eq!( + std::fs::read(folder.join("Review_road_bay.surf")).unwrap(), + b"custom surf" + ); + road.reset_bay_texture(&root).unwrap(); + assert_eq!( + image::open(&bay).unwrap().to_rgba8().get_pixel(0, 0).0, + [80, 80, 80, 255] + ); + assert_eq!( + std::fs::read(folder.join("Review_road_bay.png.cfg")).unwrap(), + b"original cfg" + ); + assert_eq!( + std::fs::read(folder.join("Review_road_bay.surf")).unwrap(), + b"original surf" + ); + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn bay_edge_markings_follow_the_actual_side() { + for (left, right) in [(true, false), (false, true), (true, true), (false, false)] { + let mut road = RoadSpec::default().normalised(false); + if right { + road.strips.insert(3, Strip::BusBay { width: 3.0 }); + } + if left { + road.strips.insert(1, Strip::BusBay { width: 3.0 }); + } + let marks = road.standard_markings(); + assert_eq!( + marks[0].style, + if left { + MarkStyle::Dashed + } else { + MarkStyle::Solid + } + ); + assert_eq!( + marks[1].style, + if right { + MarkStyle::Dashed + } else { + MarkStyle::Solid + } + ); + } +} + +#[test] +fn blank_footway_textures_inherit_the_default_or_omit_visual_profiles() { + let (root, mut road) = fixture("footways"); + let side = root.join("side.png"); + image::RgbaImage::from_pixel(2, 2, image::Rgba([150, 150, 150, 255])) + .save(&side) + .unwrap(); + // Exercise both the compatible writer and the general strip writer. + for advanced in [false, true] { + if let Strip::Lane { bus_only, .. } = &mut road.strips[2] { + *bus_only = advanced; + } + for with_texture in [false, true] { + road.footway_tex = if with_texture { + side.clone() + } else { + PathBuf::new() + }; + let rel = road.write(&root).unwrap(); + let model = omsi_scenery::Spline::load(&omsi_cfg::resolve_path(&root, &rel)).unwrap(); + assert_eq!(model.paths.iter().filter(|p| p.kind == 1).count(), 2); + assert!(road.sli(false).matches("[heightprofile]").count() >= 3); + assert_eq!( + model.profiles.len(), + match (advanced, with_texture) { + (false, false) => 1, + (false, true) => 5, + (true, false) => 2, + (true, true) => 6, + } + ); + if !with_texture { + assert!( + model + .profiles + .iter() + .all(|p| p.points.iter().all(|q| (q.z - 0.10).abs() < 1e-4)) + ); + } + } + } + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn metadata_prefers_explicit_content_root_over_map_location_and_falls_back() { + let (root, mut road) = fixture("root"); + let preferred = root.join("preferred"); + let fallback = root.join("fallback"); + if let Strip::Lane { bus_only, .. } = &mut road.strips[1] { + *bus_only = true; + } + let rel = road.write(&preferred).unwrap(); + if let Strip::Lane { bus_only, .. } = &mut road.strips[1] { + *bus_only = false; + } + if let Strip::Lane { bus_only, .. } = &mut road.strips[2] { + *bus_only = true; + } + road.write(&fallback).unwrap(); + let mut doc = crate::selection::tests::flat_map(1); + doc.dir = fallback.join("maps/Test"); + assert_eq!(bus_rules::paths_for(&doc, &rel, Some(&preferred)), [1]); + doc.content_root = Some(preferred.clone()); + assert_eq!(bus_rules::paths_for(&doc, &rel, None), [1]); + assert_eq!( + bus_rules::paths_for(&doc, &rel, Some(&root.join("missing"))), + [2] + ); + std::fs::remove_dir_all(root).unwrap(); +} diff --git a/src/road_maker/strips.rs b/src/road_maker/strips.rs index 58f9fb2..727d940 100644 --- a/src/road_maker/strips.rs +++ b/src/road_maker/strips.rs @@ -67,7 +67,7 @@ pub fn validate(strips: &[Strip], left_hand: bool) -> Result<(), String> { let first = strips .iter() .position(|s| matches!(s, Strip::Lane { .. })) - .ok_or_else(|| "道路至少需要一條 Lane".to_string())?; + .ok_or_else(|| crate::i18n::tr("A road needs at least one Lane", "Дороге нужна хотя бы одна полоса движения").to_string())?; let last = strips .iter() .rposition(|s| matches!(s, Strip::Lane { .. })) @@ -75,22 +75,22 @@ pub fn validate(strips: &[Strip], left_hand: bool) -> Result<(), String> { for (i, strip) in strips.iter().enumerate() { let w = strip.width(); if !w.is_finite() || w < 0.0 || (w == 0.0 && !matches!(strip, Strip::Median { .. })) { - return Err(format!("積木 {} 的寬度無效", i + 1)); + return Err(crate::i18n::tr("Strip {} has an invalid width", "Недопустимая ширина полосы {}").replace("{}", &(i + 1).to_string())); } match strip { Strip::Footway { .. } if i != 0 && i + 1 != strips.len() => { - return Err("Footway 只能位於道路兩端".into()); + return Err(crate::i18n::tr("Footways must be at the outer ends", "Тротуары должны быть по краям дороги").into()); } Strip::BusBay { .. } if i.checked_add(1) != Some(first) && i != last + 1 => { - return Err("BusBay 只能緊貼車道段外緣,各側最多一個".into()); + return Err(crate::i18n::tr("BusBays must border the roadway, at most one per side", "Автобусные карманы должны примыкать к дороге, не более одного с каждой стороны").into()); } Strip::Median { .. } if i < first || i > last => { - return Err("Median 必須位於車道段內".into()); + return Err(crate::i18n::tr("Medians must be inside the roadway", "Разделительные полосы должны быть внутри проезжей части").into()); } _ => {} } if (first..=last).contains(&i) && !strip.is_roadway() { - return Err("車道段內只能包含 Lane 和 Median".into()); + return Err(crate::i18n::tr("The roadway may contain only Lanes and Medians", "Проезжая часть может содержать только полосы движения и разделительные полосы").into()); } } let left_dir = if left_hand { @@ -104,7 +104,7 @@ pub fn validate(strips: &[Strip], left_hand: bool) -> Result<(), String> { if *dir != left_dir { reached_right = true; } else if reached_right { - return Err("車道方向排列不符合此道路的行駛側設定".into()); + return Err(crate::i18n::tr("Lane directions do not match this road’s traffic side", "Направления полос не соответствуют стороне движения этой дороги").into()); } } } diff --git a/src/selection.rs b/src/selection.rs index 89bef6a..64a7c2c 100644 --- a/src/selection.rs +++ b/src/selection.rs @@ -739,6 +739,7 @@ pub mod tests { pub fn flat_map(n: i32) -> Document { crate::doc::hold_map_for_test(); let mut doc = Document { + content_root: None, global: omsi_map::GlobalCfg { next_id_code: 100, ..Default::default() }, tiles: Default::default(), order: Vec::new(), diff --git a/src/ui_roads.rs b/src/ui_roads.rs index 2952119..6ca0063 100644 --- a/src/ui_roads.rs +++ b/src/ui_roads.rs @@ -29,6 +29,8 @@ pub struct RoadTypes { /// The road's textures as the previews show them. pics: TexCache, error: Option, + pending_bus_rules: Option>, + bus_rule_result: Option, /// The drawing board for the markings. canvas: crate::ui_markpaint::MarkCanvas, } @@ -124,6 +126,29 @@ impl RoadTypes { let left_hand = ed.doc.as_ref().is_some_and(|doc| doc.global.left_hand_traffic); let mut open = self.open; egui::Window::new(icons::labelled(Icon::Road, tr("Road types", "Типы дорог"))).open(&mut open).default_size(Vec2::new(760.0, 520.0)).show(ctx, |ui| { + if ui.add_enabled(ed.doc.is_some(), egui::Button::new(tr("Apply bus lane rules to all existing roads", "Применить правила автобусных полос ко всем существующим дорогам"))).clicked() { + self.pending_bus_rules = Some(ed.preview_all_bus_rules()); self.bus_rule_result = None; + } + if let Some(groups) = &self.pending_bus_rules { + ui.label(tr("Road types and spline counts to update", "Типы дорог и количество сплайнов для обновления")); + if groups.is_empty() { ui.label(tr("No roads need bus lane rules", "Нет дорог с правилами автобусных полос")); } + egui::ScrollArea::vertical().id_salt("bus rule preview").max_height(160.0).show(ui, |ui| { + for group in groups { ui.label(format!("{}: {}", group.file, group.splines.len())); } + }); + let mut confirm = false; let mut cancel = false; + ui.horizontal(|ui| { + confirm = ui.button(tr("Confirm", "Подтвердить")).clicked(); + cancel = ui.button(tr("Cancel", "Отмена")).clicked(); + }); + if confirm { + match ed.apply_all_bus_rules(groups) { + Ok(count) => self.bus_rule_result = Some(count), + Err(error) => self.error = Some(error), + } + } + if confirm || cancel { self.pending_bus_rules = None; } + } + if let Some(count) = self.bus_rule_result { ui.label(format!("{}: {count}", tr("Rules added", "Добавлено правил"))); } ui.horizontal_top(|ui| { // the list ui.vertical(|ui| { @@ -269,15 +294,15 @@ impl RoadTypes { let map_left_hand = left_hand; let left_hand = s.left_hand.unwrap_or(map_left_hand); if left_hand != map_left_hand { - ui.colored_label(Color32::YELLOW, if left_hand { "此道路是為靠左行駛建立的" } else { "此道路是為靠右行駛建立的" }); + ui.colored_label(Color32::YELLOW, if left_hand { crate::i18n::tr("This road was made for left-hand traffic", "Эта дорога создана для левостороннего движения") } else { crate::i18n::tr("This road was made for right-hand traffic", "Эта дорога создана для правостороннего движения") }); } if s.left_hand.is_none() { s.rebuild_strips(left_hand); } let mut advanced = s.advanced; - if ui.checkbox(&mut advanced, "進階:積木模式").changed() { + if ui.checkbox(&mut advanced, crate::i18n::tr("Advanced: strip mode", "Дополнительно: режим полос")).changed() { if advanced { s.advanced = true; s.mode_error = None; } else if let Err(issues) = s.use_simple_mode() { - s.mode_error = Some(format!("此道路含簡單模式無法表示的設定:{}", issues.join("、"))); + s.mode_error = Some(format!("{}: {}", crate::i18n::tr("This road contains settings that simple mode cannot represent", "Эта дорога содержит настройки, недоступные в простом режиме"), issues.join(", "))); } } if let Some(error) = &s.mode_error { ui.colored_label(Color32::YELLOW, error); } @@ -346,7 +371,7 @@ impl RoadTypes { if !s.advanced { s.rebuild_strips(left_hand); } if let Err(error) = s.validate() { ui.colored_label(Color32::RED, error); } if !s.marked && s.unequal_lane_widths() { - ui.colored_label(Color32::YELLOW, "內建多車道貼圖的線會和車道對不上"); + ui.colored_label(Color32::YELLOW, crate::i18n::tr("Built-in multi-lane texture markings may not align with these lanes", "Разметка многополосной текстуры может не совпадать с полосами")); } preview(ui, s, tex, left_hand); let list = textures.get_or_insert_with(|| spline_textures(roots)); @@ -366,7 +391,7 @@ impl RoadTypes { } ui.horizontal(|ui| { ui.label(label); - egui::ComboBox::from_id_salt(("road tex", i)).width(260.0).selected_text(if cur.as_os_str().is_empty() { tr("like the roadway", "как у проезжей части").to_string() } else { file_name(cur) }).show_ui(ui, |ui| { + egui::ComboBox::from_id_salt(("road tex", i)).width(260.0).selected_text(if cur.as_os_str().is_empty() { if i == 1 { tr("No footway texture", "Нет текстуры тротуара").to_string() } else { tr("like the roadway", "как у проезжей части").to_string() } } else { file_name(cur) }).show_ui(ui, |ui| { if i == 2 && ui.selectable_label(cur.as_os_str().is_empty(), tr("like the roadway", "как у проезжей части")).clicked() { cur.clear(); } @@ -385,6 +410,12 @@ impl RoadTypes { } }); } + if s.strips.iter().any(|strip| matches!(strip, crate::road_maker::Strip::BusBay { .. })) && ui.button(tr("Reset bay texture", "Сбросить текстуру кармана")).clicked() { + match s.reset_bay_texture(&roots.content) { + Ok(()) => { s.mode_error = Some(tr("Bay texture reset", "Текстура кармана сброшена").into()); } + Err(error) => { s.mode_error = Some(format!("{}: {error}", tr("Could not reset bay texture", "Не удалось сбросить текстуру кармана"))); } + } + } if !s.advanced { s.rebuild_strips(left_hand); } egui::CollapsingHeader::new(RichText::new(tr("Road markings", "Дорожная разметка")).strong().color(Color32::WHITE)).id_salt("road markings").default_open(s.marked).show(ui, |ui| { ui.checkbox(&mut s.marked, tr("Paint my own markings", "Нарисовать свою разметку")).on_hover_text(tr("The maker paints the lines onto the roadway texture: pick a plain asphalt texture, or its own lines show too", "Конструктор рисует линии на текстуре проезжей части: берите гладкий асфальт, иначе проступят и его собственные линии")); diff --git a/src/ui_roads/strip_panel.rs b/src/ui_roads/strip_panel.rs index f108500..52d14de 100644 --- a/src/ui_roads/strip_panel.rs +++ b/src/ui_roads/strip_panel.rs @@ -3,12 +3,15 @@ use crate::road_maker::{Direction, Strip}; pub(super) fn panel(ui: &mut egui::Ui, s: &mut RoadSpec, textures: &[PathBuf]) { ui.horizontal(|ui| { - ui.label("名稱"); + ui.label(crate::i18n::tr("Name", "Название")); ui.text_edit_singleline(&mut s.name); - ui.label("緣石高度"); + ui.label(crate::i18n::tr("Kerb height", "Высота бордюра")); ui.add(egui::Slider::new(&mut s.kerb, 0.0..=0.3).suffix(" m")); }); - ui.label("積木依道路左至右排列"); + ui.label(crate::i18n::tr( + "Strips run from left to right", + "Полосы расположены слева направо", + )); let count = s.strips.len(); let mut remove = None; let mut swap = None; @@ -18,26 +21,35 @@ pub(super) fn panel(ui: &mut egui::Ui, s: &mut RoadSpec, textures: &[PathBuf]) { ui.horizontal(|ui| { ui.label(format!("{}", i + 1)); ui.strong(match strip { - Strip::Lane { .. } => "Lane 車道", - Strip::Median { .. } => "Median 分隔島", - Strip::Footway { .. } => "Footway 人行道", - Strip::BusBay { .. } => "BusBay 巴士灣", + Strip::Lane { .. } => crate::i18n::tr("Lane", "Полоса движения"), + Strip::Median { .. } => crate::i18n::tr("Median", "Разделительная полоса"), + Strip::Footway { .. } => crate::i18n::tr("Footway", "Тротуар"), + Strip::BusBay { .. } => crate::i18n::tr("BusBay", "Автобусный карман"), }); - if ui.add_enabled(i > 0, egui::Button::new("上移")).clicked() { + if ui + .add_enabled( + i > 0, + egui::Button::new(crate::i18n::tr("Move up", "Вверх")), + ) + .clicked() + { swap = Some((i, i - 1)); } if ui - .add_enabled(i + 1 < count, egui::Button::new("下移")) + .add_enabled( + i + 1 < count, + egui::Button::new(crate::i18n::tr("Move down", "Вниз")), + ) .clicked() { swap = Some((i, i + 1)); } - if ui.button("刪除").clicked() { + if ui.button(crate::i18n::tr("Delete", "Удалить")).clicked() { remove = Some(i); } }); ui.horizontal(|ui| { - ui.label("寬度"); + ui.label(crate::i18n::tr("Width", "Ширина")); match strip { Strip::Lane { dir, @@ -45,13 +57,21 @@ pub(super) fn panel(ui: &mut egui::Ui, s: &mut RoadSpec, textures: &[PathBuf]) { bus_only, } => { ui.add(egui::Slider::new(width, 2.5..=5.0).suffix(" m")); - ui.selectable_value(dir, Direction::Fwd, "順向 ↑"); - ui.selectable_value(dir, Direction::Back, "逆向 ↓"); - ui.checkbox(bus_only, "公車專用"); + ui.selectable_value( + dir, + Direction::Fwd, + crate::i18n::tr("Forward ↑", "По ходу ↑"), + ); + ui.selectable_value( + dir, + Direction::Back, + crate::i18n::tr("Backward ↓", "Против хода ↓"), + ); + ui.checkbox(bus_only, crate::i18n::tr("bus only", "только автобусы")); } Strip::Median { width, raised, .. } => { ui.add(egui::Slider::new(width, 0.0..=12.0).suffix(" m")); - ui.checkbox(raised, "抬高"); + ui.checkbox(raised, crate::i18n::tr("raised", "приподнят")); } Strip::Footway { width, .. } => { ui.add(egui::Slider::new(width, 0.1..=8.0).suffix(" m")); @@ -61,19 +81,36 @@ pub(super) fn panel(ui: &mut egui::Ui, s: &mut RoadSpec, textures: &[PathBuf]) { } } }); + let is_footway = matches!(strip, Strip::Footway { .. }); if let Strip::Median { tex, .. } | Strip::Footway { tex, .. } = strip { ui.horizontal(|ui| { - ui.label("材質"); + ui.label(crate::i18n::tr("Texture", "Текстура")); egui::ComboBox::from_id_salt("material") .selected_text(if tex.as_os_str().is_empty() { - "使用車道材質".into() + if is_footway { + tr("Default footway texture", "Стандартная текстура тротуара") + .into() + } else { + crate::i18n::tr( + "Use roadway texture", + "Использовать текстуру дороги", + ) + .into() + } } else { file_name(tex) }) .show_ui(ui, |ui| { - if ui - .selectable_label(tex.as_os_str().is_empty(), "使用車道材質") - .clicked() + if !is_footway + && ui + .selectable_label( + tex.as_os_str().is_empty(), + crate::i18n::tr( + "Use roadway texture", + "Использовать текстуру дороги", + ), + ) + .clicked() { tex.clear(); } @@ -83,9 +120,15 @@ pub(super) fn panel(ui: &mut egui::Ui, s: &mut RoadSpec, textures: &[PathBuf]) { } } }); - if ui.button("選擇檔案…").clicked() { + if ui + .button(crate::i18n::tr("Choose file…", "Выбрать файл…")) + .clicked() + { if let Some(path) = rfd::FileDialog::new() - .add_filter("材質", &["png", "jpg", "bmp", "tga", "dds"]) + .add_filter( + crate::i18n::tr("Texture", "Текстура"), + &["png", "jpg", "bmp", "tga", "dds"], + ) .pick_file() { *tex = path; @@ -102,28 +145,37 @@ pub(super) fn panel(ui: &mut egui::Ui, s: &mut RoadSpec, textures: &[PathBuf]) { s.strips.swap(a, b); } ui.horizontal(|ui| { - ui.label("新增"); - if ui.button("Lane").clicked() { + ui.label(crate::i18n::tr("Add", "Добавить")); + if ui + .button(crate::i18n::tr("Lane", "Полоса движения")) + .clicked() + { s.strips.push(Strip::Lane { dir: Direction::Fwd, width: 3.5, bus_only: false, }); } - if ui.button("Median").clicked() { + if ui + .button(crate::i18n::tr("Median", "Разделительная полоса")) + .clicked() + { s.strips.push(Strip::Median { width: 2.0, raised: true, tex: s.median_tex.clone(), }); } - if ui.button("Footway").clicked() { + if ui.button(crate::i18n::tr("Footway", "Тротуар")).clicked() { s.strips.push(Strip::Footway { width: 2.0, tex: s.footway_tex.clone(), }); } - if ui.button("BusBay").clicked() { + if ui + .button(crate::i18n::tr("BusBay", "Автобусный карман")) + .clicked() + { s.strips.push(Strip::BusBay { width: 3.0 }); } }); diff --git a/src/ui_roads/strip_preview.rs b/src/ui_roads/strip_preview.rs index d9b8b2f..3c29c38 100644 --- a/src/ui_roads/strip_preview.rs +++ b/src/ui_roads/strip_preview.rs @@ -28,7 +28,14 @@ pub(super) fn draw(ui: &mut egui::Ui, s: &RoadSpec, tex: &mut TexCache, top: boo }, &s.roadway_tex, ), - Strip::Footway { tex, .. } => (Color32::from_gray(175), tex), + Strip::Footway { tex, .. } => ( + Color32::from_gray(175), + if tex.as_os_str().is_empty() { + &s.footway_tex + } else { + tex + }, + ), Strip::Median { tex, .. } => (Color32::from_rgb(100, 145, 90), tex), }; let pic = tex.get(ui.ctx(), path); @@ -98,7 +105,7 @@ pub(super) fn draw(ui: &mut egui::Ui, s: &RoadSpec, tex: &mut TexCache, top: boo painter.text( Pos2::new(middle, cy + 22.0), egui::Align2::CENTER_CENTER, - "BUS", + tr("BUS", "АВТОБУС"), egui::FontId::proportional(11.0), Color32::WHITE, ); @@ -150,8 +157,9 @@ pub(super) fn draw(ui: &mut egui::Ui, s: &RoadSpec, tex: &mut TexCache, top: boo Pos2::new(rect.center().x, rect.bottom() - 9.0), egui::Align2::CENTER_CENTER, format!( - "{:.1} m · roadway {:.1} m", + "{:.1} m · {} {:.1} m", s.total_width(), + tr("roadway", "проезжая часть"), s.roadway_width() ), egui::FontId::proportional(11.0), From 2b595745b46cbd1cec8f14963937bfbb49be233d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BB=B7=E6=96=87=20=E6=A5=8A?= Date: Mon, 16 Nov 2026 05:50:39 +0800 Subject: [PATCH 6/6] Use Hong Kong terms in road maker translations --- locales/zh-tw.tsv | 54 +++++++++--------- src/i18n.rs | 137 ++-------------------------------------------- 2 files changed, 33 insertions(+), 158 deletions(-) diff --git a/locales/zh-tw.tsv b/locales/zh-tw.tsv index bad8a5d..b241289 100644 --- a/locales/zh-tw.tsv +++ b/locales/zh-tw.tsv @@ -2646,7 +2646,7 @@ Another crossing file 另一個路口檔案 Crossing paths of the picked object… 所選路口物件的路徑… Crossing paths 路口路徑 The paths of a crossing or junction object, its blocking and its traffic light program, edited in a copy of the object - the original is left as it is 路口或交叉物件的行車路線、讓路/互斥規則及紅綠燈燈號階段,在物件的副本中編輯,原始檔案維持不變 -Footway 人行道 +Footway 行人路 Street 行車線 Against 逆向 Both ways 雙向 @@ -2839,46 +2839,46 @@ Click a 2nd reference point on the object, or Esc to finish 點擊物件上的 Aligned angle! (Ctrl+Z to undo) 已對齊角度!(Ctrl+Z 復原) Vertex snap complete 頂點吸附完成 Align vertex angle 對齊頂點角度 -Kerb height 緣石高度 +Kerb height 路緣高度 Strips run from left to right 積木依道路左至右排列 -Lane 車道 +Lane 行車線 Median 分隔帶 BusBay 巴士停車灣 Forward ↑ 順向 ↑ Backward ↓ 逆向 ↓ -bus only 公車專用 -Use roadway texture 使用車道材質 +bus only 巴士專用 +Use roadway texture 與行車道相同 Choose file… 選擇檔案… -Default footway texture 預設人行道材質 +Default footway texture 預設行人路貼圖 Advanced: strip mode 進階:積木模式 This road was made for left-hand traffic 此道路是為靠左行駛建立的 This road was made for right-hand traffic 此道路是為靠右行駛建立的 This road contains settings that simple mode cannot represent 此道路含簡單模式無法表示的設定 -Built-in multi-lane texture markings may not align with these lanes 內建多車道貼圖的線會和車道對不上 -Lane widths differ 車道寬度不一致 -Contains bus-only lanes 含公車專用車道 +Built-in multi-lane texture markings may not align with these lanes 內建多行車線貼圖的標線可能與行車線不符 +Lane widths differ 行車線闊度不一致 +Contains bus-only lanes 含巴士專用行車線 Contains multiple medians 含多個分隔帶 -Median is not between opposite directions 分隔帶不在兩向車道交界 +Median is not between opposite directions 分隔帶不在兩個行車方向的交界 Contains a left BusBay 左側含巴士停車灣 -Footway textures differ 兩側人行道使用不同材質 +Footway textures differ 兩側行人路使用不同貼圖 Names must not contain _bay_ (reserved for the bus bay tool) 名稱不能包含 _bay_(保留給巴士停車灣工具產生的道路類型) -A road needs at least one Lane 道路至少需要一條車道 -Strip {} has an invalid width 積木 {} 的寬度無效 -Footways must be at the outer ends 人行道只能位於道路兩端 -BusBays must border the roadway, at most one per side 巴士停車灣只能緊貼車道段外緣,各側最多一個 -Medians must be inside the roadway 分隔帶必須位於車道段內 -The roadway may contain only Lanes and Medians 車道段內只能包含車道和分隔帶 -Lane directions do not match this road’s traffic side 車道方向排列不符合此道路的行駛側設定 -Reset bay texture 重設灣貼圖 -Bay texture reset 已重設灣貼圖 -Could not reset bay texture 無法重設灣貼圖 -The roadway texture is missing 找不到車道材質 -The roadway texture could not be read 無法讀取車道材質 -Apply bus lane rules to all existing roads 套用公車道規則到所有既有道路 +A road needs at least one Lane 道路至少需要一條行車線 +Strip {} has an invalid width 積木 {} 的闊度無效 +Footways must be at the outer ends 行人路只能位於道路兩端 +BusBays must border the roadway, at most one per side 巴士停車灣只能緊貼行車道外緣,每側最多一個 +Medians must be inside the roadway 分隔帶必須位於行車道內 +The roadway may contain only Lanes and Medians 行車道內只能包含行車線和分隔帶 +Lane directions do not match this road’s traffic side 行車線方向排列不符合此道路的行駛側設定 +Reset bay texture 重設停車灣貼圖 +Bay texture reset 已重設停車灣貼圖 +Could not reset bay texture 無法重設停車灣貼圖 +The roadway texture is missing 找不到行車道貼圖 +The roadway texture could not be read 無法讀取行車道貼圖 +Apply bus lane rules to all existing roads 套用巴士專用規則到所有現有道路 Road types and spline counts to update 將套用的道路類型與 spline 數量 Rules added 新增規則數量 Roads changed; review the preview again 道路已變更,請重新檢查預覽 -No roads need bus lane rules 沒有可套用公車道規則的道路 -BUS 公車 -No footway texture 未設定人行道材質 +No roads need bus lane rules 沒有需要套用巴士專用規則的道路 +BUS 巴士 +No footway texture 未設定行人路貼圖 Road metadata not found 找不到道路製作器資料檔 diff --git a/src/i18n.rs b/src/i18n.rs index 30de516..9d093c6 100644 --- a/src/i18n.rs +++ b/src/i18n.rs @@ -304,132 +304,16 @@ mod tests { /// save overwrites the file, and things are picked with 選取, never with 挑. (The words /// these replace are listed: a translation that brings one back is caught here.) #[test] - fn traditional_chinese_preserves_existing_terms_and_requested_road_maker_terms() { + fn the_hong_kong_table_uses_hong_kong_road_words() { let t = table(Lang::ZhTw); assert!(t.len() > 2000, "{} texts", t.len()); - // The road maker explicitly uses the requested Taiwan terminology. - // Check these entries exactly while retaining the older Hong Kong vocabulary elsewhere. - let maker_terms = [ - ("Footway", "人行道"), - ("Kerb height", "緣石高度"), - ("Strips run from left to right", "積木依道路左至右排列"), - ("Lane", "車道"), - ("Median", "分隔帶"), - ("BusBay", "巴士停車灣"), - ("Forward ↑", "順向 ↑"), - ("Backward ↓", "逆向 ↓"), - ("bus only", "公車專用"), - ("Use roadway texture", "使用車道材質"), - ("Choose file…", "選擇檔案…"), - ("Default footway texture", "預設人行道材質"), - ("Advanced: strip mode", "進階:積木模式"), - ( - "This road was made for left-hand traffic", - "此道路是為靠左行駛建立的", - ), - ( - "This road was made for right-hand traffic", - "此道路是為靠右行駛建立的", - ), - ( - "This road contains settings that simple mode cannot represent", - "此道路含簡單模式無法表示的設定", - ), - ( - "Built-in multi-lane texture markings may not align with these lanes", - "內建多車道貼圖的線會和車道對不上", - ), - ("Lane widths differ", "車道寬度不一致"), - ("Contains bus-only lanes", "含公車專用車道"), - ("Contains multiple medians", "含多個分隔帶"), - ( - "Median is not between opposite directions", - "分隔帶不在兩向車道交界", - ), - ("Contains a left BusBay", "左側含巴士停車灣"), - ("Footway textures differ", "兩側人行道使用不同材質"), - ( - "Names must not contain _bay_ (reserved for the bus bay tool)", - "名稱不能包含 _bay_(保留給巴士停車灣工具產生的道路類型)", - ), - ("A road needs at least one Lane", "道路至少需要一條車道"), - ("Strip {} has an invalid width", "積木 {} 的寬度無效"), - ( - "Footways must be at the outer ends", - "人行道只能位於道路兩端", - ), - ( - "BusBays must border the roadway, at most one per side", - "巴士停車灣只能緊貼車道段外緣,各側最多一個", - ), - ( - "Medians must be inside the roadway", - "分隔帶必須位於車道段內", - ), - ( - "The roadway may contain only Lanes and Medians", - "車道段內只能包含車道和分隔帶", - ), - ( - "Lane directions do not match this road’s traffic side", - "車道方向排列不符合此道路的行駛側設定", - ), - ("Reset bay texture", "重設灣貼圖"), - ("Bay texture reset", "已重設灣貼圖"), - ("Could not reset bay texture", "無法重設灣貼圖"), - ("The roadway texture is missing", "找不到車道材質"), - ("The roadway texture could not be read", "無法讀取車道材質"), - ( - "Apply bus lane rules to all existing roads", - "套用公車道規則到所有既有道路", - ), - ( - "Road types and spline counts to update", - "將套用的道路類型與 spline 數量", - ), - ("Rules added", "新增規則數量"), - ( - "Roads changed; review the preview again", - "道路已變更,請重新檢查預覽", - ), - ("No roads need bus lane rules", "沒有可套用公車道規則的道路"), - ("BUS", "公車"), - ("No footway texture", "未設定人行道材質"), - ("Road metadata not found", "找不到道路製作器資料檔"), - ]; - for &(en, expected) in &maker_terms { - assert_eq!(t.get(en).copied(), Some(expected), "{en}"); - } - let taiwan = [ - "車道", - "拖曳", - "相位", - "時相", - "樣條", - "號誌燈", - "公車", - "既有", - "封鎖", - "挑", - "人行道", - "方向燈", - "坡度", - "寬度", - "轉燈階段", - "保持路口淨空", - ]; + let taiwan = ["車道", "拖曳", "相位", "時相", "樣條", "號誌燈", "公車", "既有", "封鎖", "挑", "人行道", "方向燈", "坡度", "寬度", "轉燈階段", "保持路口淨空"]; for (en, tr) in t.iter() { - if maker_terms.iter().any(|(key, _)| key == en) { - continue; - } for w in taiwan { // (行車道 is the roadway as a whole - a carriageway - and Hong Kong's own word; // 車道 alone, a lane, is not) let hay = tr.replace("行車道", ""); - assert!( - !hay.contains(w), - "{en:?} says {tr:?}: {w} is not Hong Kong's word" - ); + assert!(!hay.contains(w), "{en:?} says {tr:?}: {w} is not Hong Kong's word"); } } assert_eq!(t.get("Fit").copied(), Some("置中縮放")); @@ -440,20 +324,11 @@ mod tests { assert_eq!(t.get("Turn signal").copied(), Some("指揮燈")); assert_eq!(t.get("Width").copied(), Some("闊度")); assert_eq!(t.get("Slope").copied(), Some("斜度")); - assert_eq!(t.get("Footway").copied(), Some("人行道")); + assert_eq!(t.get("Footway").copied(), Some("行人路")); assert_eq!(t.get("Request loops").copied(), Some("車輛感應線圈")); - assert!( - t.get("Pick a crossing object of the map") - .is_some_and(|s| s.contains("選取")), - "{:?}", - t.get("Pick a crossing object of the map") - ); + assert!(t.get("Pick a crossing object of the map").is_some_and(|s| s.contains("選取")), "{:?}", t.get("Pick a crossing object of the map")); // (the railway's signals keep their own word: they are not traffic lights) - assert!( - t.get("Signal routes").is_some_and(|s| s.contains("號誌")), - "{:?}", - t.get("Signal routes") - ); + assert!(t.get("Signal routes").is_some_and(|s| s.contains("號誌")), "{:?}", t.get("Signal routes")); } #[test]