Skip to content

Commit

Permalink
Add a custom 3D demo using glow to egui_demo_app (#1546)
Browse files Browse the repository at this point in the history
  • Loading branch information
emilk committed Apr 30, 2022
1 parent bb421c7 commit 3a83a60
Show file tree
Hide file tree
Showing 7 changed files with 287 additions and 72 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions egui_demo_app/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ chrono = { version = "0.4", features = ["js-sys", "wasmbind"] }
eframe = { version = "0.17.0", path = "../eframe" }
egui = { version = "0.17.0", path = "../egui", features = ["extra_debug_asserts"] }
egui_demo_lib = { version = "0.17.0", path = "../egui_demo_lib", features = ["chrono"] }
egui_glow = { version = "0.17.0", path = "../egui_glow" }

# Optional dependencies:

Expand Down
183 changes: 183 additions & 0 deletions egui_demo_app/src/apps/custom3d.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
use std::sync::Arc;

use egui::mutex::Mutex;
use egui_glow::glow;

pub struct Custom3d {
/// Behind an `Arc<Mutex<…>>` so we can pass it to [`egui::PaintCallback`] and paint later.
rotating_triangle: Arc<Mutex<RotatingTriangle>>,
angle: f32,
}

impl Custom3d {
pub fn new(gl: &glow::Context) -> Self {
Self {
rotating_triangle: Arc::new(Mutex::new(RotatingTriangle::new(gl))),
angle: 0.0,
}
}
}

impl eframe::App for Custom3d {
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
egui::CentralPanel::default().show(ctx, |ui| {
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 0.0;
ui.label("The triangle is being painted using ");
ui.hyperlink_to("glow", "https://github.com/grovesNL/glow");
ui.label(" (OpenGL).");
});
ui.label(
"It's not a very impressive demo, but it shows you can embed 3D inside of egui.",
);

egui::Frame::canvas(ui.style()).show(ui, |ui| {
self.custom_painting(ui);
});
ui.label("Drag to rotate!");
ui.add(egui_demo_lib::egui_github_link_file!());
});
}

fn on_exit(&mut self, gl: &glow::Context) {
self.rotating_triangle.lock().destroy(gl);
}
}

impl Custom3d {
fn custom_painting(&mut self, ui: &mut egui::Ui) {
let (rect, response) =
ui.allocate_exact_size(egui::Vec2::splat(300.0), egui::Sense::drag());

self.angle += response.drag_delta().x * 0.01;

// Clone locals so we can move them into the paint callback:
let angle = self.angle;
let rotating_triangle = self.rotating_triangle.clone();

let callback = egui::PaintCallback {
rect,
callback: std::sync::Arc::new(move |_info, render_ctx| {
if let Some(painter) = render_ctx.downcast_ref::<egui_glow::Painter>() {
rotating_triangle.lock().paint(painter.gl(), angle);
} else {
eprintln!("Can't do custom painting because we are not using a glow context");
}
}),
};
ui.painter().add(callback);
}
}

struct RotatingTriangle {
program: glow::Program,
vertex_array: glow::VertexArray,
}

#[allow(unsafe_code)] // we need unsafe code to use glow
impl RotatingTriangle {
fn new(gl: &glow::Context) -> Self {
use glow::HasContext as _;

let shader_version = if cfg!(target_arch = "wasm32") {
"#version 300 es"
} else {
"#version 410"
};

unsafe {
let program = gl.create_program().expect("Cannot create program");

let (vertex_shader_source, fragment_shader_source) = (
r#"
const vec2 verts[3] = vec2[3](
vec2(0.0, 1.0),
vec2(-1.0, -1.0),
vec2(1.0, -1.0)
);
const vec4 colors[3] = vec4[3](
vec4(1.0, 0.0, 0.0, 1.0),
vec4(0.0, 1.0, 0.0, 1.0),
vec4(0.0, 0.0, 1.0, 1.0)
);
out vec4 v_color;
uniform float u_angle;
void main() {
v_color = colors[gl_VertexID];
gl_Position = vec4(verts[gl_VertexID], 0.0, 1.0);
gl_Position.x *= cos(u_angle);
}
"#,
r#"
precision mediump float;
in vec4 v_color;
out vec4 out_color;
void main() {
out_color = v_color;
}
"#,
);

let shader_sources = [
(glow::VERTEX_SHADER, vertex_shader_source),
(glow::FRAGMENT_SHADER, fragment_shader_source),
];

let shaders: Vec<_> = shader_sources
.iter()
.map(|(shader_type, shader_source)| {
let shader = gl
.create_shader(*shader_type)
.expect("Cannot create shader");
gl.shader_source(shader, &format!("{}\n{}", shader_version, shader_source));
gl.compile_shader(shader);
if !gl.get_shader_compile_status(shader) {
panic!("{}", gl.get_shader_info_log(shader));
}
gl.attach_shader(program, shader);
shader
})
.collect();

gl.link_program(program);
if !gl.get_program_link_status(program) {
panic!("{}", gl.get_program_info_log(program));
}

for shader in shaders {
gl.detach_shader(program, shader);
gl.delete_shader(shader);
}

let vertex_array = gl
.create_vertex_array()
.expect("Cannot create vertex array");

Self {
program,
vertex_array,
}
}
}

fn destroy(&self, gl: &glow::Context) {
use glow::HasContext as _;
unsafe {
gl.delete_program(self.program);
gl.delete_vertex_array(self.vertex_array);
}
}

fn paint(&self, gl: &glow::Context, angle: f32) {
use glow::HasContext as _;
unsafe {
gl.use_program(Some(self.program));
gl.uniform_1_f32(
gl.get_uniform_location(self.program, "u_angle").as_ref(),
angle,
);
gl.bind_vertex_array(Some(self.vertex_array));
gl.draw_arrays(glow::TRIANGLES, 0, 3);
}
}
}
4 changes: 2 additions & 2 deletions egui_demo_app/src/apps/mod.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
mod custom3d;
mod fractal_clock;

#[cfg(feature = "http")]
mod http_app;

pub use custom3d::Custom3d;
pub use fractal_clock::FractalClock;

#[cfg(feature = "http")]
pub use http_app::HttpApp;
Loading

0 comments on commit 3a83a60

Please sign in to comment.