-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
grid.rs
344 lines (294 loc) · 11.2 KB
/
grid.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
use std::collections::HashMap;
use std::sync::Mutex;
use std::sync::{Arc, RwLock};
use std::{thread, vec};
use bevy::math::{ivec2, vec3};
use bevy::prelude::*;
use bevy::sprite::{self, Anchor};
use rayon::prelude::*;
use crate::actors::*;
use crate::atom::State;
use crate::atom::*;
use crate::chunk::*;
use crate::consts::*;
use crate::grid_api::*;
/// The grid is the chunk manager, it updates and do the chunks logic
#[derive(Component)]
pub struct Grid {
pub chunks: Vec<Arc<RwLock<Chunk>>>,
pub width: usize,
pub height: usize,
pub textures_hmap: HashMap<AssetId<Image>, usize>,
pub dt: f32,
}
#[derive(Component)]
pub struct UpdateTextures(Option<TexturesHash>);
fn grid_setup(mut commands: Commands, mut images: ResMut<Assets<Image>>) {
let side_length = (CHUNK_SIZE * ATOM_SIZE) as f32;
let (width, height) = GRID_WIDTH_HEIGHT;
let mut images_vec = vec![];
let mut chunks = vec![];
let mut textures_hmap = HashMap::new();
for y in 0..height {
for x in 0..width {
let pos = Vec2::new(x as f32 * side_length, -(y as f32) * side_length);
let index = y * GRID_WIDTH_HEIGHT.0 + x;
//Get and spawn texture/chunk image
let texture = images.add(Chunk::new_image());
images_vec.push(
commands
.spawn(SpriteBundle {
texture: texture.clone(),
sprite: Sprite {
anchor: sprite::Anchor::TopLeft,
..Default::default()
},
transform: Transform::from_xyz(pos.x, pos.y, 0.).with_scale(vec3(
ATOM_SIZE as f32,
ATOM_SIZE as f32,
1.,
)),
..Default::default()
})
.id(),
);
//Add texture to grid HashMap
textures_hmap.insert(texture.id(), index);
//Create chunk
let chunk = Chunk::new(texture, index);
//Update chunk image
let image = images.get_mut(&chunk.texture).unwrap();
chunk.update_all(image);
chunks.push(Arc::new(RwLock::new(chunk)));
}
}
commands
.spawn((
Name::new("Chunks textures"),
VisibilityBundle::default(),
TransformBundle::default(),
))
.push_children(&images_vec);
let grid = Grid {
chunks,
width,
height,
dt: 0.,
textures_hmap,
};
commands.spawn(grid);
commands.spawn(UpdateTextures(None));
}
pub fn grid_update(
mut commands: Commands,
mut grid: Query<&mut Grid>,
time: Res<Time>,
actors: Query<(&Actor, &Transform)>,
rects: Query<Entity, With<DirtyRect>>,
mut uptextures_query: Query<&mut UpdateTextures>,
) {
let mut grid = grid.single_mut();
grid.dt += time.delta_seconds();
let dt = grid.dt;
let textures_update: ParTexturesHash = Arc::new(Mutex::new(HashMap::new()));
// Get actors
let mut actors_vec = vec![];
for (actor, transform) in actors.iter() {
actors_vec.push((*actor, *transform))
}
// Take dirty rects
let dirty_rects: Vec<Option<Rect>> = grid
.chunks
.iter_mut()
.map(|chunk| chunk.write().unwrap().dirty_rect.take())
.collect();
let row_range = 0..grid.width as i32;
let column_range = 0..grid.height as i32;
// Run the 4 update steps in checker like pattern
for y_thread_off in rand_range(0..2) {
for x_thread_off in rand_range(0..2) {
let handles = Arc::new(Mutex::new(vec![]));
//Acess chunks
let y_iter = (y_thread_off..grid.height).into_par_iter().step_by(2);
y_iter.for_each(|y| {
let x_iter = (x_thread_off..grid.width).into_par_iter().step_by(2);
x_iter.for_each(|x| {
if let Some(rect) = dirty_rects[y * grid.width + x] {
let mut chunks = vec![];
// Get all 3x3 chunks for each chunk updating
for y_off in -1..=1 {
for x_off in -1..=1 {
// Checks if chunk pos is within range
if !column_range.contains(&(y as i32 + y_off))
|| !row_range.contains(&(x as i32 + x_off))
{
chunks.push(None);
continue;
}
let index = ((y as i32 + y_off) * grid.width as i32
+ x as i32
+ x_off) as usize;
chunks.push(Some(Arc::clone(&grid.chunks[index])));
}
}
let textures_update = Arc::clone(&textures_update);
let actors = actors_vec.clone();
let handle = thread::spawn(move || {
update_chunks((chunks, textures_update), dt, actors, rect)
});
Arc::clone(&handles).lock().unwrap().push(handle);
}
});
});
// Wait for update step to finish
for handle in Arc::try_unwrap(handles).unwrap().into_inner().unwrap() {
handle.join().unwrap()
}
}
}
let mut uptextures_comp = uptextures_query.single_mut();
uptextures_comp.0.replace(
Arc::try_unwrap(textures_update)
.unwrap()
.into_inner()
.unwrap(),
);
// Dirty Rect rendering
for rect in rects.iter() {
commands.entity(rect).despawn();
}
let width = grid.width;
for (i, chunk) in grid.chunks.iter_mut().enumerate() {
let rect = chunk.read().unwrap().dirty_rect;
if let Some(rect) = rect {
let chunk_x = i % width;
let chunk_y = i / width;
// Rectangle
commands
.spawn(SpriteBundle {
sprite: Sprite {
color: Color::rgba(0.25, 0.25, 0.75, 0.50),
custom_size: Some(Vec2::new(
(rect.max.x - rect.min.x + 1.) * ATOM_SIZE as f32,
(rect.max.y - rect.min.y + 1.) * ATOM_SIZE as f32,
)),
anchor: Anchor::TopLeft,
..default()
},
transform: Transform::from_translation(Vec3::new(
(chunk_x * CHUNK_SIZE * ATOM_SIZE) as f32 + (rect.min.x * ATOM_SIZE as f32),
-((chunk_y * CHUNK_SIZE * ATOM_SIZE) as f32)
- (rect.min.y * ATOM_SIZE as f32),
1.,
)),
..default()
})
.insert(DirtyRect);
}
}
}
pub fn textures_update(
grid: Query<&Grid>,
mut images: ResMut<Assets<Image>>,
mut uptextures_query: Query<&mut UpdateTextures>,
) {
let mut uptextures_hash = uptextures_query.single_mut();
let grid = grid.single();
images.iter_mut().par_bridge().for_each(|(id, image)| {
if let Some(chunk_index) = grid.textures_hmap.get(&id) {
if let Some(pos_set) = uptextures_hash
.as_ref()
.0
.as_ref()
.unwrap()
.get(chunk_index)
{
let chunk = grid.chunks[*chunk_index].read().unwrap();
chunk.update_image_positions(image, pos_set);
}
}
});
uptextures_hash.0 = None;
}
pub fn update_chunks(
chunks: UpdateChunksType,
dt: f32,
actors: Vec<(Actor, Transform)>,
dirty_rect: Rect,
) {
for y in rand_range(dirty_rect.min.y as usize..dirty_rect.max.y as usize + 1) {
for x in rand_range(dirty_rect.min.x as usize..dirty_rect.max.x as usize + 1) {
let local_pos = (ivec2(x as i32, y as i32), 4);
let pos = local_to_global(local_pos);
if !dt_updatable(&chunks, pos, dt) {
continue;
}
let mut awake_self = false;
let state;
let vel;
{
let chunk = chunks.0[local_pos.1 as usize].clone().unwrap();
let mut chunk = chunk.write().unwrap();
let atom = &mut chunk.atoms[local_pos.0.d1()];
state = atom.state;
vel = atom.velocity.is_some();
if atom.f_idle < FRAMES_SLEEP && state != State::Void && state != State::Solid {
atom.f_idle += 1;
awake_self = true;
}
}
let mut awakened = if vel {
update_particle(&chunks, pos, dt, &actors)
} else {
match state {
State::Powder => update_powder(&chunks, pos, dt, &actors),
State::Liquid => update_liquid(&chunks, pos, dt, &actors),
_ => vec![],
}
};
if awakened.contains(&pos) {
let chunk = chunks.0[local_pos.1 as usize].clone().unwrap();
let mut chunk = chunk.write().unwrap();
let atom = &mut chunk.atoms[local_pos.0.d1()];
atom.f_idle = 0;
} else if awake_self {
awakened.push(pos)
}
//TODO more efficient solution
for awoke in awakened {
for x_off in -1..=1 {
for y_off in -1..=1 {
let awoke = awoke + ivec2(x_off, y_off);
let local_pos = global_to_local(awoke);
if let Some(chunk) = &mut chunks.0[local_pos.1 as usize].clone() {
let mut chunk = chunk.write().unwrap();
let dirty_rect = &mut chunk.dirty_rect;
if let Some(dirty_rect) = dirty_rect.as_mut() {
extend_rect_if_needed(
dirty_rect,
&Vec2::new(local_pos.0.x as f32, local_pos.0.y as f32),
)
} else {
*dirty_rect = Some(Rect::new(
local_pos.0.x as f32,
local_pos.0.y as f32,
local_pos.0.x as f32,
local_pos.0.y as f32,
))
}
}
}
}
}
}
}
}
pub struct GridPlugin;
impl Plugin for GridPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Startup, grid_setup)
.add_systems(Update, (grid_update, textures_update.after(grid_update)));
}
}
#[derive(Component)]
pub struct DirtyRect;