//! Campaign map: camera controls, click picking and the parchment map art. //! //! Everything on the map is drawn with gizmos each frame, except the node //! name labels, which are spawned once at startup. use bevy::ecs::system::SystemParam; use bevy::input::mouse::{AccumulatedMouseMotion, AccumulatedMouseScroll}; use bevy::prelude::*; use bevy::sprite::Anchor; use bevy::time::{Real, Time}; use bevy::ui::{CalculatedClip, ComputedNode, UiGlobalTransform, UiScale}; use bevy::window::PrimaryWindow; use crate::menu::Menu; use crate::model::{ GOODS, Good, MIN_USABLE_CONDITION, Network, Node, NodeId, NodeKind, SLOW_CONDITION, Selected, TrackClicked, UiPassThrough, }; use crate::settings::Settings; /// Default zoom limits (orthographic scale). The view is 720 world units tall at scale 1. const MIN_SCALE: f32 = 0.5; const MAX_SCALE: f32 = 2.5; /// World units of the map frame (the playfield), centred on the origin. const MAP_W: f32 = 1280.0; const MAP_H: f32 = 720.0; /// Blank space kept between the map frame and the window edges, in logical px. const FIT_MARGIN_X: f32 = 16.0; const FIT_MARGIN_Y: f32 = 8.0; /// Arrow-key pan speed in logical pixels per second. const KEY_PAN_SPEED: f32 = 450.0; /// Node pick radius in logical pixels, so clicks feel the same at any zoom or window size. const NODE_PICK_RADIUS: f32 = 20.0; /// Track pick distance in logical pixels. const TRACK_PICK_DISTANCE: f32 = 8.0; /// Node name label: glyph size in world units. About 15 px on screen at 720 px tall with the /// camera scale 1.31 (27 at the old scale 1.8). const NODE_LABEL_SIZE: f32 = 19.65; /// Offset of a label centre below the node, just under the stock bars (which end 30 units down). const NODE_LABEL_OFFSET: f32 = 46.0; /// Gap between a node centre and a label placed beside or above it. const LABEL_SIDE_GAP: f32 = 14.0; /// Average advance of the label font in ems, to estimate label width before layout. const LABEL_CHAR_EM: f32 = 0.6; /// Gap kept clear at each end of a track so it does not run into node glyphs. const NODE_GLYPH_RADIUS: f32 = 12.0; /// Spacing of crossties along a track. const TIE_SPACING: f32 = 12.0; /// Half-length of a crosstie. const TIE_HALF_LEN: f32 = 4.0; /// Stock bar scale: world units per stock unit, capped at `BAR_MAX_WIDTH`. const BAR_UNITS_PER_STOCK: f32 = 0.4; const BAR_MAX_WIDTH: f32 = 40.0; const INK: Color = Color::srgb(0.22, 0.15, 0.09); const RUST: Color = Color::srgb(0.66, 0.26, 0.12); const RED: Color = Color::srgb(0.78, 0.12, 0.10); const AMBER: Color = Color::srgb(1.0, 0.70, 0.10); const HOVER_RING: Color = Color::srgb(1.0, 0.98, 0.90); /// Name of a captured site, and the parchment that greys its glyph. const CAPTURED_INK: Color = Color::srgb(0.52, 0.48, 0.42); const PARCH: Color = Color::srgba(0.86, 0.81, 0.68, 0.6); /// Slowed track, and the repair badge on any damaged track. const SLOW_ORANGE: Color = Color::srgb(1.0, 0.55, 0.10); const CRATER: Color = Color::srgb(0.16, 0.10, 0.06); /// Warm tint of lightly scorched track. const SCORCH: Color = Color::srgb(0.80, 0.42, 0.16); /// Any track below this condition shows its damage, however mild. const DAMAGED_CONDITION: f32 = 0.95; /// Gap cut into blocked track, and the distance between the two rails. const GAP_LEN: f32 = 14.0; const RAIL_HALF: f32 = 2.5; /// Repair badge sits this far off the track's midpoint. const BADGE_OFFSET: f32 = 16.0; const BADGE_R: f32 = 8.0; pub struct MapPlugin; impl Plugin for MapPlugin { fn build(&self, app: &mut App) { app.init_resource::() .init_resource::() .add_systems(Startup, spawn_node_labels) .add_systems( Update, ( fit_camera, camera_controls, picking, draw_map, sync_node_labels, place_node_labels, update_world_text, ) .chain(), ); } } /// Zoom bounds the wheel is clamped to. `fit_camera` widens them when the fitted view /// falls outside the defaults, so the fitted view is always reachable. #[derive(Resource, Clone, Copy)] pub struct ZoomLimits { pub min: f32, pub max: f32, } impl Default for ZoomLimits { fn default() -> Self { Self { min: MIN_SCALE, max: MAX_SCALE, } } } /// Ortho scale and camera offset that fit the map frame into the free area: the full window /// width, and the height between the top bar and the bottom strip. `size` is the window in /// logical px. The camera is `FixedVertical { 720 }`, so `h` logical px show `720 * scale` /// world units, i.e. `world_per_px = 720 * scale / h`. /// /// The bars are UI nodes sized in UI px, which `UiScale` multiplies, so their logical height /// is `TOP_H * ui_scale` and `BOTTOM_H * ui_scale`. fn fit_view(size: Vec2, ui_scale: f32) -> (f32, Vec2) { let top = crate::hud::TOP_H * ui_scale; let bottom = crate::hud::BOTTOM_H * ui_scale; let free_w = (size.x - 2.0 * FIT_MARGIN_X).max(1.0); let free_h = (size.y - top - bottom - 2.0 * FIT_MARGIN_Y).max(1.0); // World units per logical px that make the frame fit both ways. let world_per_px = (MAP_W / free_w).max(MAP_H / free_h); let scale = world_per_px * size.y / MAP_H; // The free area centre is (bottom - top) / 2 px above the window centre (screen y points // down, and the bottom strip is the taller one). The camera centre looks at world y = offset, // so world y = 0 lands `offset` below the window centre: offset = (top - bottom) / 2 px. let offset_y = (top - bottom) * 0.5 * world_per_px; (scale, Vec2::new(0.0, offset_y)) } /// Everything `fit_view` depends on. The camera is refitted whenever any of it changes. #[derive(Clone, Copy, PartialEq)] struct FitKey { /// Window size in logical px. size: Vec2, /// Physical px per logical px. scale_factor: f32, /// UI scale, which sets the bar heights. ui_scale: f32, /// Logical size of the camera viewport, which the projection area is built from. viewport: Option, } /// Refits the camera whenever the window size, scale factor, UI scale or camera viewport /// changes (and once at startup). The zoom and pan are left alone between those changes. fn fit_camera( window: Single<&Window, With>, ui_scale: Res, mut limits: ResMut, mut last: Local>, mut cameras: Query<(&Camera, &mut Transform, &mut Projection), With>, ) { let size = Vec2::new(window.width(), window.height()); if size.min_element() < 1.0 { return; } let Ok((camera, mut transform, mut projection)) = cameras.single_mut() else { return; }; let key = FitKey { size, scale_factor: window.scale_factor(), ui_scale: ui_scale.0, viewport: camera.logical_viewport_size(), }; if *last == Some(key) { return; } *last = Some(key); let (scale, offset) = fit_view(size, ui_scale.0); limits.min = MIN_SCALE.min(scale); limits.max = MAX_SCALE.max(scale); if let Projection::Orthographic(ortho) = projection.as_mut() { ortho.scale = scale; } transform.translation = offset.extend(transform.translation.z); } /// Pointer state recomputed every frame by `picking`. Empty while the cursor is over the UI. #[derive(Resource, Default)] pub struct MapHover { /// Node under the cursor. pub node: Option, /// Cursor position in world units, when it is over the map. pub world: Option, /// Orthographic zoom scale. Hover and pick code outside this file reads it. pub zoom: f32, /// World units covered by one logical pixel, from the projection area and viewport size. pub world_per_px: f32, } /// Text in world space that stays sharp and readable at any zoom or window size. /// /// The font is rasterized at the screen's pixel density and the transform scales it back to /// `size`, so glyphs map one to one onto physical pixels. `update_world_text` keeps this in /// step with the zoom, the window and the text size setting. #[derive(Component, Clone, Copy, Debug)] pub struct WorldText { /// Glyph size in world units at the default text size. pub size: f32, } /// Marker for a node name label. Holds the index of the node it names. #[derive(Component)] struct NodeLabel(usize); /// Sides of a node a name label can sit on, in tie-break order. #[derive(Clone, Copy)] enum LabelSide { Below, Above, Right, Left, } const LABEL_SIDES: [LabelSide; 4] = [ LabelSide::Below, LabelSide::Above, LabelSide::Right, LabelSide::Left, ]; /// Keeps one name label per node. Spawns labels for nodes added at runtime, drops the /// labels of nodes a restart removed, and greys the labels of captured sites. fn sync_node_labels( mut commands: Commands, net: Res, mut labels: Query<(Entity, &NodeLabel, &mut TextColor)>, ) { let mut have = vec![false; net.nodes.len()]; for (entity, label, mut color) in &mut labels { let Some(node) = net.nodes.get(label.0) else { commands.entity(entity).despawn(); continue; }; have[label.0] = true; let want = if node.captured { CAPTURED_INK } else { INK }; if color.0 != want { color.0 = want; } } for (i, node) in net.nodes.iter().enumerate() { if have[i] { continue; } commands.spawn(( NodeLabel(i), Text2d(node.name.clone()), WorldText { size: NODE_LABEL_SIZE, }, TextColor(INK), TextLayout::default(), Anchor::CENTER, Transform::from_xyz(node.pos.x, node.pos.y, 1.0), )); } } fn spawn_node_labels(mut commands: Commands, net: Res) { for (i, node) in net.nodes.iter().enumerate() { commands.spawn(( NodeLabel(i), Text2d(node.name.clone()), WorldText { size: NODE_LABEL_SIZE, }, TextColor(INK), TextLayout::default(), Anchor::CENTER, Transform::from_xyz(node.pos.x, node.pos.y, 1.0), )); } } /// Anchor point (relative to the node), text anchor and justification for a label on `side`. fn label_anchor(side: LabelSide) -> (Vec2, Anchor, Justify) { match side { LabelSide::Below => ( Vec2::new(0.0, -NODE_LABEL_OFFSET), Anchor::CENTER, Justify::Center, ), LabelSide::Above => ( Vec2::new(0.0, LABEL_SIDE_GAP + NODE_LABEL_SIZE * 0.5), Anchor::CENTER, Justify::Center, ), LabelSide::Right => ( Vec2::new(LABEL_SIDE_GAP, 0.0), Anchor::CENTER_LEFT, Justify::Left, ), LabelSide::Left => ( Vec2::new(-LABEL_SIDE_GAP, 0.0), Anchor::CENTER_RIGHT, Justify::Right, ), } } /// Bounding box (relative to the node) of a label of `width` placed on `side`, padded by 1. fn label_rect(side: LabelSide, width: f32) -> (Vec2, Vec2) { let (p, _, _) = label_anchor(side); let h = NODE_LABEL_SIZE * 0.5; let half_w = width * 0.5; let (min, max) = match side { LabelSide::Below | LabelSide::Above => (p - Vec2::new(half_w, h), p + Vec2::new(half_w, h)), LabelSide::Right => (p - Vec2::new(0.0, h), p + Vec2::new(width, h)), LabelSide::Left => (p - Vec2::new(width, h), p + Vec2::new(0.0, h)), }; (min - Vec2::ONE, max + Vec2::ONE) } /// Boxes (relative to the node) that a label must avoid: the stock bars, the producer icon, /// and for a front the supply row and its warning ring. fn node_obstacles(kind: NodeKind) -> Vec<(Vec2, Vec2)> { let mut out = vec![(Vec2::new(-20.0, -31.0), Vec2::new(20.0, -16.0))]; if matches!(kind, NodeKind::Factory | NodeKind::Farm | NodeKind::City) { // Column where evacuation crates stack, north-west of the site. out.push((Vec2::new(-41.0, 9.0), Vec2::new(-31.0, 63.0))); } match kind { // Matches the producer icon offset in signals.rs. NodeKind::Factory | NodeKind::Farm | NodeKind::Capital | NodeKind::City => { out.push((Vec2::new(10.0, 10.0), Vec2::new(24.0, 24.0))); } NodeKind::Front => { // Supply row: three icons of side 14 at x = -20, 0, 20, centred on y = 44. out.push((Vec2::new(-27.0, 37.0), Vec2::new(27.0, 51.0))); out.push((Vec2::splat(-29.0), Vec2::splat(29.0))); } NodeKind::Depot => {} } out } fn rects_overlap(a_min: Vec2, a_max: Vec2, b_min: Vec2, b_max: Vec2) -> bool { a_min.x < b_max.x && b_min.x < a_max.x && a_min.y < b_max.y && b_min.y < a_max.y } /// Liang-Barsky test: does segment `a`-`b` pass through the box `min`-`max`? fn segment_hits_rect(a: Vec2, b: Vec2, min: Vec2, max: Vec2) -> bool { let d = b - a; let (mut t0, mut t1) = (0.0f32, 1.0f32); let edges = [ (-d.x, a.x - min.x), (d.x, max.x - a.x), (-d.y, a.y - min.y), (d.y, max.y - a.y), ]; for (p, q) in edges { if p == 0.0 { if q < 0.0 { return false; } } else { let r = q / p; if p < 0.0 { if r > t1 { return false; } t0 = t0.max(r); } else { if r < t0 { return false; } t1 = t1.min(r); } } } t0 <= t1 } /// Puts each name label on the side with the fewest collisions. A side costs 10 per track /// segment crossing its box and 10 per stock bar, icon or front ring it overlaps. Ties go to /// the earlier entry in `LABEL_SIDES`. Runs only when the set of tracks changes. fn place_node_labels( net: Res, mut placed: Local>>, fresh: Query<(), Added>, mut labels: Query<(&NodeLabel, &mut Transform, &mut Anchor, &mut TextLayout)>, ) { let unchanged = matches!(placed.as_ref(), Some(p) if p.len() == net.tracks.len() && p.iter().zip(&net.tracks).all(|(p, t)| *p == (t.a.0, t.b.0))); if unchanged && fresh.is_empty() { return; } *placed = Some(net.tracks.iter().map(|t| (t.a.0, t.b.0)).collect()); for (label, mut transform, mut anchor, mut layout) in &mut labels { let node = &net.nodes[label.0]; let width = node.name.chars().count() as f32 * LABEL_CHAR_EM * NODE_LABEL_SIZE; let obstacles = node_obstacles(node.kind); let mut best = (usize::MAX, LabelSide::Below); for side in LABEL_SIDES { let (min, max) = label_rect(side, width); let overlaps = obstacles .iter() .filter(|(o_min, o_max)| rects_overlap(min, max, *o_min, *o_max)) .count(); let hits = net .tracks .iter() .filter(|t| { let a = net.nodes[t.a.0].pos - node.pos; let b = net.nodes[t.b.0].pos - node.pos; segment_hits_rect(a, b, min, max) }) .count(); let score = 10 * (overlaps + hits); if score < best.0 { best = (score, side); } } let (offset, text_anchor, justify) = label_anchor(best.1); transform.translation = (node.pos + offset).extend(transform.translation.z); *anchor = text_anchor; *layout = TextLayout::justify(justify); } } /// World units covered by one logical pixel of the view. /// /// Read from the projection's area, which is updated after the frame's systems run, so it /// lags a zoom change by one frame. Returns 0 before the first projection update. fn world_per_pixel(camera: &Camera, ortho: &OrthographicProjection) -> f32 { match camera.logical_viewport_size() { Some(viewport) if viewport.y > 0.0 => ortho.area.height() / viewport.y, _ => 0.0, } } /// Keeps every `WorldText` at the right font size and transform for the current view. /// /// The font is set to `size` times the physical pixels per world unit, and the transform /// scales it back down, so the glyphs land on physical pixels with no resampling blur. fn update_world_text( settings: Res, camera: Single<(&Camera, &Projection), With>, mut texts: Query<(&WorldText, &mut TextFont, &mut Transform)>, ) { let (camera, projection) = *camera; let Projection::Orthographic(ortho) = projection else { return; }; let Some(physical) = camera.physical_viewport_size() else { return; }; let area_height = ortho.area.height(); if area_height <= 0.0 || physical.y == 0 { return; } let density = physical.y as f32 / area_height; let text_size = settings.display.text_size; for (text, mut font, mut transform) in &mut texts { let font_size = FontSize::Px(text.size * text_size * density); if font.font_size != font_size { font.font_size = font_size; } let scale = Vec3::splat(1.0 / density); if transform.scale != scale { transform.scale = scale; } } } /// Right-drag and arrow-key panning, mouse-wheel zoom. fn camera_controls( time: Res