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
|
use crate::{
data::Gamedata,
game::Game,
protocol::{Message, PacketC, PacketS, PlayerID},
};
use glam::{IVec2, Vec2};
use log::{debug, error};
use rand::thread_rng;
use std::{
cmp::Ordering,
collections::{BinaryHeap, HashMap, HashSet},
sync::Arc,
time::Duration,
};
use tokio::{
sync::{broadcast, RwLock},
time::interval,
};
struct DemandState {
data: Gamedata,
walkable: HashSet<IVec2>,
chairs: HashMap<IVec2, bool>,
customers: Vec<Customer>,
}
enum CustomerState {
WalkingToChair { path: Vec<Vec2>, chair: IVec2 },
Waiting { chair: IVec2 },
}
struct Customer {
id: PlayerID,
position: Vec2,
facing: Vec2,
vel: Vec2,
state: CustomerState,
}
pub async fn customer(game: Arc<RwLock<Game>>, mut grx: broadcast::Receiver<PacketC>) {
let mut state = DemandState {
walkable: Default::default(),
chairs: Default::default(),
customers: Default::default(),
data: Gamedata::default(),
};
let initial = game.write().await.prime_client(-1);
for p in initial {
match p {
PacketC::Init { data, .. } => {
state.data = data;
}
PacketC::UpdateMap { pos, tile, .. } => {
let tilename = &state.data.tile_names[tile];
if tilename == "floor" || tilename == "door" || tilename == "chair" {
state.walkable.insert(pos);
}
if tilename == "chair" {
state.chairs.insert(pos, true);
}
}
_ => (),
}
}
let mut interval = interval(Duration::from_millis(40));
let mut packets_out = Vec::new();
loop {
tokio::select! {
packet = grx.recv() => {
match packet.unwrap() {
// TODO handle map update
_ => ()
}
}
_ = interval.tick() => {
state.tick(&mut packets_out, 0.04);
for (player,packet) in packets_out.drain(..) {
if let Err(e) = game.write().await.packet_in(player, packet) {
error!("customer misbehaved: {e}")
}
}
}
}
}
}
impl DemandState {
pub fn tick(&mut self, packets_out: &mut Vec<(PlayerID, PacketS)>, dt: f32) {
if self.customers.is_empty() {
packets_out.push((
-1,
PacketS::Join {
name: "George".to_string(),
character: 0,
},
));
let chair = select_chair(&mut self.chairs);
let path = find_path(&self.walkable, self.data.customer_spawn.as_ivec2(), chair)
.expect("no path");
self.customers.push(Customer {
id: -1,
position: self.data.customer_spawn,
facing: Vec2::X,
vel: Vec2::ZERO,
state: CustomerState::WalkingToChair { path, chair },
});
}
for p in &mut self.customers {
match &mut p.state {
CustomerState::WalkingToChair { path, chair } => {
if let Some(next) = path.last().copied() {
debug!("next {next}");
if next.distance(p.position) < if path.len() == 1 { 0.1 } else { 0.6 } {
path.pop();
}
packets_out
.push((p.id, move_player(p, &self.walkable, next - p.position, dt)));
} else {
packets_out.push((
p.id,
PacketS::Communicate {
message: Some(Message::Item(4)),
},
));
p.state = CustomerState::Waiting { chair: *chair };
}
}
CustomerState::Waiting { chair } => {
debug!("waiting")
}
}
}
}
}
pub fn select_chair(chairs: &mut HashMap<IVec2, bool>) -> IVec2 {
use rand::seq::IteratorRandom;
let (chosen, free) = chairs
.iter_mut()
.filter(|(_p, free)| **free)
.choose(&mut thread_rng())
.unwrap();
*free = false;
*chosen
}
pub fn find_path(map: &HashSet<IVec2>, from: IVec2, to: IVec2) -> Option<Vec<Vec2>> {
#[derive(Debug, PartialEq, Eq)]
struct Open(i32, IVec2, IVec2);
impl PartialOrd for Open {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.0.partial_cmp(&other.0)
}
}
impl Ord for Open {
fn cmp(&self, other: &Self) -> Ordering {
self.0.cmp(&other.0)
}
}
let mut visited = HashMap::new();
let mut open = BinaryHeap::new();
open.push(Open(1, from, from));
loop {
let Some(Open(_, p, f)) = open.pop() else {
eprintln!("{visited:?}");
return None;
};
if visited.contains_key(&p) {
continue;
}
visited.insert(p, f);
if p == to {
break;
}
for d in [IVec2::NEG_X, IVec2::NEG_Y, IVec2::X, IVec2::Y] {
let n = p + d;
if map.contains(&n) {
open.push(Open(-d.distance_squared(to), n, p));
}
}
}
let mut path = Vec::new();
let mut c = to;
loop {
path.push(c.as_vec2() + 0.5);
let cn = visited[&c];
if cn == c {
break;
}
c = cn
}
Some(path)
}
fn move_player(p: &mut Customer, map: &HashSet<IVec2>, direction: Vec2, dt: f32) -> PacketS {
let direction = direction.normalize_or_zero();
if direction.length() > 0.1 {
p.facing = direction + (p.facing - direction) * (-dt * 10.).exp();
}
let rot = p.facing.x.atan2(p.facing.y);
p.vel += direction * dt * 0.5;
p.position += p.vel;
p.vel = p.vel * (-dt * 5.).exp();
collide_player(p, map);
PacketS::Position {
pos: p.position,
rot,
}
}
const PLAYER_SIZE: f32 = 0.4;
fn collide_player(p: &mut Customer, map: &HashSet<IVec2>) {
for xo in -1..=1 {
for yo in -1..=1 {
let tile = IVec2::new(xo, yo) + p.position.as_ivec2();
if map.contains(&tile) {
continue;
}
let tile = tile.as_vec2();
let d = aabb_circle_distance(tile, tile + Vec2::ONE, p.position);
if d > PLAYER_SIZE {
continue;
}
let h = 0.01;
let d_sample_x =
aabb_circle_distance(tile, tile + Vec2::ONE, p.position + Vec2::new(h, 0.));
let d_sample_y =
aabb_circle_distance(tile, tile + Vec2::ONE, p.position + Vec2::new(0., h));
let grad = (Vec2::new(d_sample_x, d_sample_y) - d) / h;
p.position += (PLAYER_SIZE - d) * grad;
p.vel -= grad * grad.dot(p.vel);
}
}
}
fn aabb_circle_distance(min: Vec2, max: Vec2, p: Vec2) -> f32 {
(p - p.clamp(min, max)).length()
}
|