src/selection.rs 26.7 K · 811 lines · raw · history

1 use bevy::{prelude::*, transform::TransformSystems, window::PrimaryWindow};
2
3 use crate::{
4 actions::Action,
5 animals::Animal,
6 building::{Blueprints, 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.kind) {
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(kind)) => format!(
375 "\nBUILD {}: {}, shift-drag to remove plans, B for next",
376 kind.name().to_uppercase(),
377 if kind == StructureKind::Wall {
378 "drag a room outline"
379 } else {
380 "click to place"
381 }
382 ),
383 (None, None) => String::new(),
384 };
385 let info = format!(
386 "{clock} {speed}\nSeed: {} Colonists: {}\n{materials}{tool_hint}\nHover: {}{hovered_zone}{hovered_items}{hovered_structure}\nSelected: {selected}{events}",
387 seed.0,
388 colonists.iter().count(),
389 describe_tile(&map, cursor.tile)
390 );
391 if text.0 != info {
392 text.0 = info;
393 }
394 }
395
396 pub fn describe_tile(map: &WorldMap, tile: Option<UVec2>) -> String {
397 let Some((t, terrain)) = tile.and_then(|t| map.get(t.as_ivec2()).map(|terrain| (t, terrain)))
398 else {
399 return "-".into();
400 };
401 let p = t.as_ivec2();
402 let roof = if map.is_roofed(p) { ", Roofed" } else { "" };
403 let plant = map
404 .plant(p)
405 .map(|plant| match plant.ripening_ticks() {
406 None => format!(", {plant:?}"),
407 Some(_) if plant.is_ripe(map.growth(p)) => format!(", {plant:?} (ripe)"),
408 Some(_) => format!(", {plant:?} ({:.0}% grown)", map.growth(p) * 100.0),
409 })
410 .unwrap_or_default();
411 let height = map.height(p).unwrap_or(0.0);
412 let wear = match map.wear(p) {
413 w if w >= 1.0 => format!(", worn {w:.0}"),
414 _ => String::new(),
415 };
416 format!(
417 "({}, {}) {terrain:?}{plant}{roof}, {height:.0} m{wear}",
418 t.x, t.y
419 )
420 }
421
422 pub fn describe_item(item: &Item) -> String {
423 let spoil = if item.kind.is_food() && item.spoil >= 0.01 {
424 format!(" ({:.0}% spoiled)", item.spoil * 100.0)
425 } else {
426 String::new()
427 };
428 format!(", {:?} x{}{spoil}", item.kind, item.count)
429 }
430
431 pub fn describe_speed(speed: SimSpeed, paused: bool, relative: f32) -> String {
432 match (paused, speed) {
433 (true, _) => "PAUSED".into(),
434 (false, SimSpeed::Max) => format!("Max ({relative:.0}x)"),
435 (false, _) => format!("{}x", speed.multiplier()),
436 }
437 }
438
439 pub fn time_of_day(hour: f32) -> &'static str {
440 match daylight(hour) {
441 1.0 => "day",
442 0.0 => "night",
443 _ if hour < 12.0 => "dawn",
444 _ => "dusk",
445 }
446 }
447
448 pub fn describe_structure(kind: StructureKind, fuel: Option<u32>) -> String {
449 match fuel {
450 Some(fuel) => {
451 let hours = fuel as f32 / TICKS_PER_HOUR as f32;
452 format!(", {:?} ({hours:.1}h of fuel)", kind)
453 }
454 None => format!(", {kind:?}"),
455 }
456 }
457
458 pub fn progress_fraction(task: Task) -> Option<f32> {
459 match task {
460 Task::Work { kind, progress, .. } => Some(progress as f32 / kind.work() as f32),
461 Task::ExpandStockpile { progress, .. } => Some(progress as f32 / EXPAND_WORK as f32),
462 Task::Build { kind, progress, .. } => Some(progress as f32 / kind.work() as f32),
463 Task::Hunt { kind, progress, .. } => Some(progress as f32 / kind.hunt_work() as f32),
464 Task::Cook { progress, .. } => Some(progress as f32 / COOK_WORK as f32),
465 _ => None,
466 }
467 }
468
469 fn percent(task: Task) -> u32 {
470 (progress_fraction(task).unwrap_or(0.0) * 100.0).round() as u32
471 }
472
473 pub struct ColonistView<'a> {
474 pub name: &'a str,
475 pub tile: UVec2,
476 pub job: Option<Job>,
477 pub steps_left: usize,
478 pub carrying: Option<Item>,
479 pub rest: f32,
480 pub fed: f32,
481 }
482
483 pub fn describe_colonist(view: &ColonistView) -> String {
484 let (tile, job, carrying) = (view.tile, view.job, view.carrying);
485 let activity = match (job.map(|j| j.task), view.steps_left) {
486 (None, 0) => "idle".to_string(),
487 (None, _) => "wandering".to_string(),
488 (Some(Task::MoveTo(_)), n) => format!("moving, {n} steps left"),
489 (
490 Some(Task::Work {
491 kind: WorkKind::Chop,
492 ..
493 }),
494 n,
495 ) if n > 0 => "walking to a tree".to_string(),
496 (
497 Some(Task::Work {
498 kind: WorkKind::Mine,
499 ..
500 }),
501 n,
502 ) if n > 0 => "walking to rock".to_string(),
503 (
504 Some(Task::Work {
505 kind: WorkKind::Harvest | WorkKind::Sow,
506 ..
507 }),
508 n,
509 ) if n > 0 => "walking to a plant".to_string(),
510 (Some(task @ Task::Work { kind, .. }), _) => {
511 let verb = match kind {
512 WorkKind::Chop => "chopping a tree",
513 WorkKind::Mine => "mining",
514 WorkKind::Harvest => "harvesting",
515 WorkKind::Sow => "sowing",
516 };
517 format!("{verb}, {}%", percent(task))
518 }
519 (Some(Task::ExpandStockpile { .. }), n) if n > 0 => {
520 "going to expand the stockpile".to_string()
521 }
522 (Some(task @ Task::ExpandStockpile { .. }), _) => {
523 format!("expanding the stockpile, {}%", percent(task))
524 }
525 (
526 Some(Task::Haul {
527 pickup: Some(_), ..
528 }),
529 _,
530 ) => "fetching items to haul".to_string(),
531 (Some(Task::Haul { pickup: None, .. }), _) => "hauling to the stockpile".to_string(),
532 (
533 Some(Task::Build {
534 kind,
535 pickup: Some(_),
536 ..
537 }),
538 _,
539 ) => format!("fetching {:?} for a {}", kind.cost().0, kind.name()).to_lowercase(),
540 (Some(Task::Build { kind, .. }), n) if n > 0 => {
541 format!("carrying {:?} to build a {}", kind.cost().0, kind.name()).to_lowercase()
542 }
543 (Some(Task::Sleep { .. }), n) if n > 0 => "going to sleep".to_string(),
544 (Some(Task::Sleep { .. }), _) => "sleeping".to_string(),
545 (
546 Some(Task::Eat {
547 pickup: Some(_), ..
548 }),
549 _,
550 ) => "fetching food".to_string(),
551 (Some(Task::Eat { .. }), _) => "eating".to_string(),
552 (Some(task @ Task::Hunt { kind, progress, .. }), _) if progress > 0 => {
553 format!("hunting a {}, {}%", kind.name(), percent(task))
554 }
555 (Some(Task::Hunt { kind, .. }), _) => format!("stalking a {}", kind.name()),
556 (
557 Some(Task::Cook {
558 pickup: Some(_), ..
559 }),
560 _,
561 ) => "fetching ingredients".to_string(),
562 (Some(Task::Cook { .. }), n) if n > 0 => "carrying ingredients to the fire".to_string(),
563 (Some(task @ Task::Cook { .. }), _) => format!("cooking a meal, {}%", percent(task)),
564 (Some(task @ Task::Build { kind, .. }), _) => {
565 format!("building a {}, {}%", kind.name(), percent(task))
566 }
567 };
568 let load = carrying
569 .map(|item| format!(", carrying {} {:?}", item.count, item.kind))
570 .unwrap_or_default();
571 let ordered = if job.is_some_and(|j| j.ordered) {
572 " (ordered)"
573 } else {
574 ""
575 };
576 format!(
577 "{} at ({}, {}), {activity}{ordered}{load}, rest {:.0}%, food {:.0}%",
578 view.name,
579 tile.x,
580 tile.y,
581 view.rest * 100.0,
582 view.fed * 100.0
583 )
584 }
585
586 #[cfg(test)]
587 mod tests {
588 use super::*;
589 use crate::world::Terrain;
590
591 fn selection_app(cursor: Cursor, selection: Selection) -> App {
592 let mut app = App::new();
593 app.init_resource::<ButtonInput<MouseButton>>()
594 .init_resource::<PointerOverUi>()
595 .insert_resource(cursor)
596 .insert_resource(selection)
597 .add_message::<Order>()
598 .add_message::<Action>()
599 .add_systems(Update, (update_selection, issue_move_orders));
600 app
601 }
602
603 fn cursor_on_tile(tile: UVec2) -> Cursor {
604 Cursor {
605 screen: Some(Vec2::new(50.0, 50.0)),
606 world: Some(WorldMap::tile_center(tile)),
607 tile: Some(tile),
608 }
609 }
610
611 fn press(app: &mut App, button: MouseButton) {
612 app.world_mut()
613 .resource_mut::<ButtonInput<MouseButton>>()
614 .press(button);
615 app.update();
616 }
617
618 fn release(app: &mut App, button: MouseButton) {
619 let mut input = app.world_mut().resource_mut::<ButtonInput<MouseButton>>();
620 input.clear();
621 input.release(button);
622 app.update();
623 }
624
625 fn selection(app: &App) -> Selection {
626 *app.world().resource::<Selection>()
627 }
628
629 fn sent_orders(app: &mut App) -> Vec<(Entity, UVec2)> {
630 app.world_mut()
631 .resource_mut::<Messages<Order>>()
632 .drain()
633 .map(|o| (o.colonist, o.tile))
634 .collect()
635 }
636
637 #[test]
638 fn clicking_selects_the_hovered_tile() {
639 let mut app = selection_app(cursor_on_tile(UVec2::new(3, 4)), Selection::None);
640 press(&mut app, MouseButton::Left);
641 assert_eq!(selection(&app), Selection::Tile(UVec2::new(3, 4)));
642 }
643
644 #[test]
645 fn clicking_a_colonist_selects_it_instead_of_its_tile() {
646 let tile = UVec2::new(3, 4);
647 let mut app = selection_app(cursor_on_tile(tile), Selection::None);
648 let colonist = app
649 .world_mut()
650 .spawn((
651 Colonist { name: "Ada".into() },
652 Transform::from_translation(WorldMap::tile_center(tile).extend(1.0)),
653 ))
654 .id();
655 press(&mut app, MouseButton::Left);
656 assert_eq!(selection(&app), Selection::Colonist(colonist));
657 }
658
659 #[test]
660 fn clicking_outside_the_world_clears_the_selection() {
661 let mut app = selection_app(Cursor::default(), Selection::Tile(UVec2::new(3, 4)));
662 press(&mut app, MouseButton::Left);
663 assert_eq!(selection(&app), Selection::None);
664 }
665
666 #[test]
667 fn cancel_clears_the_selection() {
668 let mut app = selection_app(
669 cursor_on_tile(UVec2::ONE),
670 Selection::Tile(UVec2::new(3, 4)),
671 );
672 app.world_mut().write_message(Action::Cancel);
673 app.update();
674 assert_eq!(selection(&app), Selection::None);
675 }
676
677 #[test]
678 fn clicks_on_the_ui_do_not_reach_the_map() {
679 let colonist = Entity::from_raw_u32(7).unwrap();
680 let mut app = selection_app(
681 cursor_on_tile(UVec2::new(5, 6)),
682 Selection::Colonist(colonist),
683 );
684 app.insert_resource(PointerOverUi(true));
685 press(&mut app, MouseButton::Left);
686 assert_eq!(selection(&app), Selection::Colonist(colonist));
687 press(&mut app, MouseButton::Right);
688 release(&mut app, MouseButton::Right);
689 assert!(sent_orders(&mut app).is_empty());
690 }
691
692 #[test]
693 fn right_click_orders_selected_colonist_to_hovered_tile() {
694 let colonist = Entity::from_raw_u32(7).unwrap();
695 let mut app = selection_app(
696 cursor_on_tile(UVec2::new(5, 6)),
697 Selection::Colonist(colonist),
698 );
699 press(&mut app, MouseButton::Right);
700 release(&mut app, MouseButton::Right);
701 assert_eq!(sent_orders(&mut app), vec![(colonist, UVec2::new(5, 6))]);
702 }
703
704 #[test]
705 fn right_drag_does_not_order_because_it_pans_the_camera() {
706 let colonist = Entity::from_raw_u32(7).unwrap();
707 let mut app = selection_app(
708 cursor_on_tile(UVec2::new(5, 6)),
709 Selection::Colonist(colonist),
710 );
711 press(&mut app, MouseButton::Right);
712 app.world_mut().resource_mut::<Cursor>().screen = Some(Vec2::new(200.0, 50.0));
713 release(&mut app, MouseButton::Right);
714 assert!(sent_orders(&mut app).is_empty());
715 }
716
717 #[test]
718 fn pick_nearest_ignores_far_candidates() {
719 let a = Entity::from_raw_u32(1).unwrap();
720 let b = Entity::from_raw_u32(2).unwrap();
721 let candidates = [(a, Vec2::new(5.0, 0.0)), (b, Vec2::new(2.0, 0.0))];
722 assert_eq!(pick_nearest(Vec2::ZERO, candidates.into_iter()), Some(b));
723 assert_eq!(
724 pick_nearest(Vec2::new(100.0, 0.0), candidates.into_iter()),
725 None
726 );
727 }
728
729 #[test]
730 fn describe_tile_shows_coordinates_terrain_plant_and_height() {
731 let mut map = WorldMap::filled(UVec2::new(4, 4), Terrain::Sand);
732 map.set_height(UVec2::new(1, 2), 12.4);
733 assert_eq!(
734 describe_tile(&map, Some(UVec2::new(1, 2))),
735 "(1, 2) Sand, 12 m"
736 );
737 map.set_plant(UVec2::new(1, 2), Some(crate::world::Plant::Tree));
738 assert_eq!(
739 describe_tile(&map, Some(UVec2::new(1, 2))),
740 "(1, 2) Sand, Tree, 12 m"
741 );
742 assert_eq!(describe_tile(&map, None), "-");
743 }
744
745 #[test]
746 fn time_of_day_labels() {
747 assert_eq!(time_of_day(12.0), "day");
748 assert_eq!(time_of_day(6.0), "dawn");
749 assert_eq!(time_of_day(19.0), "dusk");
750 assert_eq!(time_of_day(1.0), "night");
751 }
752
753 #[test]
754 fn describe_speed_shows_multiplier_or_paused() {
755 assert_eq!(describe_speed(SimSpeed::Fastest, false, 6.0), "6x");
756 assert_eq!(describe_speed(SimSpeed::Fast, true, 3.0), "PAUSED");
757 assert_eq!(describe_speed(SimSpeed::Max, false, 123.4), "Max (123x)");
758 }
759
760 fn view(job: Option<Job>, steps_left: usize, carrying: Option<Item>) -> ColonistView<'static> {
761 ColonistView {
762 name: "Ada",
763 tile: UVec2::new(1, 2),
764 job,
765 steps_left,
766 carrying,
767 rest: 1.0,
768 fed: 0.5,
769 }
770 }
771
772 #[test]
773 fn describe_colonist_shows_activity_and_needs() {
774 assert_eq!(
775 describe_colonist(&view(None, 0, None)),
776 "Ada at (1, 2), idle, rest 100%, food 50%"
777 );
778 let ordered_move = Job {
779 task: Task::MoveTo(UVec2::ZERO),
780 ordered: true,
781 };
782 assert_eq!(
783 describe_colonist(&view(Some(ordered_move), 3, None)),
784 "Ada at (1, 2), moving, 3 steps left (ordered), rest 100%, food 50%"
785 );
786 let chop = Job {
787 task: Task::Work {
788 site: UVec2::ZERO,
789 kind: WorkKind::Chop,
790 progress: WorkKind::Chop.work() / 2,
791 },
792 ordered: false,
793 };
794 assert_eq!(
795 describe_colonist(&view(Some(chop), 0, None)),
796 "Ada at (1, 2), chopping a tree, 50%, rest 100%, food 50%"
797 );
798 let eat = Job {
799 task: Task::Eat {
800 pickup: None,
801 progress: 0,
802 },
803 ordered: false,
804 };
805 let meal = Item::new(crate::items::ItemKind::Meal, 1);
806 assert_eq!(
807 describe_colonist(&view(Some(eat), 0, Some(meal))),
808 "Ada at (1, 2), eating, carrying 1 Meal, rest 100%, food 50%"
809 );
810 }
811 }