-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
particle.rs
347 lines (297 loc) · 13.1 KB
/
particle.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
use std::{collections::HashMap, hash::BuildHasherDefault, sync::Arc};
use super::{
chunk_access::FSChunkAccess, entity::Hitbox, material::MaterialInstance, Position, TickTime,
Velocity,
};
use crate::game::common::world::{
chunk_index, chunk_update_order, material::PhysicsType, pixel_to_chunk_pos,
pixel_to_chunk_pos_with_chunk_size, ChunkState, PassThroughHasherU32,
};
use itertools::Itertools;
use rand::prelude::Distribution;
use rayon::iter::{IntoParallelIterator, ParallelExtend, ParallelIterator};
use serde::{Deserialize, Serialize};
use specs::{Entities, Join, Read, ReadStorage, System, Write};
const PARTICLE_CHUNK_SIZE: u16 = 64;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Particle {
pub material: MaterialInstance,
pub pos: Position,
pub vel: Velocity,
pub in_object_state: InObjectState,
pub chunk_cache: (u32, u8), // (chunk index, chunk update order) TODO: make chunk update order a type?
}
impl Particle {
pub fn new(material: MaterialInstance, pos: Position, vel: Velocity) -> Self {
let (chunk_x, chunk_y) =
pixel_to_chunk_pos_with_chunk_size(pos.x as i64, pos.y as i64, PARTICLE_CHUNK_SIZE);
Self {
material,
chunk_cache: (
chunk_index(chunk_x, chunk_y),
chunk_update_order(chunk_x, chunk_y),
),
pos,
vel,
in_object_state: InObjectState::FirstFrame,
}
}
}
// #[derive(Debug, Clone, Serialize, Deserialize)]
// pub struct Particle {
// pub material: MaterialInstance,
// in_object_state: InObjectState,
// }
// impl Particle {
// pub fn of(material: MaterialInstance) -> Self {
// Self {
// material,
// in_object_state: InObjectState::FirstFrame,
// }
// }
// }
// impl Component for Particle {
// type Storage = VecStorage<Self>;
// }
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Clone)]
pub enum InObjectState {
FirstFrame,
Inside,
Outside,
}
// #[derive(Debug, Default, Clone, Serialize, Deserialize)]
// pub struct Sleep;
// impl Component for Sleep {
// type Storage = NullStorage<Self>;
// }
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct ParticleSystem {
pub active: Vec<Particle>,
pub sleeping: Vec<Particle>,
}
pub struct UpdateParticles<'a, H: FSChunkAccess + Send + Sync> {
pub chunk_handler: &'a mut H,
}
impl<'a, H: FSChunkAccess + Send + Sync> System<'a> for UpdateParticles<'a, H> {
#[allow(clippy::type_complexity)]
type SystemData = (
Entities<'a>,
Write<'a, ParticleSystem>,
ReadStorage<'a, Position>,
ReadStorage<'a, Velocity>,
ReadStorage<'a, Hitbox>,
Read<'a, TickTime>,
);
fn run(&mut self, data: Self::SystemData) {
let (entities, mut system, pos, vel, hitbox, tick_time) = data;
profiling::scope!(
"UpdateParticles::run",
format!("n = {}/{}", system.active.len(), system.sleeping.len()).as_str()
);
let chunk_handler = &mut *self.chunk_handler;
// system.active.push(Particle::new(
// MaterialInstance {
// material_id: material::TEST,
// physics: PhysicsType::Sand,
// color: Color::rgb(64, 255, 255),
// },
// Position { x: (rand::random::<f64>() - 0.5) * 10.0, y: -100.0 },
// Velocity {
// x: (rand::random::<f64>() - 0.5) * 4.0,
// y: (rand::random::<f64>() - 0.75) * 2.0,
// },
// ));
if tick_time.0 % 29 == 0 {
profiling::scope!("active->sleep");
// TODO: use std version once stable
use drain_filter_polyfill::VecExt;
#[allow(unstable_name_collisions)]
let mut removed = system.active.drain_filter(|p| {
!matches!(chunk_handler.chunk_at_dyn(pixel_to_chunk_pos(p.pos.x as i64, p.pos.y as i64)), Some(c) if c.state() == ChunkState::Active)
}).collect::<Vec<_>>();
system.sleeping.append(&mut removed);
} else if tick_time.0 % 29 == 10 {
profiling::scope!("sleep->active");
// TODO: use std version once stable
use drain_filter_polyfill::VecExt;
#[allow(unstable_name_collisions)]
let mut removed = system.sleeping.drain_filter(|p| {
matches!(chunk_handler.chunk_at_dyn(pixel_to_chunk_pos(p.pos.x as i64, p.pos.y as i64)), Some(c) if c.state() == ChunkState::Active)
}).collect::<Vec<_>>();
system.active.append(&mut removed);
}
self.move_particles(&mut system);
Self::interact_with_entities(&mut system, &entities, &hitbox, &pos, &vel);
}
}
impl<H: FSChunkAccess + Send + Sync> UpdateParticles<'_, H> {
fn move_particles(&mut self, system: &mut Write<ParticleSystem>) {
profiling::scope!("move_particles");
// ok so there's some pretty unsafe stuff going on here in order to get parallelism working
// chunk_handler is mutably borrowed many times on different threads in order to call get, set, and displace
// I don't know if HashMap::get is "thread-sound". Assuming it is, the reads/writes to the chunk buffer arrays
// should be sound assuming our invariant of no particle being allowed to move > CHUNK_SIZE/2 per tick (TODO: this is not enforced anywhere)
// TODO: look into replacing the chunks HashMap with https://crates.io/crates/evmap or https://crates.io/crates/chashmap so it's actually sound
struct ForceSendSync<T> {
value: T,
}
unsafe impl<T> Send for ForceSendSync<T> {}
unsafe impl<T> Sync for ForceSendSync<T> {}
let async_chunk_handler =
Arc::new(ForceSendSync::<*mut &mut H> { value: &mut self.chunk_handler });
let parts: Vec<_> = {
profiling::scope!("sort+group");
let mut maps = [
HashMap::<u32, Vec<Particle>, BuildHasherDefault<PassThroughHasherU32>>::default(),
HashMap::<u32, Vec<Particle>, BuildHasherDefault<PassThroughHasherU32>>::default(),
HashMap::<u32, Vec<Particle>, BuildHasherDefault<PassThroughHasherU32>>::default(),
HashMap::<u32, Vec<Particle>, BuildHasherDefault<PassThroughHasherU32>>::default(),
];
for p in system.active.drain(..) {
// safety: p.chunk_cache.1 is a chunk order number, assumed to be 0..=3
unsafe { maps.get_unchecked_mut(p.chunk_cache.1 as usize) }
.entry(p.chunk_cache.0)
.or_insert_with(Vec::new)
.push(p);
}
maps.into_iter()
.map(|m| m.into_values().collect_vec())
.collect()
};
for p in parts {
profiling::scope!("phase", format!("n_chunks = {}", p.len()).as_str());
let v = p.into_par_iter().flat_map_iter(|mut chunk_px| {
profiling::scope!("chunk");
chunk_px.retain_mut(|part| {
// TODO: this reborrow is UB
let unsafe_async_chunk_handler =
unsafe { &mut **((async_chunk_handler.clone()).value) };
let res = Self::process_particle(part, unsafe_async_chunk_handler);
let (chunk_x, chunk_y) = pixel_to_chunk_pos_with_chunk_size(
part.pos.x as i64,
part.pos.y as i64,
PARTICLE_CHUNK_SIZE,
);
part.chunk_cache = (
chunk_index(chunk_x, chunk_y),
chunk_update_order(chunk_x, chunk_y),
);
res
});
chunk_px
});
{
profiling::scope!("par_extend");
system.active.par_extend(v);
}
}
}
fn interact_with_entities(
system: &mut Write<ParticleSystem>,
entities: &Entities,
hitbox: &ReadStorage<Hitbox>,
pos: &ReadStorage<Position>,
vel: &ReadStorage<Velocity>,
) {
profiling::scope!("interact_with_entities");
for part in &mut system.active {
// profiling::scope!("Particle");
// let (chunk_x, chunk_y) = chunk_handler.pixel_to_chunk_pos(my_pos.x as i64, my_pos.y as i64);
// // skip if chunk not active
// if !matches!(chunk_handler.get_chunk(chunk_x, chunk_y), Some(c) if c.get_state() == ChunkState::Active) {
// return;
// }
(entities, hitbox, pos).join().for_each(|(p_ent, hb, pos)| {
if part.pos.x >= f64::from(hb.x1) + pos.x
&& part.pos.y >= f64::from(hb.y1) + pos.y
&& part.pos.x < f64::from(hb.x2) + pos.x
&& part.pos.y < f64::from(hb.y2) + pos.y
{
let p = vel.get(p_ent).cloned();
let mp = Some(&mut part.vel);
if let (Some(mp), Some(p)) = (mp, p) {
mp.x += (-p.x - mp.x) * 0.5
+ rand::distributions::Uniform::from(-1.0..=1.0)
.sample(&mut rand::thread_rng());
mp.y += (-p.y - mp.y) * 0.25
+ rand::distributions::Uniform::from(-1.0..=1.0)
.sample(&mut rand::thread_rng());
}
}
});
}
}
fn process_particle(part: &mut Particle, chunk_handler: &mut impl FSChunkAccess) -> bool {
let lx = part.pos.x;
let ly = part.pos.y;
part.vel.y += 0.1;
let dx = part.vel.x;
let dy = part.vel.y;
let steps = (dx.abs() + dy.abs()).sqrt() as u32 + 1;
{
// profiling::scope!("loop", format!("steps = {}", steps).as_str());
// let mut last_step_x = pos.x as i64;
// let mut last_step_y = pos.y as i64;
for s in 0..steps {
// profiling::scope!("step");
let thru = f64::from(s + 1) / f64::from(steps);
part.pos.x = lx + dx * thru;
part.pos.y = ly + dy * thru;
// this check does catch repeated steps, but actually makes performance slightly worse
// if pos.x as i64 != last_step_x || pos.y as i64 != last_step_y {
if let Ok(mat) = chunk_handler.pixel(part.pos.x as i64, part.pos.y as i64) {
if mat.physics == PhysicsType::Air {
part.in_object_state = InObjectState::Outside;
} else {
let is_object = mat.physics == PhysicsType::Object;
match part.in_object_state {
InObjectState::FirstFrame => {
if is_object {
part.in_object_state = InObjectState::Inside;
} else {
part.in_object_state = InObjectState::Outside;
}
},
InObjectState::Inside => {
if !is_object {
part.in_object_state = InObjectState::Outside;
}
},
InObjectState::Outside => {},
}
if !is_object || part.in_object_state == InObjectState::Outside {
match chunk_handler.pixel(lx as i64, ly as i64) {
Ok(m) if m.physics != PhysicsType::Air => {
let succeeded = chunk_handler.displace_pixel(
part.pos.x as i64,
part.pos.y as i64,
part.material.clone(),
);
if succeeded {
return false;
}
// upwarp if completely blocked
part.vel.y = -1.0;
part.pos.y -= 16.0;
break;
},
_ => {
if chunk_handler
.set_pixel(lx as i64, ly as i64, part.material.clone())
.is_ok()
{
return false;
}
},
}
}
}
}
// }
// last_step_x = pos.x as i64;
// last_step_y = pos.y as i64;
}
}
true
}
}