src/selection.rs 29.4 K · 877 lines · raw · history

1 use bevy::{prelude::*, transform::TransformSystems, window::PrimaryWindow};
2
3 use crate::{
4 actions::Action,
5 animals::{Animal, Tame},
6 building::{Blueprints, BuildMode, BuildTool},
7 camera::CameraController,
8 climate::{Warmth, day_of_season, outdoor_temperature, season},
9 colonist::{Colonist, Path},
10 designations::DesignateTool,
11 economy::{ColonyGoals, Stock, in_colony},
12 family::{Child, Partner},
13 food::Hunger,
14 items::{Carrying, Item, stock},
15 jobs::{BUTCHER_WORK, CurrentJob, EXPAND_WORK, Job, Order, Recipe, Task, Tool, WorkKind},
16 light::daylight,
17 mood::{Age, Mood, Sick},
18 needs::Rest,
19 population::ColonyLog,
20 sim::{SimSpeed, SimTick, TICKS_PER_HOUR, format_clock, hour_of_day},
21 structures::{Fuel, Structure, StructureKind},
22 ui::{HideableUi, PointerOverUi},
23 world::{TILE_SIZE, TilePos, WorldMap},
24 worldgen::{WorldGenerated, WorldSeed},
25 zones::{ZoneKind, ZoneTool, Zones},
26 };
27
28 pub struct SelectionPlugin;
29
30 impl Plugin for SelectionPlugin {
31 fn build(&self, app: &mut App) {
32 app.init_resource::<Cursor>()
33 .init_resource::<Selection>()
34 .add_systems(Startup, spawn_tile_info)
35 .add_systems(Update, clear_selection.run_if(on_message::<WorldGenerated>))
36 .add_systems(
37 PostUpdate,
38 (
39 update_cursor,
40 update_selection.run_if(
41 |tool: Res<ZoneTool>, build: Res<BuildTool>, mark: Res<DesignateTool>| {
42 !tool.active() && !build.active() && !mark.active
43 },
44 ),
45 issue_move_orders,
46 draw_highlights,
47 update_tile_info,
48 )
49 .chain()
50 .after(TransformSystems::Propagate),
51 );
52 }
53 }
54
55 #[derive(Resource, Default, Debug, PartialEq)]
56 pub struct Cursor {
57 pub screen: Option<Vec2>,
58 pub world: Option<Vec2>,
59 pub tile: Option<UVec2>,
60 }
61
62 #[derive(Resource, Default, Debug, PartialEq, Clone, Copy)]
63 pub enum Selection {
64 #[default]
65 None,
66 Tile(UVec2),
67 Colonist(Entity),
68 }
69
70 #[derive(Component)]
71 struct TileInfoText;
72
73 const HOVER_COLOR: Color = Color::srgba(1.0, 1.0, 1.0, 0.6);
74 const SELECT_COLOR: Color = Color::srgb(1.0, 0.85, 0.2);
75 const PROGRESS_COLOR: Color = Color::srgb(0.4, 0.9, 0.4);
76 const PROGRESS_BACK_COLOR: Color = Color::srgba(0.0, 0.0, 0.0, 0.6);
77 const PATH_COLOR: Color = Color::srgba(1.0, 0.85, 0.2, 0.7);
78 const PICK_RADIUS: f32 = TILE_SIZE * 0.6;
79 const CLICK_SLOP_PX: f32 = 4.0;
80
81 pub fn update_cursor(
82 map: Res<WorldMap>,
83 window: Single<&Window, With<PrimaryWindow>>,
84 camera: Single<(&Camera, &GlobalTransform), With<CameraController>>,
85 over_ui: Res<PointerOverUi>,
86 mut cursor: ResMut<Cursor>,
87 ) {
88 let (camera, global) = *camera;
89 let screen = window.cursor_position();
90 let world = screen
91 .filter(|_| !over_ui.0)
92 .and_then(|s| camera.viewport_to_world_2d(global, s).ok());
93 let tile = world.and_then(|w| map.tile_at(w));
94 cursor.set_if_neq(Cursor {
95 screen,
96 world,
97 tile,
98 });
99 }
100
101 fn clear_selection(mut selection: ResMut<Selection>) {
102 *selection = Selection::None;
103 }
104
105 fn update_selection(
106 mut actions: MessageReader<Action>,
107 buttons: Res<ButtonInput<MouseButton>>,
108 over_ui: Res<PointerOverUi>,
109 cursor: Res<Cursor>,
110 colonists: Query<(Entity, &Transform), With<Colonist>>,
111 mut selection: ResMut<Selection>,
112 ) {
113 if actions.read().any(|a| *a == Action::Cancel) {
114 selection.set_if_neq(Selection::None);
115 } else if buttons.just_pressed(MouseButton::Left) && !over_ui.0 {
116 let picked = cursor.world.and_then(|world| {
117 pick_nearest(
118 world,
119 colonists.iter().map(|(e, t)| (e, t.translation.truncate())),
120 )
121 });
122 let new = match (picked, cursor.tile) {
123 (Some(entity), _) => Selection::Colonist(entity),
124 (None, Some(tile)) => Selection::Tile(tile),
125 (None, None) => Selection::None,
126 };
127 selection.set_if_neq(new);
128 }
129 }
130
131 pub fn pick_nearest(
132 point: Vec2,
133 candidates: impl Iterator<Item = (Entity, Vec2)>,
134 ) -> Option<Entity> {
135 candidates
136 .map(|(e, pos)| (e, pos.distance(point)))
137 .filter(|&(_, d)| d <= PICK_RADIUS)
138 .min_by(|a, b| a.1.total_cmp(&b.1))
139 .map(|(e, _)| e)
140 }
141
142 fn issue_move_orders(
143 buttons: Res<ButtonInput<MouseButton>>,
144 cursor: Res<Cursor>,
145 selection: Res<Selection>,
146 over_ui: Res<PointerOverUi>,
147 mut orders: MessageWriter<Order>,
148 mut pressed_at: Local<Option<Vec2>>,
149 ) {
150 if buttons.just_pressed(MouseButton::Right) {
151 *pressed_at = cursor.screen.filter(|_| !over_ui.0);
152 }
153 if !buttons.just_released(MouseButton::Right) {
154 return;
155 }
156 let (Some(press), Some(release)) = (pressed_at.take(), cursor.screen) else {
157 return;
158 };
159 if let (true, Selection::Colonist(colonist), Some(tile)) =
160 (is_click(press, release), *selection, cursor.tile)
161 {
162 orders.write(Order { colonist, tile });
163 }
164 }
165
166 pub fn is_click(press: Vec2, release: Vec2) -> bool {
167 press.distance(release) <= CLICK_SLOP_PX
168 }
169
170 fn draw_highlights(
171 mut gizmos: Gizmos,
172 cursor: Res<Cursor>,
173 selection: Res<Selection>,
174 colonists: Query<(Entity, &Transform, &Path, &CurrentJob), With<Colonist>>,
175 ) {
176 for (_, transform, _, job) in &colonists {
177 if let Some(fraction) = job.0.and_then(|j| progress_fraction(j.task))
178 && fraction > 0.0
179 {
180 let left =
181 transform.translation.truncate() + Vec2::new(-TILE_SIZE * 0.4, TILE_SIZE * 0.6);
182 let full = TILE_SIZE * 0.8;
183 let done = full * fraction;
184 gizmos.line_2d(left, left + Vec2::X * full, PROGRESS_BACK_COLOR);
185 gizmos.line_2d(left, left + Vec2::X * done, PROGRESS_COLOR);
186 }
187 }
188 if let Some(tile) = cursor.tile {
189 gizmos.rect_2d(
190 WorldMap::tile_center(tile),
191 Vec2::splat(TILE_SIZE),
192 HOVER_COLOR,
193 );
194 }
195 match *selection {
196 Selection::None => {}
197 Selection::Tile(tile) => {
198 gizmos.rect_2d(
199 WorldMap::tile_center(tile),
200 Vec2::splat(TILE_SIZE),
201 SELECT_COLOR,
202 );
203 }
204 Selection::Colonist(entity) => {
205 let Ok((_, transform, path, job)) = colonists.get(entity) else {
206 return;
207 };
208 if let Some(Job {
209 task:
210 Task::Work { site, .. }
211 | Task::ExpandStockpile { site, .. }
212 | Task::Build { site, .. },
213 ..
214 }) = job.0
215 {
216 gizmos.rect_2d(
217 WorldMap::tile_center(site),
218 Vec2::splat(TILE_SIZE),
219 PATH_COLOR,
220 );
221 }
222 let pos = transform.translation.truncate();
223 gizmos.circle_2d(pos, TILE_SIZE * 0.5, SELECT_COLOR);
224 let points = path.0.iter().map(|&t| WorldMap::tile_center(t));
225 gizmos.linestrip_2d(std::iter::once(pos).chain(points), PATH_COLOR);
226 }
227 }
228 }
229
230 fn spawn_tile_info(mut commands: Commands) {
231 commands.spawn((
232 TileInfoText,
233 HideableUi,
234 Text::default(),
235 TextFont::from_font_size(14.0),
236 Node {
237 position_type: PositionType::Absolute,
238 top: px(8),
239 left: px(8),
240 max_width: Val::Percent(70.0),
241 padding: UiRect::all(px(6)),
242 ..default()
243 },
244 BackgroundColor(Color::srgba(0.0, 0.0, 0.0, 0.5)),
245 ));
246 }
247
248 #[allow(clippy::too_many_arguments)]
249 fn update_tile_info(
250 map: Res<WorldMap>,
251 cursor: Res<Cursor>,
252 selection: Res<Selection>,
253 colonists: Query<(
254 &Colonist,
255 &TilePos,
256 &Path,
257 &CurrentJob,
258 &Carrying,
259 &Rest,
260 &Hunger,
261 )>,
262 items: Query<(&Item, &TilePos)>,
263 structures: Query<(&Structure, &TilePos, Option<&Fuel>)>,
264 animals: Query<(&Animal, &TilePos, Has<Tame>)>,
265 blueprints: Res<Blueprints>,
266 goals: Res<ColonyGoals>,
267 log: Res<ColonyLog>,
268 zones: Res<Zones>,
269 tools: (Res<ZoneTool>, Res<BuildTool>, Res<DesignateTool>),
270 clock: (
271 Res<Time<Virtual>>,
272 Res<SimTick>,
273 Res<SimSpeed>,
274 Res<WorldSeed>,
275 ),
276 kin: Query<(
277 Option<&Partner>,
278 Option<&Child>,
279 Option<&Mood>,
280 Option<&Age>,
281 Has<Sick>,
282 Option<&Warmth>,
283 Has<Tool>,
284 )>,
285 mut text: Single<&mut Text, With<TileInfoText>>,
286 ) {
287 let (time, tick, speed, seed) = clock;
288 let selected = match *selection {
289 Selection::None => "-".to_string(),
290 Selection::Tile(tile) => describe_tile(&map, Some(tile)),
291 Selection::Colonist(entity) => colonists
292 .get(entity)
293 .map(|(colonist, tile, path, job, carrying, rest, hunger)| {
294 describe_colonist(&ColonistView {
295 name: &colonist.name,
296 tile: tile.0,
297 job: job.0,
298 steps_left: path.0.len(),
299 carrying: carrying.0,
300 rest: rest.0,
301 fed: hunger.0,
302 }) + &kin
303 .get(entity)
304 .map(|(partner, child, mood, age, sick, warmth, tool)| {
305 let partner = partner
306 .and_then(|p| colonists.get(p.0).ok())
307 .map(|p| format!(", partner {}", p.0.name));
308 let child =
309 child.map(|c| format!(", child (grows up in {}d)", c.days_left(*tick)));
310 let mood = mood
311 .map(|m| format!(", mood {:.0}%", m.0 * 100.0))
312 .unwrap_or_default();
313 let age = age
314 .map(|a| format!(", age {}", a.years(*tick)))
315 .unwrap_or_default();
316 let sick = if sick { ", sick" } else { "" };
317 let tool = if tool { ", has tools" } else { "" };
318 let warmth = warmth
319 .map(|w| {
320 let cold = if w.cold() { " (cold)" } else { "" };
321 format!(", {:.0}C{cold}", w.0)
322 })
323 .unwrap_or_default();
324 partner.unwrap_or_default()
325 + &child.unwrap_or_default()
326 + &mood
327 + &age
328 + sick
329 + tool
330 + &warmth
331 })
332 .unwrap_or_default()
333 })
334 .unwrap_or_else(|_| "-".into()),
335 };
336 let clock = format!(
337 "{} ({}), {} day {}, {:.0}C",
338 format_clock(*tick),
339 time_of_day(hour_of_day(*tick)),
340 season(*tick).name(),
341 day_of_season(*tick),
342 outdoor_temperature(*tick)
343 );
344 let speed = describe_speed(*speed, time.is_paused(), time.relative_speed());
345 let carried: Vec<Item> = colonists.iter().filter_map(|c| c.4.0).collect();
346 let home = zones.home(map.size / 2);
347 let stock_line = |food: bool| {
348 Stock::ALL
349 .iter()
350 .filter(|s| s.is_food() == food)
351 .map(|&s| {
352 let have: u32 = s
353 .members()
354 .map(|kind| {
355 stock(
356 items
357 .iter()
358 .filter(|(_, pos)| in_colony(home, pos.0))
359 .map(|(item, _)| item)
360 .chain(carried.iter()),
361 kind,
362 )
363 })
364 .sum();
365 format!("{} {have}/{}", s.label(), goals.goal(s))
366 })
367 .collect::<Vec<_>>()
368 .join(" ")
369 };
370 let materials = format!("{}\n{}", stock_line(false), stock_line(true));
371 let hovered_zone = match cursor.tile {
372 Some(tile) if zones.is_stockpile(tile) => ", Stockpile",
373 Some(tile) if zones.is_farm(tile) => ", Farm",
374 _ => "",
375 };
376 let hovered_items: String = items
377 .iter()
378 .filter(|(_, pos)| Some(pos.0) == cursor.tile)
379 .map(|(item, _)| describe_item(item))
380 .collect();
381 let hovered_structure: String = structures
382 .iter()
383 .filter(|(_, pos, _)| Some(pos.0) == cursor.tile)
384 .map(|(structure, _, fuel)| describe_structure(structure.kind, fuel.map(|f| f.0)))
385 .chain(
386 cursor
387 .tile
388 .and_then(|t| blueprints.get(t))
389 .map(|kind| format!(", planned {}", kind.name())),
390 )
391 .chain(
392 animals
393 .iter()
394 .filter(|(_, pos, _)| Some(pos.0) == cursor.tile)
395 .map(|(animal, _, tame)| {
396 format!(
397 ", {}{}",
398 if tame { "tame " } else { "" },
399 animal.kind.name()
400 )
401 }),
402 )
403 .collect();
404 let events: String = log.0.iter().map(|line| format!("\n{line}")).collect();
405 let (tool, build_tool, designate_tool) = tools;
406 let tool_hint = match (tool.mode, build_tool.mode) {
407 _ if designate_tool.active => {
408 "\nCHOP/MINE: drag over trees and rock, shift-drag to clear".to_string()
409 }
410 (Some(ZoneKind::Stockpile), _) => {
411 "\nSTOCKPILE TOOL: drag to add, shift-drag to remove".to_string()
412 }
413 (Some(ZoneKind::Farm), _) => "\nFARM TOOL: drag to add, shift-drag to remove".to_string(),
414 (None, Some(BuildMode::Deconstruct)) => {
415 "\nDECONSTRUCT: drag over structures, shift-drag to remove plans, B for next"
416 .to_string()
417 }
418 (None, Some(BuildMode::Place(kind))) => format!(
419 "\nBUILD {}: {}, shift-drag to remove plans, B for next",
420 kind.name().to_uppercase(),
421 if kind == StructureKind::Wall {
422 "drag a room outline"
423 } else {
424 "click to place"
425 }
426 ),
427 (None, None) => String::new(),
428 };
429 let info = format!(
430 "{clock} {speed}\nSeed: {} Colonists: {}\n{materials}{tool_hint}\nHover: {}{hovered_zone}{hovered_items}{hovered_structure}\nSelected: {selected}{events}",
431 seed.0,
432 colonists.iter().count(),
433 describe_tile(&map, cursor.tile)
434 );
435 if text.0 != info {
436 text.0 = info;
437 }
438 }
439
440 pub fn describe_tile(map: &WorldMap, tile: Option<UVec2>) -> String {
441 let Some((t, terrain)) = tile.and_then(|t| map.get(t.as_ivec2()).map(|terrain| (t, terrain)))
442 else {
443 return "-".into();
444 };
445 let p = t.as_ivec2();
446 let roof = if map.is_roofed(p) { ", Roofed" } else { "" };
447 let plant = map
448 .plant(p)
449 .map(|plant| match plant.ripening_ticks() {
450 None => format!(", {plant:?}"),
451 Some(_) if plant.is_ripe(map.growth(p)) => format!(", {plant:?} (ripe)"),
452 Some(_) => format!(", {plant:?} ({:.0}% grown)", map.growth(p) * 100.0),
453 })
454 .unwrap_or_default();
455 let height = map.height(p).unwrap_or(0.0);
456 let wear = match map.wear(p) {
457 w if w >= 1.0 => format!(", worn {w:.0}"),
458 _ => String::new(),
459 };
460 format!(
461 "({}, {}) {terrain:?}{plant}{roof}, {height:.0} m{wear}",
462 t.x, t.y
463 )
464 }
465
466 pub fn describe_item(item: &Item) -> String {
467 let spoil = if item.kind.is_food() && item.spoil >= 0.01 {
468 format!(" ({:.0}% spoiled)", item.spoil * 100.0)
469 } else {
470 String::new()
471 };
472 format!(", {:?} x{}{spoil}", item.kind, item.count)
473 }
474
475 pub fn describe_speed(speed: SimSpeed, paused: bool, relative: f32) -> String {
476 match (paused, speed) {
477 (true, _) => "PAUSED".into(),
478 (false, SimSpeed::Max) => format!("Max ({relative:.0}x)"),
479 (false, _) => format!("{}x", speed.multiplier()),
480 }
481 }
482
483 pub fn time_of_day(hour: f32) -> &'static str {
484 match daylight(hour) {
485 1.0 => "day",
486 0.0 => "night",
487 _ if hour < 12.0 => "dawn",
488 _ => "dusk",
489 }
490 }
491
492 pub fn describe_structure(kind: StructureKind, fuel: Option<u32>) -> String {
493 match fuel {
494 Some(fuel) => {
495 let hours = fuel as f32 / TICKS_PER_HOUR as f32;
496 format!(", {:?} ({hours:.1}h of fuel)", kind)
497 }
498 None => format!(", {kind:?}"),
499 }
500 }
501
502 pub fn progress_fraction(task: Task) -> Option<f32> {
503 match task {
504 Task::Work { kind, progress, .. } => Some(progress as f32 / kind.work() as f32),
505 Task::ExpandStockpile { progress, .. } => Some(progress as f32 / EXPAND_WORK as f32),
506 Task::Build { kind, progress, .. } => Some(progress as f32 / kind.work() as f32),
507 Task::Hunt { kind, progress, .. } => Some(progress as f32 / kind.hunt_work() as f32),
508 Task::Craft {
509 progress, recipe, ..
510 } => Some(progress as f32 / recipe.work() as f32),
511 Task::Butcher { progress, .. } => Some(progress as f32 / BUTCHER_WORK as f32),
512 Task::Tame { kind, progress, .. } => Some(progress as f32 / kind.tame_work() as f32),
513 _ => None,
514 }
515 }
516
517 fn percent(task: Task) -> u32 {
518 (progress_fraction(task).unwrap_or(0.0) * 100.0).round() as u32
519 }
520
521 pub struct ColonistView<'a> {
522 pub name: &'a str,
523 pub tile: UVec2,
524 pub job: Option<Job>,
525 pub steps_left: usize,
526 pub carrying: Option<Item>,
527 pub rest: f32,
528 pub fed: f32,
529 }
530
531 pub fn describe_colonist(view: &ColonistView) -> String {
532 let (tile, job, carrying) = (view.tile, view.job, view.carrying);
533 let activity = match (job.map(|j| j.task), view.steps_left) {
534 (None, 0) => "idle".to_string(),
535 (None, _) => "wandering".to_string(),
536 (Some(Task::MoveTo(_)), n) => format!("moving, {n} steps left"),
537 (
538 Some(Task::Work {
539 kind: WorkKind::Chop,
540 ..
541 }),
542 n,
543 ) if n > 0 => "walking to a tree".to_string(),
544 (
545 Some(Task::Work {
546 kind: WorkKind::Mine,
547 ..
548 }),
549 n,
550 ) if n > 0 => "walking to rock".to_string(),
551 (
552 Some(Task::Work {
553 kind: WorkKind::Harvest | WorkKind::Sow,
554 ..
555 }),
556 n,
557 ) if n > 0 => "walking to a plant".to_string(),
558 (Some(task @ Task::Work { kind, .. }), _) => {
559 let verb = match kind {
560 WorkKind::Chop => "chopping a tree",
561 WorkKind::Mine => "mining",
562 WorkKind::Harvest => "harvesting",
563 WorkKind::Sow => "sowing",
564 };
565 format!("{verb}, {}%", percent(task))
566 }
567 (Some(Task::ExpandStockpile { .. }), n) if n > 0 => {
568 "going to expand the stockpile".to_string()
569 }
570 (Some(task @ Task::ExpandStockpile { .. }), _) => {
571 format!("expanding the stockpile, {}%", percent(task))
572 }
573 (
574 Some(Task::Haul {
575 pickup: Some(_), ..
576 }),
577 _,
578 ) => "fetching items to haul".to_string(),
579 (Some(Task::Haul { pickup: None, .. }), _) => "hauling to the stockpile".to_string(),
580 (
581 Some(Task::Build {
582 kind,
583 pickup: Some(_),
584 ..
585 }),
586 _,
587 ) => format!("fetching {:?} for a {}", kind.cost().0, kind.name()).to_lowercase(),
588 (Some(Task::Build { kind, .. }), n) if n > 0 => {
589 format!("carrying {:?} to build a {}", kind.cost().0, kind.name()).to_lowercase()
590 }
591 (Some(Task::Sleep { .. }), n) if n > 0 => "going to sleep".to_string(),
592 (Some(Task::Sleep { .. }), _) => "sleeping".to_string(),
593 (
594 Some(Task::Eat {
595 pickup: Some(_), ..
596 }),
597 _,
598 ) => "fetching food".to_string(),
599 (Some(Task::Eat { .. }), _) => "eating".to_string(),
600 (Some(task @ Task::Hunt { kind, progress, .. }), _) if progress > 0 => {
601 format!("hunting a {}, {}%", kind.name(), percent(task))
602 }
603 (Some(Task::Hunt { kind, .. }), _) => format!("stalking a {}", kind.name()),
604 (
605 Some(Task::Craft {
606 pickup: Some(_), ..
607 }),
608 _,
609 ) => "fetching ingredients".to_string(),
610 (Some(Task::Craft { recipe, .. }), n) if n > 0 => {
611 format!("carrying ingredients to the {}", recipe.station().name())
612 }
613 (
614 Some(
615 task @ Task::Craft {
616 recipe: Recipe::Meal,
617 ..
618 },
619 ),
620 _,
621 ) => format!("cooking a meal, {}%", percent(task)),
622 (Some(task @ Task::Craft { .. }), _) => format!("making tools, {}%", percent(task)),
623 (Some(Task::Equip { .. }), _) => "fetching tools".to_string(),
624 (Some(Task::Butcher { .. }), n) if n > 0 => "walking to a carcass".to_string(),
625 (Some(Task::Tame { kind, .. }), n) if n > 0 => format!("approaching a {}", kind.name()),
626 (Some(task @ Task::Tame { kind, .. }), _) => {
627 format!("taming a {}, {}%", kind.name(), percent(task))
628 }
629 (Some(task @ Task::Butcher { .. }), _) => format!("butchering, {}%", percent(task)),
630 (Some(task @ Task::Build { kind, .. }), _) => {
631 format!("building a {}, {}%", kind.name(), percent(task))
632 }
633 };
634 let load = carrying
635 .map(|item| format!(", carrying {} {:?}", item.count, item.kind))
636 .unwrap_or_default();
637 let ordered = if job.is_some_and(|j| j.ordered) {
638 " (ordered)"
639 } else {
640 ""
641 };
642 format!(
643 "{} at ({}, {}), {activity}{ordered}{load}, rest {:.0}%, food {:.0}%",
644 view.name,
645 tile.x,
646 tile.y,
647 view.rest * 100.0,
648 view.fed * 100.0
649 )
650 }
651
652 #[cfg(test)]
653 mod tests {
654 use super::*;
655 use crate::world::Terrain;
656
657 fn selection_app(cursor: Cursor, selection: Selection) -> App {
658 let mut app = App::new();
659 app.init_resource::<ButtonInput<MouseButton>>()
660 .init_resource::<PointerOverUi>()
661 .insert_resource(cursor)
662 .insert_resource(selection)
663 .add_message::<Order>()
664 .add_message::<Action>()
665 .add_systems(Update, (update_selection, issue_move_orders));
666 app
667 }
668
669 fn cursor_on_tile(tile: UVec2) -> Cursor {
670 Cursor {
671 screen: Some(Vec2::new(50.0, 50.0)),
672 world: Some(WorldMap::tile_center(tile)),
673 tile: Some(tile),
674 }
675 }
676
677 fn press(app: &mut App, button: MouseButton) {
678 app.world_mut()
679 .resource_mut::<ButtonInput<MouseButton>>()
680 .press(button);
681 app.update();
682 }
683
684 fn release(app: &mut App, button: MouseButton) {
685 let mut input = app.world_mut().resource_mut::<ButtonInput<MouseButton>>();
686 input.clear();
687 input.release(button);
688 app.update();
689 }
690
691 fn selection(app: &App) -> Selection {
692 *app.world().resource::<Selection>()
693 }
694
695 fn sent_orders(app: &mut App) -> Vec<(Entity, UVec2)> {
696 app.world_mut()
697 .resource_mut::<Messages<Order>>()
698 .drain()
699 .map(|o| (o.colonist, o.tile))
700 .collect()
701 }
702
703 #[test]
704 fn clicking_selects_the_hovered_tile() {
705 let mut app = selection_app(cursor_on_tile(UVec2::new(3, 4)), Selection::None);
706 press(&mut app, MouseButton::Left);
707 assert_eq!(selection(&app), Selection::Tile(UVec2::new(3, 4)));
708 }
709
710 #[test]
711 fn clicking_a_colonist_selects_it_instead_of_its_tile() {
712 let tile = UVec2::new(3, 4);
713 let mut app = selection_app(cursor_on_tile(tile), Selection::None);
714 let colonist = app
715 .world_mut()
716 .spawn((
717 Colonist { name: "Ada".into() },
718 Transform::from_translation(WorldMap::tile_center(tile).extend(1.0)),
719 ))
720 .id();
721 press(&mut app, MouseButton::Left);
722 assert_eq!(selection(&app), Selection::Colonist(colonist));
723 }
724
725 #[test]
726 fn clicking_outside_the_world_clears_the_selection() {
727 let mut app = selection_app(Cursor::default(), Selection::Tile(UVec2::new(3, 4)));
728 press(&mut app, MouseButton::Left);
729 assert_eq!(selection(&app), Selection::None);
730 }
731
732 #[test]
733 fn cancel_clears_the_selection() {
734 let mut app = selection_app(
735 cursor_on_tile(UVec2::ONE),
736 Selection::Tile(UVec2::new(3, 4)),
737 );
738 app.world_mut().write_message(Action::Cancel);
739 app.update();
740 assert_eq!(selection(&app), Selection::None);
741 }
742
743 #[test]
744 fn clicks_on_the_ui_do_not_reach_the_map() {
745 let colonist = Entity::from_raw_u32(7).unwrap();
746 let mut app = selection_app(
747 cursor_on_tile(UVec2::new(5, 6)),
748 Selection::Colonist(colonist),
749 );
750 app.insert_resource(PointerOverUi(true));
751 press(&mut app, MouseButton::Left);
752 assert_eq!(selection(&app), Selection::Colonist(colonist));
753 press(&mut app, MouseButton::Right);
754 release(&mut app, MouseButton::Right);
755 assert!(sent_orders(&mut app).is_empty());
756 }
757
758 #[test]
759 fn right_click_orders_selected_colonist_to_hovered_tile() {
760 let colonist = Entity::from_raw_u32(7).unwrap();
761 let mut app = selection_app(
762 cursor_on_tile(UVec2::new(5, 6)),
763 Selection::Colonist(colonist),
764 );
765 press(&mut app, MouseButton::Right);
766 release(&mut app, MouseButton::Right);
767 assert_eq!(sent_orders(&mut app), vec![(colonist, UVec2::new(5, 6))]);
768 }
769
770 #[test]
771 fn right_drag_does_not_order_because_it_pans_the_camera() {
772 let colonist = Entity::from_raw_u32(7).unwrap();
773 let mut app = selection_app(
774 cursor_on_tile(UVec2::new(5, 6)),
775 Selection::Colonist(colonist),
776 );
777 press(&mut app, MouseButton::Right);
778 app.world_mut().resource_mut::<Cursor>().screen = Some(Vec2::new(200.0, 50.0));
779 release(&mut app, MouseButton::Right);
780 assert!(sent_orders(&mut app).is_empty());
781 }
782
783 #[test]
784 fn pick_nearest_ignores_far_candidates() {
785 let a = Entity::from_raw_u32(1).unwrap();
786 let b = Entity::from_raw_u32(2).unwrap();
787 let candidates = [(a, Vec2::new(5.0, 0.0)), (b, Vec2::new(2.0, 0.0))];
788 assert_eq!(pick_nearest(Vec2::ZERO, candidates.into_iter()), Some(b));
789 assert_eq!(
790 pick_nearest(Vec2::new(100.0, 0.0), candidates.into_iter()),
791 None
792 );
793 }
794
795 #[test]
796 fn describe_tile_shows_coordinates_terrain_plant_and_height() {
797 let mut map = WorldMap::filled(UVec2::new(4, 4), Terrain::Sand);
798 map.set_height(UVec2::new(1, 2), 12.4);
799 assert_eq!(
800 describe_tile(&map, Some(UVec2::new(1, 2))),
801 "(1, 2) Sand, 12 m"
802 );
803 map.set_plant(UVec2::new(1, 2), Some(crate::world::Plant::Tree));
804 assert_eq!(
805 describe_tile(&map, Some(UVec2::new(1, 2))),
806 "(1, 2) Sand, Tree, 12 m"
807 );
808 assert_eq!(describe_tile(&map, None), "-");
809 }
810
811 #[test]
812 fn time_of_day_labels() {
813 assert_eq!(time_of_day(12.0), "day");
814 assert_eq!(time_of_day(6.0), "dawn");
815 assert_eq!(time_of_day(19.0), "dusk");
816 assert_eq!(time_of_day(1.0), "night");
817 }
818
819 #[test]
820 fn describe_speed_shows_multiplier_or_paused() {
821 assert_eq!(describe_speed(SimSpeed::Fastest, false, 6.0), "6x");
822 assert_eq!(describe_speed(SimSpeed::Fast, true, 3.0), "PAUSED");
823 assert_eq!(describe_speed(SimSpeed::Max, false, 123.4), "Max (123x)");
824 }
825
826 fn view(job: Option<Job>, steps_left: usize, carrying: Option<Item>) -> ColonistView<'static> {
827 ColonistView {
828 name: "Ada",
829 tile: UVec2::new(1, 2),
830 job,
831 steps_left,
832 carrying,
833 rest: 1.0,
834 fed: 0.5,
835 }
836 }
837
838 #[test]
839 fn describe_colonist_shows_activity_and_needs() {
840 assert_eq!(
841 describe_colonist(&view(None, 0, None)),
842 "Ada at (1, 2), idle, rest 100%, food 50%"
843 );
844 let ordered_move = Job {
845 task: Task::MoveTo(UVec2::ZERO),
846 ordered: true,
847 };
848 assert_eq!(
849 describe_colonist(&view(Some(ordered_move), 3, None)),
850 "Ada at (1, 2), moving, 3 steps left (ordered), rest 100%, food 50%"
851 );
852 let chop = Job {
853 task: Task::Work {
854 site: UVec2::ZERO,
855 kind: WorkKind::Chop,
856 progress: WorkKind::Chop.work() / 2,
857 },
858 ordered: false,
859 };
860 assert_eq!(
861 describe_colonist(&view(Some(chop), 0, None)),
862 "Ada at (1, 2), chopping a tree, 50%, rest 100%, food 50%"
863 );
864 let eat = Job {
865 task: Task::Eat {
866 pickup: None,
867 progress: 0,
868 },
869 ordered: false,
870 };
871 let meal = Item::new(crate::items::ItemKind::Meal, 1);
872 assert_eq!(
873 describe_colonist(&view(Some(eat), 0, Some(meal))),
874 "Ada at (1, 2), eating, carrying 1 Meal, rest 100%, food 50%"
875 );
876 }
877 }