fmt: run cargo fmt

This commit is contained in:
chyyran 2022-12-21 21:39:31 -05:00
parent fe573618f8
commit 8fca2954b0
48 changed files with 631 additions and 464 deletions

View file

@ -149,9 +149,8 @@ pub unsafe extern "C" fn libra_d3d11_filter_chain_frame(
}) })
} }
pub type PFN_lbr_d3d11_filter_chain_free = unsafe extern "C" fn( pub type PFN_lbr_d3d11_filter_chain_free =
chain: *mut libra_d3d11_filter_chain_t, unsafe extern "C" fn(chain: *mut libra_d3d11_filter_chain_t) -> libra_error_t;
) -> libra_error_t;
/// Free a D3D11 filter chain. /// Free a D3D11 filter chain.
/// ///
/// The resulting value in `chain` then becomes null. /// The resulting value in `chain` then becomes null.

View file

@ -169,9 +169,8 @@ pub unsafe extern "C" fn libra_gl_filter_chain_frame(
}) })
} }
pub type PFN_lbr_gl_filter_chain_free = unsafe extern "C" fn( pub type PFN_lbr_gl_filter_chain_free =
chain: *mut libra_gl_filter_chain_t, unsafe extern "C" fn(chain: *mut libra_gl_filter_chain_t) -> libra_error_t;
)-> libra_error_t;
/// Free a GL filter chain. /// Free a GL filter chain.
/// ///

View file

@ -1,6 +1,6 @@
use crate::ImageFormat;
use windows::Win32::Graphics::Dxgi::Common as dxgi; use windows::Win32::Graphics::Dxgi::Common as dxgi;
use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT; use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT;
use crate::ImageFormat;
impl From<ImageFormat> for dxgi::DXGI_FORMAT { impl From<ImageFormat> for dxgi::DXGI_FORMAT {
fn from(format: ImageFormat) -> Self { fn from(format: ImageFormat) -> Self {
@ -77,4 +77,4 @@ impl From<DXGI_FORMAT> for ImageFormat {
_ => ImageFormat::Unknown, _ => ImageFormat::Unknown,
} }
} }
} }

View file

@ -1,5 +1,5 @@
use ash::vk;
use crate::{ImageFormat, Size}; use crate::{ImageFormat, Size};
use ash::vk;
impl From<ImageFormat> for vk::Format { impl From<ImageFormat> for vk::Format {
fn from(format: ImageFormat) -> Self { fn from(format: ImageFormat) -> Self {
@ -86,4 +86,4 @@ impl From<Size<u32>> for vk::Extent3D {
depth: 1, depth: 1,
} }
} }
} }

View file

@ -1,6 +1,6 @@
pub mod cross; pub mod cross;
pub mod targets;
mod spirv; mod spirv;
pub mod targets;
use crate::back::targets::OutputTarget; use crate::back::targets::OutputTarget;
use crate::error::{ShaderCompileError, ShaderReflectError}; use crate::error::{ShaderCompileError, ShaderReflectError};

View file

@ -1,24 +1,24 @@
use crate::back::{CompilerBackend, CompileShader, FromCompilation, ShaderCompilerOutput};
use crate::back::targets::SpirV; use crate::back::targets::SpirV;
use crate::back::{CompileShader, CompilerBackend, FromCompilation, ShaderCompilerOutput};
use crate::error::{ShaderCompileError, ShaderReflectError}; use crate::error::{ShaderCompileError, ShaderReflectError};
use crate::front::shaderc::GlslangCompilation; use crate::front::shaderc::GlslangCompilation;
use crate::reflect::{ReflectShader, ShaderReflection}; use crate::reflect::cross::GlslReflect;
use crate::reflect::cross::{GlslReflect};
use crate::reflect::semantics::ShaderSemantics; use crate::reflect::semantics::ShaderSemantics;
use crate::reflect::{ReflectShader, ShaderReflection};
struct WriteSpirV { struct WriteSpirV {
// rely on GLSL to provide out reflection but we don't actually need the AST. // rely on GLSL to provide out reflection but we don't actually need the AST.
reflect: GlslReflect, reflect: GlslReflect,
vertex: Vec<u32>, vertex: Vec<u32>,
fragment: Vec<u32> fragment: Vec<u32>,
} }
impl FromCompilation<GlslangCompilation> for SpirV { impl FromCompilation<GlslangCompilation> for SpirV {
type Target = SpirV; type Target = SpirV;
type Options = Option<()>; type Options = Option<()>;
type Context = (); type Context = ();
type Output = impl CompileShader<Self::Target, Options = Option<()>, Context = ()> type Output =
+ ReflectShader; impl CompileShader<Self::Target, Options = Option<()>, Context = ()> + ReflectShader;
fn from_compilation( fn from_compilation(
compile: GlslangCompilation, compile: GlslangCompilation,
@ -37,7 +37,11 @@ impl FromCompilation<GlslangCompilation> for SpirV {
} }
impl ReflectShader for WriteSpirV { impl ReflectShader for WriteSpirV {
fn reflect(&mut self, pass_number: usize, semantics: &ShaderSemantics) -> Result<ShaderReflection, ShaderReflectError> { fn reflect(
&mut self,
pass_number: usize,
semantics: &ShaderSemantics,
) -> Result<ShaderReflection, ShaderReflectError> {
self.reflect.reflect(pass_number, semantics) self.reflect.reflect(pass_number, semantics)
} }
} }
@ -46,11 +50,14 @@ impl CompileShader<SpirV> for WriteSpirV {
type Options = Option<()>; type Options = Option<()>;
type Context = (); type Context = ();
fn compile(self, _options: Self::Options) -> Result<ShaderCompilerOutput<Vec<u32>, Self::Context>, ShaderCompileError> { fn compile(
self,
_options: Self::Options,
) -> Result<ShaderCompilerOutput<Vec<u32>, Self::Context>, ShaderCompileError> {
Ok(ShaderCompilerOutput { Ok(ShaderCompilerOutput {
vertex: self.vertex, vertex: self.vertex,
fragment: self.fragment, fragment: self.fragment,
context: (), context: (),
}) })
} }
} }

View file

@ -1,12 +1,17 @@
use crate::error::{SemanticsErrorKind, ShaderCompileError, ShaderReflectError}; use crate::error::{SemanticsErrorKind, ShaderCompileError, ShaderReflectError};
use crate::front::shaderc::GlslangCompilation; use crate::front::shaderc::GlslangCompilation;
use crate::reflect::semantics::{BindingStage, MAX_BINDINGS_COUNT, MAX_PUSH_BUFFER_SIZE, MemberOffset, PushReflection, BindingMeta, ShaderSemantics, ShaderReflection, TextureBinding, TextureSemanticMap, TextureSemantics, TextureSizeMeta, TypeInfo, UboReflection, UniqueSemantics, ValidateTypeSemantics, VariableMeta, UniqueSemanticMap}; use crate::reflect::semantics::{
BindingMeta, BindingStage, MemberOffset, PushReflection, ShaderReflection, ShaderSemantics,
TextureBinding, TextureSemanticMap, TextureSemantics, TextureSizeMeta, TypeInfo, UboReflection,
UniqueSemanticMap, UniqueSemantics, ValidateTypeSemantics, VariableMeta, MAX_BINDINGS_COUNT,
MAX_PUSH_BUFFER_SIZE,
};
use crate::reflect::{align_uniform_size, ReflectShader}; use crate::reflect::{align_uniform_size, ReflectShader};
use std::ops::Deref; use std::ops::Deref;
use spirv_cross::hlsl::ShaderModel; use spirv_cross::hlsl::ShaderModel;
use spirv_cross::spirv::{Ast, Decoration, Module, Resource, ShaderResources, Type}; use spirv_cross::spirv::{Ast, Decoration, Module, Resource, ShaderResources, Type};
use spirv_cross::{ErrorCode, glsl, hlsl}; use spirv_cross::{glsl, hlsl, ErrorCode};
use crate::back::cross::{CrossGlslContext, CrossHlslContext}; use crate::back::cross::{CrossGlslContext, CrossHlslContext};
use crate::back::targets::{GLSL, HLSL}; use crate::back::targets::{GLSL, HLSL};
@ -862,9 +867,7 @@ mod test {
use crate::back::CompileShader; use crate::back::CompileShader;
use crate::front::shaderc::GlslangCompilation; use crate::front::shaderc::GlslangCompilation;
use crate::reflect::semantics::{ use crate::reflect::semantics::{Semantic, ShaderSemantics, UniformSemantic, UniqueSemantics};
ShaderSemantics, Semantic, UniformSemantic, UniqueSemantics,
};
use librashader_preprocess::ShaderSource; use librashader_preprocess::ShaderSource;
use spirv_cross::glsl; use spirv_cross::glsl;
use spirv_cross::glsl::{CompilerOptions, Version}; use spirv_cross::glsl::{CompilerOptions, Version};

View file

@ -201,7 +201,6 @@ pub enum MemberOffset {
PushConstant(usize), PushConstant(usize),
} }
/// Reflection information about a non-texture related uniform variable. /// Reflection information about a non-texture related uniform variable.
#[derive(Debug)] #[derive(Debug)]
pub struct VariableMeta { pub struct VariableMeta {

View file

@ -1,7 +1,7 @@
use librashader_runtime::image::ImageError;
use librashader_preprocess::PreprocessError; use librashader_preprocess::PreprocessError;
use librashader_presets::ParsePresetError; use librashader_presets::ParsePresetError;
use librashader_reflect::error::{ShaderCompileError, ShaderReflectError}; use librashader_reflect::error::{ShaderCompileError, ShaderReflectError};
use librashader_runtime::image::ImageError;
use thiserror::Error; use thiserror::Error;
#[derive(Error, Debug)] #[derive(Error, Debug)]

View file

@ -1,5 +1,4 @@
use crate::texture::{DxImageView, LutTexture, Texture}; use crate::texture::{DxImageView, LutTexture, Texture};
use librashader_runtime::image::{Image, UVDirection};
use librashader_common::{ImageFormat, Size}; use librashader_common::{ImageFormat, Size};
use librashader_preprocess::ShaderSource; use librashader_preprocess::ShaderSource;
use librashader_presets::{ShaderPassConfig, ShaderPreset, TextureConfig}; use librashader_presets::{ShaderPassConfig, ShaderPreset, TextureConfig};
@ -8,10 +7,10 @@ use librashader_reflect::back::targets::HLSL;
use librashader_reflect::back::{CompileShader, CompilerBackend, FromCompilation}; use librashader_reflect::back::{CompileShader, CompilerBackend, FromCompilation};
use librashader_reflect::front::shaderc::GlslangCompilation; use librashader_reflect::front::shaderc::GlslangCompilation;
use librashader_reflect::reflect::semantics::{ use librashader_reflect::reflect::semantics::{
ShaderSemantics, Semantic, TextureSemantics, UniformBinding, UniformSemantic, Semantic, ShaderSemantics, TextureSemantics, UniformBinding, UniformSemantic, UniqueSemantics,
UniqueSemantics,
}; };
use librashader_reflect::reflect::ReflectShader; use librashader_reflect::reflect::ReflectShader;
use librashader_runtime::image::{Image, UVDirection};
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use std::collections::VecDeque; use std::collections::VecDeque;
@ -44,7 +43,7 @@ type ShaderPassMeta = (
ShaderPassConfig, ShaderPassConfig,
ShaderSource, ShaderSource,
CompilerBackend< CompilerBackend<
impl CompileShader<HLSL, Options = Option<()>, Context =CrossHlslContext> + ReflectShader, impl CompileShader<HLSL, Options = Option<()>, Context = CrossHlslContext> + ReflectShader,
>, >,
); );
@ -157,9 +156,7 @@ impl FilterChainD3D11 {
let luts = FilterChainD3D11::load_luts(device, &current_context, &preset.textures)?; let luts = FilterChainD3D11::load_luts(device, &current_context, &preset.textures)?;
let (history_framebuffers, history_textures) = let (history_framebuffers, history_textures) =
FilterChainD3D11::init_history(device, FilterChainD3D11::init_history(device, &current_context, &filters)?;
&current_context,
&filters)?;
let draw_quad = DrawQuad::new(device, &current_context)?; let draw_quad = DrawQuad::new(device, &current_context)?;
@ -497,7 +494,11 @@ impl FilterChainD3D11 {
.zip(self.feedback_framebuffers.iter()) .zip(self.feedback_framebuffers.iter())
.zip(passes.iter()) .zip(passes.iter())
{ {
*texture = Some(Texture::from_framebuffer(fbo, pass.config.wrap_mode, pass.config.filter)?); *texture = Some(Texture::from_framebuffer(
fbo,
pass.config.wrap_mode,
pass.config.filter,
)?);
} }
for (texture, fbo) in self for (texture, fbo) in self
@ -589,7 +590,10 @@ impl FilterChainD3D11 {
)?; )?;
} }
std::mem::swap(&mut self.output_framebuffers, &mut self.feedback_framebuffers); std::mem::swap(
&mut self.output_framebuffers,
&mut self.feedback_framebuffers,
);
self.push_history(&input)?; self.push_history(&input)?;
@ -613,7 +617,13 @@ impl librashader_runtime::filter_chain::FilterChain for FilterChainD3D11 {
type Viewport<'a> = Viewport<'a>; type Viewport<'a> = Viewport<'a>;
type FrameOptions = FrameOptionsD3D11; type FrameOptions = FrameOptionsD3D11;
fn frame<'a>(&mut self, input: Self::Input<'a>, viewport: &Self::Viewport<'a>, frame_count: usize, options: Option<&Self::FrameOptions>) -> Result<(), Self::Error> { fn frame<'a>(
&mut self,
input: Self::Input<'a>,
viewport: &Self::Viewport<'a>,
frame_count: usize,
options: Option<&Self::FrameOptions>,
) -> Result<(), Self::Error> {
self.frame(input, viewport, frame_count, options) self.frame(input, viewport, frame_count, options)
} }
} }

View file

@ -3,11 +3,19 @@ use crate::texture::{DxImageView, Texture};
use crate::util::d3d11_get_closest_format; use crate::util::d3d11_get_closest_format;
use librashader_common::{ImageFormat, Size}; use librashader_common::{ImageFormat, Size};
use librashader_presets::Scale2D; use librashader_presets::Scale2D;
use librashader_runtime::scaling::ViewportSize;
use windows::core::Interface; use windows::core::Interface;
use windows::Win32::Graphics::Direct3D::D3D_SRV_DIMENSION_TEXTURE2D; use windows::Win32::Graphics::Direct3D::D3D_SRV_DIMENSION_TEXTURE2D;
use windows::Win32::Graphics::Direct3D11::{ID3D11Device, ID3D11RenderTargetView, ID3D11ShaderResourceView, ID3D11Texture2D, D3D11_BIND_RENDER_TARGET, D3D11_BIND_SHADER_RESOURCE, D3D11_CPU_ACCESS_WRITE, D3D11_FORMAT_SUPPORT_RENDER_TARGET, D3D11_FORMAT_SUPPORT_SHADER_SAMPLE, D3D11_FORMAT_SUPPORT_TEXTURE2D, D3D11_RENDER_TARGET_VIEW_DESC, D3D11_RENDER_TARGET_VIEW_DESC_0, D3D11_RTV_DIMENSION_TEXTURE2D, D3D11_SHADER_RESOURCE_VIEW_DESC, D3D11_SHADER_RESOURCE_VIEW_DESC_0, D3D11_TEX2D_RTV, D3D11_TEX2D_SRV, D3D11_TEXTURE2D_DESC, D3D11_USAGE_DEFAULT, D3D11_VIEWPORT, D3D11_RESOURCE_MISC_GENERATE_MIPS, ID3D11DeviceContext, D3D11_BOX}; use windows::Win32::Graphics::Direct3D11::{
ID3D11Device, ID3D11DeviceContext, ID3D11RenderTargetView, ID3D11ShaderResourceView,
ID3D11Texture2D, D3D11_BIND_RENDER_TARGET, D3D11_BIND_SHADER_RESOURCE, D3D11_BOX,
D3D11_CPU_ACCESS_WRITE, D3D11_FORMAT_SUPPORT_RENDER_TARGET, D3D11_FORMAT_SUPPORT_SHADER_SAMPLE,
D3D11_FORMAT_SUPPORT_TEXTURE2D, D3D11_RENDER_TARGET_VIEW_DESC, D3D11_RENDER_TARGET_VIEW_DESC_0,
D3D11_RESOURCE_MISC_GENERATE_MIPS, D3D11_RTV_DIMENSION_TEXTURE2D,
D3D11_SHADER_RESOURCE_VIEW_DESC, D3D11_SHADER_RESOURCE_VIEW_DESC_0, D3D11_TEX2D_RTV,
D3D11_TEX2D_SRV, D3D11_TEXTURE2D_DESC, D3D11_USAGE_DEFAULT, D3D11_VIEWPORT,
};
use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT, DXGI_SAMPLE_DESC}; use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT, DXGI_SAMPLE_DESC};
use librashader_runtime::scaling::ViewportSize;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub(crate) struct OwnedFramebuffer { pub(crate) struct OwnedFramebuffer {
@ -48,14 +56,13 @@ impl OwnedFramebuffer {
} }
} }
pub(crate) fn scale( pub(crate) fn scale(
&mut self, &mut self,
scaling: Scale2D, scaling: Scale2D,
format: ImageFormat, format: ImageFormat,
viewport_size: &Size<u32>, viewport_size: &Size<u32>,
_original: &Texture, _original: &Texture,
source: &Texture source: &Texture,
) -> error::Result<Size<u32>> { ) -> error::Result<Size<u32>> {
if self.is_raw { if self.is_raw {
return Ok(self.size); return Ok(self.size);
@ -215,7 +222,7 @@ fn default_desc(size: Size<u32>, format: DXGI_FORMAT, mip_levels: u32) -> D3D11_
Usage: D3D11_USAGE_DEFAULT, Usage: D3D11_USAGE_DEFAULT,
BindFlags: D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET, BindFlags: D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET,
CPUAccessFlags: D3D11_CPU_ACCESS_WRITE, CPUAccessFlags: D3D11_CPU_ACCESS_WRITE,
MiscFlags: D3D11_RESOURCE_MISC_GENERATE_MIPS MiscFlags: D3D11_RESOURCE_MISC_GENERATE_MIPS,
} }
} }
pub const fn default_viewport(size: Size<u32>) -> D3D11_VIEWPORT { pub const fn default_viewport(size: Size<u32>) -> D3D11_VIEWPORT {

View file

@ -9,17 +9,17 @@ mod filter_chain;
mod filter_pass; mod filter_pass;
mod framebuffer; mod framebuffer;
pub mod options; pub mod options;
mod parameters;
mod quad_render; mod quad_render;
mod render_target; mod render_target;
mod samplers; mod samplers;
mod texture; mod texture;
mod util; mod util;
mod viewport; mod viewport;
mod parameters;
pub use filter_chain::FilterChainD3D11; pub use filter_chain::FilterChainD3D11;
pub use viewport::Viewport;
pub use texture::DxImageView; pub use texture::DxImageView;
pub use viewport::Viewport;
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {

View file

@ -1,6 +1,6 @@
use std::collections::hash_map::Iter;
use librashader_runtime::parameters::FilterChainParameters;
use crate::FilterChainD3D11; use crate::FilterChainD3D11;
use librashader_runtime::parameters::FilterChainParameters;
use std::collections::hash_map::Iter;
impl FilterChainParameters for FilterChainD3D11 { impl FilterChainParameters for FilterChainD3D11 {
fn get_enabled_pass_count(&self) -> usize { fn get_enabled_pass_count(&self) -> usize {
@ -16,11 +16,20 @@ impl FilterChainParameters for FilterChainD3D11 {
} }
fn get_parameter(&self, parameter: &str) -> Option<f32> { fn get_parameter(&self, parameter: &str) -> Option<f32> {
self.common.config.parameters.get::<str>(parameter.as_ref()).copied() self.common
.config
.parameters
.get::<str>(parameter.as_ref())
.copied()
} }
fn set_parameter(&mut self, parameter: &str, new_value: f32) -> Option<f32> { fn set_parameter(&mut self, parameter: &str, new_value: f32) -> Option<f32> {
if let Some(value) = self.common.config.parameters.get_mut::<str>(parameter.as_ref()) { if let Some(value) = self
.common
.config
.parameters
.get_mut::<str>(parameter.as_ref())
{
let old = *value; let old = *value;
*value = new_value; *value = new_value;
Some(old) Some(old)
@ -28,4 +37,4 @@ impl FilterChainParameters for FilterChainD3D11 {
None None
} }
} }
} }

View file

@ -1,5 +1,5 @@
use librashader_runtime::image::Image;
use librashader_common::{FilterMode, Size, WrapMode}; use librashader_common::{FilterMode, Size, WrapMode};
use librashader_runtime::image::Image;
use windows::Win32::Graphics::Direct3D::D3D_SRV_DIMENSION_TEXTURE2D; use windows::Win32::Graphics::Direct3D::D3D_SRV_DIMENSION_TEXTURE2D;
use windows::Win32::Graphics::Direct3D11::{ use windows::Win32::Graphics::Direct3D11::{
ID3D11Device, ID3D11DeviceContext, ID3D11ShaderResourceView, ID3D11Texture2D, D3D11_BIND_FLAG, ID3D11Device, ID3D11DeviceContext, ID3D11ShaderResourceView, ID3D11Texture2D, D3D11_BIND_FLAG,
@ -26,14 +26,18 @@ pub(crate) struct Texture {
} }
impl Texture { impl Texture {
pub fn from_framebuffer(fbo: &OwnedFramebuffer, wrap_mode: WrapMode, filter: FilterMode) -> Result<Self> { pub fn from_framebuffer(
fbo: &OwnedFramebuffer,
wrap_mode: WrapMode,
filter: FilterMode,
) -> Result<Self> {
Ok(Texture { Ok(Texture {
view: DxImageView { view: DxImageView {
handle: fbo.create_shader_resource_view()?, handle: fbo.create_shader_resource_view()?,
size: fbo.size, size: fbo.size,
}, },
filter, filter,
wrap_mode wrap_mode,
}) })
} }
} }

View file

@ -1,8 +1,8 @@
use gl::types::GLenum; use gl::types::GLenum;
use librashader_runtime::image::ImageError;
use librashader_preprocess::PreprocessError; use librashader_preprocess::PreprocessError;
use librashader_presets::ParsePresetError; use librashader_presets::ParsePresetError;
use librashader_reflect::error::{ShaderCompileError, ShaderReflectError}; use librashader_reflect::error::{ShaderCompileError, ShaderReflectError};
use librashader_runtime::image::ImageError;
use thiserror::Error; use thiserror::Error;
#[derive(Error, Debug)] #[derive(Error, Debug)]
@ -22,7 +22,7 @@ pub enum FilterChainError {
#[error("lut loading error")] #[error("lut loading error")]
LutLoadError(#[from] ImageError), LutLoadError(#[from] ImageError),
#[error("opengl was not initialized")] #[error("opengl was not initialized")]
GLLoadError GLLoadError,
} }
pub type Result<T> = std::result::Result<T, FilterChainError>; pub type Result<T> = std::result::Result<T, FilterChainError>;

View file

@ -1,17 +1,3 @@
use librashader_presets::{ShaderPassConfig, ShaderPreset, TextureConfig};
use librashader_reflect::reflect::semantics::{MemberOffset, ShaderSemantics, Semantic, TextureSemantics, UniformBinding, UniformMeta, UniformSemantic, UniqueSemantics};
use rustc_hash::FxHashMap;
use librashader_preprocess::ShaderSource;
use librashader_reflect::back::{CompilerBackend, CompileShader, FromCompilation};
use librashader_reflect::back::cross::{CrossGlslContext, GlslVersion};
use librashader_reflect::back::targets::GLSL;
use librashader_reflect::front::shaderc::GlslangCompilation;
use spirv_cross::spirv::Decoration;
use gl::types::{GLenum, GLint, GLuint};
use librashader_common::{FilterMode, Size, WrapMode};
use std::collections::VecDeque;
use librashader_reflect::reflect::ReflectShader;
use crate::{error, GLImage, util, Viewport};
use crate::binding::{GlUniformStorage, UniformLocation, VariableLocation}; use crate::binding::{GlUniformStorage, UniformLocation, VariableLocation};
use crate::error::FilterChainError; use crate::error::FilterChainError;
use crate::filter_pass::FilterPass; use crate::filter_pass::FilterPass;
@ -21,6 +7,23 @@ use crate::render_target::RenderTarget;
use crate::samplers::SamplerSet; use crate::samplers::SamplerSet;
use crate::texture::Texture; use crate::texture::Texture;
use crate::util::{gl_get_version, gl_u16_to_version}; use crate::util::{gl_get_version, gl_u16_to_version};
use crate::{error, util, GLImage, Viewport};
use gl::types::{GLenum, GLint, GLuint};
use librashader_common::{FilterMode, Size, WrapMode};
use librashader_preprocess::ShaderSource;
use librashader_presets::{ShaderPassConfig, ShaderPreset, TextureConfig};
use librashader_reflect::back::cross::{CrossGlslContext, GlslVersion};
use librashader_reflect::back::targets::GLSL;
use librashader_reflect::back::{CompileShader, CompilerBackend, FromCompilation};
use librashader_reflect::front::shaderc::GlslangCompilation;
use librashader_reflect::reflect::semantics::{
MemberOffset, Semantic, ShaderSemantics, TextureSemantics, UniformBinding, UniformMeta,
UniformSemantic, UniqueSemantics,
};
use librashader_reflect::reflect::ReflectShader;
use rustc_hash::FxHashMap;
use spirv_cross::spirv::Decoration;
use std::collections::VecDeque;
pub(crate) struct FilterChainImpl<T: GLInterface> { pub(crate) struct FilterChainImpl<T: GLInterface> {
pub(crate) common: FilterCommon, pub(crate) common: FilterCommon,
@ -79,16 +82,19 @@ type ShaderPassMeta = (
ShaderPassConfig, ShaderPassConfig,
ShaderSource, ShaderSource,
CompilerBackend< CompilerBackend<
impl CompileShader<GLSL, Options =GlslVersion, Context =CrossGlslContext> + ReflectShader, impl CompileShader<GLSL, Options = GlslVersion, Context = CrossGlslContext> + ReflectShader,
>, >,
); );
impl<T: GLInterface> FilterChainImpl<T> { impl<T: GLInterface> FilterChainImpl<T> {
pub(crate) fn create_framebuffer_raw(&self, texture: GLuint, pub(crate) fn create_framebuffer_raw(
handle: GLuint, &self,
format: GLenum, texture: GLuint,
size: Size<u32>, handle: GLuint,
miplevels: u32,) -> Framebuffer { format: GLenum,
size: Size<u32>,
miplevels: u32,
) -> Framebuffer {
T::FramebufferInterface::new_from_raw(texture, handle, format, size, miplevels) T::FramebufferInterface::new_from_raw(texture, handle, format, size, miplevels)
} }
/// Load a filter chain from a pre-parsed `ShaderPreset`. /// Load a filter chain from a pre-parsed `ShaderPreset`.
@ -187,7 +193,8 @@ impl<T: GLInterface> FilterChainImpl<T> {
Ok::<_, FilterChainError>((shader, source, reflect)) Ok::<_, FilterChainError>((shader, source, reflect))
}) })
.into_iter() .into_iter()
.collect::<error::Result<Vec<(ShaderPassConfig, ShaderSource, CompilerBackend<_>)>>>()?; .collect::<error::Result<Vec<(ShaderPassConfig, ShaderSource, CompilerBackend<_>)>>>(
)?;
for details in &passes { for details in &passes {
librashader_runtime::semantics::insert_pass_semantics( librashader_runtime::semantics::insert_pass_semantics(
@ -542,11 +549,16 @@ impl<T: GLInterface> FilterChainImpl<T> {
&source, &source,
viewport.into(), viewport.into(),
); );
self.common.output_textures[passes_len - 1] = viewport.output.as_texture(pass.config.filter, pass.config.wrap_mode); self.common.output_textures[passes_len - 1] = viewport
.output
.as_texture(pass.config.filter, pass.config.wrap_mode);
} }
// swap feedback framebuffers with output // swap feedback framebuffers with output
std::mem::swap(&mut self.output_framebuffers, &mut self.feedback_framebuffers); std::mem::swap(
&mut self.output_framebuffers,
&mut self.feedback_framebuffers,
);
self.push_history(input)?; self.push_history(input)?;

View file

@ -1,13 +1,13 @@
use gl::types::{GLenum, GLuint};
use std::panic::catch_unwind; use std::panic::catch_unwind;
use std::path::Path; use std::path::Path;
use gl::types::{GLenum, GLuint};
use librashader_presets::ShaderPreset; use crate::error::{FilterChainError, Result};
use crate::filter_chain::filter_impl::FilterChainImpl; use crate::filter_chain::filter_impl::FilterChainImpl;
use crate::filter_chain::inner::FilterChainDispatch; use crate::filter_chain::inner::FilterChainDispatch;
use crate::{Framebuffer, GLImage, Viewport};
use crate::error::{Result, FilterChainError};
use crate::options::{FilterChainOptionsGL, FrameOptionsGL}; use crate::options::{FilterChainOptionsGL, FrameOptionsGL};
use crate::{Framebuffer, GLImage, Viewport};
use librashader_presets::ShaderPreset;
mod filter_impl; mod filter_impl;
mod inner; mod inner;
@ -21,17 +21,21 @@ pub struct FilterChainGL {
} }
impl FilterChainGL { impl FilterChainGL {
pub fn create_framebuffer_raw(&self, texture: GLuint, pub fn create_framebuffer_raw(
handle: GLuint, &self,
format: GLenum, texture: GLuint,
size: Size<u32>, handle: GLuint,
miplevels: u32,) -> Framebuffer { format: GLenum,
size: Size<u32>,
miplevels: u32,
) -> Framebuffer {
match &self.filter { match &self.filter {
FilterChainDispatch::DirectStateAccess(p) => { FilterChainDispatch::DirectStateAccess(p) => {
p.create_framebuffer_raw(texture, handle, format, size, miplevels) p.create_framebuffer_raw(texture, handle, format, size, miplevels)
} }
FilterChainDispatch::Compatibility(p) => p.create_framebuffer_raw(texture, handle, format, size, miplevels), FilterChainDispatch::Compatibility(p) => {
p.create_framebuffer_raw(texture, handle, format, size, miplevels)
}
} }
} }
pub fn load_from_preset( pub fn load_from_preset(
@ -51,10 +55,8 @@ impl FilterChainGL {
}) })
}); });
match result { match result {
Err(_) => { Err(_) => return Err(FilterChainError::GLLoadError),
return Err(FilterChainError::GLLoadError) Ok(res) => res,
}
Ok(res) => res
} }
} }
@ -103,4 +105,3 @@ impl librashader_runtime::filter_chain::FilterChain for FilterChainGL {
self.frame(input, viewport, frame_count, options) self.frame(input, viewport, frame_count, options)
} }
} }

View file

@ -1,9 +1,9 @@
use std::collections::hash_map::Iter;
use librashader_runtime::parameters::FilterChainParameters;
use crate::filter_chain::filter_impl::FilterChainImpl; use crate::filter_chain::filter_impl::FilterChainImpl;
use crate::filter_chain::inner::FilterChainDispatch; use crate::filter_chain::inner::FilterChainDispatch;
use crate::FilterChainGL;
use crate::gl::GLInterface; use crate::gl::GLInterface;
use crate::FilterChainGL;
use librashader_runtime::parameters::FilterChainParameters;
use std::collections::hash_map::Iter;
impl AsRef<dyn FilterChainParameters + 'static> for FilterChainDispatch { impl AsRef<dyn FilterChainParameters + 'static> for FilterChainDispatch {
fn as_ref<'a>(&'a self) -> &'a (dyn FilterChainParameters + 'static) { fn as_ref<'a>(&'a self) -> &'a (dyn FilterChainParameters + 'static) {
@ -45,7 +45,7 @@ impl FilterChainParameters for FilterChainGL {
} }
} }
impl <T: GLInterface> FilterChainParameters for FilterChainImpl<T> { impl<T: GLInterface> FilterChainParameters for FilterChainImpl<T> {
fn get_enabled_pass_count(&self) -> usize { fn get_enabled_pass_count(&self) -> usize {
self.common.config.passes_enabled self.common.config.passes_enabled
} }
@ -59,11 +59,20 @@ impl <T: GLInterface> FilterChainParameters for FilterChainImpl<T> {
} }
fn get_parameter(&self, parameter: &str) -> Option<f32> { fn get_parameter(&self, parameter: &str) -> Option<f32> {
self.common.config.parameters.get::<str>(parameter.as_ref()).copied() self.common
.config
.parameters
.get::<str>(parameter.as_ref())
.copied()
} }
fn set_parameter(&mut self, parameter: &str, new_value: f32) -> Option<f32> { fn set_parameter(&mut self, parameter: &str, new_value: f32) -> Option<f32> {
if let Some(value) = self.common.config.parameters.get_mut::<str>(parameter.as_ref()) { if let Some(value) = self
.common
.config
.parameters
.get_mut::<str>(parameter.as_ref())
{
let old = *value; let old = *value;
*value = new_value; *value = new_value;
Some(old) Some(old)
@ -71,4 +80,4 @@ impl <T: GLInterface> FilterChainParameters for FilterChainImpl<T> {
None None
} }
} }
} }

View file

@ -127,15 +127,13 @@ impl<T: GLInterface> FilterPass<T> {
source: &Texture, source: &Texture,
) { ) {
// Bind MVP // Bind MVP
if let Some((location, offset)) = self.uniform_bindings.get(&UniqueSemantics::MVP.into()) if let Some((location, offset)) = self.uniform_bindings.get(&UniqueSemantics::MVP.into()) {
{
self.uniform_storage self.uniform_storage
.bind_mat4(*offset, mvp, location.location()); .bind_mat4(*offset, mvp, location.location());
} }
// bind OutputSize // bind OutputSize
if let Some((location, offset)) = if let Some((location, offset)) = self.uniform_bindings.get(&UniqueSemantics::Output.into())
self.uniform_bindings.get(&UniqueSemantics::Output.into())
{ {
self.uniform_storage self.uniform_storage
.bind_vec4(*offset, fb_size, location.location()); .bind_vec4(*offset, fb_size, location.location());

View file

@ -64,7 +64,10 @@ impl FramebufferInterface for Gl3Framebuffer {
return Ok(fb.size); return Ok(fb.size);
} }
let size = source.image.size.scale_viewport(scaling, viewport.output.size); let size = source
.image
.size
.scale_viewport(scaling, viewport.output.size);
if fb.size != size { if fb.size != size {
fb.size = size; fb.size = size;

View file

@ -3,11 +3,11 @@ use crate::framebuffer::GLImage;
use crate::gl::LoadLut; use crate::gl::LoadLut;
use crate::texture::Texture; use crate::texture::Texture;
use gl::types::{GLsizei, GLuint}; use gl::types::{GLsizei, GLuint};
use librashader_runtime::image::{Image, UVDirection};
use librashader_common::Size; use librashader_common::Size;
use librashader_presets::TextureConfig; use librashader_presets::TextureConfig;
use rustc_hash::FxHashMap; use librashader_runtime::image::{Image, UVDirection};
use librashader_runtime::scaling::MipmapSize; use librashader_runtime::scaling::MipmapSize;
use rustc_hash::FxHashMap;
pub struct Gl3LutLoad; pub struct Gl3LutLoad;
impl LoadLut for Gl3LutLoad { impl LoadLut for Gl3LutLoad {

View file

@ -1,8 +1,8 @@
use crate::binding::UniformLocation; use crate::binding::UniformLocation;
use crate::gl::UboRing; use crate::gl::UboRing;
use librashader_runtime::ringbuffer::InlineRingBuffer;
use gl::types::{GLsizei, GLsizeiptr, GLuint}; use gl::types::{GLsizei, GLsizeiptr, GLuint};
use librashader_reflect::reflect::semantics::UboReflection; use librashader_reflect::reflect::semantics::UboReflection;
use librashader_runtime::ringbuffer::InlineRingBuffer;
use librashader_runtime::ringbuffer::RingBuffer; use librashader_runtime::ringbuffer::RingBuffer;
use librashader_runtime::uniforms::UniformStorageAccess; use librashader_runtime::uniforms::UniformStorageAccess;

View file

@ -76,4 +76,4 @@ impl Drop for Gl46DrawQuad {
} }
} }
} }
} }

View file

@ -62,7 +62,10 @@ impl FramebufferInterface for Gl46Framebuffer {
return Ok(fb.size); return Ok(fb.size);
} }
let size = source.image.size.scale_viewport(scaling, viewport.output.size); let size = source
.image
.size
.scale_viewport(scaling, viewport.output.size);
if fb.size != size { if fb.size != size {
fb.size = size; fb.size = size;

View file

@ -3,11 +3,11 @@ use crate::framebuffer::GLImage;
use crate::gl::LoadLut; use crate::gl::LoadLut;
use crate::texture::Texture; use crate::texture::Texture;
use gl::types::{GLsizei, GLuint}; use gl::types::{GLsizei, GLuint};
use librashader_runtime::image::{Image, UVDirection};
use librashader_common::Size; use librashader_common::Size;
use librashader_presets::TextureConfig; use librashader_presets::TextureConfig;
use rustc_hash::FxHashMap; use librashader_runtime::image::{Image, UVDirection};
use librashader_runtime::scaling::MipmapSize; use librashader_runtime::scaling::MipmapSize;
use rustc_hash::FxHashMap;
pub struct Gl46LutLoad; pub struct Gl46LutLoad;
impl LoadLut for Gl46LutLoad { impl LoadLut for Gl46LutLoad {

View file

@ -18,8 +18,6 @@ impl BindTexture for Gl46BindTexture {
} }
fn gen_mipmaps(texture: &Texture) { fn gen_mipmaps(texture: &Texture) {
unsafe { unsafe { gl::GenerateTextureMipmap(texture.image.handle) }
gl::GenerateTextureMipmap(texture.image.handle)
}
} }
} }

View file

@ -1,8 +1,8 @@
use crate::binding::UniformLocation; use crate::binding::UniformLocation;
use crate::gl::UboRing; use crate::gl::UboRing;
use librashader_runtime::ringbuffer::InlineRingBuffer;
use gl::types::{GLsizei, GLsizeiptr, GLuint}; use gl::types::{GLsizei, GLsizeiptr, GLuint};
use librashader_reflect::reflect::semantics::UboReflection; use librashader_reflect::reflect::semantics::UboReflection;
use librashader_runtime::ringbuffer::InlineRingBuffer;
use librashader_runtime::ringbuffer::RingBuffer; use librashader_runtime::ringbuffer::RingBuffer;
use librashader_runtime::uniforms::UniformStorageAccess; use librashader_runtime::uniforms::UniformStorageAccess;

View file

@ -17,10 +17,10 @@ pub mod error;
pub mod options; pub mod options;
mod viewport; mod viewport;
pub use crate::gl::Framebuffer;
pub use filter_chain::FilterChainGL; pub use filter_chain::FilterChainGL;
pub use framebuffer::GLImage; pub use framebuffer::GLImage;
pub use viewport::Viewport; pub use viewport::Viewport;
pub use crate::gl::Framebuffer;
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {

View file

@ -1,15 +1,9 @@
static VBO_OFFSCREEN_MVP: &[f32; 16] = &[ static VBO_OFFSCREEN_MVP: &[f32; 16] = &[
// Offscreen // Offscreen
-1.0, -1.0, 0.0, 0.0, -1.0, -1.0, 0.0, 0.0, -1.0, 1.0, 0.0, 1.0, 1.0, -1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0,
-1.0, 1.0, 0.0, 1.0,
1.0, -1.0, 1.0, 0.0,
1.0, 1.0, 1.0, 1.0,
]; ];
static VBO_DEFAULT_FINAL_MVP: &[f32; 16] = &[ static VBO_DEFAULT_FINAL_MVP: &[f32; 16] = &[
// Final // Final
0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0,
0.0, 1.0, 0.0, 1.0,
1.0, 0.0, 1.0, 0.0,
1.0, 1.0, 1.0, 1.0,
]; ];

View file

@ -1,3 +1,3 @@
use std::error::Error; use std::error::Error;
pub type Result<T> = std::result::Result<T, Box<dyn Error>>; pub type Result<T> = std::result::Result<T, Box<dyn Error>>;

View file

@ -1,22 +1,24 @@
use std::error::Error;
use std::path::Path;
use ash::{Device, vk};
use ash::vk::{CommandPoolCreateFlags, PFN_vkGetInstanceProcAddr, Queue, StaticFn};
use rustc_hash::FxHashMap;
use librashader_common::ImageFormat;
use librashader_preprocess::ShaderSource;
use librashader_presets::{ShaderPassConfig, ShaderPreset, TextureConfig};
use librashader_reflect::back::{CompilerBackend, CompileShader, FromCompilation};
use librashader_reflect::back::targets::SpirV;
use librashader_reflect::front::shaderc::GlslangCompilation;
use librashader_reflect::reflect::ReflectShader;
use librashader_reflect::reflect::semantics::{Semantic, ShaderSemantics, TextureSemantics, UniformBinding, UniformSemantic, UniqueSemantics};
use librashader_runtime::image::{Image, UVDirection};
use librashader_runtime::uniforms::UniformStorage;
use crate::error; use crate::error;
use crate::filter_pass::FilterPass; use crate::filter_pass::FilterPass;
use crate::luts::LutTexture; use crate::luts::LutTexture;
use crate::vulkan_state::VulkanGraphicsPipeline; use crate::vulkan_state::VulkanGraphicsPipeline;
use ash::vk::{CommandPoolCreateFlags, PFN_vkGetInstanceProcAddr, Queue, StaticFn};
use ash::{vk, Device};
use librashader_common::ImageFormat;
use librashader_preprocess::ShaderSource;
use librashader_presets::{ShaderPassConfig, ShaderPreset, TextureConfig};
use librashader_reflect::back::targets::SpirV;
use librashader_reflect::back::{CompileShader, CompilerBackend, FromCompilation};
use librashader_reflect::front::shaderc::GlslangCompilation;
use librashader_reflect::reflect::semantics::{
Semantic, ShaderSemantics, TextureSemantics, UniformBinding, UniformSemantic, UniqueSemantics,
};
use librashader_reflect::reflect::ReflectShader;
use librashader_runtime::image::{Image, UVDirection};
use librashader_runtime::uniforms::UniformStorage;
use rustc_hash::FxHashMap;
use std::error::Error;
use std::path::Path;
pub struct Vulkan { pub struct Vulkan {
// physical_device: vk::PhysicalDevice, // physical_device: vk::PhysicalDevice,
@ -31,12 +33,9 @@ pub struct Vulkan {
type ShaderPassMeta = ( type ShaderPassMeta = (
ShaderPassConfig, ShaderPassConfig,
ShaderSource, ShaderSource,
CompilerBackend< CompilerBackend<impl CompileShader<SpirV, Options = Option<()>, Context = ()> + ReflectShader>,
impl CompileShader<SpirV, Options = Option<()>, Context =()> + ReflectShader,
>,
); );
#[derive(Clone)] #[derive(Clone)]
pub struct VulkanInfo<'a> { pub struct VulkanInfo<'a> {
// physical_device: &'a vk::PhysicalDevice, // physical_device: &'a vk::PhysicalDevice,
@ -44,7 +43,7 @@ pub struct VulkanInfo<'a> {
instance: &'a vk::Instance, instance: &'a vk::Instance,
queue: &'a vk::Queue, queue: &'a vk::Queue,
memory_properties: &'a vk::PhysicalDeviceMemoryProperties, memory_properties: &'a vk::PhysicalDeviceMemoryProperties,
get_instance_proc_addr: PFN_vkGetInstanceProcAddr get_instance_proc_addr: PFN_vkGetInstanceProcAddr,
} }
impl TryFrom<VulkanInfo<'_>> for Vulkan { impl TryFrom<VulkanInfo<'_>> for Vulkan {
@ -52,21 +51,26 @@ impl TryFrom<VulkanInfo<'_>> for Vulkan {
fn try_from(vulkan: VulkanInfo) -> Result<Self, Box<dyn Error>> { fn try_from(vulkan: VulkanInfo) -> Result<Self, Box<dyn Error>> {
unsafe { unsafe {
let instance = ash::Instance::load(&StaticFn { let instance = ash::Instance::load(
get_instance_proc_addr: vulkan.get_instance_proc_addr, &StaticFn {
}, vulkan.instance.clone()); get_instance_proc_addr: vulkan.get_instance_proc_addr,
},
vulkan.instance.clone(),
);
let device = ash::Device::load(instance.fp_v1_0(), vulkan.device.clone()); let device = ash::Device::load(instance.fp_v1_0(), vulkan.device.clone());
let pipeline_cache = unsafe { let pipeline_cache = unsafe {
device.create_pipeline_cache(&vk::PipelineCacheCreateInfo::default(), device.create_pipeline_cache(&vk::PipelineCacheCreateInfo::default(), None)?
None)?
}; };
let command_pool = unsafe { let command_pool = unsafe {
device.create_command_pool(&vk::CommandPoolCreateInfo::builder() device.create_command_pool(
.flags(CommandPoolCreateFlags::RESET_COMMAND_BUFFER) &vk::CommandPoolCreateInfo::builder()
.build(), None)? .flags(CommandPoolCreateFlags::RESET_COMMAND_BUFFER)
.build(),
None,
)?
}; };
Ok(Vulkan { Ok(Vulkan {
@ -75,7 +79,7 @@ impl TryFrom<VulkanInfo<'_>> for Vulkan {
queue: vulkan.queue.clone(), queue: vulkan.queue.clone(),
command_pool, command_pool,
pipeline_cache, pipeline_cache,
memory_properties: vulkan.memory_properties.clone() memory_properties: vulkan.memory_properties.clone(),
}) })
} }
} }
@ -89,14 +93,16 @@ impl TryFrom<(ash::Device, vk::Queue, vk::PhysicalDeviceMemoryProperties)> for V
let device = value.0; let device = value.0;
let pipeline_cache = unsafe { let pipeline_cache = unsafe {
device.create_pipeline_cache(&vk::PipelineCacheCreateInfo::default(), device.create_pipeline_cache(&vk::PipelineCacheCreateInfo::default(), None)?
None)?
}; };
let command_pool = unsafe { let command_pool = unsafe {
device.create_command_pool(&vk::CommandPoolCreateInfo::builder() device.create_command_pool(
.flags(CommandPoolCreateFlags::RESET_COMMAND_BUFFER) &vk::CommandPoolCreateInfo::builder()
.build(), None)? .flags(CommandPoolCreateFlags::RESET_COMMAND_BUFFER)
.build(),
None,
)?
}; };
Ok(Vulkan { Ok(Vulkan {
@ -104,7 +110,7 @@ impl TryFrom<(ash::Device, vk::Queue, vk::PhysicalDeviceMemoryProperties)> for V
queue: value.1, queue: value.1,
command_pool, command_pool,
pipeline_cache, pipeline_cache,
memory_properties: value.2 memory_properties: value.2,
}) })
} }
} }
@ -134,7 +140,7 @@ pub type FilterChainOptionsVulkan = ();
impl FilterChainVulkan { impl FilterChainVulkan {
/// Load the shader preset at the given path into a filter chain. /// Load the shader preset at the given path into a filter chain.
pub fn load_from_path( pub fn load_from_path(
vulkan: impl TryInto<Vulkan, Error=Box<dyn Error>>, vulkan: impl TryInto<Vulkan, Error = Box<dyn Error>>,
path: impl AsRef<Path>, path: impl AsRef<Path>,
options: Option<&FilterChainOptionsVulkan>, options: Option<&FilterChainOptionsVulkan>,
) -> error::Result<FilterChainVulkan> { ) -> error::Result<FilterChainVulkan> {
@ -144,7 +150,7 @@ impl FilterChainVulkan {
} }
pub fn load_from_preset( pub fn load_from_preset(
vulkan: impl TryInto<Vulkan, Error=Box<dyn Error>>, vulkan: impl TryInto<Vulkan, Error = Box<dyn Error>>,
preset: ShaderPreset, preset: ShaderPreset,
options: Option<&FilterChainOptionsVulkan>, options: Option<&FilterChainOptionsVulkan>,
) -> error::Result<FilterChainVulkan> { ) -> error::Result<FilterChainVulkan> {
@ -158,9 +164,7 @@ impl FilterChainVulkan {
eprintln!("filters initialized ok."); eprintln!("filters initialized ok.");
Ok(FilterChainVulkan { Ok(FilterChainVulkan {
common: FilterCommon { common: FilterCommon { luts },
luts
},
passes: filters, passes: filters,
}) })
} }
@ -194,7 +198,8 @@ impl FilterChainVulkan {
Ok::<_, Box<dyn Error>>((shader, source, reflect)) Ok::<_, Box<dyn Error>>((shader, source, reflect))
}) })
.into_iter() .into_iter()
.collect::<error::Result<Vec<(ShaderPassConfig, ShaderSource, CompilerBackend<_>)>>>()?; .collect::<error::Result<Vec<(ShaderPassConfig, ShaderSource, CompilerBackend<_>)>>>(
)?;
for details in &passes { for details in &passes {
librashader_runtime::semantics::insert_pass_semantics( librashader_runtime::semantics::insert_pass_semantics(
@ -261,10 +266,15 @@ impl FilterChainVulkan {
if source.format == ImageFormat::Unknown { if source.format == ImageFormat::Unknown {
source.format = ImageFormat::R8G8B8A8Unorm source.format = ImageFormat::R8G8B8A8Unorm
} }
let graphics_pipeline = VulkanGraphicsPipeline::new(&vulkan.device, let graphics_pipeline = VulkanGraphicsPipeline::new(
&vulkan.pipeline_cache, &vulkan.device,
&spirv_words, &reflection, source.format, images)?; &vulkan.pipeline_cache,
&spirv_words,
&reflection,
source.format,
images,
)?;
// shader_vulkan: 2026 // shader_vulkan: 2026
filters.push(FilterPass { filters.push(FilterPass {
@ -273,11 +283,10 @@ impl FilterChainVulkan {
uniform_bindings, uniform_bindings,
source, source,
config, config,
graphics_pipeline graphics_pipeline,
}); });
} }
Ok(filters.into_boxed_slice()) Ok(filters.into_boxed_slice())
} }
@ -288,28 +297,28 @@ impl FilterChainVulkan {
let mut luts = FxHashMap::default(); let mut luts = FxHashMap::default();
let command_buffer = unsafe { let command_buffer = unsafe {
// panic safety: command buffer count = 1 // panic safety: command buffer count = 1
vulkan.device.allocate_command_buffers(&vk::CommandBufferAllocateInfo::builder() vulkan.device.allocate_command_buffers(
.command_pool(vulkan.command_pool) &vk::CommandBufferAllocateInfo::builder()
.level(vk::CommandBufferLevel::PRIMARY) .command_pool(vulkan.command_pool)
.command_buffer_count(1) .level(vk::CommandBufferLevel::PRIMARY)
.build())?[0] .command_buffer_count(1)
.build(),
)?[0]
}; };
unsafe { unsafe {
vulkan.device.begin_command_buffer(command_buffer, &vk::CommandBufferBeginInfo::builder() vulkan.device.begin_command_buffer(
.flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT) command_buffer,
.build())? &vk::CommandBufferBeginInfo::builder()
.flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT)
.build(),
)?
} }
for (index, texture) in textures.iter().enumerate() { for (index, texture) in textures.iter().enumerate() {
let image = Image::load(&texture.path, UVDirection::TopLeft)?; let image = Image::load(&texture.path, UVDirection::TopLeft)?;
let texture = LutTexture::new( let texture = LutTexture::new(vulkan, &command_buffer, image, texture)?;
vulkan,
&command_buffer,
image,
texture,
)?;
luts.insert(index, texture); luts.insert(index, texture);
} }
@ -317,14 +326,16 @@ impl FilterChainVulkan {
vulkan.device.end_command_buffer(command_buffer)?; vulkan.device.end_command_buffer(command_buffer)?;
let buffers = [command_buffer]; let buffers = [command_buffer];
let submits = [vk::SubmitInfo::builder() let submits = [vk::SubmitInfo::builder().command_buffers(&buffers).build()];
.command_buffers(&buffers).build()];
vulkan.device.queue_submit(vulkan.queue, &submits, vk::Fence::null())?; vulkan
.device
.queue_submit(vulkan.queue, &submits, vk::Fence::null())?;
vulkan.device.queue_wait_idle(vulkan.queue)?; vulkan.device.queue_wait_idle(vulkan.queue)?;
vulkan.device.free_command_buffers(vulkan.command_pool, &buffers); vulkan
.device
.free_command_buffers(vulkan.command_pool, &buffers);
} }
Ok(luts) Ok(luts)
} }
}
}

View file

@ -1,10 +1,10 @@
use rustc_hash::FxHashMap; use crate::vulkan_state::VulkanGraphicsPipeline;
use librashader_preprocess::ShaderSource; use librashader_preprocess::ShaderSource;
use librashader_presets::ShaderPassConfig; use librashader_presets::ShaderPassConfig;
use librashader_reflect::back::ShaderCompilerOutput; use librashader_reflect::back::ShaderCompilerOutput;
use librashader_reflect::reflect::semantics::{MemberOffset, UniformBinding}; use librashader_reflect::reflect::semantics::{MemberOffset, UniformBinding};
use librashader_runtime::uniforms::UniformStorage; use librashader_runtime::uniforms::UniformStorage;
use crate::vulkan_state::VulkanGraphicsPipeline; use rustc_hash::FxHashMap;
pub struct FilterPass { pub struct FilterPass {
pub(crate) compiled: ShaderCompilerOutput<Vec<u32>>, pub(crate) compiled: ShaderCompilerOutput<Vec<u32>>,

View file

@ -1,11 +1,14 @@
use ash::vk;
use ash::vk::{Extent3D, ImageAspectFlags, ImageLayout, ImageTiling, ImageType, ImageUsageFlags, ImageViewType, SampleCountFlags, SharingMode};
use librashader_common::Size;
use librashader_runtime::scaling::MipmapSize;
use crate::error; use crate::error;
use crate::renderpass::VulkanRenderPass; use crate::renderpass::VulkanRenderPass;
use crate::util::find_vulkan_memory_type; use crate::util::find_vulkan_memory_type;
use crate::vulkan_primitives::VulkanImageMemory; use crate::vulkan_primitives::VulkanImageMemory;
use ash::vk;
use ash::vk::{
Extent3D, ImageAspectFlags, ImageLayout, ImageTiling, ImageType, ImageUsageFlags,
ImageViewType, SampleCountFlags, SharingMode,
};
use librashader_common::Size;
use librashader_runtime::scaling::MipmapSize;
pub struct Framebuffer { pub struct Framebuffer {
device: ash::Device, device: ash::Device,
@ -13,7 +16,7 @@ pub struct Framebuffer {
max_levels: u32, max_levels: u32,
mem_props: vk::PhysicalDeviceMemoryProperties, mem_props: vk::PhysicalDeviceMemoryProperties,
render_pass: VulkanRenderPass, render_pass: VulkanRenderPass,
framebuffer: Option<VulkanFramebuffer> framebuffer: Option<VulkanFramebuffer>,
} }
pub struct VulkanFramebuffer { pub struct VulkanFramebuffer {
@ -45,14 +48,20 @@ impl Drop for VulkanFramebuffer {
} }
impl Framebuffer { impl Framebuffer {
pub fn new(device: &ash::Device, size: Size<u32>, render_pass: VulkanRenderPass, mip_levels: u32, mem_props: vk::PhysicalDeviceMemoryProperties) -> error::Result<Self> { pub fn new(
device: &ash::Device,
size: Size<u32>,
render_pass: VulkanRenderPass,
mip_levels: u32,
mem_props: vk::PhysicalDeviceMemoryProperties,
) -> error::Result<Self> {
let mut framebuffer = Framebuffer { let mut framebuffer = Framebuffer {
device: device.clone(), device: device.clone(),
size, size,
max_levels: mip_levels, max_levels: mip_levels,
mem_props, mem_props,
render_pass, render_pass,
framebuffer: None framebuffer: None,
}; };
let vulkan_image = framebuffer.create_vulkan_image()?; let vulkan_image = framebuffer.create_vulkan_image()?;
@ -66,11 +75,19 @@ impl Framebuffer {
.image_type(ImageType::TYPE_2D) .image_type(ImageType::TYPE_2D)
.format(self.render_pass.format.into()) .format(self.render_pass.format.into())
.extent(self.size.into()) .extent(self.size.into())
.mip_levels(std::cmp::min(self.max_levels, self.size.calculate_miplevels())) .mip_levels(std::cmp::min(
self.max_levels,
self.size.calculate_miplevels(),
))
.array_layers(1) .array_layers(1)
.samples(SampleCountFlags::TYPE_1) .samples(SampleCountFlags::TYPE_1)
.tiling(ImageTiling::OPTIMAL) .tiling(ImageTiling::OPTIMAL)
.usage(ImageUsageFlags::SAMPLED | ImageUsageFlags::COLOR_ATTACHMENT | ImageUsageFlags::TRANSFER_DST | ImageUsageFlags::TRANSFER_SRC) .usage(
ImageUsageFlags::SAMPLED
| ImageUsageFlags::COLOR_ATTACHMENT
| ImageUsageFlags::TRANSFER_DST
| ImageUsageFlags::TRANSFER_SRC,
)
.sharing_mode(SharingMode::EXCLUSIVE) .sharing_mode(SharingMode::EXCLUSIVE)
.initial_layout(ImageLayout::UNDEFINED) .initial_layout(ImageLayout::UNDEFINED)
.build(); .build();
@ -80,7 +97,11 @@ impl Framebuffer {
let alloc_info = vk::MemoryAllocateInfo::builder() let alloc_info = vk::MemoryAllocateInfo::builder()
.allocation_size(mem_reqs.size) .allocation_size(mem_reqs.size)
.memory_type_index(find_vulkan_memory_type(&self.mem_props, mem_reqs.memory_type_bits, vk::MemoryPropertyFlags::DEVICE_LOCAL)) .memory_type_index(find_vulkan_memory_type(
&self.mem_props,
mem_reqs.memory_type_bits,
vk::MemoryPropertyFlags::DEVICE_LOCAL,
))
.build(); .build();
// todo: optimize by reusing existing memory. // todo: optimize by reusing existing memory.
@ -109,22 +130,22 @@ impl Framebuffer {
.components(swizzle_components) .components(swizzle_components)
.build(); .build();
let image_view = unsafe { let image_view = unsafe { self.device.create_image_view(&view_info, None)? };
self.device.create_image_view(&view_info, None)?
};
view_info.subresource_range.level_count = 1; view_info.subresource_range.level_count = 1;
let fb_view = unsafe { let fb_view = unsafe { self.device.create_image_view(&view_info, None)? };
self.device.create_image_view(&view_info, None)?
};
let framebuffer = unsafe { let framebuffer = unsafe {
self.device.create_framebuffer(&vk::FramebufferCreateInfo::builder() self.device.create_framebuffer(
.render_pass(self.render_pass.render_pass) &vk::FramebufferCreateInfo::builder()
.attachments(&[image_view]) .render_pass(self.render_pass.render_pass)
.width(self.size.width) .attachments(&[image_view])
.height(self.size.height) .width(self.size.width)
.layers(1).build(), None)? .height(self.size.height)
.layers(1)
.build(),
None,
)?
}; };
Ok(VulkanFramebuffer { Ok(VulkanFramebuffer {
@ -133,8 +154,7 @@ impl Framebuffer {
memory, memory,
image_view, image_view,
fb_view, fb_view,
image image,
}) })
} }
} }

View file

@ -1,3 +1,4 @@
use crate::offset_of;
use ash::util::*; use ash::util::*;
use ash::vk; use ash::vk;
use std::default::Default; use std::default::Default;
@ -5,7 +6,6 @@ use std::ffi::CStr;
use std::io::Cursor; use std::io::Cursor;
use std::mem; use std::mem;
use std::mem::align_of; use std::mem::align_of;
use crate::offset_of;
mod base; mod base;
pub use base::*; pub use base::*;
@ -99,7 +99,7 @@ pub(crate) fn main(base: ExampleBase) {
&base.device_memory_properties, &base.device_memory_properties,
vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT, vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT,
) )
.expect("Unable to find suitable memorytype for the index buffer."); .expect("Unable to find suitable memorytype for the index buffer.");
let index_allocate_info = vk::MemoryAllocateInfo { let index_allocate_info = vk::MemoryAllocateInfo {
allocation_size: index_buffer_memory_req.size, allocation_size: index_buffer_memory_req.size,
@ -151,7 +151,7 @@ pub(crate) fn main(base: ExampleBase) {
&base.device_memory_properties, &base.device_memory_properties,
vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT, vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT,
) )
.expect("Unable to find suitable memorytype for the vertex buffer."); .expect("Unable to find suitable memorytype for the vertex buffer.");
let vertex_buffer_allocate_info = vk::MemoryAllocateInfo { let vertex_buffer_allocate_info = vk::MemoryAllocateInfo {
allocation_size: vertex_input_buffer_memory_req.size, allocation_size: vertex_input_buffer_memory_req.size,
@ -164,7 +164,6 @@ pub(crate) fn main(base: ExampleBase) {
.allocate_memory(&vertex_buffer_allocate_info, None) .allocate_memory(&vertex_buffer_allocate_info, None)
.unwrap(); .unwrap();
let vertices = [ let vertices = [
// green // green
Vertex { Vertex {
@ -202,8 +201,7 @@ pub(crate) fn main(base: ExampleBase) {
base.device base.device
.bind_buffer_memory(vertex_input_buffer, vertex_input_buffer_memory, 0) .bind_buffer_memory(vertex_input_buffer, vertex_input_buffer_memory, 0)
.unwrap(); .unwrap();
let mut vertex_spv_file = let mut vertex_spv_file = Cursor::new(&include_bytes!("../shader/triangle/vert.spv")[..]);
Cursor::new(&include_bytes!("../shader/triangle/vert.spv")[..]);
let mut frag_spv_file = Cursor::new(&include_bytes!("../shader/triangle/frag.spv")[..]); let mut frag_spv_file = Cursor::new(&include_bytes!("../shader/triangle/frag.spv")[..]);
let vertex_code = let vertex_code =

View file

@ -21,13 +21,13 @@ use ash::vk::{
KhrGetPhysicalDeviceProperties2Fn, KhrPortabilityEnumerationFn, KhrPortabilitySubsetFn, KhrGetPhysicalDeviceProperties2Fn, KhrPortabilityEnumerationFn, KhrPortabilitySubsetFn,
}; };
use winit::event_loop::EventLoopBuilder;
use winit::{ use winit::{
event::{ElementState, Event, KeyboardInput, VirtualKeyCode, WindowEvent}, event::{ElementState, Event, KeyboardInput, VirtualKeyCode, WindowEvent},
event_loop::{ControlFlow, EventLoop}, event_loop::{ControlFlow, EventLoop},
platform::run_return::EventLoopExtRunReturn, platform::run_return::EventLoopExtRunReturn,
window::WindowBuilder, window::WindowBuilder,
}; };
use winit::event_loop::EventLoopBuilder;
// Simple offset_of macro akin to C++ offsetof // Simple offset_of macro akin to C++ offsetof
#[macro_export] #[macro_export]
@ -195,16 +195,16 @@ impl ExampleBase {
match event { match event {
Event::WindowEvent { Event::WindowEvent {
event: event:
WindowEvent::CloseRequested WindowEvent::CloseRequested
| WindowEvent::KeyboardInput { | WindowEvent::KeyboardInput {
input: input:
KeyboardInput { KeyboardInput {
state: ElementState::Pressed, state: ElementState::Pressed,
virtual_keycode: Some(VirtualKeyCode::Escape), virtual_keycode: Some(VirtualKeyCode::Escape),
..
},
.. ..
}, },
..
},
.. ..
} => *control_flow = ControlFlow::Exit, } => *control_flow = ControlFlow::Exit,
Event::MainEventsCleared => f(), Event::MainEventsCleared => f(),
@ -215,9 +215,7 @@ impl ExampleBase {
pub fn new(window_width: u32, window_height: u32) -> Self { pub fn new(window_width: u32, window_height: u32) -> Self {
unsafe { unsafe {
let mut event_loop = EventLoopBuilder::new() let mut event_loop = EventLoopBuilder::new().with_any_thread(true).build();
.with_any_thread(true)
.build();
let window = WindowBuilder::new() let window = WindowBuilder::new()
.with_title("Ash - Example") .with_title("Ash - Example")
.with_inner_size(winit::dpi::LogicalSize::new( .with_inner_size(winit::dpi::LogicalSize::new(
@ -298,7 +296,7 @@ impl ExampleBase {
window.raw_window_handle(), window.raw_window_handle(),
None, None,
) )
.unwrap(); .unwrap();
let pdevices = instance let pdevices = instance
.enumerate_physical_devices() .enumerate_physical_devices()
.expect("Physical device error"); .expect("Physical device error");
@ -314,12 +312,12 @@ impl ExampleBase {
let supports_graphic_and_surface = let supports_graphic_and_surface =
info.queue_flags.contains(vk::QueueFlags::GRAPHICS) info.queue_flags.contains(vk::QueueFlags::GRAPHICS)
&& surface_loader && surface_loader
.get_physical_device_surface_support( .get_physical_device_surface_support(
*pdevice, *pdevice,
index as u32, index as u32,
surface, surface,
) )
.unwrap(); .unwrap();
if supports_graphic_and_surface { if supports_graphic_and_surface {
Some((*pdevice, index)) Some((*pdevice, index))
} else { } else {
@ -332,7 +330,7 @@ impl ExampleBase {
let device_extension_names_raw = [ let device_extension_names_raw = [
Swapchain::name().as_ptr(), Swapchain::name().as_ptr(),
#[cfg(any(target_os = "macos", target_os = "ios"))] #[cfg(any(target_os = "macos", target_os = "ios"))]
KhrPortabilitySubsetFn::name().as_ptr(), KhrPortabilitySubsetFn::name().as_ptr(),
]; ];
let features = vk::PhysicalDeviceFeatures { let features = vk::PhysicalDeviceFeatures {
shader_clip_distance: 1, shader_clip_distance: 1,
@ -471,7 +469,7 @@ impl ExampleBase {
&device_memory_properties, &device_memory_properties,
vk::MemoryPropertyFlags::DEVICE_LOCAL, vk::MemoryPropertyFlags::DEVICE_LOCAL,
) )
.expect("Unable to find suitable memory index for depth image."); .expect("Unable to find suitable memory index for depth image.");
let depth_image_allocate_info = vk::MemoryAllocateInfo::builder() let depth_image_allocate_info = vk::MemoryAllocateInfo::builder()
.allocation_size(depth_image_memory_req.size) .allocation_size(depth_image_memory_req.size)
@ -620,4 +618,4 @@ impl Drop for ExampleBase {
self.instance.destroy_instance(None); self.instance.destroy_instance(None);
} }
} }
} }

View file

@ -1,22 +1,22 @@
#![feature(type_alias_impl_trait)] #![feature(type_alias_impl_trait)]
#![feature(let_chains)] #![feature(let_chains)]
mod hello_triangle; mod draw_quad;
mod error;
mod filter_chain; mod filter_chain;
mod filter_pass; mod filter_pass;
mod error;
mod util;
mod framebuffer; mod framebuffer;
mod vulkan_state; mod hello_triangle;
mod draw_quad;
mod renderpass;
mod vulkan_primitives;
mod luts; mod luts;
mod renderpass;
mod util;
mod vulkan_primitives;
mod vulkan_state;
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::filter_chain::FilterChainVulkan;
use super::*; use super::*;
use crate::filter_chain::FilterChainVulkan;
#[test] #[test]
fn triangle_vk() { fn triangle_vk() {
let base = hello_triangle::ExampleBase::new(900, 600); let base = hello_triangle::ExampleBase::new(900, 600);
@ -27,13 +27,16 @@ mod tests {
// ) // )
let mut filter = FilterChainVulkan::load_from_path( let mut filter = FilterChainVulkan::load_from_path(
(base.device.clone(), base.present_queue.clone(), base.device_memory_properties.clone()), (
base.device.clone(),
base.present_queue.clone(),
base.device_memory_properties.clone(),
),
"../test/slang-shaders/border/gameboy-player/gameboy-player-crt-royale.slangp", "../test/slang-shaders/border/gameboy-player/gameboy-player-crt-royale.slangp",
None None,
) )
// FilterChain::load_from_path("../test/slang-shaders/bezel/Mega_Bezel/Presets/MBZ__0__SMOOTH-ADV.slangp", None) // FilterChain::load_from_path("../test/slang-shaders/bezel/Mega_Bezel/Presets/MBZ__0__SMOOTH-ADV.slangp", None)
.unwrap(); .unwrap();
hello_triangle::main(base); hello_triangle::main(base);
} }
} }

View file

@ -1,13 +1,13 @@
use crate::filter_chain::Vulkan;
use crate::vulkan_primitives::{VulkanBuffer, VulkanImageMemory};
use crate::{error, util};
use ash::vk; use ash::vk;
use ash::vk::ImageSubresourceLayers; use ash::vk::ImageSubresourceLayers;
use glfw::Key::P; use glfw::Key::P;
use librashader_common::{FilterMode, WrapMode}; use librashader_common::{FilterMode, WrapMode};
use librashader_presets::TextureConfig; use librashader_presets::TextureConfig;
use librashader_runtime::image::{BGRA8, Image}; use librashader_runtime::image::{Image, BGRA8};
use librashader_runtime::scaling::MipmapSize; use librashader_runtime::scaling::MipmapSize;
use crate::filter_chain::Vulkan;
use crate::{error, util};
use crate::vulkan_primitives::{VulkanBuffer, VulkanImageMemory};
pub struct LutTexture { pub struct LutTexture {
pub texture: vk::Image, pub texture: vk::Image,
@ -20,8 +20,12 @@ pub struct LutTexture {
} }
impl LutTexture { impl LutTexture {
pub fn new(vulkan: &Vulkan, cmd: &vk::CommandBuffer, image: Image<BGRA8>, config: &TextureConfig) -> error::Result<LutTexture> { pub fn new(
vulkan: &Vulkan,
cmd: &vk::CommandBuffer,
image: Image<BGRA8>,
config: &TextureConfig,
) -> error::Result<LutTexture> {
// todo: might need to use bgra8 // todo: might need to use bgra8
let image_info = vk::ImageCreateInfo::builder() let image_info = vk::ImageCreateInfo::builder()
.image_type(vk::ImageType::TYPE_2D) .image_type(vk::ImageType::TYPE_2D)
@ -35,20 +39,29 @@ impl LutTexture {
.array_layers(1) .array_layers(1)
.samples(vk::SampleCountFlags::TYPE_1) .samples(vk::SampleCountFlags::TYPE_1)
.tiling(vk::ImageTiling::OPTIMAL) .tiling(vk::ImageTiling::OPTIMAL)
.usage(vk::ImageUsageFlags::SAMPLED | vk::ImageUsageFlags::TRANSFER_SRC | vk::ImageUsageFlags::TRANSFER_DST) .usage(
vk::ImageUsageFlags::SAMPLED
| vk::ImageUsageFlags::TRANSFER_SRC
| vk::ImageUsageFlags::TRANSFER_DST,
)
.initial_layout(vk::ImageLayout::UNDEFINED) .initial_layout(vk::ImageLayout::UNDEFINED)
.build(); .build();
let texture = unsafe { let texture = unsafe { vulkan.device.create_image(&image_info, None)? };
vulkan.device.create_image(&image_info, None)?
};
let memory = unsafe { let memory = unsafe {
let mem_reqs = vulkan.device.get_image_memory_requirements(texture.clone()); let mem_reqs = vulkan.device.get_image_memory_requirements(texture.clone());
let mem_type = util::find_vulkan_memory_type(&vulkan.memory_properties, mem_reqs.memory_type_bits, vk::MemoryPropertyFlags::DEVICE_LOCAL); let mem_type = util::find_vulkan_memory_type(
crate::vulkan_primitives::VulkanImageMemory::new(&vulkan.device, &vk::MemoryAllocateInfo::builder() &vulkan.memory_properties,
.memory_type_index(mem_type) mem_reqs.memory_type_bits,
.allocation_size(mem_reqs.size))? vk::MemoryPropertyFlags::DEVICE_LOCAL,
);
crate::vulkan_primitives::VulkanImageMemory::new(
&vulkan.device,
&vk::MemoryAllocateInfo::builder()
.memory_type_index(mem_type)
.allocation_size(mem_reqs.size),
)?
}; };
memory.bind(&texture)?; memory.bind(&texture)?;
@ -74,20 +87,26 @@ impl LutTexture {
.components(swizzle_components) .components(swizzle_components)
.build(); .build();
let texture_view = unsafe { let texture_view = unsafe { vulkan.device.create_image_view(&view_info, None)? };
vulkan.device.create_image_view(&view_info, None)?
};
let mut staging = VulkanBuffer::new(&vulkan.device, &vulkan.memory_properties, vk::BufferUsageFlags::TRANSFER_SRC, image.bytes.len())?; let mut staging = VulkanBuffer::new(
&vulkan.device,
&vulkan.memory_properties,
vk::BufferUsageFlags::TRANSFER_SRC,
image.bytes.len(),
)?;
unsafe { unsafe {
let mut handle = staging.map()?; let mut handle = staging.map()?;
handle.copy_from(&image.bytes) handle.copy_from(&image.bytes)
} }
unsafe { unsafe {
util::vulkan_image_layout_transition_levels(&vulkan.device, *cmd, texture, util::vulkan_image_layout_transition_levels(
vk::REMAINING_MIP_LEVELS, &vulkan.device,
vk::ImageLayout::UNDEFINED, *cmd,
texture,
vk::REMAINING_MIP_LEVELS,
vk::ImageLayout::UNDEFINED,
if config.mipmap { if config.mipmap {
vk::ImageLayout::GENERAL vk::ImageLayout::GENERAL
} else { } else {
@ -97,23 +116,31 @@ impl LutTexture {
vk::AccessFlags::TRANSFER_WRITE, vk::AccessFlags::TRANSFER_WRITE,
vk::PipelineStageFlags::TOP_OF_PIPE, vk::PipelineStageFlags::TOP_OF_PIPE,
vk::PipelineStageFlags::TRANSFER, vk::PipelineStageFlags::TRANSFER,
vk::QUEUE_FAMILY_IGNORED, vk::QUEUE_FAMILY_IGNORED,
vk::QUEUE_FAMILY_IGNORED vk::QUEUE_FAMILY_IGNORED,
); );
vulkan.device.cmd_copy_buffer_to_image(*cmd, vulkan.device.cmd_copy_buffer_to_image(
staging.handle, *cmd,
texture, staging.handle,
if config.mipmap { vk::ImageLayout::GENERAL } else { vk::ImageLayout::TRANSFER_DST_OPTIMAL }, texture,
&[vk::BufferImageCopy::builder() if config.mipmap {
.image_subresource(vk::ImageSubresourceLayers::builder() vk::ImageLayout::GENERAL
.aspect_mask(vk::ImageAspectFlags::COLOR) } else {
.mip_level(0) vk::ImageLayout::TRANSFER_DST_OPTIMAL
.base_array_layer(0) },
.layer_count(1) &[vk::BufferImageCopy::builder()
.build()) .image_subresource(
.image_extent(image.size.into()).build()]) vk::ImageSubresourceLayers::builder()
.aspect_mask(vk::ImageAspectFlags::COLOR)
.mip_level(0)
.base_array_layer(0)
.layer_count(1)
.build(),
)
.image_extent(image.size.into())
.build()],
)
} }
// generate mipmaps // generate mipmaps
@ -122,11 +149,7 @@ impl LutTexture {
let target_size = image.size.scale_mipmap(level); let target_size = image.size.scale_mipmap(level);
let src_offsets = [ let src_offsets = [
vk::Offset3D { vk::Offset3D { x: 0, y: 0, z: 0 },
x: 0,
y: 0,
z: 0,
},
vk::Offset3D { vk::Offset3D {
x: source_size.width as i32, x: source_size.width as i32,
y: source_size.height as i32, y: source_size.height as i32,
@ -135,11 +158,7 @@ impl LutTexture {
]; ];
let dst_offsets = [ let dst_offsets = [
vk::Offset3D { vk::Offset3D { x: 0, y: 0, z: 0 },
x: 0,
y: 0,
z: 0,
},
vk::Offset3D { vk::Offset3D {
x: target_size.width as i32, x: target_size.width as i32,
y: target_size.height as i32, y: target_size.height as i32,
@ -168,34 +187,52 @@ impl LutTexture {
.build()]; .build()];
unsafe { unsafe {
util::vulkan_image_layout_transition_levels(&vulkan.device, *cmd, texture, util::vulkan_image_layout_transition_levels(
vk::REMAINING_MIP_LEVELS, &vulkan.device,
vk::ImageLayout::GENERAL, *cmd,
vk::ImageLayout::GENERAL, texture,
vk::AccessFlags::TRANSFER_WRITE, vk::REMAINING_MIP_LEVELS,
vk::AccessFlags::TRANSFER_READ, vk::ImageLayout::GENERAL,
vk::PipelineStageFlags::TRANSFER, vk::ImageLayout::GENERAL,
vk::PipelineStageFlags::TRANSFER, vk::AccessFlags::TRANSFER_WRITE,
vk::QUEUE_FAMILY_IGNORED, vk::AccessFlags::TRANSFER_READ,
vk::QUEUE_FAMILY_IGNORED vk::PipelineStageFlags::TRANSFER,
vk::PipelineStageFlags::TRANSFER,
vk::QUEUE_FAMILY_IGNORED,
vk::QUEUE_FAMILY_IGNORED,
); );
// todo: respect mipmap filter? // todo: respect mipmap filter?
vulkan.device.cmd_blit_image(*cmd, texture, vk::ImageLayout::GENERAL, texture, vk::ImageLayout::GENERAL, &image_blit, vk::Filter::LINEAR); vulkan.device.cmd_blit_image(
*cmd,
texture,
vk::ImageLayout::GENERAL,
texture,
vk::ImageLayout::GENERAL,
&image_blit,
vk::Filter::LINEAR,
);
} }
} }
unsafe { unsafe {
util::vulkan_image_layout_transition_levels(&vulkan.device, *cmd, texture, util::vulkan_image_layout_transition_levels(
vk::REMAINING_MIP_LEVELS, &vulkan.device,
if config.mipmap { vk::ImageLayout::GENERAL } else { vk::ImageLayout::TRANSFER_DST_OPTIMAL }, *cmd,
vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL, texture,
vk::AccessFlags::TRANSFER_WRITE, vk::REMAINING_MIP_LEVELS,
vk::AccessFlags::TRANSFER_READ, if config.mipmap {
vk::PipelineStageFlags::TRANSFER, vk::ImageLayout::GENERAL
vk::PipelineStageFlags::FRAGMENT_SHADER, } else {
vk::QUEUE_FAMILY_IGNORED, vk::ImageLayout::TRANSFER_DST_OPTIMAL
vk::QUEUE_FAMILY_IGNORED },
vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL,
vk::AccessFlags::TRANSFER_WRITE,
vk::AccessFlags::TRANSFER_READ,
vk::PipelineStageFlags::TRANSFER,
vk::PipelineStageFlags::FRAGMENT_SHADER,
vk::QUEUE_FAMILY_IGNORED,
vk::QUEUE_FAMILY_IGNORED,
); );
} }
@ -206,7 +243,7 @@ impl LutTexture {
staging, staging,
filter_mode: config.filter_mode, filter_mode: config.filter_mode,
wrap_mode: config.wrap_mode, wrap_mode: config.wrap_mode,
mipmap: config.mipmap mipmap: config.mipmap,
}) })
} }
} }

View file

@ -1,15 +1,20 @@
use ash::vk;
use ash::vk::{AttachmentLoadOp, AttachmentStoreOp, ImageLayout, PipelineBindPoint, SampleCountFlags};
use librashader_common::ImageFormat;
use crate::error; use crate::error;
use ash::vk;
use ash::vk::{
AttachmentLoadOp, AttachmentStoreOp, ImageLayout, PipelineBindPoint, SampleCountFlags,
};
use librashader_common::ImageFormat;
pub struct VulkanRenderPass { pub struct VulkanRenderPass {
pub render_pass: vk::RenderPass, pub render_pass: vk::RenderPass,
pub format: ImageFormat pub format: ImageFormat,
} }
impl VulkanRenderPass { impl VulkanRenderPass {
pub fn create_render_pass(device: &ash::Device, mut format: ImageFormat) -> error::Result<Self> { pub fn create_render_pass(
device: &ash::Device,
mut format: ImageFormat,
) -> error::Result<Self> {
// default to reasonable choice if unknown // default to reasonable choice if unknown
if format == ImageFormat::Unknown { if format == ImageFormat::Unknown {
format = ImageFormat::R8G8B8A8Unorm; format = ImageFormat::R8G8B8A8Unorm;
@ -47,7 +52,7 @@ impl VulkanRenderPass {
let rp = device.create_render_pass(&renderpass_info, None)?; let rp = device.create_render_pass(&renderpass_info, None)?;
Ok(Self { Ok(Self {
render_pass: rp, render_pass: rp,
format format,
}) })
} }
} }

View file

@ -1,8 +1,8 @@
use crate::error;
use ash::vk; use ash::vk;
use ash::vk::{AccessFlags, Extent3D, ImageAspectFlags}; use ash::vk::{AccessFlags, Extent3D, ImageAspectFlags};
use librashader_common::Size; use librashader_common::Size;
use librashader_reflect::reflect::semantics::BindingStage; use librashader_reflect::reflect::semantics::BindingStage;
use crate::error;
pub fn binding_stage_to_vulkan_stage(stage_mask: BindingStage) -> vk::ShaderStageFlags { pub fn binding_stage_to_vulkan_stage(stage_mask: BindingStage) -> vk::ShaderStageFlags {
let mut mask = vk::ShaderStageFlags::default(); let mut mask = vk::ShaderStageFlags::default();
@ -17,11 +17,16 @@ pub fn binding_stage_to_vulkan_stage(stage_mask: BindingStage) -> vk::ShaderStag
mask mask
} }
pub fn find_vulkan_memory_type(props: &vk::PhysicalDeviceMemoryProperties, device_reqs: u32, host_reqs: vk::MemoryPropertyFlags) -> u32 { pub fn find_vulkan_memory_type(
props: &vk::PhysicalDeviceMemoryProperties,
device_reqs: u32,
host_reqs: vk::MemoryPropertyFlags,
) -> u32 {
for i in 0..vk::MAX_MEMORY_TYPES { for i in 0..vk::MAX_MEMORY_TYPES {
if device_reqs & (1 << i) != 0 if device_reqs & (1 << i) != 0
&& props.memory_types[i].property_flags & host_reqs == host_reqs { && props.memory_types[i].property_flags & host_reqs == host_reqs
return i as u32 {
return i as u32;
} }
} }
@ -33,21 +38,21 @@ pub fn find_vulkan_memory_type(props: &vk::PhysicalDeviceMemoryProperties, devic
} }
#[inline(always)] #[inline(always)]
pub unsafe fn vulkan_image_layout_transition_levels(device: &ash::Device, pub unsafe fn vulkan_image_layout_transition_levels(
cmd: vk::CommandBuffer, device: &ash::Device,
image: vk::Image, cmd: vk::CommandBuffer,
levels: u32, old_layout: vk::ImageLayout, image: vk::Image,
new_layout: vk::ImageLayout, levels: u32,
src_access: vk::AccessFlags, old_layout: vk::ImageLayout,
dst_access: vk::AccessFlags, new_layout: vk::ImageLayout,
src_stage: vk::PipelineStageFlags, src_access: vk::AccessFlags,
dst_stage: vk::PipelineStageFlags, dst_access: vk::AccessFlags,
src_stage: vk::PipelineStageFlags,
dst_stage: vk::PipelineStageFlags,
src_queue_family_index: u32,
src_queue_family_index: u32, dst_queue_family_index: u32,
dst_queue_family_index: u32, ) {
) {
let mut barrier = vk::ImageMemoryBarrier::default(); let mut barrier = vk::ImageMemoryBarrier::default();
barrier.s_type = vk::StructureType::IMAGE_MEMORY_BARRIER; barrier.s_type = vk::StructureType::IMAGE_MEMORY_BARRIER;
barrier.p_next = std::ptr::null(); barrier.p_next = std::ptr::null();
@ -62,6 +67,13 @@ pub unsafe fn vulkan_image_layout_transition_levels(device: &ash::Device,
barrier.subresource_range.base_array_layer = 0; barrier.subresource_range.base_array_layer = 0;
barrier.subresource_range.level_count = levels; barrier.subresource_range.level_count = levels;
barrier.subresource_range.layer_count = vk::REMAINING_ARRAY_LAYERS; barrier.subresource_range.layer_count = vk::REMAINING_ARRAY_LAYERS;
device.cmd_pipeline_barrier(cmd, src_stage, dst_stage, vk::DependencyFlags::empty(), device.cmd_pipeline_barrier(
&[], &[], &[barrier]) cmd,
src_stage,
dst_stage,
vk::DependencyFlags::empty(),
&[],
&[],
&[barrier],
)
} }

View file

@ -1,25 +1,30 @@
use std::ffi::c_void;
use ash::vk;
use crate::{error, util}; use crate::{error, util};
use ash::vk;
use std::ffi::c_void;
pub struct VulkanImageMemory { pub struct VulkanImageMemory {
pub handle: vk::DeviceMemory, pub handle: vk::DeviceMemory,
device: ash::Device device: ash::Device,
} }
impl VulkanImageMemory { impl VulkanImageMemory {
pub fn new(device: &ash::Device, alloc: &vk::MemoryAllocateInfo) -> error::Result<VulkanImageMemory> { pub fn new(
device: &ash::Device,
alloc: &vk::MemoryAllocateInfo,
) -> error::Result<VulkanImageMemory> {
unsafe { unsafe {
Ok(VulkanImageMemory { Ok(VulkanImageMemory {
handle: device.allocate_memory(alloc, None)?, handle: device.allocate_memory(alloc, None)?,
device: device.clone() device: device.clone(),
}) })
} }
} }
pub fn bind(&self, image: &vk::Image) -> error::Result<()>{ pub fn bind(&self, image: &vk::Image) -> error::Result<()> {
unsafe { unsafe {
Ok(self.device.bind_image_memory(image.clone(), self.handle.clone(), 0)?) Ok(self
.device
.bind_image_memory(image.clone(), self.handle.clone(), 0)?)
} }
} }
} }
@ -32,7 +37,6 @@ impl Drop for VulkanImageMemory {
} }
} }
pub struct VulkanBuffer { pub struct VulkanBuffer {
pub handle: vk::Buffer, pub handle: vk::Buffer,
device: ash::Device, device: ash::Device,
@ -42,12 +46,16 @@ pub struct VulkanBuffer {
pub struct VulkanBufferMapHandle<'a> { pub struct VulkanBufferMapHandle<'a> {
buffer: &'a mut VulkanBuffer, buffer: &'a mut VulkanBuffer,
ptr: *mut c_void ptr: *mut c_void,
} }
impl VulkanBuffer { impl VulkanBuffer {
pub fn new(device: &ash::Device, mem_props: &vk::PhysicalDeviceMemoryProperties, usage: vk::BufferUsageFlags, pub fn new(
size: usize) -> error::Result<VulkanBuffer> { device: &ash::Device,
mem_props: &vk::PhysicalDeviceMemoryProperties,
usage: vk::BufferUsageFlags,
size: usize,
) -> error::Result<VulkanBuffer> {
unsafe { unsafe {
let buffer_info = vk::BufferCreateInfo::builder() let buffer_info = vk::BufferCreateInfo::builder()
.size(size as vk::DeviceSize) .size(size as vk::DeviceSize)
@ -59,8 +67,11 @@ impl VulkanBuffer {
let memory_reqs = device.get_buffer_memory_requirements(buffer); let memory_reqs = device.get_buffer_memory_requirements(buffer);
let alloc_info = vk::MemoryAllocateInfo::builder() let alloc_info = vk::MemoryAllocateInfo::builder()
.allocation_size(memory_reqs.size) .allocation_size(memory_reqs.size)
.memory_type_index(util::find_vulkan_memory_type(mem_props, memory_reqs.memory_type_bits, .memory_type_index(util::find_vulkan_memory_type(
vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT)) mem_props,
memory_reqs.memory_type_bits,
vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT,
))
.build(); .build();
let alloc = device.allocate_memory(&alloc_info, None)?; let alloc = device.allocate_memory(&alloc_info, None)?;
@ -70,23 +81,25 @@ impl VulkanBuffer {
handle: buffer, handle: buffer,
memory: alloc, memory: alloc,
size: size as vk::DeviceSize, size: size as vk::DeviceSize,
device: device.clone() device: device.clone(),
}) })
} }
} }
pub unsafe fn copy_from(&mut self, buffer: &[u8]) -> error::Result<()> { pub unsafe fn copy_from(&mut self, buffer: &[u8]) -> error::Result<()> {
let dst = self.device.map_memory(self.memory, 0, self.size, vk::MemoryMapFlags::empty())?; let dst = self
.device
.map_memory(self.memory, 0, self.size, vk::MemoryMapFlags::empty())?;
std::ptr::copy_nonoverlapping(buffer.as_ptr(), dst.cast(), buffer.len()); std::ptr::copy_nonoverlapping(buffer.as_ptr(), dst.cast(), buffer.len());
self.device.unmap_memory(self.memory); self.device.unmap_memory(self.memory);
Ok(()) Ok(())
} }
pub fn map(&mut self) -> error::Result<VulkanBufferMapHandle> { pub fn map(&mut self) -> error::Result<VulkanBufferMapHandle> {
let dst = let dst = unsafe {
unsafe { self.device
self.device.map_memory(self.memory, 0, self.size, vk::MemoryMapFlags::empty())? .map_memory(self.memory, 0, self.size, vk::MemoryMapFlags::empty())?
}; };
Ok(VulkanBufferMapHandle { Ok(VulkanBufferMapHandle {
buffer: self, buffer: self,
@ -109,16 +122,14 @@ impl Drop for VulkanBuffer {
} }
} }
impl <'a> VulkanBufferMapHandle<'a> { impl<'a> VulkanBufferMapHandle<'a> {
pub unsafe fn copy_from(&mut self, src: &[u8]) { pub unsafe fn copy_from(&mut self, src: &[u8]) {
std::ptr::copy_nonoverlapping(src.as_ptr(), self.ptr.cast(), src.len()); std::ptr::copy_nonoverlapping(src.as_ptr(), self.ptr.cast(), src.len());
} }
} }
impl <'a> Drop for VulkanBufferMapHandle<'a> { impl<'a> Drop for VulkanBufferMapHandle<'a> {
fn drop(&mut self) { fn drop(&mut self) {
unsafe { unsafe { self.buffer.device.unmap_memory(self.buffer.memory) }
self.buffer.device.unmap_memory(self.buffer.memory)
}
} }
} }

View file

@ -1,16 +1,16 @@
use std::ffi::CStr; use crate::renderpass::VulkanRenderPass;
use crate::{error, util};
use ash::vk; use ash::vk;
use librashader_common::ImageFormat; use librashader_common::ImageFormat;
use librashader_reflect::back::ShaderCompilerOutput; use librashader_reflect::back::ShaderCompilerOutput;
use librashader_reflect::reflect::semantics::{TextureBinding, UboReflection}; use librashader_reflect::reflect::semantics::{TextureBinding, UboReflection};
use librashader_reflect::reflect::ShaderReflection; use librashader_reflect::reflect::ShaderReflection;
use crate::{error, util}; use std::ffi::CStr;
use crate::renderpass::VulkanRenderPass;
pub struct PipelineDescriptors { pub struct PipelineDescriptors {
pub replicas: u32, pub replicas: u32,
pub layout_bindings: Vec<vk::DescriptorSetLayoutBinding>, pub layout_bindings: Vec<vk::DescriptorSetLayoutBinding>,
pub pool_sizes: Vec<vk::DescriptorPoolSize> pub pool_sizes: Vec<vk::DescriptorPoolSize>,
} }
impl PipelineDescriptors { impl PipelineDescriptors {
@ -67,13 +67,17 @@ impl PipelineDescriptors {
self.layout_bindings.as_ref() self.layout_bindings.as_ref()
} }
pub fn create_descriptor_set_layout(&self, device: &ash::Device) -> error::Result<vk::DescriptorSetLayout> { pub fn create_descriptor_set_layout(
&self,
device: &ash::Device,
) -> error::Result<vk::DescriptorSetLayout> {
unsafe { unsafe {
let layout = device.create_descriptor_set_layout( let layout = device.create_descriptor_set_layout(
&vk::DescriptorSetLayoutCreateInfo::builder() &vk::DescriptorSetLayoutCreateInfo::builder()
.bindings(self.bindings()) .bindings(self.bindings())
.build(), .build(),
None)?; None,
)?;
Ok(layout) Ok(layout)
} }
} }
@ -87,38 +91,43 @@ pub struct PipelineLayoutObjects {
} }
impl PipelineLayoutObjects { impl PipelineLayoutObjects {
pub fn new(reflection: &ShaderReflection, replicas: u32, device: &ash::Device) -> error::Result<Self> { pub fn new(
reflection: &ShaderReflection,
replicas: u32,
device: &ash::Device,
) -> error::Result<Self> {
let mut descriptors = PipelineDescriptors::new(replicas); let mut descriptors = PipelineDescriptors::new(replicas);
descriptors.add_ubo_binding(reflection.ubo.as_ref()); descriptors.add_ubo_binding(reflection.ubo.as_ref());
descriptors.add_texture_bindings(reflection.meta.texture_meta.values()); descriptors.add_texture_bindings(reflection.meta.texture_meta.values());
let mut descriptor_set_layout = [descriptors.create_descriptor_set_layout(device)?]; let mut descriptor_set_layout = [descriptors.create_descriptor_set_layout(device)?];
let mut pipeline_create_info = vk::PipelineLayoutCreateInfo::builder() let mut pipeline_create_info =
.set_layouts(&descriptor_set_layout); vk::PipelineLayoutCreateInfo::builder().set_layouts(&descriptor_set_layout);
let pipeline_create_info = if let Some(push_constant) = &reflection.push_constant { let pipeline_create_info = if let Some(push_constant) = &reflection.push_constant {
let mut stage_mask = util::binding_stage_to_vulkan_stage(push_constant.stage_mask); let mut stage_mask = util::binding_stage_to_vulkan_stage(push_constant.stage_mask);
let push_constant_range = [ let push_constant_range = [vk::PushConstantRange::builder()
vk::PushConstantRange::builder() .stage_flags(stage_mask)
.stage_flags(stage_mask) .size(push_constant.size)
.size(push_constant.size) .build()];
.build() pipeline_create_info
]; .push_constant_ranges(&push_constant_range)
pipeline_create_info.push_constant_ranges(&push_constant_range).build() .build()
} else { } else {
pipeline_create_info.build() pipeline_create_info.build()
}; };
let layout = unsafe { let layout = unsafe { device.create_pipeline_layout(&pipeline_create_info, None)? };
device.create_pipeline_layout(&pipeline_create_info, None)?
};
let pool = unsafe { let pool = unsafe {
device.create_descriptor_pool(&vk::DescriptorPoolCreateInfo::builder() device.create_descriptor_pool(
.max_sets(replicas) &vk::DescriptorPoolCreateInfo::builder()
.pool_sizes(&descriptors.pool_sizes) .max_sets(replicas)
.build(), None)? .pool_sizes(&descriptors.pool_sizes)
.build(),
None,
)?
}; };
let mut descriptor_sets = Vec::new(); let mut descriptor_sets = Vec::new();
@ -128,19 +137,18 @@ impl PipelineLayoutObjects {
.build(); .build();
for _ in 0..replicas { for _ in 0..replicas {
unsafe { unsafe { descriptor_sets.push(device.allocate_descriptor_sets(&alloc_info)?) }
descriptor_sets.push(device.allocate_descriptor_sets(&alloc_info)?)
}
} }
let descriptor_sets: Vec<vk::DescriptorSet> = descriptor_sets.into_iter().flatten().collect(); let descriptor_sets: Vec<vk::DescriptorSet> =
descriptor_sets.into_iter().flatten().collect();
return Ok(PipelineLayoutObjects { return Ok(PipelineLayoutObjects {
layout, layout,
descriptor_set_layout, descriptor_set_layout,
descriptor_sets, descriptor_sets,
pool, pool,
}) });
} }
} }
@ -150,30 +158,38 @@ pub struct VulkanShaderModule {
} }
impl VulkanShaderModule { impl VulkanShaderModule {
pub fn new(device: &ash::Device, info: &vk::ShaderModuleCreateInfo) -> error::Result<VulkanShaderModule> { pub fn new(
device: &ash::Device,
info: &vk::ShaderModuleCreateInfo,
) -> error::Result<VulkanShaderModule> {
Ok(VulkanShaderModule { Ok(VulkanShaderModule {
shader: unsafe { device.create_shader_module(info, None)? }, shader: unsafe { device.create_shader_module(info, None)? },
device: device.clone() device: device.clone(),
}) })
} }
} }
impl Drop for VulkanShaderModule { impl Drop for VulkanShaderModule {
fn drop(&mut self) { fn drop(&mut self) {
unsafe { unsafe { self.device.destroy_shader_module(self.shader, None) }
self.device.destroy_shader_module(self.shader, None)
}
} }
} }
pub struct VulkanGraphicsPipeline { pub struct VulkanGraphicsPipeline {
layout: PipelineLayoutObjects, layout: PipelineLayoutObjects,
render_pass: VulkanRenderPass, render_pass: VulkanRenderPass,
pipeline: vk::Pipeline pipeline: vk::Pipeline,
} }
impl VulkanGraphicsPipeline { impl VulkanGraphicsPipeline {
pub fn new(device: &ash::Device, cache: &vk::PipelineCache, shader_assembly: &ShaderCompilerOutput<Vec<u32>>, reflection: &ShaderReflection, mut format: ImageFormat, replicas: u32) -> error::Result<VulkanGraphicsPipeline> { pub fn new(
device: &ash::Device,
cache: &vk::PipelineCache,
shader_assembly: &ShaderCompilerOutput<Vec<u32>>,
reflection: &ShaderReflection,
mut format: ImageFormat,
replicas: u32,
) -> error::Result<VulkanGraphicsPipeline> {
// default to something sane // default to something sane
if format == ImageFormat::Unknown { if format == ImageFormat::Unknown {
format = ImageFormat::R8G8B8A8Unorm format = ImageFormat::R8G8B8A8Unorm
@ -186,17 +202,20 @@ impl VulkanGraphicsPipeline {
.topology(vk::PrimitiveTopology::TRIANGLE_STRIP) .topology(vk::PrimitiveTopology::TRIANGLE_STRIP)
.build(); .build();
let vao_state = [vk::VertexInputAttributeDescription { let vao_state = [
location: 0, vk::VertexInputAttributeDescription {
binding: 0, location: 0,
format: vk::Format::R32G32_SFLOAT, binding: 0,
offset: 0, format: vk::Format::R32G32_SFLOAT,
}, vk::VertexInputAttributeDescription { offset: 0,
location: 1, },
binding: 0, vk::VertexInputAttributeDescription {
format: vk::Format::R32G32_SFLOAT, location: 1,
offset: (2 * std::mem::size_of::<f32>()) as u32, binding: 0,
}]; format: vk::Format::R32G32_SFLOAT,
offset: (2 * std::mem::size_of::<f32>()) as u32,
},
];
let input_binding = vk::VertexInputBindingDescription::builder() let input_binding = vk::VertexInputBindingDescription::builder()
.binding(0) .binding(0)
@ -289,15 +308,16 @@ impl VulkanGraphicsPipeline {
let pipeline = unsafe { let pipeline = unsafe {
// panic_safety: if this is successful this should return 1 pipelines. // panic_safety: if this is successful this should return 1 pipelines.
device.create_graphics_pipelines(cache.clone(), &[pipeline_info], None) device
.map_err(|e| e.1).unwrap()[0] .create_graphics_pipelines(cache.clone(), &[pipeline_info], None)
.map_err(|e| e.1)
.unwrap()[0]
}; };
Ok(VulkanGraphicsPipeline { Ok(VulkanGraphicsPipeline {
layout: pipeline_layout, layout: pipeline_layout,
render_pass, render_pass,
pipeline pipeline,
}) })
} }
} }

View file

@ -27,4 +27,4 @@ pub trait FilterChain {
frame_count: usize, frame_count: usize,
options: Option<&Self::FrameOptions>, options: Option<&Self::FrameOptions>,
) -> Result<(), Self::Error>; ) -> Result<(), Self::Error>;
} }

View file

@ -1,6 +1,6 @@
use std::marker::PhantomData;
use librashader_common::Size;
pub use image::ImageError; pub use image::ImageError;
use librashader_common::Size;
use std::marker::PhantomData;
use std::path::Path; use std::path::Path;
@ -8,7 +8,7 @@ pub struct Image<P: PixelFormat = RGBA8> {
pub bytes: Vec<u8>, pub bytes: Vec<u8>,
pub size: Size<u32>, pub size: Size<u32>,
pub pitch: usize, pub pitch: usize,
_pd: PhantomData<P> _pd: PhantomData<P>,
} }
pub struct RGBA8; pub struct RGBA8;
@ -20,9 +20,7 @@ pub trait PixelFormat {
} }
impl PixelFormat for RGBA8 { impl PixelFormat for RGBA8 {
fn convert(_pixels: &mut Vec<u8>) { fn convert(_pixels: &mut Vec<u8>) {}
}
} }
impl PixelFormat for BGRA8 { impl PixelFormat for BGRA8 {

View file

@ -16,4 +16,4 @@ pub trait FilterChainParameters {
/// ///
/// Returns `None` if the parameter did not exist, or the old value if successful. /// Returns `None` if the parameter did not exist, or the old value if successful.
fn set_parameter(&mut self, parameter: &str, new_value: f32) -> Option<f32>; fn set_parameter(&mut self, parameter: &str, new_value: f32) -> Option<f32>;
} }

View file

@ -69,9 +69,9 @@ pub struct BoxRingBuffer<T> {
} }
impl<T> BoxRingBuffer<T> impl<T> BoxRingBuffer<T>
where where
T: Copy, T: Copy,
T: Default, T: Default,
{ {
pub fn new(size: usize) -> Self { pub fn new(size: usize) -> Self {
Self { Self {
@ -81,12 +81,11 @@ impl<T> BoxRingBuffer<T>
} }
} }
impl<T> BoxRingBuffer<T> { impl<T> BoxRingBuffer<T> {
pub fn from_vec(items: Vec<T>) -> Self { pub fn from_vec(items: Vec<T>) -> Self {
Self { Self {
items: items.into_boxed_slice(), items: items.into_boxed_slice(),
index: 0 index: 0,
} }
} }
@ -126,4 +125,4 @@ impl<T> RingBuffer<T> for BoxRingBuffer<T> {
fn current_index(&self) -> usize { fn current_index(&self) -> usize {
self.index self.index
} }
} }

View file

@ -1,23 +1,28 @@
use crate::scaling;
use librashader_common::Size; use librashader_common::Size;
use librashader_presets::{Scale2D, ScaleFactor, ScaleType, Scaling}; use librashader_presets::{Scale2D, ScaleFactor, ScaleType, Scaling};
use num_traits::AsPrimitive; use num_traits::AsPrimitive;
use std::ops::Mul; use std::ops::Mul;
use crate::scaling;
pub trait ViewportSize<T> pub trait ViewportSize<T>
where where
T: Mul<ScaleFactor, Output = f32> + Copy + 'static, T: Mul<ScaleFactor, Output = f32> + Copy + 'static,
f32: AsPrimitive<T> f32: AsPrimitive<T>,
{ {
/// Produce a `Size<T>` scaled with the input scaling options. /// Produce a `Size<T>` scaled with the input scaling options.
fn scale_viewport(self, scaling: Scale2D, viewport: Size<T>) -> Size<T>; fn scale_viewport(self, scaling: Scale2D, viewport: Size<T>) -> Size<T>;
} }
impl<T> ViewportSize<T> for Size<T> impl<T> ViewportSize<T> for Size<T>
where
T: Mul<ScaleFactor, Output = f32> + Copy + 'static,
f32: AsPrimitive<T>,
{
fn scale_viewport(self, scaling: Scale2D, viewport: Size<T>) -> Size<T>
where where
T: Mul<ScaleFactor, Output = f32> + Copy + 'static, T: Mul<ScaleFactor, Output = f32> + Copy + 'static,
f32: AsPrimitive<T>{ f32: AsPrimitive<T>,
fn scale_viewport(self, scaling: Scale2D, viewport: Size<T>) -> Size<T> where T: Mul<ScaleFactor, Output=f32> + Copy + 'static, f32: AsPrimitive<T> { {
scaling::scale(scaling, self, viewport) scaling::scale(scaling, self, viewport)
} }
} }

View file

@ -63,7 +63,6 @@ where
H: for<'a> BindUniform<C, &'a [f32; 4]>, H: for<'a> BindUniform<C, &'a [f32; 4]>,
H: for<'a> BindUniform<C, &'a [f32; 16]>, H: for<'a> BindUniform<C, &'a [f32; 16]>,
{ {
/// Create a new `UniformStorage` with the given size for UBO and Push Constant Buffer sizes. /// Create a new `UniformStorage` with the given size for UBO and Push Constant Buffer sizes.
pub fn new(ubo_size: usize, push_size: usize) -> Self { pub fn new(ubo_size: usize, push_size: usize) -> Self {
UniformStorage { UniformStorage {

View file

@ -35,8 +35,8 @@
/// Shader presets contain shader and texture parameters, and the order in which to apply a set of shaders /// Shader presets contain shader and texture parameters, and the order in which to apply a set of shaders
/// in a filter chain. /// in a filter chain.
pub mod presets { pub mod presets {
pub use librashader_presets::*;
use librashader_preprocess::{PreprocessError, ShaderParameter, ShaderSource}; use librashader_preprocess::{PreprocessError, ShaderParameter, ShaderSource};
pub use librashader_presets::*;
/// Get full parameter metadata from a shader preset. /// Get full parameter metadata from a shader preset.
pub fn get_parameter_meta( pub fn get_parameter_meta(
preset: &ShaderPreset, preset: &ShaderPreset,
@ -66,20 +66,18 @@ pub mod preprocess {
pub mod reflect { pub mod reflect {
/// Supported shader compiler targets. /// Supported shader compiler targets.
pub mod targets { pub mod targets {
pub use librashader_reflect::back::targets::SpirV;
pub use librashader_reflect::back::targets::GLSL; pub use librashader_reflect::back::targets::GLSL;
pub use librashader_reflect::back::targets::HLSL; pub use librashader_reflect::back::targets::HLSL;
pub use librashader_reflect::back::targets::SpirV;
} }
pub use librashader_reflect::error::*; pub use librashader_reflect::error::*;
pub use librashader_reflect::reflect::{ pub use librashader_reflect::reflect::{semantics, ReflectShader, ShaderReflection};
ReflectShader, semantics, ShaderReflection,
};
pub use librashader_reflect::back::{ pub use librashader_reflect::back::{
CompilerBackend, CompileShader, FromCompilation, ShaderCompilerOutput, targets::OutputTarget, CompileShader, CompilerBackend, FromCompilation,
targets::OutputTarget, ShaderCompilerOutput,
}; };
pub use librashader_reflect::front::shaderc::GlslangCompilation; pub use librashader_reflect::front::shaderc::GlslangCompilation;
pub use librashader_reflect::reflect::semantics::BindingMeta; pub use librashader_reflect::reflect::semantics::BindingMeta;
@ -88,8 +86,8 @@ pub mod reflect {
/// Shader runtimes to execute a filter chain on a GPU surface. /// Shader runtimes to execute a filter chain on a GPU surface.
#[cfg(feature = "runtime")] #[cfg(feature = "runtime")]
pub mod runtime { pub mod runtime {
pub use librashader_runtime::parameters::FilterChainParameters;
pub use librashader_runtime::filter_chain::FilterChain; pub use librashader_runtime::filter_chain::FilterChain;
pub use librashader_runtime::parameters::FilterChainParameters;
#[cfg(feature = "gl")] #[cfg(feature = "gl")]
/// Shader runtime for OpenGL 3.3+. /// Shader runtime for OpenGL 3.3+.
@ -108,9 +106,7 @@ pub mod runtime {
#[cfg(feature = "vk")] #[cfg(feature = "vk")]
/// Shader compiler targets and runtime for Vulkan. /// Shader compiler targets and runtime for Vulkan.
pub mod vk { pub mod vk {}
}
} }
pub use librashader_common::{FilterMode, ImageFormat, Size, WrapMode}; pub use librashader_common::{FilterMode, ImageFormat, Size, WrapMode};