rt(wgpu): basic triangle example

This commit is contained in:
chyyran 2023-11-30 00:52:49 -05:00 committed by Ronny Chan
parent ec98494202
commit c05d8ff06a
12 changed files with 629 additions and 16 deletions

8
.idea/.gitignore vendored
View file

@ -1,8 +0,0 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

View file

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CMakeWorkspace">
<contentRoot DIR="$PROJECT_DIR$" />
</component>
</project>

8
.idea/modules.xml Normal file
View file

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/librashader.iml" filepath="$PROJECT_DIR$/.idea/librashader.iml" />
</modules>
</component>
</project>

View file

@ -1 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>

View file

@ -13,7 +13,7 @@ members = [
"librashader-cache",
"librashader-capi",
"librashader-build-script"
]
, "librashader-runtime-wgpu"]
resolver = "2"
[workspace.metadata.release]

View file

@ -0,0 +1,24 @@
struct VertexInput {
@location(0) position: 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(model.position, 1.0);
return out;
}
@fragment
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
return vec4(in.color, 1.0);
}

View file

@ -0,0 +1,33 @@
//! Vulkan shader runtime errors.
use librashader_preprocess::PreprocessError;
use librashader_presets::ParsePresetError;
use librashader_reflect::error::{ShaderCompileError, ShaderReflectError};
use librashader_runtime::image::ImageError;
use std::convert::Infallible;
use thiserror::Error;
/// Cumulative error type for Vulkan filter chains.
#[derive(Error, Debug)]
pub enum FilterChainError {
#[error("SPIRV reflection error")]
SpirvCrossReflectError(#[from] spirv_cross::ErrorCode),
#[error("shader preset parse error")]
ShaderPresetError(#[from] ParsePresetError),
#[error("shader preprocess error")]
ShaderPreprocessError(#[from] PreprocessError),
#[error("shader compile error")]
ShaderCompileError(#[from] ShaderCompileError),
#[error("shader reflect error")]
ShaderReflectError(#[from] ShaderReflectError),
#[error("lut loading error")]
LutLoadError(#[from] ImageError),
}
impl From<Infallible> for FilterChainError {
fn from(_value: Infallible) -> Self {
panic!("uninhabited error")
}
}
/// Result type for Vulkan filter chains.
pub type Result<T> = std::result::Result<T, FilterChainError>;

View file

@ -0,0 +1,236 @@
use librashader_presets::{ShaderPassConfig, ShaderPreset, TextureConfig};
use librashader_reflect::back::targets::SPIRV;
use librashader_reflect::back::{CompileReflectShader, CompileShader};
use librashader_reflect::front::GlslangCompilation;
use librashader_reflect::reflect::presets::{CompilePresetTarget, ShaderPassArtifact};
use librashader_reflect::reflect::semantics::ShaderSemantics;
use librashader_reflect::reflect::ReflectShader;
use librashader_runtime::binding::BindingUtil;
use librashader_runtime::image::{Image, ImageError, UVDirection, BGRA8};
use librashader_runtime::quad::QuadType;
use librashader_runtime::uniforms::UniformStorage;
use parking_lot::RwLock;
use rustc_hash::FxHashMap;
use std::collections::VecDeque;
use std::convert::Infallible;
use std::path::Path;
use std::sync::Arc;
use librashader_cache::CachedCompilation;
use librashader_runtime::framebuffer::FramebufferInit;
use librashader_runtime::render_target::RenderTarget;
use librashader_runtime::scaling::ScaleFramebuffer;
use rayon::prelude::*;
use crate::error;
use crate::error::FilterChainError;
use crate::filter_pass::FilterPass;
type ShaderPassMeta =
ShaderPassArtifact<impl CompileReflectShader<SPIRV, GlslangCompilation> + Send>;
fn compile_passes(
shaders: Vec<ShaderPassConfig>,
textures: &[TextureConfig],
disable_cache: bool,
) -> Result<(Vec<ShaderPassMeta>, ShaderSemantics), FilterChainError> {
let (passes, semantics) = if !disable_cache {
SPIRV::compile_preset_passes::<CachedCompilation<GlslangCompilation>, FilterChainError>(
shaders, &textures,
)?
} else {
SPIRV::compile_preset_passes::<GlslangCompilation, FilterChainError>(shaders, &textures)?
};
Ok((passes, semantics))
}
/// A Vulkan filter chain.
pub struct FilterChainWGPU {
pub(crate) common: FilterCommon,
// passes: Box<[FilterPass]>,
// vulkan: VulkanObjects,
// output_framebuffers: Box<[OwnedImage]>,
// feedback_framebuffers: Box<[OwnedImage]>,
// history_framebuffers: VecDeque<OwnedImage>,
// disable_mipmaps: bool,
// residuals: Box<[FrameResiduals]>,
}
pub struct FilterMutable {
// pub(crate) passes_enabled: usize,
// pub(crate) parameters: FxHashMap<String, f32>,
}
pub(crate) struct FilterCommon {
// pub(crate) luts: FxHashMap<usize, LutTexture>,
// pub samplers: SamplerSet,
// pub(crate) draw_quad: DrawQuad,
// pub output_textures: Box<[Option<InputImage>]>,
// pub feedback_textures: Box<[Option<InputImage>]>,
// pub history_textures: Box<[Option<InputImage>]>,
// pub config: FilterMutable,
// pub device: Arc<ash::Device>,
// pub(crate) internal_frame_count: usize,
}
impl FilterChainWGPU {
/// Load a filter chain from a pre-parsed `ShaderPreset`, deferring and GPU-side initialization
/// to the caller. This function therefore requires no external synchronization of the device queue.
///
/// ## Safety
/// The provided command buffer must be ready for recording and contain no prior commands.
/// The caller is responsible for ending the command buffer and immediately submitting it to a
/// graphics queue. The command buffer must be completely executed before calling [`frame`](Self::frame).
pub unsafe fn load_from_preset_deferred(
preset: ShaderPreset,
) -> error::Result<FilterChainWGPU>
{
let disable_cache = true;
let (passes, semantics) = compile_passes(preset.shaders, &preset.textures, disable_cache)?;
todo!()
// let device = vulkan.try_into().map_err(From::from)?;
//
// let mut frames_in_flight = options.map_or(0, |o| o.frames_in_flight);
// if frames_in_flight == 0 {
// frames_in_flight = 3;
// }
//
// // initialize passes
// let filters = Self::init_passes(
// &device,
// passes,
// &semantics,
// frames_in_flight,
// options.map_or(false, |o| o.use_render_pass),
// disable_cache,
// )?;
//
// let luts = FilterChainVulkan::load_luts(&device, cmd, &preset.textures)?;
// let samplers = SamplerSet::new(&device.device)?;
//
// let framebuffer_gen =
// || OwnedImage::new(&device, Size::new(1, 1), ImageFormat::R8G8B8A8Unorm, 1);
// let input_gen = || None;
// let framebuffer_init = FramebufferInit::new(
// filters.iter().map(|f| &f.reflection.meta),
// &framebuffer_gen,
// &input_gen,
// );
//
// // initialize output framebuffers
// let (output_framebuffers, output_textures) = framebuffer_init.init_output_framebuffers()?;
//
// // initialize feedback framebuffers
// let (feedback_framebuffers, feedback_textures) =
// framebuffer_init.init_output_framebuffers()?;
//
// // initialize history
// let (history_framebuffers, history_textures) = framebuffer_init.init_history()?;
//
// let mut intermediates = Vec::new();
// intermediates.resize_with(frames_in_flight as usize, || {
// FrameResiduals::new(&device.device)
// });
// Ok(FilterChainVulkan {
// common: FilterCommon {
// luts,
// samplers,
// config: FilterMutable {
// passes_enabled: preset.shader_count as usize,
// parameters: preset
// .parameters
// .into_iter()
// .map(|param| (param.name, param.value))
// .collect(),
// },
// draw_quad: DrawQuad::new(&device.device, &device.alloc)?,
// device: device.device.clone(),
// output_textures,
// feedback_textures,
// history_textures,
// internal_frame_count: 0,
// },
// passes: filters,
// vulkan: device,
// output_framebuffers,
// feedback_framebuffers,
// history_framebuffers,
// residuals: intermediates.into_boxed_slice(),
// disable_mipmaps: options.map_or(false, |o| o.force_no_mipmaps),
// })
}
fn init_passes(
passes: Vec<ShaderPassMeta>,
semantics: &ShaderSemantics,
disable_cache: bool,
) -> error::Result<Box<[FilterPass]>> {
// let frames_in_flight = std::cmp::max(1, frames_in_flight);
//
let filters: Vec<error::Result<FilterPass>> = passes
.into_par_iter()
.enumerate()
.map(|(index, (config, source, mut reflect))| {
let reflection = reflect.reflect(index, semantics)?;
let spirv_words = reflect.compile(None)?;
let ubo_size = reflection.ubo.as_ref().map_or(0, |ubo| ubo.size as usize);
// let uniform_storage = UniformStorage::new_with_ubo_storage(
// RawVulkanBuffer::new(
// &vulkan.device,
// &vulkan.alloc,
// vk::BufferUsageFlags::UNIFORM_BUFFER,
// ubo_size,
// )?,
// reflection
// .push_constant
// .as_ref()
// .map_or(0, |push| push.size as usize),
// );
//
let uniform_bindings = reflection.meta.create_binding_map(|param| param.offset());
//
// let render_pass_format = if !use_render_pass {
// vk::Format::UNDEFINED
// } else if let Some(format) = config.get_format_override() {
// format.into()
// } else if source.format != ImageFormat::Unknown {
// source.format.into()
// } else {
// ImageFormat::R8G8B8A8Unorm.into()
// };
//
// let graphics_pipeline = VulkanGraphicsPipeline::new(
// &vulkan.device,
// &spirv_words,
// &reflection,
// frames_in_flight,
// render_pass_format,
// disable_cache,
// )?;
Ok(FilterPass {
// device: vulkan.device.clone(),
reflection,
compiled: spirv_words,
// uniform_storage,
uniform_bindings,
source,
config,
// graphics_pipeline,
// // ubo_ring,
// frames_in_flight,
})
})
.collect();
//
let filters: error::Result<Vec<FilterPass>> = filters.into_iter().collect();
let filters = filters?;
Ok(filters.into_boxed_slice())
}
}

View file

@ -0,0 +1,20 @@
use std::sync::Arc;
use rustc_hash::FxHashMap;
use librashader_preprocess::ShaderSource;
use librashader_presets::ShaderPassConfig;
use librashader_reflect::back::ShaderCompilerOutput;
use librashader_reflect::reflect::semantics::{MemberOffset, UniformBinding};
use librashader_reflect::reflect::ShaderReflection;
use librashader_runtime::uniforms::{NoUniformBinder, UniformStorage};
pub struct FilterPass {
pub reflection: ShaderReflection,
pub(crate) compiled: ShaderCompilerOutput<Vec<u32>>,
// pub(crate) uniform_storage: UniformStorage<NoUniformBinder, Option<()>, RawVulkanBuffer>,
pub uniform_bindings: FxHashMap<UniformBinding, MemberOffset>,
pub source: ShaderSource,
pub config: ShaderPassConfig,
// pub graphics_pipeline: VulkanGraphicsPipeline,
// pub ubo_ring: VkUboRing,
// pub frames_in_flight: u32,
}

View file

View file

@ -0,0 +1,300 @@
use winit::{
event::*,
event_loop::{ControlFlow, EventLoop},
window::{Window, WindowBuilder},
};
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,
},
]
}
}
}
const VERTICES: &[Vertex] = &[
Vertex { // top
position: [0.0, 0.5, 0.0],
color: [1.0, 0.0, 0.0],
},
Vertex { // bottom left
position: [-0.5, -0.5, 0.0],
color: [0.0, 1.0, 0.0],
},
Vertex { // bottom right
position: [0.5, -0.5, 0.0],
color: [0.0, 0.0, 1.0],
},
];
struct State {
surface: wgpu::Surface,
device: wgpu::Device,
queue: wgpu::Queue,
config: wgpu::SurfaceConfiguration,
size: winit::dpi::PhysicalSize<u32>,
clear_color: wgpu::Color,
render_pipeline: wgpu::RenderPipeline,
vertex_buffer: wgpu::Buffer,
num_vertices: u32,
}
impl State {
async fn new(window: &Window) -> Self {
let size = window.inner_size();
let instance = wgpu::Instance::default();
let surface = unsafe { instance.create_surface(window).unwrap() };
// 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
.request_device(
&wgpu::DeviceDescriptor {
features: wgpu::Features::empty(),
limits: wgpu::Limits::default(),
label: None,
},
None,
)
.await
.unwrap();
let swapchain_capabilities = surface.get_capabilities(&adapter);
let swapchain_format = swapchain_capabilities.formats[0];
let mut config = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format: swapchain_format,
width: size.width,
height: size.height,
present_mode: wgpu::PresentMode::Fifo,
alpha_mode: swapchain_capabilities.alpha_modes[0],
view_formats: vec![],
};
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",
buffers: &[
Vertex::desc(),
],
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: "fs_main",
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,
});
let vertex_buffer = device.create_buffer_init(
&wgpu::util::BufferInitDescriptor {
label: Some("Vertex Buffer"),
contents: bytemuck::cast_slice(VERTICES),
usage: wgpu::BufferUsages::VERTEX,
},
);
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,
}
}
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 {
false
}
fn update(&mut self) {}
fn render(&mut self) -> Result<(), wgpu::SurfaceError> {
let output = self.surface.get_current_texture()?;
let view = output
.texture
.create_view(&wgpu::TextureViewDescriptor::default());
let mut encoder = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("Render Encoder"),
});
{
let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
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,
},
})],
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.queue.submit(std::iter::once(encoder.finish()));
output.present();
Ok(())
}
}
pub fn run() {
env_logger::init();
let event_loop = EventLoopBuilder::new()
.with_any_thread(true)
.with_dpi_aware(true)
.build();
let window = WindowBuilder::new().build(&event_loop).unwrap();
pollster::block_on(async {
let mut state = State::new(&window).await;
event_loop.run(move |event, _, control_flow| {
match event {
Event::WindowEvent {
ref event,
window_id,
} if window_id == window.id() => {
if !state.input(event) {
// UPDATED!
match event {
WindowEvent::CloseRequested
| WindowEvent::KeyboardInput {
input:
KeyboardInput {
state: ElementState::Pressed,
virtual_keycode: Some(VirtualKeyCode::Escape),
..
},
..
} => *control_flow = ControlFlow::Exit,
WindowEvent::Resized(physical_size) => {
state.resize(*physical_size);
}
WindowEvent::ScaleFactorChanged { new_inner_size, .. } => {
state.resize(**new_inner_size);
}
_ => {}
}
}
}
Event::RedrawRequested(window_id) if window_id == window.id() => {
state.update();
match state.render() {
Ok(_) => {}
Err(wgpu::SurfaceError::Lost | wgpu::SurfaceError::Outdated) => {
state.resize(state.size)
}
Err(wgpu::SurfaceError::OutOfMemory) => *control_flow = ControlFlow::Exit,
Err(wgpu::SurfaceError::Timeout) => log::warn!("Surface timeout"),
}
}
Event::RedrawEventsCleared => {
window.request_redraw();
}
_ => {}
}
});
});
}

View file

@ -0,0 +1,7 @@
mod hello_triangle;
#[test]
fn triangle_wgpu()
{
hello_triangle::run()
}