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
use std::{borrow::BorrowMut, cell::RefCell};

pub use egui;
pub use egui_wgpu_backend;

use egui::{pos2, ClippedMesh, CtxRef};
use egui_wgpu_backend::ScreenDescriptor;
use winit::event::VirtualKeyCode;
use winit::event::WindowEvent::*;

const OUTPUT_FORMAT: egui_wgpu_backend::wgpu::TextureFormat =
    egui_wgpu_backend::wgpu::TextureFormat::Rgba16Float;

pub struct EguiBackend {
    render_pass: RefCell<egui_wgpu_backend::RenderPass>,
    raw_input: egui::RawInput,
    modifier_state: winit::event::ModifiersState,
    pointer_pos: egui::Pos2,
    width: u32,
    height: u32,
    scale_factor: f64,
    context: egui::CtxRef,
    paint_jobs: Vec<ClippedMesh>,
}

impl EguiBackend {
    pub fn new(window: &nannou::window::Window) -> EguiBackend {
        let scale_factor = window.scale_factor() as f64;
        let width = window.inner_size_pixels().0;
        let height = window.inner_size_pixels().1;

        let raw_input = egui::RawInput {
            pixels_per_point: Some(scale_factor as f32),
            screen_rect: Some(egui::Rect::from_min_size(
                Default::default(),
                egui::vec2(width as f32, height as f32) / scale_factor as f32,
            )),
            ..Default::default()
        };

        let context = egui::CtxRef::default();
        context.set_fonts(egui::FontDefinitions::default());
        context.set_style(egui::Style::default());

        EguiBackend {
            render_pass: RefCell::new(egui_wgpu_backend::RenderPass::new(
                window.swap_chain_device(),
                OUTPUT_FORMAT,
            )),
            context,
            modifier_state: winit::event::ModifiersState::empty(),
            width,
            height,
            scale_factor,
            raw_input,
            pointer_pos: Default::default(),
            paint_jobs: Vec::new(),
        }
    }

    pub fn handle_event(&mut self, event: &winit::event::WindowEvent) {
        let mut raw_input = &mut self.raw_input;
        match event {
            Resized(physical_size) => {
                raw_input.screen_rect = Some(egui::Rect::from_min_size(
                    Default::default(),
                    egui::vec2(physical_size.width as f32, physical_size.height as f32)
                        / self.scale_factor as f32,
                ));
            }
            ScaleFactorChanged {
                scale_factor,
                new_inner_size,
            } => {
                self.scale_factor = *scale_factor;
                raw_input.pixels_per_point = Some(*scale_factor as f32);
                raw_input.screen_rect = Some(egui::Rect::from_min_size(
                    Default::default(),
                    egui::vec2(new_inner_size.width as f32, new_inner_size.height as f32)
                        / self.scale_factor as f32,
                ));
            }
            MouseInput { state, button, .. } => {
                if let winit::event::MouseButton::Other(..) = button {
                } else {
                    raw_input.events.push(egui::Event::PointerButton {
                        pos: self.pointer_pos,
                        button: match button {
                            winit::event::MouseButton::Left => egui::PointerButton::Primary,
                            winit::event::MouseButton::Right => egui::PointerButton::Secondary,
                            winit::event::MouseButton::Middle => egui::PointerButton::Middle,
                            winit::event::MouseButton::Other(_) => unreachable!(),
                        },
                        pressed: *state == winit::event::ElementState::Pressed,
                        modifiers: Default::default(),
                    });
                }
            }
            MouseWheel { delta, .. } => {
                match delta {
                    winit::event::MouseScrollDelta::LineDelta(x, y) => {
                        let line_height = 24.0;
                        raw_input.scroll_delta = egui::vec2(*x, *y) * line_height;
                    }
                    winit::event::MouseScrollDelta::PixelDelta(delta) => {
                        // Actually point delta
                        raw_input.scroll_delta = egui::vec2(delta.x as f32, delta.y as f32);
                    }
                }
            }
            CursorMoved { position, .. } => {
                self.pointer_pos = pos2(
                    position.x as f32 / self.scale_factor as f32,
                    position.y as f32 / self.scale_factor as f32,
                );
                raw_input
                    .events
                    .push(egui::Event::PointerMoved(self.pointer_pos));
            }
            CursorLeft { .. } => {
                raw_input.events.push(egui::Event::PointerGone);
            }
            ModifiersChanged(input) => self.modifier_state = *input,
            KeyboardInput { input, .. } => {
                if let Some(virtual_keycode) = input.virtual_keycode {
                    if let Some(key) = winit_to_egui_key_code(virtual_keycode) {
                        // TODO figure out why if I enable this the characters get ignored

                        raw_input.events.push(egui::Event::Key {
                            key,
                            pressed: input.state == winit::event::ElementState::Pressed,
                            // modifiers: winit_to_egui_modifiers(self.modifier_state),
                            modifiers: winit_to_egui_modifiers(self.modifier_state),
                        });
                    }
                }
            }
            ReceivedCharacter(ch) => {
                if ch.is_alphabetic() && !self.modifier_state.ctrl() && !self.modifier_state.logo()
                {
                    raw_input.events.push(egui::Event::Text(ch.to_string()));
                }
            }
            _ => {}
        }
    }

    pub fn begin_frame(&mut self) -> CtxRef {
        self.context.begin_frame(self.raw_input.borrow_mut().take());
        self.context.clone()
    }

    pub fn end_frame(&mut self) {
        let (_, paint_cmds) = self.context.end_frame();
        self.paint_jobs = self.context.tessellate(paint_cmds);
    }

    pub fn update_time(&mut self, elapsed_seconds: f64) {
        self.raw_input.time = Some(elapsed_seconds);
    }

    pub fn draw_ui_to_frame(&self, frame: &nannou::Frame) {
        let device_queue_pair = frame.device_queue_pair();
        let device = device_queue_pair.device();
        let queue = device_queue_pair.queue();
        let mut render_pass = self.render_pass.borrow_mut();
        let paint_jobs = &self.paint_jobs;
        let mut encoder = frame.command_encoder();

        let screen_descriptor = ScreenDescriptor {
            physical_width: self.width,
            physical_height: self.height,
            scale_factor: self.scale_factor as f32,
        };
        render_pass.update_texture(device, queue, &self.context.texture());
        render_pass.update_user_textures(&device, &queue);
        render_pass.update_buffers(device, queue, &paint_jobs, &screen_descriptor);

        // Record all render passes.
        render_pass.execute(
            &mut encoder,
            frame.texture_view(),
            &paint_jobs,
            &screen_descriptor,
            None,
        );
    }
}

/// Translates winit to egui keycodes.
#[inline]
fn winit_to_egui_key_code(key: VirtualKeyCode) -> Option<egui::Key> {
    use egui::Key;

    Some(match key {
        VirtualKeyCode::Escape => Key::Escape,
        VirtualKeyCode::Insert => Key::Insert,
        VirtualKeyCode::Home => Key::Home,
        VirtualKeyCode::Delete => Key::Delete,
        VirtualKeyCode::End => Key::End,
        VirtualKeyCode::PageDown => Key::PageDown,
        VirtualKeyCode::PageUp => Key::PageUp,
        VirtualKeyCode::Left => Key::ArrowLeft,
        VirtualKeyCode::Up => Key::ArrowUp,
        VirtualKeyCode::Right => Key::ArrowRight,
        VirtualKeyCode::Down => Key::ArrowDown,
        VirtualKeyCode::Back => Key::Backspace,
        VirtualKeyCode::Return => Key::Enter,
        VirtualKeyCode::Tab => Key::Tab,
        VirtualKeyCode::Space => Key::Space,

        VirtualKeyCode::A => Key::A,
        VirtualKeyCode::K => Key::K,
        VirtualKeyCode::U => Key::U,
        VirtualKeyCode::W => Key::W,
        VirtualKeyCode::Z => Key::Z,

        _ => {
            return None;
        }
    })
}

/// Translates winit to egui modifier keys.
#[inline]
fn winit_to_egui_modifiers(modifiers: winit::event::ModifiersState) -> egui::Modifiers {
    egui::Modifiers {
        alt: modifiers.alt(),
        ctrl: modifiers.ctrl(),
        shift: modifiers.shift(),
        #[cfg(target_os = "macos")]
        mac_cmd: modifiers.logo(),
        #[cfg(target_os = "macos")]
        command: modifiers.logo(),
        #[cfg(not(target_os = "macos"))]
        mac_cmd: false,
        #[cfg(not(target_os = "macos"))]
        command: modifiers.ctrl(),
    }
}