librashader/librashader-runtime-wgpu/tests/hello_triangle.rs

368 lines
13 KiB
Rust
Raw Normal View History

2024-01-18 14:35:52 +11:00
use std::sync::Arc;
2023-11-30 16:52:49 +11:00
use winit::{
event::*,
window::{Window, WindowBuilder},
};
2024-02-06 17:32:08 +11:00
use librashader_common::Viewport;
use librashader_presets::ShaderPreset;
2024-02-07 10:42:32 +11:00
use librashader_runtime_wgpu::FilterChainWgpu;
2023-11-30 16:52:49 +11:00
use wgpu::util::DeviceExt;
use winit::event_loop::EventLoopBuilder;
use winit::platform::windows::EventLoopBuilderExtWindows;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::prelude::*;
#[repr(C)]
#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
struct Vertex {
position: [f32; 3],
color: [f32; 3],
}
impl Vertex {
fn desc<'a>() -> wgpu::VertexBufferLayout<'a> {
wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<Vertex>() as wgpu::BufferAddress,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &[
wgpu::VertexAttribute {
offset: 0,
shader_location: 0,
format: wgpu::VertexFormat::Float32x3,
},
wgpu::VertexAttribute {
offset: std::mem::size_of::<[f32; 3]>() as wgpu::BufferAddress,
shader_location: 1,
format: wgpu::VertexFormat::Float32x3,
},
],
2023-11-30 16:52:49 +11:00
}
}
}
const VERTICES: &[Vertex] = &[
Vertex {
// top
2023-11-30 16:52:49 +11:00
position: [0.0, 0.5, 0.0],
color: [1.0, 0.0, 0.0],
},
Vertex {
// bottom left
2023-11-30 16:52:49 +11:00
position: [-0.5, -0.5, 0.0],
color: [0.0, 1.0, 0.0],
},
Vertex {
// bottom right
2023-11-30 16:52:49 +11:00
position: [0.5, -0.5, 0.0],
color: [0.0, 0.0, 1.0],
},
];
2024-01-18 14:35:52 +11:00
struct State<'a> {
surface: wgpu::Surface<'a>,
device: Arc<wgpu::Device>,
queue: Arc<wgpu::Queue>,
2023-11-30 16:52:49 +11:00
config: wgpu::SurfaceConfiguration,
size: winit::dpi::PhysicalSize<u32>,
clear_color: wgpu::Color,
render_pipeline: wgpu::RenderPipeline,
vertex_buffer: wgpu::Buffer,
num_vertices: u32,
2024-02-07 10:42:32 +11:00
chain: FilterChainWgpu,
2024-02-06 17:32:08 +11:00
frame_count: usize,
2023-11-30 16:52:49 +11:00
}
2024-01-18 14:35:52 +11:00
impl<'a> State<'a> {
async fn new(window: &'a Window) -> Self {
2023-11-30 16:52:49 +11:00
let size = window.inner_size();
let instance = wgpu::Instance::default();
2024-02-06 17:58:39 +11:00
let surface = instance.create_surface(window).unwrap();
2023-11-30 16:52:49 +11:00
// NOTE: could be none, see: https://sotrh.github.io/learn-wgpu/beginner/tutorial2-surface/#state-new
let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::default(),
compatible_surface: Some(&surface),
force_fallback_adapter: false,
})
.await
.unwrap();
let (device, queue) = adapter
2023-11-30 16:52:49 +11:00
.request_device(
&wgpu::DeviceDescriptor {
2024-08-01 16:06:28 +10:00
required_features: wgpu::Features::ADDRESS_MODE_CLAMP_TO_BORDER
| wgpu::Features::PIPELINE_CACHE
| wgpu::Features::TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES
| wgpu::Features::FLOAT32_FILTERABLE,
2024-01-18 14:35:52 +11:00
required_limits: wgpu::Limits::default(),
2023-11-30 16:52:49 +11:00
label: None,
2024-08-01 16:06:28 +10:00
memory_hints: Default::default(),
2023-11-30 16:52:49 +11:00
},
None,
)
.await
.unwrap();
let swapchain_capabilities = surface.get_capabilities(&adapter);
let swapchain_format = swapchain_capabilities.formats[0];
let config = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_DST,
2023-11-30 16:52:49 +11:00
format: swapchain_format,
width: size.width,
height: size.height,
present_mode: wgpu::PresentMode::Fifo,
2024-01-18 14:35:52 +11:00
desired_maximum_frame_latency: 2,
2023-11-30 16:52:49 +11:00
alpha_mode: swapchain_capabilities.alpha_modes[0],
view_formats: vec![],
};
2024-01-18 14:35:52 +11:00
let device = Arc::new(device);
let queue = Arc::new(queue);
//
2024-08-01 16:06:28 +10:00
// let preset = ShaderPreset::try_parse("../test/basic.slangp").unwrap();
//
let preset = ShaderPreset::try_parse("../test/shaders_slang/test/feedback.slangp").unwrap();
2024-01-18 14:35:52 +11:00
// let preset = ShaderPreset::try_parse(
// "../test/shaders_slang/bezel/Mega_Bezel/Presets/MBZ__0__SMOOTH-ADV.slangp",
// )
// .unwrap();
2024-01-18 14:35:52 +11:00
2024-02-07 10:42:32 +11:00
let chain = FilterChainWgpu::load_from_preset(
2024-02-06 17:58:39 +11:00
preset,
Arc::clone(&device),
Arc::clone(&queue),
2024-02-06 17:58:39 +11:00
None,
)
.unwrap();
2024-01-18 14:35:52 +11:00
2023-11-30 16:52:49 +11:00
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Shader"),
source: wgpu::ShaderSource::Wgsl(include_str!("../shader/triangle.wgsl").into()),
});
let render_pipeline_layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Render Pipeline Layout"),
bind_group_layouts: &[],
push_constant_ranges: &[],
});
let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Render Pipeline"),
layout: Some(&render_pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: "vs_main",
2024-08-01 16:06:28 +10:00
compilation_options: Default::default(),
buffers: &[Vertex::desc()],
2023-11-30 16:52:49 +11:00
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: "fs_main",
2024-08-01 16:06:28 +10:00
compilation_options: Default::default(),
2023-11-30 16:52:49 +11:00
targets: &[Some(wgpu::ColorTargetState {
format: config.format,
blend: Some(wgpu::BlendState::REPLACE),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
strip_index_format: None,
front_face: wgpu::FrontFace::Ccw,
cull_mode: Some(wgpu::Face::Back),
polygon_mode: wgpu::PolygonMode::Fill,
unclipped_depth: false,
conservative: false,
},
depth_stencil: None,
multisample: wgpu::MultisampleState {
count: 1,
mask: !0,
alpha_to_coverage_enabled: false,
},
multiview: None,
2024-08-01 16:06:28 +10:00
cache: None,
2023-11-30 16:52:49 +11:00
});
let vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
2024-01-18 14:35:52 +11:00
label: Some("triangle vertices"),
contents: bytemuck::cast_slice(VERTICES),
usage: wgpu::BufferUsages::VERTEX,
});
2023-11-30 16:52:49 +11:00
let clear_color = wgpu::Color {
r: 0.1,
g: 0.2,
b: 0.3,
a: 1.0,
};
let num_vertices = VERTICES.len() as u32;
Self {
surface,
device,
queue,
config,
size,
clear_color,
render_pipeline,
vertex_buffer,
num_vertices,
chain,
frame_count: 0,
2023-11-30 16:52:49 +11:00
}
}
fn resize(&mut self, new_size: winit::dpi::PhysicalSize<u32>) {
if new_size.width > 0 && new_size.height > 0 {
self.size = new_size;
self.config.width = new_size.width;
self.config.height = new_size.height;
self.surface.configure(&self.device, &self.config);
}
}
fn input(&mut self, _event: &WindowEvent) -> bool {
2023-11-30 16:52:49 +11:00
false
}
fn update(&mut self) {}
fn render(&mut self) -> Result<(), wgpu::SurfaceError> {
let output = self.surface.get_current_texture()?;
2024-02-06 17:32:08 +11:00
let render_output = Arc::new(self.device.create_texture(&wgpu::TextureDescriptor {
label: Some("rendertexture"),
size: output.texture.size(),
mip_level_count: output.texture.mip_level_count(),
sample_count: output.texture.sample_count(),
dimension: output.texture.dimension(),
format: output.texture.format(),
usage: wgpu::TextureUsages::TEXTURE_BINDING
| wgpu::TextureUsages::RENDER_ATTACHMENT
| wgpu::TextureUsages::COPY_DST
| wgpu::TextureUsages::COPY_SRC,
view_formats: &[output.texture.format()],
}));
let filter_output = Arc::new(self.device.create_texture(&wgpu::TextureDescriptor {
label: Some("filteroutput"),
size: output.texture.size(),
mip_level_count: output.texture.mip_level_count(),
sample_count: output.texture.sample_count(),
dimension: output.texture.dimension(),
format: output.texture.format(),
usage: wgpu::TextureUsages::TEXTURE_BINDING
| wgpu::TextureUsages::RENDER_ATTACHMENT
| wgpu::TextureUsages::COPY_DST
| wgpu::TextureUsages::COPY_SRC,
view_formats: &[output.texture.format()],
}));
let view = render_output.create_view(&wgpu::TextureViewDescriptor::default());
let filter_view = filter_output.create_view(&wgpu::TextureViewDescriptor::default());
2023-11-30 16:52:49 +11:00
let mut encoder = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("Render Encoder"),
});
{
2024-02-06 17:32:08 +11:00
let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
2023-11-30 16:52:49 +11:00
label: Some("Render Pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(self.clear_color),
store: wgpu::StoreOp::Store,
2023-11-30 16:52:49 +11:00
},
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
});
render_pass.set_pipeline(&self.render_pipeline);
render_pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
render_pass.draw(0..self.num_vertices, 0..1);
}
self.chain
2024-02-06 17:32:08 +11:00
.frame(
Arc::clone(&render_output),
&Viewport {
x: 0.0,
y: 0.0,
mvp: None,
output: librashader_runtime_wgpu::WgpuOutputView::new_from_raw(
2024-02-06 17:45:31 +11:00
&filter_view,
filter_output.size().into(),
filter_output.format(),
),
2024-02-06 17:32:08 +11:00
},
&mut encoder,
self.frame_count,
None,
)
.expect("failed to draw frame");
encoder.copy_texture_to_texture(
filter_output.as_image_copy(),
output.texture.as_image_copy(),
2024-02-06 17:32:08 +11:00
output.texture.size(),
);
2023-11-30 16:52:49 +11:00
self.queue.submit(std::iter::once(encoder.finish()));
output.present();
self.frame_count += 1;
2023-11-30 16:52:49 +11:00
Ok(())
}
}
pub fn run() {
env_logger::init();
let event_loop = EventLoopBuilder::new()
.with_any_thread(true)
.with_dpi_aware(true)
2024-01-18 14:35:52 +11:00
.build()
.unwrap();
2023-11-30 16:52:49 +11:00
let window = WindowBuilder::new().build(&event_loop).unwrap();
pollster::block_on(async {
let mut state = State::new(&window).await;
event_loop
.run(|event, target| {
match event {
Event::WindowEvent {
window_id: _,
event,
} => match event {
WindowEvent::Resized(new_size) => {
state.resize(new_size);
// On macos the window needs to be redrawn manually after resizing
window.request_redraw();
}
WindowEvent::RedrawRequested => {
state.update();
match state.render() {
Ok(_) => {}
Err(wgpu::SurfaceError::Lost | wgpu::SurfaceError::Outdated) => {
state.resize(state.size)
}
Err(wgpu::SurfaceError::OutOfMemory) => target.exit(),
Err(wgpu::SurfaceError::Timeout) => log::warn!("Surface timeout"),
2024-01-18 14:35:52 +11:00
}
2023-11-30 16:52:49 +11:00
}
WindowEvent::CloseRequested => target.exit(),
_ => {}
},
Event::AboutToWait => window.request_redraw(),
2024-01-18 14:35:52 +11:00
_ => {}
2023-11-30 16:52:49 +11:00
}
})
.unwrap();
2023-11-30 16:52:49 +11:00
});
}