cyborg/editor/src/ui.rs

402 lines
12 KiB
Rust

use crossbeam_channel::Sender;
use cyborg::camera::Flycam;
use legion::Entity;
use std::path::PathBuf;
use crate::winit;
use crate::world::{Object, World};
#[derive(Clone, Debug)]
pub enum FileEvent {
Save,
SaveAs(PathBuf),
Import(ImportKind, PathBuf),
LoadScript(PathBuf),
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum ImportKind {
Stl,
Gltf,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Workspace {
Scene,
NodeEditor,
}
pub struct UiResources<'a> {
pub world: &'a mut World,
pub viewport: &'a mut ViewportWidget,
}
pub struct UserInterface {
file_sender: Sender<FileEvent>,
developer_mode: bool,
show_profiler: bool,
quit: bool,
show_about: bool,
show_log: bool,
log_contents: String,
workspace: Workspace,
}
impl UserInterface {
pub fn new(file_sender: Sender<FileEvent>) -> Self {
Self {
file_sender,
developer_mode: true,
show_profiler: false,
show_log: false,
quit: false,
show_about: false,
log_contents: "Hello logging!\n".to_string(),
workspace: Workspace::Scene,
}
}
pub fn should_quit(&self) -> bool {
self.quit
}
pub fn run(&mut self, ctx: &egui::Context, resources: &mut UiResources) {
egui::TopBottomPanel::top("menu_bar").show(ctx, |ui| {
egui::menu::bar(ui, |ui| self.ui_menu_bar(ui));
});
if self.show_profiler {
self.show_profiler = puffin_egui::profiler_window(ctx);
}
if self.show_about {
egui::Window::new("About")
.open(&mut self.show_about)
.resizable(false)
.collapsible(false)
.show(ctx, |ui| {
ui.vertical_centered(|ui| {
ui.heading("Cyborg Editor");
});
});
}
if self.show_log {
egui::TopBottomPanel::bottom("info_panel")
.resizable(true)
.show(ctx, |ui| {
ui.heading("Log Output");
egui::containers::ScrollArea::vertical()
.auto_shrink([false, false])
.max_width(f32::INFINITY)
.max_height(f32::INFINITY)
.show(ui, |ui| {
let text_edit = egui::TextEdit::multiline(&mut self.log_contents)
.desired_width(f32::INFINITY)
.frame(false);
ui.add(text_edit);
});
});
}
match self.workspace {
Workspace::Scene => self.ui_scene(ctx, resources),
Workspace::NodeEditor => {
egui::CentralPanel::default().show(ctx, |ui| self.ui_node_editor(ui));
}
}
}
pub fn ui_menu_bar(&mut self, ui: &mut egui::Ui) {
ui.menu_button("File", |ui| {
if self.developer_mode {
if ui.button("fuck").clicked() {
println!("fuck");
}
}
if ui.button("Save").clicked() {
ui.close_menu();
self.file_sender.send(FileEvent::Save).unwrap();
}
if ui.button("Save as...").clicked() {
ui.close_menu();
let file_sender = self.file_sender.to_owned();
std::thread::spawn(move || {
if let Some(path) = rfd::FileDialog::new().save_file() {
file_sender.send(FileEvent::SaveAs(path)).unwrap();
}
});
}
ui.menu_button("Import...", |ui| {
if ui.button("STL").clicked() {
ui.close_menu();
self.on_import(ImportKind::Stl);
}
if ui.button("glTF").clicked() {
ui.close_menu();
self.on_import(ImportKind::Gltf);
}
});
if ui.button("Load script...").clicked() {
ui.close_menu();
self.on_load_script();
}
if ui.button("Open...").clicked() {
println!("Opening!");
ui.close_menu();
}
if ui.button("Quit").clicked() {
println!("Quitting!");
ui.close_menu();
self.quit = true;
}
});
ui.menu_button("Edit", |ui| {
if ui.button("Undo").clicked() {
println!("Undoing!");
}
if ui.button("Redo").clicked() {
println!("Redoing!");
}
});
ui.menu_button("View", |ui| {
ui.checkbox(&mut self.show_log, "Log");
ui.checkbox(&mut self.developer_mode, "Developer mode");
if ui.checkbox(&mut self.show_profiler, "Profiler").changed() {
puffin_egui::puffin::set_scopes_on(self.show_profiler);
}
});
ui.menu_button("Help", |ui| {
if ui.button("About").clicked() {
self.show_about = true;
ui.close_menu();
}
});
ui.separator();
self.ui_select_workspace(ui);
}
pub fn ui_select_workspace(&mut self, ui: &mut egui::Ui) {
ui.selectable_value(&mut self.workspace, Workspace::Scene, "Scene");
ui.selectable_value(&mut self.workspace, Workspace::NodeEditor, "Node Editor");
}
pub fn ui_scene(&mut self, ctx: &egui::Context, resources: &mut UiResources) {
egui::SidePanel::left("objects_panel")
.resizable(true)
.show(ctx, |ui| self.ui_objects(ui, resources));
egui::CentralPanel::default().show(ctx, |ui| {
resources.viewport.show(ui);
ui.heading("Viewport");
});
}
pub fn ui_objects(&mut self, ui: &mut egui::Ui, resources: &mut UiResources) {
egui::ScrollArea::vertical().show(ui, |ui| {
let roots = resources.world.root_objects.to_owned();
for object in roots.into_iter() {
self.ui_object(ui, resources, object);
}
});
}
pub fn ui_object(
&mut self,
ui: &mut egui::Ui,
resources: &mut UiResources,
id: Entity,
) -> bool {
let object: &mut Object = resources.world.get_component_mut(id);
let name = object
.name
.as_ref()
.unwrap_or(&"<unnamed>".into())
.to_owned();
let children = object.children.to_owned();
let mut any_dirty = false;
egui::CollapsingHeader::new(name)
.id_source(format!("child_{:?}", id))
.default_open(true)
.show(ui, |ui| {
let object: &mut Object = resources.world.get_component_mut(id);
object.ui(ui);
for child in children.into_iter() {
if self.ui_object(ui, resources, child) {
any_dirty = true;
}
}
});
let object: &mut Object = resources.world.get_component_mut(id);
if any_dirty {
object.children_dirty = true;
}
object.dirty || any_dirty
}
pub fn ui_node_editor(&mut self, ui: &mut egui::Ui) {
ui.label("Node editor goes here!");
}
pub fn on_import(&self, kind: ImportKind) {
let kind_name = match kind {
ImportKind::Stl => "STL",
ImportKind::Gltf => "glTF",
};
let extensions: &[&str] = match kind {
ImportKind::Stl => &["stl"],
ImportKind::Gltf => &["gltf", "glb", "vrm"],
};
let file_sender = self.file_sender.to_owned();
std::thread::spawn(move || {
let dialog = rfd::FileDialog::new().add_filter(kind_name, extensions);
if let Some(paths) = dialog.pick_files() {
for path in paths.iter() {
let event = FileEvent::Import(kind, path.into());
file_sender.send(event).unwrap();
}
}
});
}
pub fn on_load_script(&self) {
let file_sender = self.file_sender.to_owned();
std::thread::spawn(move || {
let dialog = rfd::FileDialog::new().add_filter("Lua script", &["lua"]);
if let Some(path) = dialog.pick_file() {
let event = FileEvent::LoadScript(path.into());
file_sender.send(event).unwrap();
}
});
}
}
pub struct ViewportWidget {
pub texture: egui::TextureId,
pub flycam: Flycam,
pub width: u32,
pub height: u32,
pub dragging: bool,
}
impl ViewportWidget {
pub fn new(texture: egui::TextureId) -> Self {
Self {
texture,
flycam: Flycam::new(0.002, 10.0, 0.25),
width: 640,
height: 480,
dragging: false,
}
}
fn should_drag(
&self,
viewport: egui::Rect,
gizmo_active: bool,
pointer: &egui::PointerState,
) -> bool {
if gizmo_active {
false
} else if !pointer.primary_down() {
false
} else if self.dragging {
true
} else if let Some(pos) = pointer.interact_pos() {
viewport.contains(pos)
} else {
false
}
}
fn show(&mut self, ui: &mut egui::Ui) {
ui.style_mut().spacing.window_margin = egui::style::Margin::same(0.0);
let rect = ui.max_rect();
self.width = rect.width().round() as u32;
self.height = rect.height().round() as u32;
self.flycam.resize(self.width, self.height);
self.flycam.update();
use egui::{pos2, Color32, Mesh, Rect, Shape};
let mut mesh = Mesh::with_texture(self.texture);
let uv = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0));
let tint = Color32::WHITE;
mesh.add_rect_with_uv(rect, uv, tint);
ui.painter().add(Shape::mesh(mesh));
let gizmo = egui_gizmo::Gizmo::new("My gizmo")
.viewport(rect)
.view_matrix(self.flycam.get_view().to_cols_array_2d())
.projection_matrix(self.flycam.get_projection().to_cols_array_2d());
let gizmo = gizmo.interact(ui);
let input = ui.input();
self.dragging = self.should_drag(rect, gizmo.is_some(), &input.pointer);
if self.dragging {
let delta = input.pointer.delta();
self.flycam.process_mouse(delta.x as f64, delta.y as f64);
for event in input.events.iter() {
match event {
egui::Event::Key { key, pressed, .. } => {
use winit::event::{ElementState, VirtualKeyCode};
let key = match key {
egui::Key::W => Some(VirtualKeyCode::W),
egui::Key::A => Some(VirtualKeyCode::A),
egui::Key::S => Some(VirtualKeyCode::S),
egui::Key::D => Some(VirtualKeyCode::D),
// TODO remap from shift key somehow?
egui::Key::E => Some(VirtualKeyCode::E),
egui::Key::Q => Some(VirtualKeyCode::Q),
_ => None,
};
let state = if *pressed {
ElementState::Pressed
} else {
ElementState::Released
};
if let Some(key) = key {
self.flycam.process_keyboard(key, state);
}
}
_ => {}
}
}
} else {
self.flycam.defocus();
}
}
}