This repository has been archived by the owner on Jul 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
change.rs
463 lines (411 loc) · 15 KB
/
change.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
use crate::prelude::*;
#[derive(Debug, Clone)]
pub enum WorldChange {
Tick(usize),
Block(BlockPosition, BlockWithState),
EntitySpawned {
eid: Eid,
uuid: UUID,
ty: NetworkEntity,
position: Position,
pitch: f32,
yaw: f32,
head_yaw: f32,
data: u32,
velocity: Translation,
},
EntityDispawned {
eid: Eid,
},
EntityMetadata {
eid: Eid,
metadata: (),
},
EntityPosition {
eid: Eid,
from: Position,
to: Position,
},
EntityVelocity {
eid: Eid,
velocity: Translation,
},
EntityPitch {
eid: Eid,
pitch: f32,
yaw: f32,
head_yaw: f32,
},
}
pub struct EntityChanges(u8);
impl EntityChanges {
pub const fn other() -> EntityChanges {
EntityChanges(0)
}
pub const fn nothing() -> EntityChanges {
EntityChanges(0)
}
pub const fn position() -> EntityChanges {
EntityChanges(1)
}
pub const fn velocity() -> EntityChanges {
EntityChanges(1 << 1)
}
pub const fn pitch() -> EntityChanges {
EntityChanges(1 << 2)
}
pub const fn metadata() -> EntityChanges {
EntityChanges(1 << 3)
}
pub const fn nothing_changed(&self) -> bool {
self.0 == 0
}
pub const fn position_changed(&self) -> bool {
self.0 & 1 != 0
}
pub const fn velocity_changed(&self) -> bool {
self.0 & (1 << 1) != 0
}
pub const fn pitch_changed(&self) -> bool {
self.0 & (1 << 2) != 0
}
pub const fn metadata_changed(&self) -> bool {
self.0 & (1 << 3) != 0
}
}
impl std::ops::Add<EntityChanges> for EntityChanges {
type Output = EntityChanges;
fn add(self, rhs: EntityChanges) -> EntityChanges {
EntityChanges(self.0 | rhs.0)
}
}
impl std::ops::AddAssign<EntityChanges> for EntityChanges {
fn add_assign(&mut self, rhs: EntityChanges) {
self.0 |= rhs.0;
}
}
pub struct WorldObserver {
receiver: MpscReceiver<WorldChange>,
eid: Eid,
observer_manager: &'static WorldObserverManager,
}
impl WorldObserver {
pub async fn recv(&mut self) -> Option<WorldChange> {
self.receiver.recv().await
}
pub fn try_recv(&mut self) -> Result<WorldChange, tokio::sync::mpsc::error::TryRecvError> {
self.receiver.try_recv()
}
pub async fn enable_ticks(&self) {
let mut trackers = self.observer_manager.trackers.write().await;
let Some(tracker) = trackers.get_mut(&self.eid) else { return };
if !tracker.ticks {
tracker.ticks = true;
self.observer_manager.ticks.write().await.insert(self.eid);
}
}
pub async fn disable_ticks(&self) {
let mut trackers = self.observer_manager.trackers.write().await;
let Some(tracker) = trackers.get_mut(&self.eid) else { return };
if tracker.ticks {
tracker.ticks = false;
self.observer_manager.ticks.write().await.remove(&self.eid);
}
}
}
impl Drop for WorldObserver {
fn drop(&mut self) {
let manager = self.observer_manager;
let eid = self.eid;
tokio::spawn(async move {
manager.remove_subscriber(eid).await;
});
}
}
struct WorldObserverTracker {
sender: MpscSender<WorldChange>,
ticks: bool,
blocks: HashSet<ChunkColumnPosition>,
entities: HashSet<ChunkColumnPosition>,
nearby_blocks: HashSet<ChunkColumnPosition>,
specific_entities: HashSet<Eid>,
}
#[must_use = "The observer must be added to the manager to be used"]
pub struct WorldObserverBuilder {
eid: Eid,
observer_manager: &'static WorldObserverManager,
ticks: bool,
blocks: Vec<ChunkColumnPosition>,
entities: Vec<ChunkColumnPosition>,
nearby_blocks: Vec<NearbyBlockSubscription>,
specific_entities: Vec<Eid>,
}
impl WorldObserverBuilder {
pub fn new(eid: Eid, observer_manager: &'static WorldObserverManager) -> WorldObserverBuilder {
WorldObserverBuilder {
eid,
observer_manager,
ticks: false,
blocks: Vec::new(),
nearby_blocks: Vec::new(),
entities: Vec::new(),
specific_entities: Vec::new(),
}
}
pub fn with_ticks(mut self) -> WorldObserverBuilder {
self.ticks = true;
self
}
pub fn with_blocks_in_chunk(mut self, position: ChunkColumnPosition) -> WorldObserverBuilder {
self.blocks.push(position);
self
}
pub fn with_entities_in_chunk(mut self, position: ChunkColumnPosition) -> WorldObserverBuilder {
self.entities.push(position);
self
}
pub fn with_nearby_blocks(mut self, position: BlockPosition, radius: u8) -> WorldObserverBuilder {
self.nearby_blocks.push(NearbyBlockSubscription {
position,
radius,
});
self
}
pub fn with_entity(mut self, eid: Eid) -> WorldObserverBuilder {
self.specific_entities.push(eid);
self
}
pub async fn build(self) -> WorldObserver {
let (sender, receiver) = mpsc_channel(30);
let eid = self.eid;
let observer_manager = self.observer_manager;
observer_manager.add_subscriber(eid, self, sender).await;
WorldObserver {
receiver,
eid,
observer_manager,
}
}
}
#[derive(Debug, Clone)]
struct NearbyBlockSubscription {
position: BlockPosition,
radius: u8,
}
// TODO: remove sets and maps when they are empty
// TODO: allow different observers for same entity
pub struct WorldObserverManager {
trackers: RwLock<HashMap<Eid, WorldObserverTracker>>,
ticks: RwLock<HashSet<Eid>>,
blocks: RwLock<HashMap<ChunkColumnPosition, HashMap<Eid, MpscSender<WorldChange>>>>,
entities: RwLock<HashMap<ChunkColumnPosition, HashMap<Eid, MpscSender<WorldChange>>>>,
nearby_blocks: RwLock<HashMap<ChunkColumnPosition, HashMap<Eid, (NearbyBlockSubscription, MpscSender<WorldChange>)>>>,
specific_entities: RwLock<HashMap<Eid, HashMap<Eid, MpscSender<WorldChange>>>>,
}
impl WorldObserverManager {
pub fn new() -> WorldObserverManager {
WorldObserverManager {
trackers: RwLock::new(HashMap::new()),
ticks: RwLock::new(HashSet::new()),
blocks: RwLock::new(HashMap::new()),
entities: RwLock::new(HashMap::new()),
nearby_blocks: RwLock::new(HashMap::new()),
specific_entities: RwLock::new(HashMap::new()),
}
}
async fn add_subscriber(&self, eid: Eid, observer_builder: WorldObserverBuilder, sender: MpscSender<WorldChange>) {
let mut entities = self.trackers.write().await;
if !observer_builder.blocks.is_empty() {
let mut blocks = self.blocks.write().await;
for column in &observer_builder.blocks {
blocks.entry(column.clone()).or_default().insert(eid, sender.clone());
}
}
if !observer_builder.entities.is_empty() {
let mut entities = self.blocks.write().await;
for column in &observer_builder.entities {
entities.entry(column.clone()).or_default().insert(eid, sender.clone());
}
}
let mut observer_nearby_blocks = HashSet::new();
if !observer_builder.nearby_blocks.is_empty() {
let mut nearby_blocks = self.nearby_blocks.write().await;
for nearby_block in &observer_builder.nearby_blocks {
let min_column = BlockPosition {
x: nearby_block.position.x.saturating_sub(nearby_block.radius as i32),
z: nearby_block.position.z.saturating_sub(nearby_block.radius as i32),
y: 0,
}.chunk_column();
let max_column = BlockPosition {
x: nearby_block.position.x.saturating_add(nearby_block.radius as i32),
z: nearby_block.position.z.saturating_add(nearby_block.radius as i32),
y: 0,
}.chunk_column();
for cx in min_column.cx..=max_column.cx {
for cz in min_column.cz..=max_column.cz {
nearby_blocks.entry(ChunkColumnPosition {cx, cz}).or_default().insert(eid, (nearby_block.clone(), sender.clone()));
observer_nearby_blocks.insert(ChunkColumnPosition {cx, cz});
}
}
}
}
if !observer_builder.specific_entities.is_empty() {
let mut specific_entities = self.specific_entities.write().await;
for entity in &observer_builder.specific_entities {
specific_entities.entry(*entity).or_default().insert(eid, sender.clone());
}
}
entities.insert(eid, WorldObserverTracker {
sender,
ticks: observer_builder.ticks,
blocks: observer_builder.blocks.into_iter().collect(),
entities: observer_builder.entities.into_iter().collect(),
nearby_blocks: observer_nearby_blocks,
specific_entities: observer_builder.specific_entities.into_iter().collect(),
});
}
pub async fn notify_block_change(&self, position: BlockPosition, block: BlockWithState) {
let column = position.chunk_column();
let blocks = self.blocks.read().await;
if let Some(subscribers) = blocks.get(&column) {
for sender in subscribers.values() {
let _ = sender.try_send(WorldChange::Block(position.clone(), block.clone()));
}
}
}
pub async fn notify_tick(&self, tick_id: usize) {
let ticks = self.ticks.read().await;
for eid in ticks.iter() {
let trackers = self.trackers.read().await;
if let Some(tracker) = trackers.get(eid) {
let _ = tracker.sender.try_send(WorldChange::Tick(tick_id));
}
}
}
#[inline]
async fn notify_entity_change(&self, eid: Eid, position: Position, from: Option<Position>, change: WorldChange) {
let specific_entities = self.specific_entities.read().await;
// Notify for specific entities
let specific_entities_subscribers = specific_entities.get(&eid);
if let Some(subscribers) = specific_entities_subscribers {
for sender in subscribers.values() {
let _ = sender.try_send(change.clone());
}
}
// Notify for current column those who were not already notified
let entities = self.entities.read().await;
let current_column = entities.get(&position.chunk_column());
if let Some(subscribers) = current_column {
for (subscriber, sender) in subscribers {
if specific_entities_subscribers.map(|c| c.contains_key(subscriber)).unwrap_or(true) {
let _ = sender.try_send(change.clone());
}
}
}
// Notify for previous column those who were not already notified
if let Some(from) = from {
if from.chunk_column() != position.chunk_column() {
let previous_column = entities.get(&from.chunk_column());
if let Some(subscribers) = previous_column {
for (subscriber, sender) in subscribers {
if current_column.map(|c| c.contains_key(subscriber)).unwrap_or(true) &&
specific_entities_subscribers.map(|c| c.contains_key(subscriber)).unwrap_or(true)
{
let _ = sender.try_send(change.clone());
}
}
}
}
}
}
pub async fn notify_entity_spawned(&self, eid: Eid, uuid: UUID, ty: NetworkEntity, position: Position, pitch: f32, yaw: f32, head_yaw: f32, data: u32, velocity: Translation) {
let change = WorldChange::EntitySpawned {
eid,
uuid,
ty,
position: position.clone(),
pitch,
yaw,
head_yaw,
data,
velocity,
};
self.notify_entity_change(eid, position, None, change).await;
}
pub async fn notify_entity_dispawned(&self, eid: Eid, position: Position) {
let change = WorldChange::EntityDispawned {
eid,
};
self.notify_entity_change(eid, position, None, change).await;
self.specific_entities.write().await.remove(&eid);
}
pub async fn notify_metadata_change(&self, eid: Eid, position: Position, metadata: ()) {
let change = WorldChange::EntityMetadata {
eid,
metadata,
};
self.notify_entity_change(eid, position, None, change).await;
}
pub async fn notify_entity_moved(&self, eid: Eid, from: Position, to: Position) {
let change = WorldChange::EntityPosition {
eid,
from: from.clone(),
to: to.clone(),
};
self.notify_entity_change(eid, to, Some(from), change).await;
}
pub async fn notify_entity_velocity(&self, eid: Eid, position: Position, velocity: Translation) {
let change = WorldChange::EntityVelocity {
eid,
velocity,
};
self.notify_entity_change(eid, position, None, change).await;
}
pub async fn notify_entity_pitch(&self, eid: Eid, position: Position, pitch: f32, yaw: f32, head_yaw: f32) {
let change = WorldChange::EntityPitch {
eid,
pitch,
yaw,
head_yaw,
};
self.notify_entity_change(eid, position, None, change).await;
}
pub async fn remove_subscriber(&self, eid: Eid) {
let mut entities = self.trackers.write().await;
let Some(observer) = entities.remove(&eid) else {return};
if observer.ticks {
self.ticks.write().await.remove(&eid);
}
if !observer.blocks.is_empty() {
let mut block_subscriptions = self.blocks.write().await;
for column in observer.blocks {
block_subscriptions.get_mut(&column).map(|set| set.remove(&eid));
}
}
if !observer.nearby_blocks.is_empty() {
let mut precise_block_subscriptions = self.nearby_blocks.write().await;
for column in observer.nearby_blocks {
precise_block_subscriptions.get_mut(&column).map(|map| map.remove(&eid));
}
}
if !observer.entities.is_empty() {
let mut entity_subscriptions = self.entities.write().await;
for column in observer.entities {
entity_subscriptions.get_mut(&column).map(|set| set.remove(&eid));
}
}
if !observer.specific_entities.is_empty() {
let mut specific_entity_subscriptions = self.specific_entities.write().await;
for entity in observer.specific_entities {
specific_entity_subscriptions.get_mut(&entity).map(|set| set.remove(&eid));
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_ticks() {
}
}