src/economy.rs 9.6 K · 319 lines · raw · history

1 use std::collections::HashMap;
2
3 use bevy::prelude::*;
4
5 use crate::{
6 building::Blueprints,
7 climate::cold_days_ahead,
8 items::ItemKind,
9 sim::{SimSystems, SimTick, TICKS_PER_HOUR},
10 };
11
12 pub struct EconomyPlugin;
13
14 impl Plugin for EconomyPlugin {
15 fn build(&self, app: &mut App) {
16 app.init_resource::<ColonyGoals>()
17 .add_systems(FixedUpdate, learn_needs.in_set(SimSystems::Decide));
18 }
19 }
20
21 pub const COLONY_RADIUS: i32 = 60;
22 const HOURS_OF_MEMORY: f32 = 24.0;
23 const MAX_GOAL: f32 = 300.0;
24
25 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
26 pub enum Stock {
27 Wood,
28 Stone,
29 Iron,
30 Gold,
31 RawFood,
32 Meals,
33 }
34
35 impl Stock {
36 pub const ALL: [Stock; 6] = [
37 Stock::Wood,
38 Stock::Stone,
39 Stock::Iron,
40 Stock::Gold,
41 Stock::RawFood,
42 Stock::Meals,
43 ];
44
45 pub fn of(kind: ItemKind) -> Stock {
46 match kind {
47 ItemKind::Wood => Stock::Wood,
48 ItemKind::Stone => Stock::Stone,
49 ItemKind::Iron => Stock::Iron,
50 ItemKind::Gold => Stock::Gold,
51 ItemKind::Berries | ItemKind::Meat | ItemKind::Vegetables | ItemKind::Carcass => {
52 Stock::RawFood
53 }
54 ItemKind::Meal => Stock::Meals,
55 }
56 }
57
58 pub fn members(self) -> impl Iterator<Item = ItemKind> {
59 ItemKind::ALL
60 .into_iter()
61 .filter(move |&k| Stock::of(k) == self)
62 }
63
64 pub fn is_food(self) -> bool {
65 matches!(self, Stock::RawFood | Stock::Meals)
66 }
67
68 pub fn label(self) -> &'static str {
69 match self {
70 Stock::Wood => "Wood",
71 Stock::Stone => "Stone",
72 Stock::Iron => "Iron",
73 Stock::Gold => "Gold",
74 Stock::RawFood => "Raw food",
75 Stock::Meals => "Meals",
76 }
77 }
78
79 fn buffer_days(self, cold_days: u64) -> f32 {
80 let normal: f32 = if self.is_food() { 1.5 } else { 2.0 };
81 match self {
82 Stock::Wood | Stock::RawFood | Stock::Meals => normal.max(cold_days as f32),
83 _ => normal,
84 }
85 }
86
87 fn minimum(self) -> f32 {
88 match self {
89 Stock::Wood => 15.0,
90 Stock::Stone => 5.0,
91 Stock::Iron | Stock::Gold => 0.0,
92 Stock::RawFood => 10.0,
93 Stock::Meals => 3.0,
94 }
95 }
96
97 fn initial_use_per_day(self) -> f32 {
98 match self {
99 Stock::Wood => 20.0,
100 Stock::Stone => 10.0,
101 Stock::Iron | Stock::Gold => 0.0,
102 Stock::RawFood => 30.0,
103 Stock::Meals => 3.0,
104 }
105 }
106 }
107
108 #[derive(Resource, Debug, Clone)]
109 pub struct ColonyGoals {
110 goals: HashMap<Stock, u32>,
111 use_per_day: HashMap<Stock, f32>,
112 used_this_hour: HashMap<Stock, u32>,
113 overrides: HashMap<Stock, u32>,
114 cold_days: u64,
115 }
116
117 impl Default for ColonyGoals {
118 fn default() -> Self {
119 let mut goals = Self {
120 goals: HashMap::new(),
121 use_per_day: Stock::ALL
122 .iter()
123 .map(|&s| (s, s.initial_use_per_day()))
124 .collect(),
125 used_this_hour: HashMap::new(),
126 overrides: HashMap::new(),
127 cold_days: 0,
128 };
129 goals.recompute(&HashMap::new());
130 goals
131 }
132 }
133
134 impl ColonyGoals {
135 #[cfg(test)]
136 pub fn fixed(goals: &[(ItemKind, u32)]) -> Self {
137 Self {
138 goals: goals.iter().map(|&(k, n)| (Stock::of(k), n)).collect(),
139 use_per_day: HashMap::new(),
140 used_this_hour: HashMap::new(),
141 overrides: HashMap::new(),
142 cold_days: 0,
143 }
144 }
145
146 pub fn goal(&self, stock: Stock) -> u32 {
147 self.overrides
148 .get(&stock)
149 .or_else(|| self.goals.get(&stock))
150 .copied()
151 .unwrap_or(0)
152 }
153
154 pub fn is_overridden(&self, stock: Stock) -> bool {
155 self.overrides.contains_key(&stock)
156 }
157
158 pub fn adjust(&mut self, stock: Stock, delta: i32) {
159 let goal = (self.goal(stock) as i32 + delta).clamp(0, MAX_GOAL as i32) as u32;
160 self.overrides.insert(stock, goal);
161 }
162
163 pub fn reset(&mut self, stock: Stock) {
164 self.overrides.remove(&stock);
165 }
166
167 pub fn use_per_day(&self, stock: Stock) -> f32 {
168 self.use_per_day.get(&stock).copied().unwrap_or(0.0)
169 }
170
171 pub fn record_use(&mut self, kind: ItemKind, count: u32) {
172 *self.used_this_hour.entry(Stock::of(kind)).or_insert(0) += count;
173 }
174
175 pub fn wanted(
176 &self,
177 kind: ItemKind,
178 stocks: &HashMap<ItemKind, u32>,
179 on_the_way: &HashMap<ItemKind, u32>,
180 ) -> bool {
181 let stock = Stock::of(kind);
182 let have: u32 = stock
183 .members()
184 .map(|k| {
185 stocks.get(&k).copied().unwrap_or(0) + on_the_way.get(&k).copied().unwrap_or(0)
186 })
187 .sum();
188 have < self.goal(stock)
189 }
190
191 pub fn set_cold_days(&mut self, days: u64) {
192 self.cold_days = days;
193 }
194
195 pub fn learn_hour(&mut self, planned: &HashMap<Stock, u32>) {
196 for stock in Stock::ALL {
197 let used = self.used_this_hour.remove(&stock).unwrap_or(0) as f32;
198 let rate = self.use_per_day.entry(stock).or_insert(0.0);
199 *rate += (used * 24.0 - *rate) / HOURS_OF_MEMORY;
200 }
201 self.recompute(planned);
202 }
203
204 fn recompute(&mut self, planned: &HashMap<Stock, u32>) {
205 for stock in Stock::ALL {
206 let learned = (self.use_per_day(stock) * stock.buffer_days(self.cold_days))
207 .clamp(stock.minimum(), MAX_GOAL)
208 .ceil() as u32;
209 let goal = learned + planned.get(&stock).copied().unwrap_or(0);
210 self.goals.insert(stock, goal);
211 }
212 }
213 }
214
215 pub fn in_colony(home: UVec2, tile: UVec2) -> bool {
216 (tile.as_ivec2() - home.as_ivec2()).abs().max_element() <= COLONY_RADIUS
217 }
218
219 pub fn planned_needs(blueprints: &Blueprints) -> HashMap<Stock, u32> {
220 let mut needs = HashMap::new();
221 for kind in blueprints.0.values() {
222 let (item, count) = kind.cost();
223 *needs.entry(Stock::of(item)).or_insert(0) += count;
224 }
225 needs
226 }
227
228 fn learn_needs(tick: Res<SimTick>, blueprints: Res<Blueprints>, mut goals: ResMut<ColonyGoals>) {
229 if tick.0 == 0 || !tick.0.is_multiple_of(TICKS_PER_HOUR) {
230 return;
231 }
232 goals.set_cold_days(cold_days_ahead(*tick));
233 goals.learn_hour(&planned_needs(&blueprints));
234 }
235
236 #[cfg(test)]
237 mod tests {
238 use super::*;
239 use crate::building::BuildKind;
240
241 fn learn_days(goals: &mut ColonyGoals, kind: ItemKind, per_hour: u32, days: u32) {
242 for _ in 0..days * 24 {
243 goals.record_use(kind, per_hour);
244 goals.learn_hour(&HashMap::new());
245 }
246 }
247
248 #[test]
249 fn targets_follow_what_the_colony_actually_uses() {
250 let mut goals = ColonyGoals::default();
251 learn_days(&mut goals, ItemKind::Meal, 1, 5);
252 let meals = goals.goal(Stock::Meals);
253 assert!((32..=40).contains(&meals), "{meals}");
254 learn_days(&mut goals, ItemKind::Meal, 0, 5);
255 assert_eq!(goals.goal(Stock::Meals), 3);
256 }
257
258 #[test]
259 fn players_can_override_learned_targets_and_hand_them_back() {
260 let mut goals = ColonyGoals::default();
261 let learned = goals.goal(Stock::Wood);
262 goals.adjust(Stock::Wood, 10);
263 assert_eq!(goals.goal(Stock::Wood), learned + 10);
264 learn_days(&mut goals, ItemKind::Wood, 5, 3);
265 assert_eq!(goals.goal(Stock::Wood), learned + 10);
266 goals.adjust(Stock::Iron, -10);
267 assert_eq!(goals.goal(Stock::Iron), 0);
268 goals.reset(Stock::Wood);
269 assert!(!goals.is_overridden(Stock::Wood));
270 assert!(goals.goal(Stock::Wood) > learned);
271 }
272
273 // Nothing grows in the cold days ahead and fires burn all day, so food and wood targets cover
274 // those days instead of the usual short buffer.
275 #[test]
276 fn winter_ahead_raises_food_and_wood_targets() {
277 let mut goals = ColonyGoals::default();
278 learn_days(&mut goals, ItemKind::Berries, 1, 3);
279 let (food, stone) = (goals.goal(Stock::RawFood), goals.goal(Stock::Stone));
280 goals.set_cold_days(5);
281 goals.learn_hour(&HashMap::new());
282 assert!(goals.goal(Stock::RawFood) > food * 3);
283 assert_eq!(goals.goal(Stock::Stone), stone);
284 }
285
286 #[test]
287 fn unused_materials_are_not_stockpiled() {
288 let mut goals = ColonyGoals::default();
289 learn_days(&mut goals, ItemKind::Wood, 0, 10);
290 assert_eq!(goals.goal(Stock::Wood), 15);
291 assert_eq!(goals.goal(Stock::Iron), 0);
292 }
293
294 // Raw foods stand in for each other (cooking accepts any), so the colony targets them as one
295 // group and is free to forage, hunt or farm whichever is at hand.
296 #[test]
297 fn raw_foods_share_one_target() {
298 let goals = ColonyGoals::fixed(&[(ItemKind::Berries, 20)]);
299 let stocks = HashMap::from([(ItemKind::Meat, 15), (ItemKind::Vegetables, 4)]);
300 assert!(goals.wanted(ItemKind::Berries, &stocks, &HashMap::new()));
301 let on_the_way = HashMap::from([(ItemKind::Berries, 1)]);
302 assert!(!goals.wanted(ItemKind::Meat, &stocks, &on_the_way));
303 }
304
305 #[test]
306 fn planned_construction_raises_material_targets() {
307 let mut blueprints = Blueprints::default();
308 for x in 0..10 {
309 blueprints.0.insert(
310 UVec2::new(x, 0),
311 BuildKind::Structure(crate::structures::StructureKind::Wall),
312 );
313 }
314 let mut goals = ColonyGoals::default();
315 let before = goals.goal(Stock::Stone);
316 goals.learn_hour(&planned_needs(&blueprints));
317 assert!(goals.goal(Stock::Stone) >= before + 19);
318 }
319 }