src/mood.rs 11.1 K · 407 lines · raw · history

1 use bevy::prelude::*;
2
3 use crate::{
4 climate::Warmth,
5 colonist::Colonist,
6 family::{Child, Family, Homes, Partner},
7 food::{HUNGRY, Hunger},
8 items::{Carrying, ItemAssets, ItemKind, ItemQuery, drop_items},
9 jobs::Reservations,
10 needs::Rest,
11 population::ColonyLog,
12 rng::SimRng,
13 sim::{SimSystems, SimTick, TICKS_PER_HOUR},
14 structures::{Structure, StructureKind},
15 world::{TilePos, WorldMap},
16 worldgen::WorldGenerated,
17 };
18
19 pub struct MoodPlugin;
20
21 impl Plugin for MoodPlugin {
22 fn build(&self, app: &mut App) {
23 app.add_message::<Ate>()
24 .init_resource::<Losses>()
25 .add_systems(Update, clear_losses.run_if(on_message::<WorldGenerated>))
26 .add_systems(
27 FixedUpdate,
28 (assign_age, digest, update_mood, leave, old_age)
29 .chain()
30 .in_set(SimSystems::Act),
31 );
32 }
33 }
34
35 pub const DAY_TICKS: u64 = 24 * TICKS_PER_HOUR;
36 pub const SICK_TICKS: u64 = 12 * TICKS_PER_HOUR;
37 pub const MOOD_HOURS: f32 = 12.0;
38 pub const LEAVE_MOOD: f32 = 0.2;
39 pub const LEAVE_AFTER_HOURS: u32 = 48;
40 pub const OLD_AGE: u64 = 60;
41 pub const OLD_AGE_DEATH_PER_YEAR: f32 = 0.03;
42 const MEAL_MEMORY_TICKS: u64 = DAY_TICKS;
43 const GRIEF_TICKS: u64 = 2 * DAY_TICKS;
44 const ADULT_AGES: std::ops::Range<i32> = 18..41;
45
46 #[derive(Message, Debug, Clone, Copy)]
47 pub struct Ate {
48 pub colonist: Entity,
49 pub kind: ItemKind,
50 }
51
52 #[derive(Component, Debug, Clone, Copy, PartialEq)]
53 pub struct Mood(pub f32);
54
55 impl Default for Mood {
56 fn default() -> Self {
57 Self(0.6)
58 }
59 }
60
61 #[derive(Component, Debug, Clone, Copy, PartialEq, Eq)]
62 pub struct Sick {
63 pub until: u64,
64 }
65
66 #[derive(Component, Debug, Clone, Copy, PartialEq, Eq)]
67 pub struct LastMeal {
68 pub cooked: bool,
69 pub tick: u64,
70 }
71
72 #[derive(Component, Debug, Default, Clone, Copy, PartialEq, Eq)]
73 pub struct Unhappy(pub u32);
74
75 #[derive(Component, Debug, Clone, Copy, PartialEq, Eq)]
76 pub struct Age {
77 pub born: i64,
78 }
79
80 impl Age {
81 pub fn years(&self, tick: SimTick) -> u64 {
82 ((tick.0 as i64 - self.born).max(0) as u64) / DAY_TICKS
83 }
84 }
85
86 #[derive(Resource, Default, Debug)]
87 pub struct Losses(pub Vec<u64>);
88
89 fn clear_losses(mut losses: ResMut<Losses>) {
90 losses.0.clear();
91 }
92
93 pub fn poison_chance(kind: ItemKind) -> f32 {
94 match kind {
95 ItemKind::Meat => 0.15,
96 ItemKind::Berries | ItemKind::Vegetables => 0.04,
97 _ => 0.0,
98 }
99 }
100
101 #[derive(Debug, Default, Clone, Copy)]
102 pub struct MoodFactors {
103 pub fed: f32,
104 pub rest: f32,
105 pub sick: bool,
106 pub last_meal_cooked: Option<bool>,
107 pub partner: bool,
108 pub home: bool,
109 pub grieving: bool,
110 pub cold: bool,
111 pub beauty: bool,
112 }
113
114 pub fn mood_target(f: MoodFactors) -> f32 {
115 let mut mood: f32 = 0.5;
116 mood += if f.fed < HUNGRY { -0.25 } else { 0.1 };
117 mood += if f.rest < 0.2 { -0.15 } else { 0.05 };
118 mood += match f.last_meal_cooked {
119 Some(true) => 0.1,
120 Some(false) => -0.05,
121 None => 0.0,
122 };
123 if f.sick {
124 mood -= 0.2;
125 }
126 if f.partner {
127 mood += 0.1;
128 }
129 if f.home {
130 mood += 0.1;
131 }
132 if f.grieving {
133 mood -= 0.15;
134 }
135 if f.cold {
136 mood -= 0.15;
137 }
138 if f.beauty {
139 mood += 0.1;
140 }
141 mood.clamp(0.0, 1.0)
142 }
143
144 fn assign_age(
145 mut commands: Commands,
146 tick: Res<SimTick>,
147 mut rng: ResMut<SimRng>,
148 newcomers: Query<(Entity, Has<Child>), (With<Colonist>, Without<Age>)>,
149 ) {
150 for (entity, child) in &newcomers {
151 let years = if child { 0 } else { rng.range_i32(ADULT_AGES) };
152 let born = tick.0 as i64 - years as i64 * DAY_TICKS as i64;
153 commands
154 .entity(entity)
155 .insert((Age { born }, Mood::default()));
156 }
157 }
158
159 fn digest(
160 mut commands: Commands,
161 tick: Res<SimTick>,
162 mut rng: ResMut<SimRng>,
163 mut log: ResMut<ColonyLog>,
164 mut ate: MessageReader<Ate>,
165 colonists: Query<(&Colonist, Option<&Sick>)>,
166 ) {
167 for meal in ate.read() {
168 let Ok((colonist, sick)) = colonists.get(meal.colonist) else {
169 continue;
170 };
171 let mut entity = commands.entity(meal.colonist);
172 entity.insert(LastMeal {
173 cooked: !meal.kind.is_raw_food(),
174 tick: tick.0,
175 });
176 if sick.is_none() && rng.range_f32(0.0..1.0) < poison_chance(meal.kind) {
177 entity.insert(Sick {
178 until: tick.0 + SICK_TICKS,
179 });
180 log.push(*tick, format!("{} has food poisoning", colonist.name));
181 }
182 }
183 }
184
185 #[allow(clippy::type_complexity)]
186 fn update_mood(
187 mut commands: Commands,
188 tick: Res<SimTick>,
189 homes: Res<Homes>,
190 map: Res<WorldMap>,
191 losses: Res<Losses>,
192 structures: Query<(&TilePos, &Structure), Without<Colonist>>,
193 mut colonists: Query<(
194 Entity,
195 &mut Mood,
196 &Hunger,
197 &Rest,
198 Option<&Sick>,
199 Option<&LastMeal>,
200 Has<Partner>,
201 Option<&Family>,
202 &Warmth,
203 )>,
204 ) {
205 if !tick.0.is_multiple_of(TICKS_PER_HOUR) {
206 return;
207 }
208 let grieving = losses.0.iter().any(|&t| tick.0 < t + GRIEF_TICKS);
209 let statues: Vec<UVec2> = structures
210 .iter()
211 .filter(|(_, s)| s.kind == StructureKind::Statue)
212 .map(|(pos, _)| pos.0)
213 .collect();
214 for (entity, mut mood, hunger, rest, sick, meal, partner, family, warmth) in &mut colonists {
215 let sick_now = sick.is_some_and(|s| tick.0 < s.until);
216 if sick.is_some() && !sick_now {
217 commands.entity(entity).remove::<Sick>();
218 }
219 let own_home = homes.of(family.copied());
220 let home = own_home.is_some_and(|h| h.interior().all(|t| map.is_roofed(t.as_ivec2())));
221 let beauty = own_home.is_some_and(|h| statues.iter().any(|&t| h.contains(t)));
222 let target = mood_target(MoodFactors {
223 fed: hunger.0,
224 rest: rest.0,
225 sick: sick_now,
226 last_meal_cooked: meal
227 .filter(|m| tick.0 < m.tick + MEAL_MEMORY_TICKS)
228 .map(|m| m.cooked),
229 partner,
230 home,
231 grieving,
232 cold: warmth.cold(),
233 beauty,
234 });
235 mood.0 += (target - mood.0) / MOOD_HOURS;
236 }
237 }
238
239 #[allow(clippy::too_many_arguments)]
240 fn leave(
241 mut commands: Commands,
242 tick: Res<SimTick>,
243 item_assets: Res<ItemAssets>,
244 mut log: ResMut<ColonyLog>,
245 mut reservations: ResMut<Reservations>,
246 mut items: ItemQuery,
247 mut colonists: Query<
248 (
249 Entity,
250 &Colonist,
251 &Mood,
252 &TilePos,
253 &Carrying,
254 Option<&mut Unhappy>,
255 ),
256 Without<Child>,
257 >,
258 ) {
259 if !tick.0.is_multiple_of(TICKS_PER_HOUR) {
260 return;
261 }
262 for (entity, colonist, mood, tile, carrying, unhappy) in &mut colonists {
263 let hours = if mood.0 < LEAVE_MOOD {
264 unhappy.as_ref().map_or(0, |u| u.0) + 1
265 } else {
266 0
267 };
268 match unhappy {
269 Some(mut u) => u.0 = hours,
270 None => {
271 commands.entity(entity).insert(Unhappy(hours));
272 }
273 }
274 if hours < LEAVE_AFTER_HOURS {
275 continue;
276 }
277 if let Some(load) = carrying.0 {
278 drop_items(&mut commands, &mut items, &item_assets, tile.0, load);
279 }
280 reservations.release_all(entity);
281 commands.entity(entity).despawn();
282 log.push(*tick, format!("{} left the colony, unhappy", colonist.name));
283 }
284 }
285
286 pub fn dies_of_old_age(years: u64, roll: f32) -> bool {
287 years >= OLD_AGE && roll < (years - OLD_AGE + 1) as f32 * OLD_AGE_DEATH_PER_YEAR
288 }
289
290 #[allow(clippy::too_many_arguments)]
291 fn old_age(
292 mut commands: Commands,
293 tick: Res<SimTick>,
294 item_assets: Res<ItemAssets>,
295 mut rng: ResMut<SimRng>,
296 mut log: ResMut<ColonyLog>,
297 mut losses: ResMut<Losses>,
298 mut reservations: ResMut<Reservations>,
299 mut items: ItemQuery,
300 colonists: Query<(Entity, &Colonist, &Age, &TilePos, &Carrying)>,
301 ) {
302 if !tick.0.is_multiple_of(DAY_TICKS) {
303 return;
304 }
305 for (entity, colonist, age, tile, carrying) in &colonists {
306 if !dies_of_old_age(age.years(*tick), rng.range_f32(0.0..1.0)) {
307 continue;
308 }
309 if let Some(load) = carrying.0 {
310 drop_items(&mut commands, &mut items, &item_assets, tile.0, load);
311 }
312 reservations.release_all(entity);
313 commands.entity(entity).despawn();
314 losses.0.push(tick.0);
315 log.push(*tick, format!("{} died of old age", colonist.name));
316 }
317 }
318
319 #[cfg(test)]
320 mod tests {
321 use super::*;
322
323 fn content() -> MoodFactors {
324 MoodFactors {
325 fed: 0.8,
326 rest: 0.8,
327 ..default()
328 }
329 }
330
331 #[test]
332 fn needs_meals_family_and_loss_move_mood() {
333 let base = mood_target(content());
334 let hungry = mood_target(MoodFactors {
335 fed: 0.1,
336 ..content()
337 });
338 assert!(hungry < base);
339 let settled = mood_target(MoodFactors {
340 partner: true,
341 home: true,
342 beauty: true,
343 last_meal_cooked: Some(true),
344 ..content()
345 });
346 assert!(settled > base + 0.25);
347 let miserable = mood_target(MoodFactors {
348 fed: 0.1,
349 rest: 0.1,
350 sick: true,
351 grieving: true,
352 cold: true,
353 last_meal_cooked: Some(false),
354 ..default()
355 });
356 assert!(miserable < LEAVE_MOOD);
357 }
358
359 // Cooking is what makes raw meat safe: meals never poison, raw meat is the riskiest.
360 #[test]
361 fn raw_food_can_poison_and_meals_never() {
362 assert_eq!(poison_chance(ItemKind::Meal), 0.0);
363 assert!(poison_chance(ItemKind::Meat) > poison_chance(ItemKind::Berries));
364 }
365
366 #[test]
367 fn old_age_comes_for_everyone_eventually() {
368 assert!(!dies_of_old_age(OLD_AGE - 1, 0.0));
369 assert!(dies_of_old_age(OLD_AGE, 0.0));
370 assert!(!dies_of_old_age(OLD_AGE, 0.5));
371 assert!(dies_of_old_age(OLD_AGE + 40, 0.99));
372 }
373
374 #[test]
375 fn colonists_leave_after_two_unhappy_days() {
376 let mut app = App::new();
377 app.init_resource::<SimTick>()
378 .init_resource::<ItemAssets>()
379 .init_resource::<ColonyLog>()
380 .init_resource::<Reservations>()
381 .add_systems(Update, leave);
382 let spawn = |app: &mut App, mood: f32| {
383 app.world_mut()
384 .spawn((
385 Colonist { name: "Ada".into() },
386 Mood(mood),
387 Unhappy(LEAVE_AFTER_HOURS - 1),
388 ))
389 .id()
390 };
391 let gloomy = spawn(&mut app, LEAVE_MOOD / 2.0);
392 let cheered_up = spawn(&mut app, 0.5);
393 app.update();
394 assert!(app.world().get_entity(gloomy).is_err());
395 assert_eq!(app.world().get::<Unhappy>(cheered_up), Some(&Unhappy(0)));
396 let log = app.world().resource::<ColonyLog>();
397 assert!(log.0[0].ends_with("Ada left the colony, unhappy"));
398 }
399
400 #[test]
401 fn ages_count_days_as_years() {
402 let age = Age {
403 born: -(20 * DAY_TICKS as i64),
404 };
405 assert_eq!(age.years(SimTick(DAY_TICKS / 2)), 20);
406 }
407 }