src/selection.rs 26.9 K · 815 lines · raw · history

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