-
Notifications
You must be signed in to change notification settings - Fork 144
Expand file tree
/
Copy pathgame.rs
More file actions
417 lines (367 loc) · 12.8 KB
/
game.rs
File metadata and controls
417 lines (367 loc) · 12.8 KB
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
use crate::{BlockUpdateCause, Network, ServerToWorkerMessage};
use crate::{
BlockUpdateEvent, CanRespawn, Dead, EntityDeathEvent, EntityDespawnEvent, Health,
HealthUpdateEvent, Name, PlayerLeaveEvent,
};
use ahash::AHashMap;
use bumpalo::Bump;
use feather_core::anvil::level::LevelData;
use feather_core::blocks::BlockId;
use feather_core::chunk_map::ChunkMap;
use feather_core::game_rules::GameRules;
use feather_core::network::{packets::DisconnectPlay, Packet};
use feather_core::text::Text;
use feather_core::util::{BlockPosition, ChunkPosition, Position};
use feather_server_config::Config;
use fecs::{Entity, Event, EventHandlers, IntoQuery, OwnedResources, Read, RefResources, World};
use rand::rngs::SmallRng;
use rand::{Rng, SeedableRng};
use smallvec::SmallVec;
use std::cell::{RefCell, RefMut};
use std::fmt::Display;
use std::ops::Deref;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Arc;
use thread_local::CachedThreadLocal;
/// Resources which can be _shared_ between threads.
/// These only require immutable access.
pub struct Shared {
/// The server configuration.
pub config: Arc<Config>,
/// General-purpose, non-cryptographic random number generator
pub rng: CachedThreadLocal<RefCell<SmallRng>>,
/// The server player count.
pub player_count: Arc<AtomicU32>, // fixme: double Arc
}
/// The `Game` resource, which acts as a central bus to bind together
/// the feather-server-* crates. Resources which are accessed frequently,
/// such as the chunk map, are stored in here.
pub struct Game {
pub chunk_map: ChunkMap,
/// Number of ticks since the program started. Can be used
/// to make a system which only runs at a fixed interval.
pub tick_count: u64,
/// Stores entities which have a hold on chunks,
/// preventing the chunk from being unloaded.
pub chunk_holders: ChunkHolders,
/// Block entity map. Each `BlockPosition` may have a block
/// entity associated with it.
pub block_entities: AHashMap<BlockPosition, Entity>,
/// The level data.
pub level: LevelData,
/// Associates chunks with the entities that reside in them. Used
/// as an acceleration structure for spacial lookups.
pub chunk_entities: ChunkEntities,
/// World time, in the Minecraft way.
pub time: Time,
/// The event handler map.
pub event_handlers: Arc<EventHandlers>,
/// Resources other than `Game`, used to run event handlers.
pub resources: Arc<OwnedResources>,
/// Shared bump allocator, reset each tick.
pub bump: CachedThreadLocal<Bump>,
/// Values which can be shared between threads.
pub shared: Arc<Shared>,
/// Gamrules
pub game_rules: GameRules,
}
impl Deref for Game {
type Target = Shared;
fn deref(&self) -> &Self::Target {
&self.shared
}
}
impl Game {
/// Handles an event or message. All handlers
/// for the given event will be run.
pub fn handle(&mut self, world: &mut World, event: impl Event) {
// TODO: optimize this by avoiding Rc clone.
let resources = Arc::clone(&self.resources);
let event_handlers = Arc::clone(&self.event_handlers);
let resources = RefResources::new(Arc::as_ref(&resources), (self,));
event_handlers.trigger(&resources, world, event);
}
/// Retrieves the block at the given position.
/// Returns `None` if the block's chunk is not loaded
/// or the coordinates are out of bounds.
pub fn block_at(&self, pos: BlockPosition) -> Option<BlockId> {
self.chunk_map.block_at(pos)
}
/// Sets the block at the given position.
///
/// Returns `false` if the block's chunk is not loaded
/// or the coordinates are out of bounds;
/// otherwise, returns `true`.
pub fn set_block_at(
&mut self,
world: &mut World,
pos: BlockPosition,
block: BlockId,
cause: BlockUpdateCause,
) -> bool {
let old = match self.block_at(pos) {
Some(block) => block,
None => return false,
};
let result = self.chunk_map.set_block_at(pos, block);
self.handle(
world,
BlockUpdateEvent {
pos,
old,
new: block,
cause,
},
);
result
}
/// Returns a bump allocator.
pub fn bump(&self) -> &Bump {
self.bump.get_or_default()
}
/// Returns a random number generator.
pub fn rng(&self) -> RefMut<impl Rng> {
self.rng
.get_or(|| RefCell::new(SmallRng::from_entropy()))
.borrow_mut()
}
/// Despawns an entity. This should be used instead of `World::despawn`
/// as it properly handles events.
pub fn despawn(&mut self, entity: Entity, world: &mut World) {
self.handle(world, EntityDespawnEvent { entity });
world.despawn(entity);
}
/// Disconnects a player.
pub fn disconnect(&mut self, player: Entity, world: &mut World, reason: impl Display) {
self.disconnect_player(player, world, &reason, &reason);
}
/// Disconnects a player.
/// Sends disconnect packet with `reason_client` and logs `reason_console` to the server console.
pub fn disconnect_and_log(
&mut self,
player: Entity,
world: &mut World,
reason_client: &Text,
reason_console: impl Display,
) {
self.disconnect_player(player, world, reason_client, reason_console);
}
fn disconnect_player(
&mut self,
player: Entity,
world: &mut World,
reason_client: impl Display,
reason_console: impl Display,
) {
let name = world.get::<Name>(player);
let network = world.get::<Network>(player);
network.send(DisconnectPlay {
reason: reason_client.to_string(),
});
let _ = network.tx.send(ServerToWorkerMessage::Disconnect);
log::info!("{} disconnected: {}", name.0, reason_console);
drop(name);
drop(network);
self.player_count.fetch_sub(1, Ordering::AcqRel);
self.handle(world, PlayerLeaveEvent { player });
self.despawn(player, world);
}
/* BROADCAST FUNCTIONS */
/// Broadcasts a packet to all online players.
pub fn broadcast_global(&self, world: &World, packet: impl Packet, neq: Option<Entity>) {
self.broadcast_global_boxed(world, Box::new(packet), neq);
}
/// Broadcasts a boxed packet to all online players.
pub fn broadcast_global_boxed(
&self,
world: &World,
packet: Box<dyn Packet>,
neq: Option<Entity>,
) {
for (entity, network) in <Read<Network>>::query().iter_entities(world.inner()) {
if neq.map(|neq| neq == entity).unwrap_or(false) {
continue;
}
network.send_boxed(packet.box_clone());
}
}
/// Broadcasts a packet to all players able to see a given chunk.
pub fn broadcast_chunk_update(
&self,
world: &World,
packet: impl Packet,
chunk: ChunkPosition,
neq: Option<Entity>,
) {
self.broadcast_chunk_update_boxed(world, Box::new(packet), chunk, neq);
}
/// Broadcasts a boxed packet to all players able to see a given chunk.
pub fn broadcast_chunk_update_boxed(
&self,
world: &World,
packet: Box<dyn Packet>,
chunk: ChunkPosition,
neq: Option<Entity>,
) {
// we can use the chunk holders structure to accelerate this
for entity in self.chunk_holders.holders_for(chunk) {
if neq.map(|neq| neq == *entity).unwrap_or(false) {
continue;
}
if let Some(network) = world.try_get::<Network>(*entity) {
network.send_boxed(packet.box_clone());
}
}
}
/// Broadcasts a packet to all players able to see a given entity.
pub fn broadcast_entity_update(
&self,
world: &World,
packet: impl Packet,
entity: Entity,
neq: Option<Entity>,
) {
self.broadcast_entity_update_boxed(world, Box::new(packet), entity, neq);
}
/// Broadcasts a boxed packet to all players able to see a given entity.
pub fn broadcast_entity_update_boxed(
&self,
world: &World,
packet: Box<dyn Packet>,
entity: Entity,
neq: Option<Entity>,
) {
// Send the packet to all players who have a hold on the entity's chunk.
let entity_chunk = world.get::<Position>(entity).chunk();
self.broadcast_chunk_update_boxed(world, packet, entity_chunk, neq);
}
/// Applies damage to the given entity. Handles all logic,
/// including killing the entity if its health drops below 1.
pub fn damage(&mut self, entity: Entity, damage: u32, world: &mut World) {
if world.has::<Dead>(entity) {
return;
}
let (old_health, new_health) = if let Some(mut health) = world.try_get_mut::<Health>(entity)
{
let old_health = health.0;
let new_health = health.0.saturating_sub(damage);
health.0 = new_health;
(Some(old_health), new_health)
} else {
(None, 0)
};
if let Some(old_health) = old_health {
self.handle(
world,
HealthUpdateEvent {
old: old_health,
new: new_health,
entity,
},
);
if new_health == 0 {
self.kill(entity, world);
}
}
}
/// Kills an entity.
pub fn kill(&mut self, entity: Entity, world: &mut World) {
// Don't kill if already on respawn screen
if world.has::<Dead>(entity) {
return;
}
self.handle(world, EntityDeathEvent { entity });
if !world.has::<CanRespawn>(entity) {
self.despawn(entity, world);
}
}
}
/// The chunk holder map contains a mapping
/// of chunk positions to any number of entities, called "holders."
/// When a chunk position has no holders, it will be queued
/// for unloading.
///
/// In addition, the chunk holders map can be used to select
/// which players to broadcast an entity movement to: a player
/// who has a chunk hold on the entity's chunk would be able to see
/// the movement, while other players would be outside of the view
/// distance. This technique allows for higher performance and
/// avoids constant nearby entity queries.
#[derive(Default, Clone, Debug)]
pub struct ChunkHolders {
pub inner: AHashMap<ChunkPosition, SmallVec<[Entity; 4]>>,
}
impl ChunkHolders {
pub fn holders_for(&self, chunk: ChunkPosition) -> &[Entity] {
self.inner
.get(&chunk)
.map(SmallVec::as_slice)
.unwrap_or(&[])
}
pub fn chunk_has_holders(&self, chunk: ChunkPosition) -> bool {
let holders = self.holders_for(chunk);
!holders.is_empty()
}
pub fn insert_holder(&mut self, chunk: ChunkPosition, holder: Entity) {
self.inner.entry(chunk).or_default().push(holder)
}
}
/// Stores which entities belong to every given chunk.
///
/// This data structure can be used to accelerate certain
/// operations, such as querying for entities
/// within some distance of a position. In addition,
/// it can be used to send all entities in a chunk
/// to a player.
///
/// Do note that the information in this structure is not necessarily up to date,
/// although a best effort is made to update the data.
#[derive(Default)]
pub struct ChunkEntities(pub AHashMap<ChunkPosition, SmallVec<[Entity; 4]>>);
impl ChunkEntities {
pub fn new() -> Self {
Self::default()
}
/// Returns a slice of entities in the given chunk.
pub fn entities_in_chunk(&self, chunk: ChunkPosition) -> &[Entity] {
self.0.get(&chunk).map(|vec| vec.as_slice()).unwrap_or(&[])
}
}
/// The current time of the world.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Time {
game_time: u64,
day_time: u64,
}
impl Time {
/// Adds some time to the time of day.
pub fn set_time_of_day(&mut self, new_time: u64) {
self.day_time = new_time;
self.day_time %= 24_000;
}
/// Adds some time to world age.
pub fn set_world_age(&mut self, new_time: u64) {
self.game_time = new_time;
}
/// Returns the time of day.
pub fn time_of_day(self) -> u64 {
self.day_time
}
/// Returns the days passed. This is calculated
/// as `time.0 / 24_000`.
pub fn days(self) -> u64 {
self.game_time / 24_000
}
/// Returns the age of the world in ticks. Equivalent to `time.0`.
pub fn world_age(self) -> u64 {
self.game_time
}
}
#[fecs::system]
pub fn reset_bump_allocators(game: &mut Game) {
game.bump.iter_mut().for_each(Bump::reset);
}
#[fecs::system]
pub fn increment_tick_count(game: &mut Game) {
game.tick_count += 1;
}