diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml index 0d9ead518..50be221f7 100644 --- a/.github/workflows/pipeline.yml +++ b/.github/workflows/pipeline.yml @@ -10,7 +10,7 @@ jobs: - uses: actions-rs/toolchain@v1 with: profile: minimal - toolchain: stable + toolchain: 1.41.0 override: true - uses: actions-rs/cargo@v1 name: Default test diff --git a/Cargo.toml b/Cargo.toml index 010482e13..19157929a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -30,6 +30,7 @@ glsl-out = [] serialize = ["serde"] deserialize = ["serde"] spirv-in = ["petgraph", "spirv"] +spirv-out = ["spirv"] [dev-dependencies] difference = "2.0" diff --git a/examples/convert.rs b/examples/convert.rs index 1fb5f428d..4cb4d1297 100644 --- a/examples/convert.rs +++ b/examples/convert.rs @@ -38,7 +38,7 @@ fn main() { .to_str() .unwrap() { - #[cfg(feature = "spirv")] + #[cfg(feature = "spirv-in")] "spv" => { let input = fs::read(&args[1]).unwrap(); naga::front::spv::parse_u8_slice(&input).unwrap() @@ -165,7 +165,7 @@ fn main() { let msl = msl::write_string(&module, options).unwrap(); fs::write(&args[2], msl).unwrap(); } - #[cfg(feature = "spirv")] + #[cfg(feature = "spirv-out")] "spv" => { use naga::back::spv; diff --git a/src/back/glsl.rs b/src/back/glsl.rs index 03b9697d9..8e1a5cbb0 100644 --- a/src/back/glsl.rs +++ b/src/back/glsl.rs @@ -1,6 +1,6 @@ use crate::{ Arena, ArraySize, BinaryOperator, BuiltIn, Constant, ConstantInner, DerivativeAxis, Expression, - FastHashMap, Function, FunctionOrigin, GlobalVariable, Handle, ImageFlags, Interpolation, + FastHashMap, Function, FunctionOrigin, GlobalVariable, Handle, ImageClass, Interpolation, IntrinsicFunction, LocalVariable, Module, ScalarKind, ShaderStage, Statement, StorageClass, StructMember, Type, TypeInner, UnaryOperator, }; @@ -182,13 +182,13 @@ pub fn write<'a>(module: &'a Module, out: &mut impl Write, options: Options) -> continue; } - let block = matches!( - global.class, + let block = match global.class { StorageClass::Input - | StorageClass::Output - | StorageClass::StorageBuffer - | StorageClass::Uniform - ); + | StorageClass::Output + | StorageClass::StorageBuffer + | StorageClass::Uniform => true, + _ => false, + }; match module.types[global.ty].inner { TypeInner::Struct { .. } if block => { @@ -396,9 +396,7 @@ pub fn write<'a>(module: &'a Module, out: &mut impl Write, options: Options) -> }; for sta in func.body.iter() { - if !matches!(sta, Statement::Empty) { - writeln!(out, "{}", write_statement(sta, module, &mut builder, 1)?)?; - } + writeln!(out, "{}", write_statement(sta, module, &mut builder, 1)?)?; } writeln!(out, "}}")?; @@ -459,25 +457,21 @@ fn write_statement( )?; for sta in accept { - if !matches!(sta, Statement::Empty) { - writeln!( - &mut out, - "{}", - write_statement(sta, module, builder, indent + 1)? - )?; - } + writeln!( + &mut out, + "{}", + write_statement(sta, module, builder, indent + 1)? + )?; } if !reject.is_empty() { writeln!(&mut out, "{}}} else {{", "\t".repeat(indent),)?; for sta in reject { - if !matches!(sta, Statement::Empty) { - writeln!( - &mut out, - "{}", - write_statement(sta, module, builder, indent + 1)? - )?; - } + writeln!( + &mut out, + "{}", + write_statement(sta, module, builder, indent + 1)? + )?; } } @@ -503,13 +497,11 @@ fn write_statement( writeln!(&mut out, "{}case {}:", "\t".repeat(indent + 1), label)?; for sta in block { - if !matches!(sta, Statement::Empty) { - writeln!( - &mut out, - "{}", - write_statement(sta, module, builder, indent + 2)? - )?; - } + writeln!( + &mut out, + "{}", + write_statement(sta, module, builder, indent + 2)? + )?; } if fallthrough.is_some() { @@ -521,13 +513,11 @@ fn write_statement( writeln!(&mut out, "{}default:", "\t".repeat(indent + 1),)?; for sta in default { - if !matches!(sta, Statement::Empty) { - writeln!( - &mut out, - "{}", - write_statement(sta, module, builder, indent + 2)? - )?; - } + writeln!( + &mut out, + "{}", + write_statement(sta, module, builder, indent + 2)? + )?; } } @@ -541,13 +531,11 @@ fn write_statement( writeln!(&mut out, "{}while(true) {{", "\t".repeat(indent),)?; for sta in body.iter().chain(continuing.iter()) { - if !matches!(sta, Statement::Empty) { - writeln!( - &mut out, - "{}", - write_statement(sta, module, builder, indent + 1)? - )?; - } + writeln!( + &mut out, + "{}", + write_statement(sta, module, builder, indent + 1)? + )?; } write!(&mut out, "{}}}", "\t".repeat(indent),)?; @@ -583,18 +571,15 @@ fn write_expression<'a>( module: &'a Module, builder: &mut StatementBuilder<'_>, ) -> Result<(String, Cow<'a, TypeInner>), Error> { - Ok(match expr { + Ok(match *expr { Expression::Access { base, index } => { - let (base_expr, ty) = write_expression(&builder.expressions[*base], module, builder)?; + let (base_expr, ty) = write_expression(&builder.expressions[base], module, builder)?; - let inner = match ty.as_ref() { + let inner = match *ty.as_ref() { TypeInner::Vector { kind, width, .. } | TypeInner::Matrix { kind, width, .. } => { - Cow::Owned(TypeInner::Scalar { - kind: *kind, - width: *width, - }) + Cow::Owned(TypeInner::Scalar { kind, width }) } - TypeInner::Array { base, .. } => Cow::Borrowed(&module.types[*base].inner), + TypeInner::Array { base, .. } => Cow::Borrowed(&module.types[base].inner), _ => return Err(Error::Custom(format!("Cannot dynamically index {:?}", ty))), }; @@ -602,51 +587,48 @@ fn write_expression<'a>( format!( "{}[{}]", base_expr, - write_expression(&builder.expressions[*index], module, builder)?.0 + write_expression(&builder.expressions[index], module, builder)?.0 ), inner, ) } Expression::AccessIndex { base, index } => { - let (base_expr, ty) = write_expression(&builder.expressions[*base], module, builder)?; + let (base_expr, ty) = write_expression(&builder.expressions[base], module, builder)?; - match ty.as_ref() { + match *ty.as_ref() { TypeInner::Vector { kind, width, .. } | TypeInner::Matrix { kind, width, .. } => ( format!("{}[{}]", base_expr, index), - Cow::Owned(TypeInner::Scalar { - kind: *kind, - width: *width, - }), + Cow::Owned(TypeInner::Scalar { kind, width }), ), TypeInner::Array { base, .. } => ( format!("{}[{}]", base_expr, index), - Cow::Borrowed(&module.types[*base].inner), + Cow::Borrowed(&module.types[base].inner), ), - TypeInner::Struct { members } => ( + TypeInner::Struct { ref members } => ( format!( "{}.{}", base_expr, - members[*index as usize] + members[index as usize] .name .as_ref() .unwrap_or(&format!("_{}", index)) ), - Cow::Borrowed(&module.types[members[*index as usize].ty].inner), + Cow::Borrowed(&module.types[members[index as usize].ty].inner), ), _ => return Err(Error::Custom(format!("Cannot index {:?}", ty))), } } Expression::Constant(constant) => ( write_constant( - &module.constants[*constant], + &module.constants[constant], module, builder, builder.features, )?, - Cow::Borrowed(&module.types[module.constants[*constant].ty].inner), + Cow::Borrowed(&module.types[module.constants[constant].ty].inner), ), - Expression::Compose { ty, components } => { - let constructor = match module.types[*ty].inner { + Expression::Compose { ty, ref components } => { + let constructor = match module.types[ty].inner { TypeInner::Vector { size, kind, width } => format!( "{}vec{}", match kind { @@ -690,14 +672,14 @@ fn write_expression<'a>( rows as u8, ), TypeInner::Array { .. } => { - write_type(*ty, &module.types, builder.structs, None, builder.features)? + write_type(ty, &module.types, builder.structs, None, builder.features)? .into_owned() } - TypeInner::Struct { .. } => builder.structs.get(ty).unwrap().clone(), + TypeInner::Struct { .. } => builder.structs.get(&ty).unwrap().clone(), _ => { return Err(Error::Custom(format!( "Cannot compose type {}", - write_type(*ty, &module.types, builder.structs, None, builder.features)? + write_type(ty, &module.types, builder.structs, None, builder.features)? ))) } }; @@ -717,7 +699,7 @@ fn write_expression<'a>( .collect::, _>>()? .join(","), ), - Cow::Borrowed(&module.types[*ty].inner), + Cow::Borrowed(&module.types[ty].inner), ) } Expression::FunctionParameter(pos) => { @@ -727,56 +709,43 @@ fn write_expression<'a>( } Expression::GlobalVariable(handle) => ( builder.globals.get(&handle).unwrap().clone(), - Cow::Borrowed(&module.types[module.global_variables[*handle].ty].inner), + Cow::Borrowed(&module.types[module.global_variables[handle].ty].inner), ), Expression::LocalVariable(handle) => ( builder.locals_lookup.get(&handle).unwrap().clone(), - Cow::Borrowed(&module.types[builder.locals[*handle].ty].inner), + Cow::Borrowed(&module.types[builder.locals[handle].ty].inner), ), Expression::Load { pointer } => { - write_expression(&builder.expressions[*pointer], module, builder)? + write_expression(&builder.expressions[pointer], module, builder)? } Expression::ImageSample { image, sampler, coordinate, + level, depth_ref, } => { let (image_expr, image_ty) = - write_expression(&builder.expressions[*image], module, builder)?; + write_expression(&builder.expressions[image], module, builder)?; let (sampler_expr, sampler_ty) = - write_expression(&builder.expressions[*sampler], module, builder)?; + write_expression(&builder.expressions[sampler], module, builder)?; let (coordinate_expr, coordinate_ty) = - write_expression(&builder.expressions[*coordinate], module, builder)?; + write_expression(&builder.expressions[coordinate], module, builder)?; - let (kind, dim, arrayed, ms, width) = match image_ty.as_ref() { - TypeInner::Image { base, dim, flags } => match module.types[*base].inner { - TypeInner::Scalar { kind, width } => ( - kind, - *dim, - flags.contains(ImageFlags::ARRAYED), - flags.contains(ImageFlags::MULTISAMPLED), - width, - ), - _ => { - return Err(Error::Custom(format!( - "Cannot build image of {}", - write_type( - *base, - &module.types, - builder.structs, - None, - builder.features - )? - ))) - } - }, - TypeInner::DepthImage { dim, arrayed } => { - (ScalarKind::Float, *dim, *arrayed, false, 4) - } + let (kind, dim, arrayed, class) = match *image_ty.as_ref() { + TypeInner::Image { + kind, + dim, + arrayed, + class, + } => (kind, dim, arrayed, class), _ => return Err(Error::Custom(format!("Cannot sample {:?}", image_ty))), }; + let ms = match class { + crate::ImageClass::Multisampled => true, + _ => false, + }; let shadow = match sampler_ty.as_ref() { TypeInner::Sampler { comparison } => *comparison, _ => { @@ -786,7 +755,6 @@ fn write_expression<'a>( ))) } }; - let size = match coordinate_ty.as_ref() { TypeInner::Vector { size, .. } => *size, _ => { @@ -818,18 +786,29 @@ fn write_expression<'a>( "vec{}({},{})", size as u8 + 1, coordinate_expr, - write_expression(&builder.expressions[*depth_ref], module, builder)?.0 + write_expression(&builder.expressions[depth_ref], module, builder)?.0 ) } else { coordinate_expr }; - let expr = if !ms { - format!("texture({},{})", sampler_constructor, coordinate) - } else { - todo!() + //TODO: handle MS + let expr = match level { + crate::SampleLevel::Auto => { + format!("texture({},{})", sampler_constructor, coordinate) + } + crate::SampleLevel::Exact(expr) => { + let (level_expr, _) = + write_expression(&builder.expressions[expr], module, builder)?; + format!( + "textureLod({}, {}, {})", + sampler_constructor, coordinate, level_expr + ) + } + crate::SampleLevel::Bias(_) => todo!(), }; + let width = 4; let ty = if shadow { Cow::Owned(TypeInner::Scalar { kind, width }) } else { @@ -838,8 +817,66 @@ fn write_expression<'a>( (expr, ty) } + Expression::ImageLoad { + image, + coordinate, + index: _, + } => { + let (image_expr, image_ty) = + write_expression(&builder.expressions[image], module, builder)?; + let (coordinate_expr, coordinate_ty) = + write_expression(&builder.expressions[coordinate], module, builder)?; + + let (kind, dim, arrayed, class) = match *image_ty.as_ref() { + TypeInner::Image { + kind, + dim, + arrayed, + class, + } => (kind, dim, arrayed, class), + _ => return Err(Error::Custom(format!("Cannot load {:?}", image_ty))), + }; + + let ms = match class { + crate::ImageClass::Multisampled => true, + _ => false, + }; + let size = match coordinate_ty.as_ref() { + TypeInner::Vector { size, .. } => *size, + _ => { + return Err(Error::Custom(format!( + "Cannot sample with coordinates of type {:?}", + coordinate_ty + ))) + } + }; + + //TODO: fix this + let sampler_constructor = format!( + "{}sampler{}{}{}({})", + match kind { + ScalarKind::Sint => "i", + ScalarKind::Uint => "u", + ScalarKind::Float => "", + _ => return Err(Error::Custom(String::from("Cannot build image of bools",))), + }, + ImageDimension(dim), + if ms { "MS" } else { "" }, + if arrayed { "Array" } else { "" }, + image_expr, + ); + + let expr = if !ms { + format!("texture({},{})", sampler_constructor, coordinate_expr) + } else { + todo!() + }; + + let width = 4; + (expr, Cow::Owned(TypeInner::Vector { kind, width, size })) + } Expression::Unary { op, expr } => { - let (expr, ty) = write_expression(&builder.expressions[*expr], module, builder)?; + let (expr, ty) = write_expression(&builder.expressions[expr], module, builder)?; ( format!( @@ -855,9 +892,9 @@ fn write_expression<'a>( } Expression::Binary { op, left, right } => { let (left_expr, left_ty) = - write_expression(&builder.expressions[*left], module, builder)?; + write_expression(&builder.expressions[left], module, builder)?; let (right_expr, right_ty) = - write_expression(&builder.expressions[*right], module, builder)?; + write_expression(&builder.expressions[right], module, builder)?; let op = match op { BinaryOperator::Add => "+", @@ -902,7 +939,7 @@ fn write_expression<'a>( (format!("({} {} {})", left_expr, op, right_expr), ty) } Expression::Intrinsic { fun, argument } => { - let (expr, ty) = write_expression(&builder.expressions[*argument], module, builder)?; + let (expr, ty) = write_expression(&builder.expressions[argument], module, builder)?; ( format!( @@ -922,8 +959,8 @@ fn write_expression<'a>( } Expression::DotProduct(left, right) => { let (left_expr, left_ty) = - write_expression(&builder.expressions[*left], module, builder)?; - let (right_expr, _) = write_expression(&builder.expressions[*right], module, builder)?; + write_expression(&builder.expressions[left], module, builder)?; + let (right_expr, _) = write_expression(&builder.expressions[right], module, builder)?; let ty = match left_ty.as_ref() { TypeInner::Vector { kind, width, .. } => Cow::Owned(TypeInner::Scalar { @@ -942,13 +979,13 @@ fn write_expression<'a>( } Expression::CrossProduct(left, right) => { let (left_expr, left_ty) = - write_expression(&builder.expressions[*left], module, builder)?; - let (right_expr, _) = write_expression(&builder.expressions[*right], module, builder)?; + write_expression(&builder.expressions[left], module, builder)?; + let (right_expr, _) = write_expression(&builder.expressions[right], module, builder)?; (format!("cross({},{})", left_expr, right_expr), left_ty) } Expression::Derivative { axis, expr } => { - let (expr, ty) = write_expression(&builder.expressions[*expr], module, builder)?; + let (expr, ty) = write_expression(&builder.expressions[expr], module, builder)?; ( format!( @@ -963,9 +1000,12 @@ fn write_expression<'a>( ty, ) } - Expression::Call { origin, arguments } => { - let ty = match origin { - FunctionOrigin::Local(function) => module.functions[*function] + Expression::Call { + ref origin, + ref arguments, + } => { + let ty = match *origin { + FunctionOrigin::Local(function) => module.functions[function] .return_type .map(|ty| Cow::Borrowed(&module.types[ty].inner)) .unwrap_or(Cow::Owned( @@ -979,8 +1019,8 @@ fn write_expression<'a>( ( format!( "{}({})", - match origin { - FunctionOrigin::External(name) => name, + match *origin { + FunctionOrigin::External(ref name) => name, FunctionOrigin::Local(handle) => builder.functions.get(&handle).unwrap(), }, arguments @@ -1141,8 +1181,13 @@ fn write_type( Cow::Owned(structs.get(&ty).unwrap().clone()) } } - TypeInner::Image { base, dim, flags } => { - if flags.contains(ImageFlags::ARRAYED) + TypeInner::Image { + kind, + dim, + arrayed, + class, + } => { + if arrayed && dim != crate::ImageDimension::D2 && !features.contains(SupportedFeatures::NON_2D_TEXTURE_ARRAYS) { @@ -1153,31 +1198,19 @@ fn write_type( Cow::Owned(format!( "{}texture{}{}", - match types[base].inner { - TypeInner::Scalar { kind, .. } => match kind { - ScalarKind::Sint => "i", - ScalarKind::Uint => "u", - ScalarKind::Float => "", - ScalarKind::Bool => - return Err(Error::Custom(String::from( - "Cannot build image of booleans", - ))), - }, - _ => - return Err(Error::Custom(format!( - "Cannot build image of type {}", - write_type(base, types, structs, block, features)? + match kind { + ScalarKind::Sint => "i", + ScalarKind::Uint => "u", + ScalarKind::Float => "", + ScalarKind::Bool => + return Err(Error::Custom(String::from( + "Cannot build image of booleans", ))), }, ImageDimension(dim), - write_image_flags(flags, features)? + write_image_flags(arrayed, class, features)? )) } - TypeInner::DepthImage { dim, arrayed } => Cow::Owned(format!( - "texture{}{}", - ImageDimension(dim), - if arrayed { "Array" } else { "" } - )), TypeInner::Sampler { comparison } => Cow::Borrowed(if comparison { "sampler" } else { @@ -1240,32 +1273,29 @@ fn write_array_size(size: ArraySize) -> Result { }) } -fn write_image_flags(flags: ImageFlags, features: SupportedFeatures) -> Result { - let ms = if flags.contains(ImageFlags::MULTISAMPLED) { - if features.contains(SupportedFeatures::MULTISAMPLED_TEXTURES) { +fn write_image_flags( + arrayed: bool, + class: ImageClass, + features: SupportedFeatures, +) -> Result { + let ms = match class { + ImageClass::Multisampled => { + if !features.contains(SupportedFeatures::MULTISAMPLED_TEXTURES) { + return Err(Error::Custom(String::from( + "Multi sampled textures aren't supported", + ))); + } + if arrayed && !features.contains(SupportedFeatures::MULTISAMPLED_TEXTURE_ARRAYS) { + return Err(Error::Custom(String::from( + "Multi sampled texture arrays aren't supported", + ))); + } "MS" - } else { - return Err(Error::Custom(String::from( - "Multi sampled textures aren't supported", - ))); } - } else { - "" + _ => "", }; - let array = if flags.contains(ImageFlags::ARRAYED) { - "Array" - } else { - "" - }; - - if flags.contains(ImageFlags::ARRAYED & ImageFlags::MULTISAMPLED) - && !features.contains(SupportedFeatures::MULTISAMPLED_TEXTURE_ARRAYS) - { - return Err(Error::Custom(String::from( - "Multi sampled texture arrays aren't supported", - ))); - } + let array = if arrayed { "Array" } else { "" }; Ok(format!("{}{}", ms, array)) } diff --git a/src/back/mod.rs b/src/back/mod.rs index 11439f934..fc601cd9f 100644 --- a/src/back/mod.rs +++ b/src/back/mod.rs @@ -3,5 +3,5 @@ #[cfg(feature = "glsl-out")] pub mod glsl; pub mod msl; -#[cfg(feature = "spirv")] +#[cfg(feature = "spirv-out")] pub mod spv; diff --git a/src/back/msl.rs b/src/back/msl.rs index 627bd1751..4bf57ba0b 100644 --- a/src/back/msl.rs +++ b/src/back/msl.rs @@ -63,7 +63,7 @@ pub enum Error { MixedExecutionModels(crate::Handle), MissingBinding(crate::Handle), MissingBindTarget(BindSource), - InvalidImageFlags(crate::ImageFlags), + InvalidImageAccess(crate::StorageAccess), MutabilityViolation(crate::Handle), BadName(String), UnexpectedGlobalType(crate::Handle), @@ -74,6 +74,7 @@ pub enum Error { UnsupportedBinaryOp(crate::BinaryOperator), UnableToInferBinaryOpOutput(crate::TypeInner, crate::BinaryOperator, crate::TypeInner), UnexpectedImageType(crate::TypeInner), + UnexpectedSampleLevel(crate::SampleLevel), UnexpectedDistanceArgument(crate::TypeInner), UnsupportedCall(String), UnsupportedExpression(crate::Expression), @@ -96,15 +97,6 @@ enum LocationMode { Uniform, } -fn dim_str(dim: crate::ImageDimension) -> &'static str { - match dim { - crate::ImageDimension::D1 => "1d", - crate::ImageDimension::D2 => "2d", - crate::ImageDimension::D3 => "3d", - crate::ImageDimension::Cube => "Cube", - } -} - #[derive(Debug, Clone, Copy)] pub struct Options<'a> { pub binding_map: &'a BindingMap, @@ -112,7 +104,7 @@ pub struct Options<'a> { impl Options<'_> { fn resolve_binding( - &self, + self, binding: &crate::Binding, mode: LocationMode, ) -> Result { @@ -591,16 +583,37 @@ impl Writer { image, sampler, coordinate, + level, depth_ref: None, } => { + //TODO: handle arrayed images let ty_image = self.put_expression(image, function, module)?; write!(self.out, ".sample(")?; self.put_expression(sampler, function, module)?; write!(self.out, ", ")?; self.put_expression(coordinate, function, module)?; + match level { + crate::SampleLevel::Auto => {} + crate::SampleLevel::Exact(h) => { + write!(self.out, ", level(")?; + self.put_expression(h, function, module)?; + write!(self.out, ")")?; + } + crate::SampleLevel::Bias(h) => { + write!(self.out, ", bias(")?; + self.put_expression(h, function, module)?; + write!(self.out, ")")?; + } + } write!(self.out, ")")?; match *ty_image.borrow() { - crate::TypeInner::Image { base, .. } => Ok(module.borrow_type(base)), + crate::TypeInner::Image { kind, .. } => { + Ok(MaybeOwned::Owned(crate::TypeInner::Vector { + size: crate::VectorSize::Quad, + kind, + width: 4, + })) + } ref other => Err(Error::UnexpectedImageType(other.clone())), } } @@ -608,8 +621,10 @@ impl Writer { image, sampler, coordinate, + level, depth_ref: Some(dref), } => { + //TODO: handle arrayed images self.put_expression(image, function, module)?; write!(self.out, ".sample_compare(")?; self.put_expression(sampler, function, module)?; @@ -617,12 +632,44 @@ impl Writer { self.put_expression(coordinate, function, module)?; write!(self.out, ", ")?; self.put_expression(dref, function, module)?; + match level { + crate::SampleLevel::Auto => {} + crate::SampleLevel::Exact(h) => { + write!(self.out, ", level(")?; + self.put_expression(h, function, module)?; + write!(self.out, ")")?; + } + crate::SampleLevel::Bias(_) => return Err(Error::UnexpectedSampleLevel(level)), + } write!(self.out, ")")?; Ok(MaybeOwned::Owned(crate::TypeInner::Scalar { kind: crate::ScalarKind::Float, width: 4, })) } + crate::Expression::ImageLoad { + image, + coordinate, + index, + } => { + //TODO: handle arrayed images + let ty_image = self.put_expression(image, function, module)?; + write!(self.out, ".read(")?; + self.put_expression(coordinate, function, module)?; + write!(self.out, ", ")?; + self.put_expression(index, function, module)?; + write!(self.out, ")")?; + match *ty_image.borrow() { + crate::TypeInner::Image { kind, .. } => { + Ok(MaybeOwned::Owned(crate::TypeInner::Vector { + size: crate::VectorSize::Quad, + kind, + width: 4, + })) + } + ref other => Err(Error::UnexpectedImageType(other.clone())), + } + } crate::Expression::Call { origin: crate::FunctionOrigin::External(ref name), ref arguments, @@ -895,48 +942,48 @@ impl Writer { } write!(self.out, "}}")?; } - crate::TypeInner::Image { base, dim, flags } => { - let base_name = module.types[base].name.or_index(base); - let dim_str = dim_str(dim); - let msaa_str = if flags.contains(crate::ImageFlags::MULTISAMPLED) { - "_ms" - } else { - "" + crate::TypeInner::Image { + kind, + dim, + arrayed, + class, + } => { + let base_name = scalar_kind_string(kind); + let dim_str = match dim { + crate::ImageDimension::D1 => "1d", + crate::ImageDimension::D2 => "2d", + crate::ImageDimension::D3 => "3d", + crate::ImageDimension::Cube => "Cube", }; - let array_str = if flags.contains(crate::ImageFlags::ARRAYED) { - "_array" - } else { - "" + let texture_str = match class { + crate::ImageClass::Depth => "depth", + _ => "texture", }; - let access = if flags.contains(crate::ImageFlags::SAMPLED) { - if flags.intersects(crate::ImageFlags::CAN_STORE) { - return Err(Error::InvalidImageFlags(flags)); - } - "sample" - } else if flags - .contains(crate::ImageFlags::CAN_LOAD | crate::ImageFlags::CAN_STORE) - { - "read_write" - } else if flags.contains(crate::ImageFlags::CAN_STORE) { - "write" - } else if flags.contains(crate::ImageFlags::CAN_LOAD) { - "read" - } else { - return Err(Error::InvalidImageFlags(flags)); + let msaa_str = match class { + crate::ImageClass::Multisampled => "_ms", + _ => "", }; - write!( - self.out, - "typedef texture{}{}{}<{}, access::{}> {}", - dim_str, msaa_str, array_str, base_name, access, name - )?; - } - crate::TypeInner::DepthImage { dim, arrayed } => { - let dim_str = dim_str(dim); let array_str = if arrayed { "_array" } else { "" }; + let access = match class { + crate::ImageClass::Storage(_, access) => { + if access + .contains(crate::StorageAccess::LOAD | crate::StorageAccess::STORE) + { + "read_write" + } else if access.contains(crate::StorageAccess::STORE) { + "write" + } else if access.contains(crate::StorageAccess::LOAD) { + "read" + } else { + return Err(Error::InvalidImageAccess(access)); + } + } + _ => "sample", + }; write!( self.out, - "typedef depth{}{} {}", - dim_str, array_str, name + "typedef {}{}{}{}<{}, access::{}> {}", + texture_str, dim_str, msaa_str, array_str, base_name, access, name )?; } crate::TypeInner::Sampler { comparison: _ } => { diff --git a/src/back/spv/writer.rs b/src/back/spv/writer.rs index f4448bd11..07c98b96d 100644 --- a/src/back/spv/writer.rs +++ b/src/back/spv/writer.rs @@ -1,10 +1,9 @@ /*! Standard Portable Intermediate Representation (SPIR-V) backend !*/ use super::{helpers, Instruction, LogicalLayout, PhysicalLayout, WriterFlags}; -use crate::{Bytes, FastHashMap, FastHashSet, ImageFlags, VectorSize}; use spirv::{Op, Word}; use std::collections::hash_map::Entry; -const BITS_PER_BYTE: Bytes = 8; +const BITS_PER_BYTE: crate::Bytes = 8; enum Signedness { Unsigned = 0, @@ -15,12 +14,12 @@ enum Signedness { enum LocalType { Scalar { kind: crate::ScalarKind, - width: Bytes, + width: crate::Bytes, }, Vector { size: crate::VectorSize, kind: crate::ScalarKind, - width: Bytes, + width: crate::Bytes, }, Pointer { base: crate::Handle, @@ -53,16 +52,16 @@ pub struct Writer { physical_layout: PhysicalLayout, logical_layout: LogicalLayout, id_count: u32, - capabilities: FastHashSet, + capabilities: crate::FastHashSet, debugs: Vec, annotations: Vec, writer_flags: WriterFlags, void_type: Option, - lookup_type: FastHashMap, - lookup_function: FastHashMap, Word>, - lookup_function_type: FastHashMap, - lookup_constant: FastHashMap, Word>, - lookup_global_variable: FastHashMap, Word>, + lookup_type: crate::FastHashMap, + lookup_function: crate::FastHashMap, Word>, + lookup_function_type: crate::FastHashMap, + lookup_constant: crate::FastHashMap, Word>, + lookup_global_variable: crate::FastHashMap, Word>, } impl Writer { @@ -71,16 +70,16 @@ impl Writer { physical_layout: PhysicalLayout::new(header), logical_layout: LogicalLayout::default(), id_count: 0, - capabilities: FastHashSet::default(), + capabilities: crate::FastHashSet::default(), debugs: vec![], annotations: vec![], writer_flags, void_type: None, - lookup_type: FastHashMap::default(), - lookup_function: FastHashMap::default(), - lookup_function_type: FastHashMap::default(), - lookup_constant: FastHashMap::default(), - lookup_global_variable: FastHashMap::default(), + lookup_type: crate::FastHashMap::default(), + lookup_function: crate::FastHashMap::default(), + lookup_function_type: crate::FastHashMap::default(), + lookup_constant: crate::FastHashMap::default(), + lookup_global_variable: crate::FastHashMap::default(), } } @@ -368,7 +367,7 @@ impl Writer { &self, id: Word, component_type_id: Word, - component_count: VectorSize, + component_count: crate::VectorSize, ) -> Instruction { let mut instruction = Instruction::new(Op::TypeVector); instruction.set_result(id); @@ -381,7 +380,7 @@ impl Writer { &self, id: Word, column_type_id: Word, - column_count: VectorSize, + column_count: crate::VectorSize, ) -> Instruction { let mut instruction = Instruction::new(Op::TypeMatrix); instruction.set_result(id); @@ -395,49 +394,50 @@ impl Writer { id: Word, sampled_type_id: Word, dim: spirv::Dim, - flags: ImageFlags, - comparison: bool, + arrayed: bool, + class: crate::ImageClass, ) -> Instruction { let mut instruction = Instruction::new(Op::TypeImage); instruction.set_result(id); instruction.add_operand(sampled_type_id); instruction.add_operand(dim as u32); - instruction.add_operand(if comparison { 1 } else { 0 }); - - instruction.add_operand(if flags.contains(crate::ImageFlags::ARRAYED) { - 1 - } else { - 0 + instruction.add_operand(match class { + crate::ImageClass::Depth => 1, + _ => 0, + }); + instruction.add_operand(if arrayed { 1 } else { 0 }); + instruction.add_operand(match class { + crate::ImageClass::Multisampled => 1, + _ => 0, + }); + instruction.add_operand(match class { + crate::ImageClass::Sampled => 1, + _ => 0, }); - instruction.add_operand(if flags.contains(crate::ImageFlags::MULTISAMPLED) { - 1 - } else { - 0 - }); - - instruction.add_operand(if flags.contains(crate::ImageFlags::SAMPLED) { - 1 - } else { - 0 - }); - - // TODO Image Format defaults to Unknown, not yet in IR - instruction.add_operand(spirv::ImageFormat::Unknown as u32); + let (format, access) = match class { + crate::ImageClass::Storage(format, access) => { + let spv_format = match format { + crate::StorageFormat::Rgba32f => spirv::ImageFormat::Rgba32f, + }; + (spv_format, access) + } + _ => (spirv::ImageFormat::Unknown, crate::StorageAccess::empty()), + }; + instruction.add_operand(format as u32); // Access Qualifier - instruction.add_operand( - if flags.contains(crate::ImageFlags::CAN_STORE) - && flags.contains(crate::ImageFlags::CAN_LOAD) - { + if !access.is_empty() { + instruction.add_operand(if access == crate::StorageAccess::all() { 2 - } else if flags.contains(crate::ImageFlags::CAN_STORE) { + } else if access.contains(crate::StorageAccess::STORE) { 1 } else { 0 - }, - ); + }); + } + instruction } @@ -704,7 +704,7 @@ impl Writer { /// Primitive Instructions /// - fn write_scalar(&self, id: Word, kind: crate::ScalarKind, width: Bytes) -> Instruction { + fn write_scalar(&self, id: Word, kind: crate::ScalarKind, width: crate::Bytes) -> Instruction { let bits = (width * BITS_PER_BYTE) as u32; match kind { crate::ScalarKind::Sint => self.instruction_type_int(id, bits, Signedness::Signed), @@ -786,23 +786,23 @@ impl Writer { ); self.instruction_type_matrix(id, vector_id, columns) } - crate::TypeInner::Image { base, dim, flags } => { - let type_id = self.get_type_id(arena, LookupType::Handle(base)); + crate::TypeInner::Image { + kind, + dim, + arrayed, + class, + } => { + let type_id = self.get_type_id( + arena, + LookupType::Local(LocalType::Vector { + size: crate::VectorSize::Quad, + kind, + width: 4, + }), + ); let dim = map_dim(dim); self.try_add_capabilities(dim.required_capabilities()); - self.instruction_type_image(id, type_id, dim, flags, false) - } - crate::TypeInner::DepthImage { dim, arrayed } => { - let type_id = 0; //TODO! - let dim = map_dim(dim); - self.try_add_capabilities(dim.required_capabilities()); - - let flags = if arrayed { - crate::ImageFlags::ARRAYED - } else { - crate::ImageFlags::empty() - }; - self.instruction_type_image(id, type_id, dim, flags, true) + self.instruction_type_image(id, type_id, dim, arrayed, class) } crate::TypeInner::Sampler { comparison: _ } => self.instruction_type_sampler(id), crate::TypeInner::Array { size, stride, .. } => { diff --git a/src/front/glsl/helpers.rs b/src/front/glsl/helpers.rs index 1a43ed973..101448c1d 100644 --- a/src/front/glsl/helpers.rs +++ b/src/front/glsl/helpers.rs @@ -1,4 +1,4 @@ -use crate::{Arena, ImageDimension, ImageFlags, ScalarKind, Type, TypeInner, VectorSize}; +use crate::{ImageClass, ImageDimension, ScalarKind, TypeInner, VectorSize}; use glsl::syntax::{BinaryOp, TypeSpecifierNonArray, UnaryOp}; pub fn glsl_to_spirv_unary_op(op: UnaryOp) -> crate::UnaryOperator { @@ -36,7 +36,7 @@ pub fn glsl_to_spirv_binary_op(op: BinaryOp) -> crate::BinaryOperator { } } -pub fn glsl_to_spirv_type(ty: TypeSpecifierNonArray, types: &mut Arena) -> Option { +pub fn glsl_to_spirv_type(ty: TypeSpecifierNonArray) -> Option { use TypeSpecifierNonArray::*; Some(match ty { @@ -248,53 +248,28 @@ pub fn glsl_to_spirv_type(ty: TypeSpecifierNonArray, types: &mut Arena) -> }, TypeName(ty_name) => { if let Some(t_pos) = ty_name.0.find("texture") { - let scalar_kind = match &ty_name.0[..t_pos] { + let kind = match &ty_name.0[..t_pos] { "" => ScalarKind::Float, "i" => ScalarKind::Sint, "u" => ScalarKind::Uint, _ => panic!(), }; - let base = types.fetch_or_append(Type { - name: None, - inner: TypeInner::Scalar { - kind: scalar_kind, - width: 4, - }, - }); - - let (dim, flags) = match &ty_name.0[(t_pos + 7)..] { - "1D" => (ImageDimension::D1, ImageFlags::SAMPLED), - "2D" => (ImageDimension::D2, ImageFlags::SAMPLED), - "3D" => (ImageDimension::D3, ImageFlags::SAMPLED), - "1DArray" => ( - ImageDimension::D1, - ImageFlags::SAMPLED | ImageFlags::ARRAYED, - ), - "2DArray" => ( - ImageDimension::D2, - ImageFlags::SAMPLED | ImageFlags::ARRAYED, - ), - "3DArray" => ( - ImageDimension::D3, - ImageFlags::SAMPLED | ImageFlags::ARRAYED, - ), - "2DMS" => ( - ImageDimension::D2, - ImageFlags::SAMPLED | ImageFlags::MULTISAMPLED, - ), - "2DMSArray" => ( - ImageDimension::D2, - ImageFlags::SAMPLED | ImageFlags::ARRAYED | ImageFlags::MULTISAMPLED, - ), - "Cube" => (ImageDimension::Cube, ImageFlags::SAMPLED), - "CubeArray" => ( - ImageDimension::Cube, - ImageFlags::SAMPLED | ImageFlags::ARRAYED, - ), + let arrayed = ty_name.0.ends_with("Array"); + let (dim, class) = match &ty_name.0[(t_pos + 7)..] { + "1D" | "1DArray" => (ImageDimension::D1, ImageClass::Sampled), + "2D" | "2DArray" => (ImageDimension::D2, ImageClass::Sampled), + "3D" | "3DArray" => (ImageDimension::D3, ImageClass::Sampled), + "2DMS" | "2DMSArray" => (ImageDimension::D2, ImageClass::Multisampled), + "Cube" | "CubeArray" => (ImageDimension::Cube, ImageClass::Sampled), _ => panic!(), }; - return Some(TypeInner::Image { base, dim, flags }); + return Some(TypeInner::Image { + kind, + dim, + arrayed, + class, + }); } match ty_name.0.as_str() { diff --git a/src/front/glsl/mod.rs b/src/front/glsl/mod.rs index 888e9b63c..b4061233b 100644 --- a/src/front/glsl/mod.rs +++ b/src/front/glsl/mod.rs @@ -877,6 +877,7 @@ impl<'a> Parser<'a> { image: expressions.append(image), sampler: expressions.append(sampler), coordinate: expressions.append(coordinate), + level: crate::SampleLevel::Auto, depth_ref: None, //TODO }) } @@ -1005,7 +1006,7 @@ impl<'a> Parser<'a> { // None = void fn parse_type(&mut self, ty: TypeSpecifier) -> Option> { - let base_ty = helpers::glsl_to_spirv_type(ty.ty, &mut self.types)?; + let base_ty = helpers::glsl_to_spirv_type(ty.ty)?; let ty = if let Some(array_spec) = ty.array_specifier { let handle = self.types.fetch_or_append(Type { diff --git a/src/front/glsl_new/parser.rs b/src/front/glsl_new/parser.rs index ae4443bb1..953a0034d 100644 --- a/src/front/glsl_new/parser.rs +++ b/src/front/glsl_new/parser.rs @@ -1,5 +1,4 @@ -#![allow(unused_braces)] -#![allow(clippy::panic)] +#![allow(clippy::panic, unused_braces)] use pomelo::pomelo; pomelo! { @@ -566,8 +565,10 @@ pomelo! { for (id, initializer) in d.ids_initializers { // check if already declared in current scope #[cfg(feature = "glsl-validate")] - if extra.context.lookup_local_var_current_scope(&id).is_some() { - return Err(ErrorKind::VariableAlreadyDeclared(id)) + { + if extra.context.lookup_local_var_current_scope(&id).is_some() { + return Err(ErrorKind::VariableAlreadyDeclared(id)) + } } let localVar = extra.context.local_variables.append( LocalVariable { diff --git a/src/front/spv/convert.rs b/src/front/spv/convert.rs index 6329975e4..0c4d23da5 100644 --- a/src/front/spv/convert.rs +++ b/src/front/spv/convert.rs @@ -59,15 +59,24 @@ pub fn map_storage_class(word: spirv::Word) -> Result Result { - match spirv::Dim::from_u32(word) { - Some(spirv::Dim::Dim1D) => Ok(crate::ImageDimension::D1), - Some(spirv::Dim::Dim2D) => Ok(crate::ImageDimension::D2), - Some(spirv::Dim::Dim3D) => Ok(crate::ImageDimension::D3), - Some(spirv::Dim::DimCube) => Ok(crate::ImageDimension::Cube), + use spirv::Dim as D; + match D::from_u32(word) { + Some(D::Dim1D) => Ok(crate::ImageDimension::D1), + Some(D::Dim2D) => Ok(crate::ImageDimension::D2), + Some(D::Dim3D) => Ok(crate::ImageDimension::D3), + Some(D::DimCube) => Ok(crate::ImageDimension::Cube), _ => Err(Error::UnsupportedImageDim(word)), } } +pub fn map_image_format(word: spirv::Word) -> Result { + use spirv::ImageFormat as If; + match If::from_u32(word) { + Some(If::Rgba32f) => Ok(crate::StorageFormat::Rgba32f), + _ => Err(Error::UnsupportedImageFormat(word)), + } +} + pub fn map_width(word: spirv::Word) -> Result { (word >> 3) // bits to bytes .try_into() diff --git a/src/front/spv/error.rs b/src/front/spv/error.rs index f4384cd89..b467020b5 100644 --- a/src/front/spv/error.rs +++ b/src/front/spv/error.rs @@ -17,6 +17,7 @@ pub enum Error { UnsupportedExecutionModel(spirv::Word), UnsupportedStorageClass(spirv::Word), UnsupportedImageDim(spirv::Word), + UnsupportedImageFormat(spirv::Word), UnsupportedBuiltIn(spirv::Word), UnsupportedControlFlow(spirv::Word), UnsupportedBinaryOperator(spirv::Word), @@ -37,6 +38,7 @@ pub enum Error { InvalidStoreType(spirv::Word), InvalidBinding(spirv::Word), InvalidImageExpression(Handle), + InvalidImageBaseType(Handle), InvalidSamplerExpression(Handle), InvalidSampleImage(Handle), InvalidSampleSampler(Handle), diff --git a/src/front/spv/mod.rs b/src/front/spv/mod.rs index 701c150db..0f3d8dcb4 100644 --- a/src/front/spv/mod.rs +++ b/src/front/spv/mod.rs @@ -40,7 +40,7 @@ pub struct Instruction { } impl Instruction { - fn expect(&self, count: u16) -> Result<(), Error> { + fn expect(self, count: u16) -> Result<(), Error> { if self.wc == count { Ok(()) } else { @@ -48,7 +48,7 @@ impl Instruction { } } - fn expect_at_least(&self, count: u16) -> Result<(), Error> { + fn expect_at_least(self, count: u16) -> Result<(), Error> { if self.wc >= count { Ok(()) } else { @@ -817,18 +817,16 @@ impl> Parser { match type_arena[image_type_handle].inner { //TODO: compare the result type crate::TypeInner::Image { - base: _, + kind: _, dim, - flags, - } if flags - & (crate::ImageFlags::MULTISAMPLED | crate::ImageFlags::SAMPLED) - == crate::ImageFlags::SAMPLED => - { + arrayed, + class: crate::ImageClass::Sampled, + } => { if !check_sample_coordinates( &type_arena[coord_type_handle], crate::ScalarKind::Float, dim, - flags.contains(crate::ImageFlags::ARRAYED), + arrayed, ) { return Err(Error::InvalidSampleCoordinates(coord_type_handle)); } @@ -840,6 +838,7 @@ impl> Parser { image: si_lexp.image, sampler: si_lexp.sampler, coordinate: coord_lexp.handle, + level: crate::SampleLevel::Auto, depth_ref: None, }; self.lookup_expression.insert( @@ -877,7 +876,12 @@ impl> Parser { }; match type_arena[image_type_handle].inner { //TODO: compare the result type - crate::TypeInner::DepthImage { dim, arrayed } => { + crate::TypeInner::Image { + kind: _, + dim, + arrayed, + class: crate::ImageClass::Depth, + } => { if !check_sample_coordinates( &type_arena[coord_type_handle], crate::ScalarKind::Float, @@ -904,6 +908,7 @@ impl> Parser { image: si_lexp.image, sampler: si_lexp.sampler, coordinate: coord_lexp.handle, + level: crate::SampleLevel::Auto, depth_ref: Some(dref_lexp.handle), }; self.lookup_expression.insert( @@ -1236,15 +1241,9 @@ impl> Parser { }; *comparison = true; } - crate::TypeInner::Image { - base: _, - dim, - flags, - } => { - ty.inner = crate::TypeInner::DepthImage { - dim, - arrayed: flags.contains(crate::ImageFlags::ARRAYED), - }; + crate::TypeInner::Image { ref mut class, .. } => { + assert_eq!(*class, crate::ImageClass::Sampled); + *class = crate::ImageClass::Multisampled; } _ => panic!("Unexpected comparison type {:?}", ty), } @@ -1753,36 +1752,43 @@ impl> Parser { let id = self.next()?; let sample_type_id = self.next()?; let dim = self.next()?; - let mut flags = crate::ImageFlags::empty(); let _is_depth = self.next()?; - if self.next()? != 0 { - flags |= crate::ImageFlags::ARRAYED; - } - if self.next()? != 0 { - flags |= crate::ImageFlags::MULTISAMPLED; - } - let is_sampled = self.next()?; - if is_sampled != 0 { - flags |= crate::ImageFlags::SAMPLED; - } - let _format = self.next()?; - if inst.wc > 9 { + let is_array = self.next()? != 0; + let is_msaa = self.next()? != 0; + let _is_sampled = self.next()?; + let format = self.next()?; + + let base_handle = self.lookup_type.lookup(sample_type_id)?.handle; + let kind = match module.types[base_handle].inner { + crate::TypeInner::Scalar { kind, .. } | crate::TypeInner::Vector { kind, .. } => kind, + _ => return Err(Error::InvalidImageBaseType(base_handle)), + }; + + let class = if inst.wc > 9 { + let storage_format = map_image_format(format)?; + let mut flags = crate::StorageAccess::empty(); inst.expect(10)?; let access = self.next()?; if access == 0 || access == 2 { - flags |= crate::ImageFlags::CAN_LOAD; + flags |= crate::StorageAccess::LOAD; } if access == 1 || access == 2 { - flags |= crate::ImageFlags::CAN_STORE; + flags |= crate::StorageAccess::STORE; } + crate::ImageClass::Storage(storage_format, flags) + } else if is_msaa { + crate::ImageClass::Multisampled + } else { + crate::ImageClass::Sampled }; let decor = self.future_decor.remove(&id).unwrap_or_default(); let inner = crate::TypeInner::Image { - base: self.lookup_type.lookup(sample_type_id)?.handle, + class, + kind, dim: map_image_dim(dim)?, - flags, + arrayed: is_array, }; let handle = module.types.append(crate::Type { name: decor.name, diff --git a/src/lib.rs b/src/lib.rs index e45ca820f..6d6a6aa09 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -4,7 +4,7 @@ //! //! To improve performance and reduce memory usage, most structures are stored //! in an [`Arena`], and can be retrieved using the corresponding [`Handle`]. -#![allow(clippy::new_without_default)] +#![allow(clippy::new_without_default, clippy::unneeded_field_pattern)] #![deny(clippy::panic)] mod arena; @@ -207,20 +207,39 @@ bitflags::bitflags! { /// Flags describing an image. #[cfg_attr(feature = "serialize", derive(Serialize))] #[cfg_attr(feature = "deserialize", derive(Deserialize))] - pub struct ImageFlags: u32 { - /// Image is an array. - const ARRAYED = 0x1; - /// Image is multisampled. - const MULTISAMPLED = 0x2; - /// Image is to be accessed with a sampler. - const SAMPLED = 0x4; - /// Image can be used as a source for load ops. - const CAN_LOAD = 0x10; - /// Image can be used as a target for store ops. - const CAN_STORE = 0x20; + pub struct StorageAccess: u32 { + /// Storage can be used as a source for load ops. + const LOAD = 0x1; + /// Storage can be used as a target for store ops. + const STORE = 0x2; } } +// Storage image format. +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] +pub enum StorageFormat { + /// + Rgba32f, + //TODO +} + +/// Sub-class of the image type. +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] +pub enum ImageClass { + /// Regular sampled image. + Sampled, + /// Multi-sampled image. + Multisampled, + /// Depth comparison image. + Depth, + /// Storage image. + Storage(StorageFormat, StorageAccess), +} + /// A data type declared in the module. #[derive(Debug, PartialEq)] #[cfg_attr(feature = "serialize", derive(Serialize))] @@ -268,12 +287,11 @@ pub enum TypeInner { Struct { members: Vec }, /// Possibly multidimensional array of texels. Image { - base: Handle, + kind: ScalarKind, dim: ImageDimension, - flags: ImageFlags, + arrayed: bool, + class: ImageClass, }, - /// Depth-comparison image. - DepthImage { dim: ImageDimension, arrayed: bool }, /// Can be used to sample values from images. Sampler { comparison: bool }, } @@ -431,6 +449,16 @@ pub enum FunctionOrigin { External(String), } +/// Sampling modifier to control the level of detail. +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +#[cfg_attr(feature = "deserialize", derive(Deserialize))] +pub enum SampleLevel { + Auto, + Exact(Handle), + Bias(Handle), +} + /// An expression that can be evaluated to obtain a value. #[derive(Clone, Debug)] #[cfg_attr(feature = "serialize", derive(Serialize))] @@ -461,13 +489,21 @@ pub enum Expression { LocalVariable(Handle), /// Load a value indirectly. Load { pointer: Handle }, - /// Sample a point from an image. + /// Sample a point from a sampled or a depth image. ImageSample { image: Handle, sampler: Handle, coordinate: Handle, + level: SampleLevel, depth_ref: Option>, }, + /// Load a texel from an image. + ImageLoad { + image: Handle, + coordinate: Handle, + /// This is either LOD index, or sample index, based on the image class. + index: Handle, + }, /// Apply an unary operator. Unary { op: UnaryOperator, diff --git a/src/proc/interface.rs b/src/proc/interface.rs index 7459248ea..814285e23 100644 --- a/src/proc/interface.rs +++ b/src/proc/interface.rs @@ -34,15 +34,31 @@ impl<'a> Interface<'a> { image, sampler, coordinate, + level, depth_ref, } => { self.add_inputs(image); self.add_inputs(sampler); self.add_inputs(coordinate); + match level { + crate::SampleLevel::Auto => (), + crate::SampleLevel::Exact(h) | crate::SampleLevel::Bias(h) => { + self.add_inputs(h) + } + } if let Some(dref) = depth_ref { self.add_inputs(dref); } } + E::ImageLoad { + image, + coordinate, + index, + } => { + self.add_inputs(image); + self.add_inputs(coordinate); + self.add_inputs(index); + } E::Unary { expr, .. } => { self.add_inputs(expr); } diff --git a/src/proc/typifier.rs b/src/proc/typifier.rs index c967bd80c..9a4d5e4a1 100644 --- a/src/proc/typifier.rs +++ b/src/proc/typifier.rs @@ -85,7 +85,8 @@ impl Typifier { crate::Expression::GlobalVariable(h) => global_vars[h].ty, crate::Expression::LocalVariable(h) => local_vars[h].ty, crate::Expression::Load { .. } => unimplemented!(), - crate::Expression::ImageSample { image, .. } => { + crate::Expression::ImageSample { image, .. } + | crate::Expression::ImageLoad { image, .. } => { let image = self.resolve( image, expressions, @@ -96,22 +97,21 @@ impl Typifier { functions, )?; - let (kind, width) = match types[image].inner { - TypeInner::Image { base, .. } => match types[base].inner { - TypeInner::Scalar { kind, width } => (kind, width), - _ => unimplemented!(), + let inner = match types[image].inner { + TypeInner::Image { + kind, + class: crate::ImageClass::Depth, + .. + } => TypeInner::Scalar { kind, width: 4 }, + TypeInner::Image { kind, .. } => TypeInner::Vector { + kind, + width: 4, + size: VectorSize::Quad, }, _ => unreachable!(), }; - types.fetch_or_append(Type { - name: None, - inner: TypeInner::Vector { - kind, - width, - size: VectorSize::Quad, - }, - }) + types.fetch_or_append(Type { name: None, inner }) } crate::Expression::Unary { expr, .. } => self.types[expr.index()], crate::Expression::Binary { op, left, right } => match op { diff --git a/src/proc/validator.rs b/src/proc/validator.rs index b528fc069..364d7fd10 100644 --- a/src/proc/validator.rs +++ b/src/proc/validator.rs @@ -53,7 +53,7 @@ impl Validator { } } } - Ti::Image { .. } | Ti::DepthImage { .. } => {} + Ti::Image { .. } => {} Ti::Sampler { comparison: _ } => {} } }