First!
commit
b0504f5861
@ -0,0 +1,9 @@
|
||||
#!/usr/bin/env bash
|
||||
# the shebang is ignored, but nice for editors
|
||||
|
||||
if type -P lorri &>/dev/null; then
|
||||
eval "$(lorri direnv)"
|
||||
else
|
||||
echo 'while direnv evaluated .envrc, could not find the command "lorri" [https://github.com/nix-community/lorri]'
|
||||
use nix
|
||||
fi
|
@ -0,0 +1,3 @@
|
||||
/target
|
||||
|
||||
Cargo.lock
|
@ -0,0 +1,27 @@
|
||||
[package]
|
||||
name = "winit_test"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
resolver = "2"
|
||||
|
||||
[dependencies]
|
||||
pollster = "0.3"
|
||||
bytemuck = { version = "1.12", features = [ "derive" ] }
|
||||
|
||||
|
||||
[dependencies.wgpu]
|
||||
version = "0.16"
|
||||
features = [ "glsl", "vulkan-portability", "webgl" ]
|
||||
|
||||
[dependencies.winit]
|
||||
version = "0.28.6"
|
||||
|
||||
[dependencies.imgui-wgpu]
|
||||
git = "https://github.com/vynwg/imgui-wgpu-rs"
|
||||
|
||||
[dependencies.imgui]
|
||||
git = "https://github.com/vynwg/imgui-rs"
|
||||
features = [ "docking" ]
|
||||
|
||||
[dependencies.imgui-winit-support]
|
||||
git = "https://github.com/vynwg/imgui-rs"
|
@ -0,0 +1,42 @@
|
||||
{ pkgs ? import <nixpkgs> { } }:
|
||||
let
|
||||
rust_overlay = import (builtins.fetchTarball "https://github.com/oxalica/rust-overlay/archive/master.tar.gz");
|
||||
pkgs = import <nixpkgs> { config.allowUnfree = true; overlays = [ rust_overlay ]; };
|
||||
rustVersion = "1.69.0";
|
||||
rust = pkgs.rust-bin.stable.${rustVersion}.default.override {
|
||||
extensions = [ "rust-src" ];
|
||||
};
|
||||
in
|
||||
pkgs.mkShell {
|
||||
buildInputs = [
|
||||
rust
|
||||
] ++ (with pkgs; [
|
||||
pkgconfig
|
||||
rust-analyzer
|
||||
cmake
|
||||
fontconfig
|
||||
xorg.libX11
|
||||
xorg.libXi
|
||||
xorg.libXcursor
|
||||
xorg.libXrandr
|
||||
xorg.libXext
|
||||
xorg.libxshmfence
|
||||
xorg.libXxf86vm
|
||||
libxkbcommon
|
||||
libGL
|
||||
glslang
|
||||
vulkan-headers
|
||||
vulkan-loader
|
||||
vulkan-validation-layers
|
||||
vulkan-tools
|
||||
]);
|
||||
|
||||
shellHook = ''
|
||||
export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:${
|
||||
with pkgs;
|
||||
lib.makeLibraryPath [ vulkan-loader libGL xorg.libXrandr xorg.libXcursor xorg.libX11 xorg.libXi libxkbcommon ]
|
||||
}"
|
||||
'';
|
||||
|
||||
RUST_BACKTRACE = 0;
|
||||
}
|
@ -0,0 +1,71 @@
|
||||
use winit::window::Window;
|
||||
use imgui_winit_support::{
|
||||
HiDpiMode,
|
||||
WinitPlatform,
|
||||
};
|
||||
use imgui_wgpu::{
|
||||
Renderer,
|
||||
RendererConfig,
|
||||
};
|
||||
use imgui::{
|
||||
Context,
|
||||
FontConfig,
|
||||
FontSource,
|
||||
ConfigFlags,
|
||||
MouseCursor,
|
||||
};
|
||||
use wgpu::{
|
||||
Queue,
|
||||
Device,
|
||||
SurfaceConfiguration,
|
||||
};
|
||||
|
||||
pub struct Imgui {
|
||||
pub context: Context,
|
||||
pub renderer: Renderer,
|
||||
pub platform: WinitPlatform,
|
||||
pub last_cursor: Option<MouseCursor>,
|
||||
}
|
||||
|
||||
impl Imgui {
|
||||
pub fn new(window: &Window, device: &Device, queue: &Queue, config: &SurfaceConfiguration) -> Self {
|
||||
let mut context = Context::create();
|
||||
let mut platform = WinitPlatform::init(&mut context);
|
||||
let scale_factor = window.scale_factor();
|
||||
|
||||
platform.attach_window(
|
||||
context.io_mut(),
|
||||
&window,
|
||||
HiDpiMode::Default,
|
||||
);
|
||||
context.set_ini_filename(None);
|
||||
|
||||
context.io_mut().font_global_scale = (1.0/scale_factor) as f32;
|
||||
context.io_mut().config_flags |= ConfigFlags::DOCKING_ENABLE;
|
||||
|
||||
let font_config = FontConfig {
|
||||
oversample_h: 1,
|
||||
pixel_snap_h: true,
|
||||
size_pixels: (13.0 * scale_factor) as f32,
|
||||
..Default::default()
|
||||
};
|
||||
let font = FontSource::DefaultFontData {
|
||||
config: Some(font_config)
|
||||
};
|
||||
context.fonts().add_font(&[font]);
|
||||
|
||||
let renderer_config = RendererConfig {
|
||||
texture_format: config.format,
|
||||
..Default::default()
|
||||
};
|
||||
let renderer = Renderer::new(&mut context, &device, &queue, renderer_config);
|
||||
let last_cursor = None;
|
||||
|
||||
Imgui {
|
||||
context,
|
||||
platform,
|
||||
renderer,
|
||||
last_cursor,
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,67 @@
|
||||
mod gui;
|
||||
mod state;
|
||||
|
||||
use std::time::Instant;
|
||||
|
||||
use gui::Imgui;
|
||||
use state::State;
|
||||
|
||||
use pollster::block_on;
|
||||
|
||||
use winit::event::Event;
|
||||
use winit::event::WindowEvent;
|
||||
use winit::event_loop::EventLoop;
|
||||
use winit::window::WindowBuilder;
|
||||
|
||||
|
||||
fn main() {
|
||||
let event_loop = EventLoop::new();
|
||||
|
||||
let window = WindowBuilder::new()
|
||||
.with_inner_size(winit::dpi::LogicalSize::new(800.0, 600.0))
|
||||
.with_title("A fantastic window!")
|
||||
.build(&event_loop)
|
||||
.expect("FFFFFFFFFFFf couldn't create window");
|
||||
|
||||
let mut state = block_on(State::new(window));
|
||||
let mut imgui = Imgui::new(&state.window, &state.device, &state.queue, &state.config);
|
||||
|
||||
let mut inst = Instant::now();
|
||||
|
||||
event_loop.run(move |event, _, control_flow| {
|
||||
//control_flow.set_wait();
|
||||
|
||||
match event {
|
||||
Event::WindowEvent {
|
||||
ref event,
|
||||
window_id,
|
||||
} if window_id == state.window().id() => if !state.input(event) {
|
||||
match event {
|
||||
WindowEvent::Resized(size) => state.resize(*size),
|
||||
WindowEvent::ScaleFactorChanged {
|
||||
new_inner_size, ..
|
||||
} => state.resize(**new_inner_size),
|
||||
WindowEvent::CloseRequested => control_flow.set_exit(),
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
Event::MainEventsCleared => state.window().request_redraw(),
|
||||
Event::RedrawRequested(_) => {
|
||||
let now = Instant::now();
|
||||
let delta = (now-inst).as_secs_f64();
|
||||
|
||||
if delta >= 0.0166666666666 {
|
||||
println!("Framerate: {:?} fps", 1.0/delta);
|
||||
|
||||
//state.render(&mut imgui);
|
||||
let now2 = Instant::now();
|
||||
println!("Renderer took {:?}s", (now2-inst).as_secs_f64());
|
||||
inst = now;
|
||||
}
|
||||
},
|
||||
_ => (),
|
||||
}
|
||||
|
||||
imgui.platform.handle_event(imgui.context.io_mut(), &state.window(), &event);
|
||||
});
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
struct VertexInput {
|
||||
@location(0) pos: vec3<f32>,
|
||||
@location(1) color: vec3<f32>,
|
||||
};
|
||||
|
||||
struct VertexOutput {
|
||||
@builtin(position) clip_position: vec4<f32>,
|
||||
@location(0) color: vec3<f32>,
|
||||
};
|
||||
|
||||
@vertex
|
||||
fn vs_main(
|
||||
model: VertexInput,
|
||||
) -> VertexOutput {
|
||||
var out: VertexOutput;
|
||||
out.color = model.color;
|
||||
out.clip_position = vec4<f32>(model.pos, 1.0);
|
||||
return out;
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
|
||||
return vec4<f32>(in.color, 1.0);
|
||||
}
|
@ -0,0 +1,388 @@
|
||||
use crate::Imgui;
|
||||
|
||||
use bytemuck::{
|
||||
Pod,
|
||||
Zeroable,
|
||||
};
|
||||
|
||||
use std::time::Instant;
|
||||
|
||||
use imgui::Condition;
|
||||
|
||||
use winit::window::Window;
|
||||
use winit::dpi::PhysicalSize;
|
||||
use winit::event::WindowEvent;
|
||||
|
||||
use wgpu::util::{
|
||||
DeviceExt,
|
||||
BufferInitDescriptor,
|
||||
};
|
||||
use wgpu::{
|
||||
Face,
|
||||
Color,
|
||||
Queue,
|
||||
Buffer,
|
||||
Device,
|
||||
LoadOp,
|
||||
Surface,
|
||||
Backends,
|
||||
Instance,
|
||||
FrontFace,
|
||||
BlendState,
|
||||
Operations,
|
||||
ColorWrites,
|
||||
PolygonMode,
|
||||
VertexState,
|
||||
BufferUsages,
|
||||
VertexFormat,
|
||||
BufferAddress,
|
||||
FragmentState,
|
||||
TextureUsages,
|
||||
PrimitiveState,
|
||||
RenderPipeline,
|
||||
VertexStepMode,
|
||||
PowerPreference,
|
||||
VertexAttribute,
|
||||
ColorTargetState,
|
||||
DeviceDescriptor,
|
||||
MultisampleState,
|
||||
PrimitiveTopology,
|
||||
InstanceDescriptor,
|
||||
VertexBufferLayout,
|
||||
RenderPassDescriptor,
|
||||
SurfaceConfiguration,
|
||||
RequestAdapterOptions,
|
||||
TextureViewDescriptor,
|
||||
CommandEncoderDescriptor,
|
||||
PipelineLayoutDescriptor,
|
||||
RenderPipelineDescriptor,
|
||||
RenderPassColorAttachment,
|
||||
};
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
|
||||
struct Vertex {
|
||||
pos: [f32; 3],
|
||||
color: [f32; 3]
|
||||
}
|
||||
|
||||
impl Vertex {
|
||||
fn desc() -> VertexBufferLayout<'static> {
|
||||
VertexBufferLayout {
|
||||
array_stride: std::mem::size_of::<Vertex>() as BufferAddress,
|
||||
step_mode: VertexStepMode::Vertex,
|
||||
attributes: &[
|
||||
VertexAttribute {
|
||||
offset: 0,
|
||||
shader_location: 0,
|
||||
format: VertexFormat::Float32x3,
|
||||
},
|
||||
VertexAttribute {
|
||||
offset: std::mem::size_of::<[f32; 3]>() as BufferAddress,
|
||||
shader_location: 1,
|
||||
format: VertexFormat::Float32x3,
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const VERTICES: &[Vertex] = &[
|
||||
Vertex { pos: [0.0, 1.0, 0.0], color: [1.0, 0.0, 0.0] },
|
||||
Vertex { pos: [-1.0, -1.0, 0.0], color: [0.0, 1.0, 0.0] },
|
||||
Vertex { pos: [1.0, -1.0, 0.0], color: [0.0, 0.0, 1.0] },
|
||||
];
|
||||
|
||||
pub struct State {
|
||||
pub queue: Queue,
|
||||
pub buffer: Buffer,
|
||||
pub device: Device,
|
||||
pub window: Window,
|
||||
pub surface: Surface,
|
||||
pub last_frame: Instant,
|
||||
pub size: PhysicalSize<u32>,
|
||||
pub config: SurfaceConfiguration,
|
||||
pub render_pipeline: RenderPipeline,
|
||||
}
|
||||
|
||||
impl State {
|
||||
pub async fn new(window: Window) -> Self {
|
||||
let instance = Instance::new(InstanceDescriptor {
|
||||
backends: Backends::all(),
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
let surface = unsafe { instance.create_surface(&window) }
|
||||
.expect("Couldn't create surface");
|
||||
|
||||
let adapter = instance
|
||||
.request_adapter(&RequestAdapterOptions {
|
||||
power_preference: PowerPreference::HighPerformance,
|
||||
compatible_surface: Some(&surface),
|
||||
force_fallback_adapter: false,
|
||||
})
|
||||
.await
|
||||
.expect("No supported adapters found");
|
||||
|
||||
|
||||
let (device, queue) = adapter
|
||||
.request_device(&DeviceDescriptor::default(), None)
|
||||
.await
|
||||
.expect("Couldn't get logic device");
|
||||
|
||||
let size = window.inner_size();
|
||||
let surface_caps = surface.get_capabilities(&adapter);
|
||||
let surface_format = surface_caps.formats
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|f| f.is_srgb())
|
||||
.unwrap_or(surface_caps.formats[0]);
|
||||
|
||||
let config = SurfaceConfiguration {
|
||||
width: size.width,
|
||||
height: size.height,
|
||||
view_formats: vec![],
|
||||
format: surface_format,
|
||||
usage: TextureUsages::RENDER_ATTACHMENT,
|
||||
alpha_mode: surface_caps.alpha_modes[0],
|
||||
present_mode: surface_caps.present_modes[0],
|
||||
};
|
||||
|
||||
surface.configure(&device, &config);
|
||||
|
||||
let last_frame = Instant::now();
|
||||
|
||||
let shader = device.create_shader_module(wgpu::include_wgsl!("shader.wgsl"));
|
||||
|
||||
let render_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDescriptor {
|
||||
label: Some("Render Pipeline Layout"),
|
||||
bind_group_layouts: &[],
|
||||
push_constant_ranges: &[],
|
||||
});
|
||||
|
||||
let render_pipeline = device.create_render_pipeline(&RenderPipelineDescriptor {
|
||||
label: Some("Render Pipeline"),
|
||||
layout: Some(&render_pipeline_layout),
|
||||
vertex: VertexState {
|
||||
module: &shader,
|
||||
entry_point: "vs_main",
|
||||
buffers: &[Vertex::desc()],
|
||||
},
|
||||
fragment: Some(FragmentState {
|
||||
module: &shader,
|
||||
entry_point: "fs_main",
|
||||
targets: &[Some(ColorTargetState {
|
||||
format: config.format,
|
||||
blend: Some(BlendState::REPLACE),
|
||||
write_mask: ColorWrites::ALL,
|
||||
})],
|
||||
}),
|
||||
primitive: PrimitiveState {
|
||||
topology: PrimitiveTopology::TriangleList,
|
||||
strip_index_format: None,
|
||||
front_face: FrontFace::Ccw,
|
||||
cull_mode: Some(Face::Back),
|
||||
polygon_mode: PolygonMode::Fill,
|
||||
unclipped_depth: false,
|
||||
conservative: false,
|
||||
},
|
||||
depth_stencil: None,
|
||||
multisample: MultisampleState {
|
||||
count: 1,
|
||||
mask: !0,
|
||||
alpha_to_coverage_enabled: false,
|
||||
},
|
||||
multiview: None,
|
||||
});
|
||||
|
||||
let buffer = device.create_buffer_init(&BufferInitDescriptor {
|
||||
label: Some("Vertex Buffer"),
|
||||
contents: bytemuck::cast_slice(VERTICES),
|
||||
usage: BufferUsages::VERTEX,
|
||||
});
|
||||
|
||||
State {
|
||||
size,
|
||||
queue,
|
||||
buffer,
|
||||
config,
|
||||
device,
|
||||
window,
|
||||
surface,
|
||||
last_frame,
|
||||
render_pipeline,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn window(&self) -> &Window {
|
||||
&self.window
|
||||
}
|
||||
|
||||
pub fn resize(&mut self, new_size: PhysicalSize<u32>) {
|
||||
if new_size.height <= 0 || new_size.width <= 0 {
|
||||
return;
|
||||
}
|
||||
|
||||
self.size = new_size;
|
||||
self.config.width = new_size.width;
|
||||
self.config.height = new_size.height;
|
||||
self.surface.configure(&self.device, &self.config);
|
||||
}
|
||||
|
||||
pub fn input(&mut self, _event: &WindowEvent) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
pub fn render(&mut self, imgui: &mut Imgui) {
|
||||
let mut profile = Instant::now();
|
||||
let now = Instant::now();
|
||||
imgui.context
|
||||
.io_mut()
|
||||
.update_delta_time(now-self.last_frame);
|
||||
self.last_frame = now;
|
||||
|
||||
{
|
||||
let n = Instant::now();
|
||||
let delta = (n-profile).as_secs_f64()*1000.0;
|
||||
profile = n;
|
||||
println!("Point 1 took: {:?}ms", delta);
|
||||
}
|
||||
|
||||
let frame = match self.surface.get_current_texture() {
|
||||
Ok(frame) => frame,
|
||||
Err(wgpu::SurfaceError::Lost) => {
|
||||
self.resize(self.size);
|
||||
return;
|
||||
},
|
||||
Err(e) => {
|
||||
println!("pauuuu {:?}", e);
|
||||
return;
|
||||
},
|
||||
};
|
||||
|
||||
{
|
||||
let n = Instant::now();
|
||||
let delta = (n-profile).as_secs_f64()*1000.0;
|
||||
profile = n;
|
||||
println!("Point 2 took: {:?}ms", delta);
|
||||
}
|
||||
|
||||
imgui.platform
|
||||
.prepare_frame(imgui.context.io_mut(), self.window())
|
||||
.expect("Failed to prepare frame");
|
||||
|
||||
{
|
||||
let n = Instant::now();
|
||||
let delta = (n-profile).as_secs_f64()*1000.0;
|
||||
profile = n;
|
||||
println!("Point3 took: {:?}ms", delta);
|
||||
}
|
||||
|
||||
let ui = imgui.context.frame();
|
||||
{
|
||||
let window = ui.window("Hello world");
|
||||
window
|
||||
.size([300.0, 100.0], Condition::FirstUseEver)
|
||||
.build(|| {
|
||||
ui.text("Hello world!");
|
||||
ui.text("This...is...imgui-rs on WGPU!");
|
||||
ui.separator();
|
||||
let mouse_pos = ui.io().mouse_pos;
|
||||
ui.text(format!(
|
||||
"Mouse Position: ({:.1},{:.1})",
|
||||
mouse_pos[0], mouse_pos[1]
|
||||
));
|
||||
});
|
||||
}
|
||||
|
||||
{
|
||||
let n = Instant::now();
|
||||
let delta = (n-profile).as_secs_f64()*1000.0;
|
||||
profile = n;
|
||||
println!("Point 4 took: {:?}ms", delta);
|
||||
}
|
||||
|
||||
if imgui.last_cursor != ui.mouse_cursor() {
|
||||
imgui.last_cursor = ui.mouse_cursor();
|
||||
imgui.platform.prepare_render(ui, &self.window());
|
||||
}
|
||||
|
||||
{
|
||||
let n = Instant::now();
|
||||
let delta = (n-profile).as_secs_f64()*1000.0;
|
||||
profile = n;
|
||||
println!("Point 5 took: {:?}ms", delta);
|
||||
}
|
||||
|
||||
let view = frame.texture.create_view(&TextureViewDescriptor::default());
|
||||
let mut encoder = self.device
|
||||
.create_command_encoder(&CommandEncoderDescriptor {
|
||||
label: None
|
||||
});
|
||||
|
||||
{
|
||||
let n = Instant::now();
|
||||
let delta = (n-profile).as_secs_f64()*1000.0;
|
||||
profile = n;
|
||||
println!("Point 6 took: {:?}ms", delta);
|
||||
}
|
||||
|
||||
{
|
||||
let render_pass = RenderPassDescriptor {
|
||||
label: Some("Render Pass"),
|
||||
color_attachments: &[Some(RenderPassColorAttachment {
|
||||
view: &view,
|
||||
resolve_target: None,
|
||||
ops: Operations {
|
||||
load: LoadOp::Clear(Color {
|
||||
r: 0.1,
|
||||
g: 0.2,
|
||||
b: 0.3,
|
||||
a: 1.0,
|
||||
}),
|
||||
store: true,
|
||||
},
|
||||
})],
|
||||
depth_stencil_attachment: None,
|
||||
};
|
||||
|
||||
let mut render_pass = encoder.begin_render_pass(&render_pass);
|
||||
|
||||
render_pass.set_pipeline(&self.render_pipeline);
|
||||
render_pass.set_vertex_buffer(0, self.buffer.slice(..));
|
||||
render_pass.draw(0..(VERTICES.len() as u32), 0..1);
|
||||
|
||||
imgui.renderer.render(
|
||||
imgui.context.render(),
|
||||
&self.queue,
|
||||
&self.device,
|
||||
&mut render_pass
|
||||
).expect("Rendering failed");
|
||||
}
|
||||
|
||||
{
|
||||
let n = Instant::now();
|
||||
let delta = (n-profile).as_secs_f64()*1000.0;
|
||||
profile = n;
|
||||
println!("Point 7 took: {:?}ms", delta);
|
||||
}
|
||||
|
||||
self.queue.submit(Some(encoder.finish()));
|
||||
|
||||
{
|
||||
let n = Instant::now();
|
||||
let delta = (n-profile).as_secs_f64()*1000.0;
|
||||
profile = n;
|
||||
println!("Point 8 took: {:?}ms", delta);
|
||||
}
|
||||
|
||||
frame.present();
|
||||
|
||||
{
|
||||
let n = Instant::now();
|
||||
let delta = (n-profile).as_secs_f64()*1000.0;
|
||||
profile = n;
|
||||
println!("Point 9 took: {:?}ms", delta);
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue