verticopolis_engine/view/reader.rs
1//! The dynamic frame: what a view reads every rendered frame. The header,
2//! the crowd's people and every transport's cars go in full each time; the
3//! rooms go only when their frame fields changed since this reader's last
4//! frame. The reader finds them in the tower's mark log (`marks.rs`), which
5//! the setters of those fields write, so a frame visits only the rooms that
6//! changed (a full frame aside) and no floor or lobby tile (their fields
7//! move only with the revision, which the structural snapshot covers).
8use std::sync::Arc;
9
10use super::layout::header::PEOPLE;
11use super::layout::{HEADER, PERSON_RECORD, UNIT_RECORD};
12use super::window::PeopleWindow;
13use crate::frame::{person_state_code, push_transports, transports_len, unit_fields, weather_code};
14use crate::sim::Simulation;
15use crate::tower::Unit;
16
17/// Reads the view's frame for one game, sending only what changed since its
18/// last frame. Keep one per game: a host that loads another game starts a
19/// new reader. A reader handed another game sends a full frame.
20#[derive(Default)]
21pub struct ViewReader {
22 sent: Option<(u64, i64, usize)>,
23 last: Vec<[u64; 5]>,
24 census: Vec<i64>,
25 population: i64,
26 read: u64,
27 seq: u64,
28 marked: Vec<usize>,
29 changed: Vec<f64>,
30 /// The part of the tower the view draws; `None` sends every person.
31 window: Option<PeopleWindow>,
32}
33
34impl ViewReader {
35 /// A reader that has sent nothing, so its first frame is full.
36 pub fn new() -> ViewReader {
37 ViewReader::default()
38 }
39
40 /// Send only the people in `window` from the next frame on, or every
41 /// person with `None` (the default). The rooms and the cars still go in
42 /// full: the window trims only the people, the record that grows with
43 /// the crowd.
44 pub fn set_people_window(&mut self, window: Option<PeopleWindow>) {
45 self.window = window;
46 }
47
48 /// The dynamic frame as one flat number array.
49 ///
50 /// Header (`HEADER` slots, see `layout::header`): minutes, tower
51 /// revision, meta revision, meal overlay revision, logSeq, money, star,
52 /// the unlocked kinds (bit k set when the kind with code k is unlocked),
53 /// the population (as `Simulation::population` counts it), weather, the
54 /// Santa, explosion, thief, treasure and VIP effects and the event
55 /// counts as `frameView` carries them, a pending choice (0 or 1),
56 /// onHourRuns, the room count the slots index, the full flag, this
57 /// reader's frame number (1 for its first), then the people, room record
58 /// and transport counts.
59 ///
60 /// Then `people` records of `PERSON_RECORD`, every person in the crowd
61 /// as [`crate::frame::frame_view`] sends them: id, seed, staff (0 or 1), state, floor, x,
62 /// fy, wait. With a people window set ([`ViewReader::set_people_window`])
63 /// they are only the people in it, padded so every rider of a car on
64 /// screen comes along ([`PeopleWindow::padded`]), in crowd order. Then `units` room records of `UNIT_RECORD`:
65 /// the room's slot (its position in the structural snapshot's room list),
66 /// then state, occupants, customersIn, hotelCustomersIn, outForMeal (an
67 /// absent counter is -1). Then every transport as [`crate::frame::frame_view`] writes it.
68 ///
69 /// The room records are every room, in slot order, with the full flag
70 /// set, when `full` is true, on this reader's first frame, or when the
71 /// revision or the unit count moved since its last frame (the slots then
72 /// index a new structure). Otherwise they are the rooms whose fields
73 /// changed since its last frame, in slot order, a field compared bit for
74 /// bit.
75 ///
76 /// A full frame makes one pass over the rooms index, which happens once
77 /// per revision move (a command), on a new tower, or when the host asks.
78 /// Any other frame visits the rooms the mark log names since this
79 /// reader's last frame, each once, plus a binary search of the rooms
80 /// index for each; with nothing marked it visits no room. When the marks
81 /// it reads reach half the rooms (an hour can mark nearly all of them),
82 /// or the log has dropped marks this reader never read (it fell more than
83 /// `MARK_CAP` marks behind), the frame compares every room once instead,
84 /// which sends the same rooms for less (`compare_all`). The population
85 /// is a running total that each visited room corrects. One allocation,
86 /// made at the frame's size.
87 ///
88 /// The engine's own writes go through the setters, which mark the room.
89 /// A native host that writes a unit's frame fields or residents itself,
90 /// outside the commands and the tick, leaves the room unmarked, so its
91 /// next frame passes `full`.
92 pub fn frame(&mut self, sim: &Simulation, full: bool) -> Vec<f64> {
93 let tower = &sim.tower;
94 let rooms: Arc<[usize]> = tower.room_index();
95 let marks = &tower.view.marks;
96 let key = (marks.id(), tower.revision, tower.units.len());
97 let full = full || self.sent != Some(key) || self.last.len() != rooms.len();
98 self.changed.clear();
99 if full {
100 self.last.clear();
101 self.last.reserve(rooms.len());
102 self.census.clear();
103 self.census.reserve(rooms.len());
104 self.changed.reserve(rooms.len() * UNIT_RECORD);
105 self.population = 0;
106 for (slot, &i) in rooms.iter().enumerate() {
107 let u = &tower.units[i];
108 let fields = unit_fields(u);
109 self.last.push(fields.map(f64::to_bits));
110 let census = u.census_share();
111 self.census.push(census);
112 self.population += census;
113 self.changed.push(slot as f64);
114 self.changed.extend_from_slice(&fields);
115 }
116 } else {
117 let mut marked = std::mem::take(&mut self.marked);
118 marked.clear();
119 // The count decides first, so a frame that compares every room
120 // copies no mark.
121 let few = marks
122 .unread(self.read)
123 .is_some_and(|n| !compare_all(n, rooms.len()));
124 if few && marks.read_since(self.read, &mut marked) {
125 // Unit-list order is the rooms index's order, so sorted
126 // indices give the slots in order.
127 marked.sort_unstable();
128 marked.dedup();
129 for &i in &marked {
130 if let Ok(slot) = rooms.binary_search(&i) {
131 self.update(slot, &tower.units[i]);
132 }
133 }
134 } else {
135 for (slot, &i) in rooms.iter().enumerate() {
136 self.update(slot, &tower.units[i]);
137 }
138 }
139 self.marked = marked;
140 }
141 self.read = marks.end();
142 self.sent = Some(key);
143 self.seq += 1;
144 let population = self.population;
145 let people = &sim.crowd.people;
146 let window = self.window.map(|w| w.padded(&tower.transports));
147 let shown = |p: &&crate::crowd::Person| window.is_none_or(|w| w.holds(p));
148 // Reserved for every person, so the frame is one allocation whatever
149 // the window keeps; the people count is written once they are in.
150 let rest = self.changed.len() + transports_len(&tower.transports);
151 let mut v = Vec::with_capacity(HEADER + people.len() * PERSON_RECORD + rest);
152 let fx = &sim.fx;
153 let clock = &sim.clock;
154 v.extend_from_slice(&[
155 clock.minutes,
156 tower.revision as f64,
157 tower.meta_revision as f64,
158 tower.meal_overlay_revision as f64,
159 sim.log_seq as f64,
160 sim.money,
161 sim.star as f64,
162 unlocked_mask(sim),
163 population as f64,
164 weather_code(sim.weather),
165 fx.santa_seq as f64,
166 fx.explosion.seq as f64,
167 fx.explosion.floor as f64,
168 fx.explosion.x,
169 fx.thief.seq as f64,
170 if fx.thief.caught { 1.0 } else { 0.0 },
171 fx.thief.floor as f64,
172 fx.treasure.seq as f64,
173 fx.treasure.floor as f64,
174 fx.treasure.x,
175 fx.vip_seq as f64,
176 sim.events.fires_started as f64,
177 sim.events.fires_gut_rooms as f64,
178 sim.events.bombs_detonated as f64,
179 if sim.events.pending.is_some() {
180 1.0
181 } else {
182 0.0
183 },
184 sim.on_hour_runs as f64,
185 rooms.len() as f64,
186 if full { 1.0 } else { 0.0 },
187 self.seq as f64,
188 // The people count, set below.
189 0.0,
190 (self.changed.len() / UNIT_RECORD) as f64,
191 tower.transports.len() as f64,
192 clock.day() as f64,
193 clock.day_of_week() as f64,
194 if clock.is_weekend() { 1.0 } else { 0.0 },
195 clock.quarter() as f64,
196 clock.year() as f64,
197 clock.calendar.week_days as f64,
198 clock.calendar.weekend_days as f64,
199 sim.events.bomb.as_ref().map_or(0.0, |b| b.seq as f64),
200 fx.thief.x as f64,
201 ]);
202 debug_assert_eq!(v.len(), HEADER);
203 let mut sent = 0;
204 for p in people.iter().filter(shown) {
205 sent += 1;
206 v.extend_from_slice(&[
207 p.id as f64,
208 p.seed as f64,
209 if p.staff { 1.0 } else { 0.0 },
210 person_state_code(p.state),
211 p.floor as f64,
212 p.x,
213 p.fy,
214 p.wait,
215 ]);
216 }
217 v[PEOPLE] = sent as f64;
218 v.extend_from_slice(&self.changed);
219 push_transports(&mut v, &tower.transports);
220 debug_assert_eq!(v.len(), HEADER + sent * PERSON_RECORD + rest);
221 v
222 }
223
224 /// Bring the room in `slot` up to date: correct the population by the
225 /// change in its census, and queue its record when a frame field
226 /// changed, compared bit for bit.
227 fn update(&mut self, slot: usize, u: &Unit) {
228 let census = u.census_share();
229 self.population += census - self.census[slot];
230 self.census[slot] = census;
231 let fields = unit_fields(u);
232 let bits = fields.map(f64::to_bits);
233 let last = &mut self.last[slot];
234 if (0..5).any(|k| bits[k] != last[k]) {
235 *last = bits;
236 self.changed.push(slot as f64);
237 self.changed.extend_from_slice(&fields);
238 }
239 }
240}
241
242/// Whether a frame that read `marks` marks (repeats counted, before the
243/// sort) compares every room instead of finding each marked one. From
244/// about half the rooms the sort and a binary search per mark cost more
245/// than one compare over the rooms. The review measured two frames after an
246/// hour on the large tower (2,900 rooms): 2,886 marks cost 875K
247/// instructions on the marks and 489K with this threshold, the compare's
248/// cost; 1,377 marks cost 406.6K on the marks against 339.4K for a compare.
249/// The compare's cost moves with the rooms that changed, so no one share of
250/// the rooms breaks even on every frame, and just below half the marks cost
251/// up to 1.2 times a compare on the frames measured. Both branches send the
252/// same rooms, since every write of a frame field marks. The census tally
253/// (`tally.rs`) uses the same threshold with no sort, at one constant visit
254/// per mark, so either of its branches costs at most about one visit per
255/// room.
256pub(super) fn compare_all(marks: usize, rooms: usize) -> bool {
257 marks * 2 >= rooms
258}
259
260/// The unlocked kinds as a bitmask by kind code: bit k is set when the kind
261/// with code k (`Kind as usize`) is unlocked (`Simulation::is_unlocked`).
262/// A double holds 53 bits exactly, and `layout_tests.rs` keeps the catalog
263/// inside them.
264fn unlocked_mask(sim: &Simulation) -> f64 {
265 let mut mask = 0u64;
266 for (k, f) in crate::facilities::FACILITIES.iter().enumerate() {
267 if sim.is_unlocked(f.kind) {
268 mask |= 1 << k;
269 }
270 }
271 mask as f64
272}