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