rezcraft 0.2.0

Minecraft like game written in rust using wgpu, supporting both native and wasm
Documentation
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
use std::{
    rc::Rc,
    sync::{
        atomic::{AtomicBool, Ordering},
        Arc,
    },
};

use egui::{Align, Align2, Area, ComboBox, Context, CursorIcon, Layout, Order, RichText, Window};
use either::Either;

use crate::{
    game::{
        world::{Block, BlockManager, LightSource, TextureID, MAX_LIGHT_VAL},
        Player,
    },
    misc::settings::Settings,
};

pub struct UI<'a> {
    running: Arc<AtomicBool>,
    elapsed_secs: f64,
    player: Player,
    settings: &'a mut Settings,
    selected_block: &'a mut Block,
    selected_block_template: &'a mut String,
    block_manager: Rc<BlockManager>,
    loading_chunks: u32,
    saving_chunks: u32,
    selected_save: &'a mut String,
    do_save: &'a mut bool,
    do_load: &'a mut bool,
}

impl<'a> UI<'a> {
    pub fn new(
        running: Arc<AtomicBool>,
        elapsed_secs: f64,
        player: Player,
        settings: &'a mut Settings,
        selected_block: &'a mut Block,
        selected_block_template: &'a mut String,
        block_manager: Rc<BlockManager>,
        loading_chunks: u32,
        saving_chunks: u32,
        selected_save: &'a mut String,
        do_save: &'a mut bool,
        do_load: &'a mut bool,
    ) -> Self {
        Self {
            running,
            elapsed_secs,
            player,
            settings,
            selected_block,
            selected_block_template,
            block_manager,
            loading_chunks,
            saving_chunks,
            selected_save,
            do_save,
            do_load,
        }
    }

    fn show_camera(&mut self, ctx: &Context) {
        Window::new("Camera")
            .title_bar(false)
            .anchor(Align2::LEFT_TOP, [4.0, 4.0])
            .show(ctx, |ui| {
                let cam_pos = self.player.camera.pos.abs_pos();
                ui.label(format!("Pos: ({:.2}, {:.2}, {:.2})", cam_pos.x, cam_pos.y, cam_pos.z,));

                ui.label(format!(
                    "Rotation: ({:?}, {:?})",
                    self.player.camera.yaw(),
                    self.player.camera.pitch()
                ));

                let chunk_pos = self.player.camera.pos.chunk_pos();
                ui.label(format!(
                    "Chunk pos: ({}, {}, {})",
                    chunk_pos.x, chunk_pos.y, chunk_pos.z,
                ));
                let in_chunk_pos = self.player.camera.pos.in_chunk_pos_f32();
                ui.label(format!(
                    "InChunk pos: ({:.2}, {:.2}, {:.2})",
                    in_chunk_pos.x, in_chunk_pos.y, in_chunk_pos.z,
                ));
            });
    }

    fn show_crosshair(&mut self, ctx: &Context) {
        if self.settings.show_crosshair {
            Area::new("Crosshair")
                .order(Order::TOP)
                .anchor(Align2::CENTER_CENTER, [0.0, 0.0])
                .show(ctx, |ui| {
                    ui.label(RichText::new("+").strong().size(20.0));
                });
        }
    }

    #[cfg(feature = "save_system")]
    fn show_saves(&mut self, ctx: &Context) {
        Window::new("Saves")
            .collapsible(false)
            .default_width(0.01)
            .default_height(0.01)
            .show(ctx, |ui| {
                ui.group(|ui| {
                    ui.horizontal(|ui| {
                        let current_selected = self.selected_save.clone();

                        ui.label("Select save:");
                        egui::ComboBox::from_label("")
                            .selected_text(format!("{:?}", current_selected))
                            .show_ui(ui, |ui| {
                                let available_saves = crate::misc::save_helper::available_saves();

                                if !available_saves.contains(&self.selected_save.clone()) {
                                    ui.selectable_value(
                                        self.selected_save,
                                        self.selected_save.clone(),
                                        RichText::new(format!("{:?}", self.selected_save.clone())).italics(),
                                    );
                                }
                                for save_name in available_saves {
                                    ui.selectable_value(
                                        self.selected_save,
                                        save_name.clone(),
                                        format!("{:?}", save_name),
                                    );
                                }
                            });
                    });

                    ui.horizontal(|ui| {
                        ui.label("Rename save:");
                        ui.text_edit_singleline(self.selected_save);
                    });
                });

                ui.group(|ui| {
                    ui.horizontal(|ui| {
                        *self.do_save = ui.button("Save").clicked();
                        *self.do_load = ui.button("Load").clicked();
                    });
                });
            });
    }

    fn show_performance(&mut self, ctx: &Context) {
        Window::new("Performance")
            .title_bar(false)
            .anchor(Align2::RIGHT_TOP, [-4.0, 4.0])
            .show(ctx, |ui| {
                let frame_time = self.elapsed_secs * 1000.0;
                let fps = 1.0 / self.elapsed_secs;

                ui.label(format!("FPS: {:.2}", fps));
                ui.label(format!("Frametime: {:.2} ms", frame_time));
            });
    }

    fn show_resume(&mut self, ctx: &Context) {
        Area::new("Paused")
            .order(Order::TOP)
            .anchor(Align2::CENTER_CENTER, [0.0, 0.0])
            .show(ctx, |ui| {
                self.running.store(
                    ui.button(RichText::new("RESUME").heading()).clicked() ^ self.running.load(Ordering::Relaxed),
                    Ordering::Relaxed,
                );

                #[cfg(target_arch = "wasm32")]
                if self.running.load(Ordering::Relaxed) {
                    crate::misc::wasm::request_pointer_lock()
                }
            });
    }

    fn show_edit_block(&mut self, ctx: &Context) {
        Window::new("Edit block").collapsible(false).default_width(0.01).default_height(0.01).show(ctx, |ui| {
            ui.group(|ui| {
                ui.with_layout(Layout::top_down(Align::Center), |ui| {
                    ui.label("Template");
                });

                ComboBox::from_label("Select template").selected_text(self.selected_block_template.to_owned()).show_ui(ui, |ui| {
                    for block_name in self.block_manager.all_rendered_block_names() {
                        ui.selectable_value(self.selected_block_template, block_name.clone(), block_name);
                    }
                });

                if ui.button("Load template").clicked() {
                    *self.selected_block = Block::new_with_default(self.selected_block_template, self.block_manager.as_ref())
                }
            });

            if let Some(textures) = self.selected_block.texture_id() {
                match textures {
                    Either::Left(texture_id) => {
                        if let Some(mut texture_name) = self.block_manager.get_texture_name(texture_id) {
                            ui.group(|ui| {
                                ui.with_layout(Layout::top_down(Align::Center), |ui| {
                                    ui.label("Texture");
                                });

                                ComboBox::from_label("Select texture").selected_text(texture_name) .show_ui(ui, |ui| {
                                    for possible_texture_name in self.block_manager.all_texture_names() {
                                        ui.selectable_value(&mut texture_name,possible_texture_name, possible_texture_name );
                                    }
                                });

                                ui.separator();

                                if ui.button("Make sides have different textures").clicked() {
                                    self.selected_block.set_texture_id(Some(Either::Right([TextureID::from(texture_name.as_str()), TextureID::from(texture_name.as_str()),TextureID::from(texture_name.as_str())])))
                                } else {
                                    self.selected_block.set_texture_id(Some(Either::Left(TextureID::from(texture_name.as_str()))))
                                }
                            });
                        }
                    }
                    Either::Right([texture_id_top, texture_id_side, texture_id_bottom]) => {
                        if let [Some(mut texture_name_top), Some(mut texture_name_side), Some(mut texture_name_bottom)] = [
                            self.block_manager.get_texture_name(texture_id_top),
                            self.block_manager.get_texture_name(texture_id_side),
                            self.block_manager.get_texture_name(texture_id_bottom),
                        ] {
                            ui.group(|ui| {
                                ui.with_layout(Layout::top_down(Align::Center), |ui| {
                                    ui.label("Textures");
                                });

                                ComboBox::from_label("Select top texture") .selected_text(texture_name_top) .show_ui(ui, |ui| {
                                    for possible_texture_name in self.block_manager.all_texture_names() {
                                        ui.selectable_value(&mut texture_name_top, possible_texture_name, possible_texture_name);
                                    }
                                });
                                ComboBox::from_label("Select side texture") .selected_text(texture_name_side) .show_ui(ui, |ui| {
                                    for possible_texture_name in self.block_manager.all_texture_names() {
                                        ui.selectable_value(&mut texture_name_side, possible_texture_name, possible_texture_name);
                                    }
                                });
                                ComboBox::from_label("Select bottom texture") .selected_text(texture_name_bottom) .show_ui(ui, |ui| {
                                    for possible_texture_name in self.block_manager.all_texture_names() {
                                        ui.selectable_value(&mut texture_name_bottom, possible_texture_name, possible_texture_name);
                                    }
                                });

                                ui.separator();

                                if ui.button("Make sides share a texture").clicked() {
                                    self.selected_block.set_texture_id(Some(Either::Left(TextureID::from(texture_name_top.as_str()))))
                                } else {
                                    self.selected_block.set_texture_id(Some(Either::Right([TextureID::from(texture_name_top.as_str()), TextureID::from(texture_name_side.as_str()),TextureID::from(texture_name_bottom.as_str())])))
                                }

                            });
                        }
                    }
                }

                ui.group(|ui| {
                    ui.with_layout(Layout::top_down(Align::Center), |ui| {
                        ui.label("Light source");
                    });

                    if let Some(light_source) = self.selected_block.light_source_mut() {
                        let light_source_old = light_source.clone();

                        ui.horizontal(|ui| {
                            ui.checkbox(&mut light_source.red, "Red");
                            ui.checkbox(&mut light_source.green, "Green");
                            ui.checkbox(&mut light_source.blue, "Blue");
                        });
                        ui.add(egui::Slider::new(&mut light_source.strength, 1..=MAX_LIGHT_VAL).text("Light strength"));

                        ui.separator();

                        if !light_source.is_valid() {
                            if light_source_old.is_valid() {
                                self.selected_block.set_light_source(Some(light_source_old));
                            } else {
                                self.selected_block.set_light_source(Some(LightSource::default()))
                            }
                        }

                        if ui.button("Remove light source").clicked() {
                            self.selected_block.set_light_source(None)
                        }
                    } else {
                        if ui.button("Add light source").clicked() {
                            self.selected_block.set_light_source(Some(LightSource::default()))
                        }
                    }
                });

                {
                    ui.group(|ui| {
                        ui.with_layout(Layout::top_down(Align::Center), |ui| {
                            ui.label("Properties");
                        });

                        ui.checkbox(&mut self.selected_block.is_transparent_mut(), "Transparent");
                        ui.checkbox(&mut self.selected_block.is_solid_mut(), "Solid");
                    });
                }
            }
        });
    }

    fn show_settings(&mut self, ctx: &Context) {
        Window::new("Settings")
            .collapsible(false)
            .default_width(0.01)
            .default_height(0.01)
            .show(ctx, |ui| {
                ui.group(|ui| {
                    ui.with_layout(Layout::top_down(Align::Center), |ui| {
                        ui.label("Render distance");
                    });

                    ui.add(
                        egui::Slider::new(&mut self.settings.render_distance_horizontal, 2..=32)
                            .text("Horizontal radius"),
                    );
                    ui.add(
                        egui::Slider::new(&mut self.settings.render_distance_vertical, 2..=32).text("Vertical radius"),
                    );
                });

                ui.group(|ui| {
                    ui.with_layout(Layout::top_down(Align::Center), |ui| {
                        ui.label("Camera");
                    });

                    ui.add(egui::Slider::new(&mut self.settings.camera_speed, 1.0..=100.0).text("Movement speed"));
                    ui.add(
                        egui::Slider::new(&mut self.settings.camera_sensitivity, 0.01..=5.0).text("Mouse sensitivity"),
                    );
                    ui.add(egui::Slider::new(&mut self.settings.vertical_fov, 1.0..=179.0).text("Vertical FOV"));
                });

                ui.group(|ui| {
                    ui.with_layout(Layout::top_down(Align::Center), |ui| {
                        ui.label("Physics");
                    });

                    ui.checkbox(&mut self.settings.collision, "Collision detection");
                });

                ui.group(|ui| {
                    ui.with_layout(Layout::top_down(Align::Center), |ui| {
                        ui.label("UI");
                    });

                    ui.checkbox(&mut self.settings.show_crosshair, "Show Crosshair");
                    ui.checkbox(&mut self.settings.show_performance, "Show Performance info");
                    ui.checkbox(&mut self.settings.show_camera, "Show Camera info");
                    ui.checkbox(&mut self.settings.show_working, "Show Progress when loading / saving");
                });

                ui.group(|ui| {
                    ui.with_layout(Layout::top_down(Align::Center), |ui| {
                        ui.label("Rendering");
                    });

                    ui.horizontal(|ui| {
                        ui.label("Sky color");
                        egui::widgets::color_picker::color_edit_button_rgb(ui, &mut self.settings.sky_color);
                    });
                    ui.add(egui::Slider::new(&mut self.settings.sunlight_intensity, 0..=15).text("Sunlight intensity"));
                    ui.add(egui::Slider::new(&mut self.settings.base_light_value, 0.0..=0.1).text("Base light value"));
                    ui.add(
                        egui::Slider::new(&mut self.settings.light_power_factor, 1.0..=2.0).text("Light power factor"),
                    );
                });
            });
    }

    fn show_working(&mut self, ctx: &Context) {
        Window::new("Working...")
            .collapsible(false)
            .anchor(Align2::LEFT_BOTTOM, [4.0, -4.0])
            .show(ctx, |ui| {
                if self.saving_chunks > 0 {
                    ui.label(format!("Saving {} chunks...", self.saving_chunks));
                }
                if self.loading_chunks > 0 {
                    ui.label(format!("Loading {} chunks...", self.loading_chunks));
                }
            });
    }
}

impl<'a> crate::engine::GUI for UI<'a> {
    fn show_ui(&mut self, ctx: &Context) {
        ctx.set_cursor_icon(if self.running.load(Ordering::Relaxed) {
            CursorIcon::None
        } else {
            CursorIcon::default()
        });

        if self.settings.show_working && (self.saving_chunks > 0 || self.loading_chunks > 26) {
            self.show_working(ctx);
        }

        if self.settings.show_performance {
            self.show_performance(ctx);
        }
        if self.settings.show_camera {
            self.show_camera(ctx);
        }

        if self.running.load(Ordering::Relaxed) {
            self.show_crosshair(ctx);
        } else {
            self.show_resume(ctx);
            self.show_settings(ctx);

            #[cfg(feature = "save_system")]
            self.show_saves(ctx);

            self.show_edit_block(ctx);
        }
    }

    fn elapsed_secs(&self) -> f64 {
        self.elapsed_secs
    }
}