src/colonist.rs 7.9 K · 263 lines · raw · history

1 use std::{collections::VecDeque, time::Duration};
2
3 use bevy::prelude::*;
4
5 use crate::{
6 pathfinding::find_path,
7 rng::SimRng,
8 world::{TILE_SIZE, WorldMap},
9 worldgen::{WorldGenerated, spawn_tiles},
10 };
11
12 pub struct ColonistPlugin;
13
14 impl Plugin for ColonistPlugin {
15 fn build(&self, app: &mut App) {
16 app.insert_resource(SimRng::new(0x5EED))
17 .add_message::<MoveOrder>()
18 .add_systems(Update, spawn_colonists.run_if(on_message::<WorldGenerated>))
19 .add_systems(
20 Update,
21 (
22 toggle_pause,
23 (handle_move_orders, wander, follow_path).chain(),
24 ),
25 );
26 }
27 }
28
29 const TILES_PER_SECOND: f32 = 4.0;
30 const WANDER_RADIUS: i32 = 8;
31 const WANDER_PAUSE_SECS: std::ops::Range<f32> = 1.0..4.0;
32
33 const STARTING_COLONISTS: [(&str, Color); 3] = [
34 ("Ada", Color::srgb(0.9, 0.3, 0.3)),
35 ("Bram", Color::srgb(0.3, 0.5, 0.95)),
36 ("Cleo", Color::srgb(0.95, 0.75, 0.3)),
37 ];
38
39 #[derive(Component, Debug)]
40 #[require(Transform, TilePos, Path, Wander)]
41 pub struct Colonist {
42 pub name: String,
43 }
44
45 #[derive(Component, Default, Debug, Clone, Copy, PartialEq)]
46 pub struct TilePos(pub UVec2);
47
48 #[derive(Component, Default, Debug)]
49 pub struct Path(pub VecDeque<UVec2>);
50
51 #[derive(Component, Debug)]
52 pub struct Wander(Timer);
53
54 impl Default for Wander {
55 fn default() -> Self {
56 Self(Timer::from_seconds(
57 WANDER_PAUSE_SECS.start,
58 TimerMode::Once,
59 ))
60 }
61 }
62
63 #[derive(Message, Debug, Clone, Copy)]
64 pub struct MoveOrder {
65 pub colonist: Entity,
66 pub goal: UVec2,
67 }
68
69 fn spawn_colonists(
70 mut commands: Commands,
71 map: Res<WorldMap>,
72 existing: Query<Entity, With<Colonist>>,
73 mut meshes: ResMut<Assets<Mesh>>,
74 mut materials: ResMut<Assets<ColorMaterial>>,
75 ) {
76 for entity in &existing {
77 commands.entity(entity).despawn();
78 }
79 let mesh = meshes.add(Circle::new(TILE_SIZE * 0.35));
80 let tiles = spawn_tiles(&map, STARTING_COLONISTS.len());
81 for ((name, color), tile) in STARTING_COLONISTS.into_iter().zip(tiles) {
82 commands.spawn((
83 Name::new(name),
84 Colonist { name: name.into() },
85 TilePos(tile),
86 Mesh2d(mesh.clone()),
87 MeshMaterial2d(materials.add(color)),
88 Transform::from_translation(WorldMap::tile_center(tile).extend(1.0)),
89 ));
90 }
91 }
92
93 fn toggle_pause(keys: Res<ButtonInput<KeyCode>>, mut time: ResMut<Time<Virtual>>) {
94 if keys.just_pressed(KeyCode::Space) {
95 if time.is_paused() {
96 time.unpause();
97 } else {
98 time.pause();
99 }
100 }
101 }
102
103 fn handle_move_orders(
104 mut orders: MessageReader<MoveOrder>,
105 map: Res<WorldMap>,
106 mut colonists: Query<(&TilePos, &mut Path)>,
107 ) {
108 for order in orders.read() {
109 let Ok((tile, mut path)) = colonists.get_mut(order.colonist) else {
110 continue;
111 };
112 if let Some(new_path) = repath(&map, tile.0, &path.0, order.goal) {
113 path.0 = new_path;
114 }
115 }
116 }
117
118 pub fn repath(
119 map: &WorldMap,
120 tile: UVec2,
121 current: &VecDeque<UVec2>,
122 goal: UVec2,
123 ) -> Option<VecDeque<UVec2>> {
124 match current.front() {
125 Some(&next) => {
126 let mut path: VecDeque<_> = find_path(map, next, goal)?.into();
127 path.push_front(next);
128 Some(path)
129 }
130 None => find_path(map, tile, goal).map(VecDeque::from),
131 }
132 }
133
134 fn wander(
135 time: Res<Time>,
136 map: Res<WorldMap>,
137 mut rng: ResMut<SimRng>,
138 mut colonists: Query<(&TilePos, &mut Path, &mut Wander)>,
139 ) {
140 for (tile, mut path, mut wander) in &mut colonists {
141 if !path.0.is_empty() || !wander.0.tick(time.delta()).is_finished() {
142 continue;
143 }
144 let offset = IVec2::new(
145 rng.range_i32(-WANDER_RADIUS..WANDER_RADIUS + 1),
146 rng.range_i32(-WANDER_RADIUS..WANDER_RADIUS + 1),
147 );
148 let goal = tile.0.as_ivec2() + offset;
149 if !map.in_bounds(goal) {
150 continue;
151 }
152 if let Some(new_path) = find_path(&map, tile.0, goal.as_uvec2()) {
153 path.0 = new_path.into();
154 let pause = rng.range_f32(WANDER_PAUSE_SECS);
155 wander.0.set_duration(Duration::from_secs_f32(pause));
156 wander.0.reset();
157 }
158 }
159 }
160
161 fn follow_path(
162 time: Res<Time>,
163 map: Res<WorldMap>,
164 mut colonists: Query<(&mut TilePos, &mut Path, &mut Transform)>,
165 ) {
166 for (mut tile, mut path, mut transform) in &mut colonists {
167 let Some(&next) = path.0.front() else {
168 continue;
169 };
170 let cost = map.move_cost(next.as_ivec2()).unwrap_or(100) as f32 / 100.0;
171 let max_distance = TILES_PER_SECOND * TILE_SIZE / cost * time.delta_secs();
172 let target = WorldMap::tile_center(next);
173 let (pos, arrived) = step_towards(transform.translation.truncate(), target, max_distance);
174 transform.translation = pos.extend(transform.translation.z);
175 if arrived {
176 tile.0 = next;
177 path.0.pop_front();
178 }
179 }
180 }
181
182 pub fn step_towards(pos: Vec2, target: Vec2, max_distance: f32) -> (Vec2, bool) {
183 let delta = target - pos;
184 if delta.length() <= max_distance {
185 (target, true)
186 } else {
187 (pos + delta.normalize() * max_distance, false)
188 }
189 }
190
191 #[cfg(test)]
192 mod tests {
193 use super::*;
194 use crate::world::Terrain;
195
196 #[test]
197 fn step_towards_stops_exactly_on_target() {
198 assert_eq!(
199 step_towards(Vec2::ZERO, Vec2::new(3.0, 4.0), 10.0),
200 (Vec2::new(3.0, 4.0), true)
201 );
202 let (pos, arrived) = step_towards(Vec2::ZERO, Vec2::new(3.0, 4.0), 2.5);
203 assert!(!arrived);
204 assert!(pos.abs_diff_eq(Vec2::new(1.5, 2.0), 1e-5));
205 }
206
207 // A colonist halfway between two tiles keeps heading to the tile it is entering; repathing
208 // from its last reached tile would make it turn around mid-step or walk diagonally past walls.
209 #[test]
210 fn repath_while_moving_keeps_the_tile_being_entered() {
211 let map = WorldMap::filled(UVec2::new(10, 10), Terrain::Grass);
212 let current = VecDeque::from([UVec2::new(3, 2), UVec2::new(4, 2)]);
213 let path = repath(&map, UVec2::new(2, 2), &current, UVec2::new(3, 5)).unwrap();
214 assert_eq!(path.front(), Some(&UVec2::new(3, 2)));
215 assert_eq!(path.back(), Some(&UVec2::new(3, 5)));
216 }
217
218 #[test]
219 fn repath_when_idle_starts_from_current_tile() {
220 let map = WorldMap::filled(UVec2::new(10, 10), Terrain::Grass);
221 let path = repath(&map, UVec2::new(2, 2), &VecDeque::new(), UVec2::new(4, 2)).unwrap();
222 assert_eq!(path, VecDeque::from([UVec2::new(3, 2), UVec2::new(4, 2)]));
223 }
224
225 #[test]
226 fn colonists_walk_their_path_and_update_tile_pos() {
227 let mut app = App::new();
228 app.insert_resource(WorldMap::filled(UVec2::new(10, 10), Terrain::Grass))
229 .init_resource::<Time>()
230 .add_systems(Update, follow_path);
231 let colonist = app
232 .world_mut()
233 .spawn((
234 Colonist {
235 name: "Test".into(),
236 },
237 TilePos(UVec2::new(1, 1)),
238 Path(VecDeque::from([UVec2::new(2, 1), UVec2::new(3, 1)])),
239 Transform::from_translation(WorldMap::tile_center(UVec2::new(1, 1)).extend(0.0)),
240 ))
241 .id();
242 for _ in 0..100 {
243 app.world_mut()
244 .resource_mut::<Time>()
245 .advance_by(Duration::from_millis(50));
246 app.update();
247 }
248 let world = app.world();
249 assert_eq!(
250 world.get::<TilePos>(colonist),
251 Some(&TilePos(UVec2::new(3, 1)))
252 );
253 assert!(world.get::<Path>(colonist).unwrap().0.is_empty());
254 assert_eq!(
255 world
256 .get::<Transform>(colonist)
257 .unwrap()
258 .translation
259 .truncate(),
260 WorldMap::tile_center(UVec2::new(3, 1))
261 );
262 }
263 }