| 1 |
/*! |
| 2 |
Helpers for the hlsl backend |
| 3 |
|
| 4 |
Important note about `Expression::ImageQuery`/`Expression::ArrayLength` and hlsl backend: |
| 5 |
|
| 6 |
Due to implementation of `GetDimensions` function in hlsl (<https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-getdimensions>) |
| 7 |
backend can't work with it as an expression. |
| 8 |
Instead, it generates a unique wrapped function per `Expression::ImageQuery`, based on texture info and query function. |
| 9 |
See `WrappedImageQuery` struct that represents a unique function and will be generated before writing all statements and expressions. |
| 10 |
This allowed to works with `Expression::ImageQuery` as expression and write wrapped function. |
| 11 |
|
| 12 |
For example: |
| 13 |
```wgsl |
| 14 |
let dim_1d = textureDimensions(image_1d); |
| 15 |
``` |
| 16 |
|
| 17 |
```hlsl |
| 18 |
int NagaDimensions1D(Texture1D<float4>) |
| 19 |
{ |
| 20 |
uint4 ret; |
| 21 |
image_1d.GetDimensions(ret.x); |
| 22 |
return ret.x; |
| 23 |
} |
| 24 |
|
| 25 |
int dim_1d = NagaDimensions1D(image_1d); |
| 26 |
``` |
| 27 |
*/ |
| 28 |
|
| 29 |
use alloc::format; |
| 30 |
use core::fmt::Write; |
| 31 |
|
| 32 |
use super::{ |
| 33 |
super::FunctionCtx, |
| 34 |
writer::{ |
| 35 |
ABS_FUNCTION, DIV_FUNCTION, EXTRACT_BITS_FUNCTION, F2I32_FUNCTION, F2I64_FUNCTION, |
| 36 |
F2U32_FUNCTION, F2U64_FUNCTION, INSERT_BITS_FUNCTION, MOD_FUNCTION, NEG_FUNCTION, |
| 37 |
}, |
| 38 |
BackendResult, WrappedType, |
| 39 |
}; |
| 40 |
use crate::{arena::Handle, proc::NameKey, ScalarKind}; |
| 41 |
|
| 42 |
#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] |
| 43 |
pub(super) struct WrappedArrayLength { |
| 44 |
pub(super) writable: bool, |
| 45 |
} |
| 46 |
|
| 47 |
#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] |
| 48 |
pub(super) struct WrappedImageQuery { |
| 49 |
pub(super) dim: crate::ImageDimension, |
| 50 |
pub(super) arrayed: bool, |
| 51 |
pub(super) class: crate::ImageClass, |
| 52 |
pub(super) query: ImageQuery, |
| 53 |
} |
| 54 |
|
| 55 |
#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] |
| 56 |
pub(super) struct WrappedConstructor { |
| 57 |
pub(super) ty: Handle<crate::Type>, |
| 58 |
} |
| 59 |
|
| 60 |
#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] |
| 61 |
pub(super) struct WrappedStructMatrixAccess { |
| 62 |
pub(super) ty: Handle<crate::Type>, |
| 63 |
pub(super) index: u32, |
| 64 |
} |
| 65 |
|
| 66 |
#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] |
| 67 |
pub(super) struct WrappedMatCx2 { |
| 68 |
pub(super) columns: crate::VectorSize, |
| 69 |
} |
| 70 |
|
| 71 |
#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] |
| 72 |
pub(super) struct WrappedMath { |
| 73 |
pub(super) fun: crate::MathFunction, |
| 74 |
pub(super) scalar: crate::Scalar, |
| 75 |
pub(super) components: Option<u32>, |
| 76 |
} |
| 77 |
|
| 78 |
#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] |
| 79 |
pub(super) struct WrappedZeroValue { |
| 80 |
pub(super) ty: Handle<crate::Type>, |
| 81 |
} |
| 82 |
|
| 83 |
#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] |
| 84 |
pub(super) struct WrappedUnaryOp { |
| 85 |
pub(super) op: crate::UnaryOperator, |
| 86 |
// This can only represent scalar or vector types. If we ever need to wrap |
| 87 |
// unary ops with other types, we'll need a better representation. |
| 88 |
pub(super) ty: (Option<crate::VectorSize>, crate::Scalar), |
| 89 |
} |
| 90 |
|
| 91 |
#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] |
| 92 |
pub(super) struct WrappedBinaryOp { |
| 93 |
pub(super) op: crate::BinaryOperator, |
| 94 |
// This can only represent scalar or vector types. If we ever need to wrap |
| 95 |
// binary ops with other types, we'll need a better representation. |
| 96 |
pub(super) left_ty: (Option<crate::VectorSize>, crate::Scalar), |
| 97 |
pub(super) right_ty: (Option<crate::VectorSize>, crate::Scalar), |
| 98 |
} |
| 99 |
|
| 100 |
#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] |
| 101 |
pub(super) struct WrappedCast { |
| 102 |
// This can only represent scalar or vector types. If we ever need to wrap |
| 103 |
// casts with other types, we'll need a better representation. |
| 104 |
pub(super) vector_size: Option<crate::VectorSize>, |
| 105 |
pub(super) src_scalar: crate::Scalar, |
| 106 |
pub(super) dst_scalar: crate::Scalar, |
| 107 |
} |
| 108 |
|
| 109 |
/// HLSL backend requires its own `ImageQuery` enum. |
| 110 |
/// |
| 111 |
/// It is used inside `WrappedImageQuery` and should be unique per ImageQuery function. |
| 112 |
/// IR version can't be unique per function, because it's store mipmap level as an expression. |
| 113 |
/// |
| 114 |
/// For example: |
| 115 |
/// ```wgsl |
| 116 |
/// let dim_cube_array_lod = textureDimensions(image_cube_array, 1); |
| 117 |
/// let dim_cube_array_lod2 = textureDimensions(image_cube_array, 1); |
| 118 |
/// ``` |
| 119 |
/// |
| 120 |
/// ```ir |
| 121 |
/// ImageQuery { |
| 122 |
/// image: [1], |
| 123 |
/// query: Size { |
| 124 |
/// level: Some( |
| 125 |
/// [1], |
| 126 |
/// ), |
| 127 |
/// }, |
| 128 |
/// }, |
| 129 |
/// ImageQuery { |
| 130 |
/// image: [1], |
| 131 |
/// query: Size { |
| 132 |
/// level: Some( |
| 133 |
/// [2], |
| 134 |
/// ), |
| 135 |
/// }, |
| 136 |
/// }, |
| 137 |
/// ``` |
| 138 |
/// |
| 139 |
/// HLSL should generate only 1 function for this case. |
| 140 |
#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] |
| 141 |
pub(super) enum ImageQuery { |
| 142 |
Size, |
| 143 |
SizeLevel, |
| 144 |
NumLevels, |
| 145 |
NumLayers, |
| 146 |
NumSamples, |
| 147 |
} |
| 148 |
|
| 149 |
impl From<crate::ImageQuery> for ImageQuery { |
| 150 |
fn from(q: crate::ImageQuery) -> Self { |
| 151 |
use crate::ImageQuery as Iq; |
| 152 |
match q { |
| 153 |
Iq::Size { level: Some(_) } => ImageQuery::SizeLevel, |
| 154 |
Iq::Size { level: None } => ImageQuery::Size, |
| 155 |
Iq::NumLevels => ImageQuery::NumLevels, |
| 156 |
Iq::NumLayers => ImageQuery::NumLayers, |
| 157 |
Iq::NumSamples => ImageQuery::NumSamples, |
| 158 |
} |
| 159 |
} |
| 160 |
} |
| 161 |
|
| 162 |
pub(super) const IMAGE_STORAGE_LOAD_SCALAR_WRAPPER: &str = "LoadedStorageValueFrom"; |
| 163 |
|
| 164 |
impl<W: Write> super::Writer<'_, W> { |
| 165 |
pub(super) fn write_image_type( |
| 166 |
&mut self, |
| 167 |
dim: crate::ImageDimension, |
| 168 |
arrayed: bool, |
| 169 |
class: crate::ImageClass, |
| 170 |
) -> BackendResult { |
| 171 |
let access_str = match class { |
| 172 |
crate::ImageClass::Storage { .. } => "RW", |
| 173 |
_ => "", |
| 174 |
}; |
| 175 |
let dim_str = dim.to_hlsl_str(); |
| 176 |
let arrayed_str = if arrayed { "Array" } else { "" }; |
| 177 |
write!(self.out, "{access_str}Texture{dim_str}{arrayed_str}")?; |
| 178 |
match class { |
| 179 |
crate::ImageClass::Depth { multi } => { |
| 180 |
let multi_str = if multi { "MS" } else { "" }; |
| 181 |
write!(self.out, "{multi_str}<float>")? |
| 182 |
} |
| 183 |
crate::ImageClass::Sampled { kind, multi } => { |
| 184 |
let multi_str = if multi { "MS" } else { "" }; |
| 185 |
let scalar_kind_str = crate::Scalar { kind, width: 4 }.to_hlsl_str()?; |
| 186 |
write!(self.out, "{multi_str}<{scalar_kind_str}4>")? |
| 187 |
} |
| 188 |
crate::ImageClass::Storage { format, .. } => { |
| 189 |
let storage_format_str = format.to_hlsl_str(); |
| 190 |
write!(self.out, "<{storage_format_str}>")? |
| 191 |
} |
| 192 |
} |
| 193 |
Ok(()) |
| 194 |
} |
| 195 |
|
| 196 |
pub(super) fn write_wrapped_array_length_function_name( |
| 197 |
&mut self, |
| 198 |
query: WrappedArrayLength, |
| 199 |
) -> BackendResult { |
| 200 |
let access_str = if query.writable { "RW" } else { "" }; |
| 201 |
write!(self.out, "NagaBufferLength{access_str}",)?; |
| 202 |
|
| 203 |
Ok(()) |
| 204 |
} |
| 205 |
|
| 206 |
/// Helper function that write wrapped function for `Expression::ArrayLength` |
| 207 |
/// |
| 208 |
/// <https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/sm5-object-rwbyteaddressbuffer-getdimensions> |
| 209 |
pub(super) fn write_wrapped_array_length_function( |
| 210 |
&mut self, |
| 211 |
wal: WrappedArrayLength, |
| 212 |
) -> BackendResult { |
| 213 |
use crate::back::INDENT; |
| 214 |
|
| 215 |
const ARGUMENT_VARIABLE_NAME: &str = "buffer"; |
| 216 |
const RETURN_VARIABLE_NAME: &str = "ret"; |
| 217 |
|
| 218 |
// Write function return type and name |
| 219 |
write!(self.out, "uint ")?; |
| 220 |
self.write_wrapped_array_length_function_name(wal)?; |
| 221 |
|
| 222 |
// Write function parameters |
| 223 |
write!(self.out, "(")?; |
| 224 |
let access_str = if wal.writable { "RW" } else { "" }; |
| 225 |
writeln!( |
| 226 |
self.out, |
| 227 |
"{access_str}ByteAddressBuffer {ARGUMENT_VARIABLE_NAME})" |
| 228 |
)?; |
| 229 |
// Write function body |
| 230 |
writeln!(self.out, "{{")?; |
| 231 |
|
| 232 |
// Write `GetDimensions` function. |
| 233 |
writeln!(self.out, "{INDENT}uint {RETURN_VARIABLE_NAME};")?; |
| 234 |
writeln!( |
| 235 |
self.out, |
| 236 |
"{INDENT}{ARGUMENT_VARIABLE_NAME}.GetDimensions({RETURN_VARIABLE_NAME});" |
| 237 |
)?; |
| 238 |
|
| 239 |
// Write return value |
| 240 |
writeln!(self.out, "{INDENT}return {RETURN_VARIABLE_NAME};")?; |
| 241 |
|
| 242 |
// End of function body |
| 243 |
writeln!(self.out, "}}")?; |
| 244 |
// Write extra new line |
| 245 |
writeln!(self.out)?; |
| 246 |
|
| 247 |
Ok(()) |
| 248 |
} |
| 249 |
|
| 250 |
pub(super) fn write_wrapped_image_query_function_name( |
| 251 |
&mut self, |
| 252 |
query: WrappedImageQuery, |
| 253 |
) -> BackendResult { |
| 254 |
let dim_str = query.dim.to_hlsl_str(); |
| 255 |
let class_str = match query.class { |
| 256 |
crate::ImageClass::Sampled { multi: true, .. } => "MS", |
| 257 |
crate::ImageClass::Depth { multi: true } => "DepthMS", |
| 258 |
crate::ImageClass::Depth { multi: false } => "Depth", |
| 259 |
crate::ImageClass::Sampled { multi: false, .. } => "", |
| 260 |
crate::ImageClass::Storage { .. } => "RW", |
| 261 |
}; |
| 262 |
let arrayed_str = if query.arrayed { "Array" } else { "" }; |
| 263 |
let query_str = match query.query { |
| 264 |
ImageQuery::Size => "Dimensions", |
| 265 |
ImageQuery::SizeLevel => "MipDimensions", |
| 266 |
ImageQuery::NumLevels => "NumLevels", |
| 267 |
ImageQuery::NumLayers => "NumLayers", |
| 268 |
ImageQuery::NumSamples => "NumSamples", |
| 269 |
}; |
| 270 |
|
| 271 |
write!(self.out, "Naga{class_str}{query_str}{dim_str}{arrayed_str}")?; |
| 272 |
|
| 273 |
Ok(()) |
| 274 |
} |
| 275 |
|
| 276 |
/// Helper function that write wrapped function for `Expression::ImageQuery` |
| 277 |
/// |
| 278 |
/// <https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-getdimensions> |
| 279 |
pub(super) fn write_wrapped_image_query_function( |
| 280 |
&mut self, |
| 281 |
module: &crate::Module, |
| 282 |
wiq: WrappedImageQuery, |
| 283 |
expr_handle: Handle<crate::Expression>, |
| 284 |
func_ctx: &FunctionCtx, |
| 285 |
) -> BackendResult { |
| 286 |
use crate::{ |
| 287 |
back::{COMPONENTS, INDENT}, |
| 288 |
ImageDimension as IDim, |
| 289 |
}; |
| 290 |
|
| 291 |
const ARGUMENT_VARIABLE_NAME: &str = "tex"; |
| 292 |
const RETURN_VARIABLE_NAME: &str = "ret"; |
| 293 |
const MIP_LEVEL_PARAM: &str = "mip_level"; |
| 294 |
|
| 295 |
// Write function return type and name |
| 296 |
let ret_ty = func_ctx.resolve_type(expr_handle, &module.types); |
| 297 |
self.write_value_type(module, ret_ty)?; |
| 298 |
write!(self.out, " ")?; |
| 299 |
self.write_wrapped_image_query_function_name(wiq)?; |
| 300 |
|
| 301 |
// Write function parameters |
| 302 |
write!(self.out, "(")?; |
| 303 |
// Texture always first parameter |
| 304 |
self.write_image_type(wiq.dim, wiq.arrayed, wiq.class)?; |
| 305 |
write!(self.out, " {ARGUMENT_VARIABLE_NAME}")?; |
| 306 |
// Mipmap is a second parameter if exists |
| 307 |
if let ImageQuery::SizeLevel = wiq.query { |
| 308 |
write!(self.out, ", uint {MIP_LEVEL_PARAM}")?; |
| 309 |
} |
| 310 |
writeln!(self.out, ")")?; |
| 311 |
|
| 312 |
// Write function body |
| 313 |
writeln!(self.out, "{{")?; |
| 314 |
|
| 315 |
let array_coords = usize::from(wiq.arrayed); |
| 316 |
// extra parameter is the mip level count or the sample count |
| 317 |
let extra_coords = match wiq.class { |
| 318 |
crate::ImageClass::Storage { .. } => 0, |
| 319 |
crate::ImageClass::Sampled { .. } | crate::ImageClass::Depth { .. } => 1, |
| 320 |
}; |
| 321 |
|
| 322 |
// GetDimensions Overloaded Methods |
| 323 |
// https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-getdimensions#overloaded-methods |
| 324 |
let (ret_swizzle, number_of_params) = match wiq.query { |
| 325 |
ImageQuery::Size | ImageQuery::SizeLevel => { |
| 326 |
let ret = match wiq.dim { |
| 327 |
IDim::D1 => "x", |
| 328 |
IDim::D2 => "xy", |
| 329 |
IDim::D3 => "xyz", |
| 330 |
IDim::Cube => "xy", |
| 331 |
}; |
| 332 |
(ret, ret.len() + array_coords + extra_coords) |
| 333 |
} |
| 334 |
ImageQuery::NumLevels | ImageQuery::NumSamples | ImageQuery::NumLayers => { |
| 335 |
if wiq.arrayed || wiq.dim == IDim::D3 { |
| 336 |
("w", 4) |
| 337 |
} else { |
| 338 |
("z", 3) |
| 339 |
} |
| 340 |
} |
| 341 |
}; |
| 342 |
|
| 343 |
// Write `GetDimensions` function. |
| 344 |
writeln!(self.out, "{INDENT}uint4 {RETURN_VARIABLE_NAME};")?; |
| 345 |
write!(self.out, "{INDENT}{ARGUMENT_VARIABLE_NAME}.GetDimensions(")?; |
| 346 |
match wiq.query { |
| 347 |
ImageQuery::SizeLevel => { |
| 348 |
write!(self.out, "{MIP_LEVEL_PARAM}, ")?; |
| 349 |
} |
| 350 |
_ => match wiq.class { |
| 351 |
crate::ImageClass::Sampled { multi: true, .. } |
| 352 |
| crate::ImageClass::Depth { multi: true } |
| 353 |
| crate::ImageClass::Storage { .. } => {} |
| 354 |
_ => { |
| 355 |
// Write zero mipmap level for supported types |
| 356 |
write!(self.out, "0, ")?; |
| 357 |
} |
| 358 |
}, |
| 359 |
} |
| 360 |
|
| 361 |
for component in COMPONENTS[..number_of_params - 1].iter() { |
| 362 |
write!(self.out, "{RETURN_VARIABLE_NAME}.{component}, ")?; |
| 363 |
} |
| 364 |
|
| 365 |
// write last parameter without comma and space for last parameter |
| 366 |
write!( |
| 367 |
self.out, |
| 368 |
"{}.{}", |
| 369 |
RETURN_VARIABLE_NAME, |
| 370 |
COMPONENTS[number_of_params - 1] |
| 371 |
)?; |
| 372 |
|
| 373 |
writeln!(self.out, ");")?; |
| 374 |
|
| 375 |
// Write return value |
| 376 |
writeln!( |
| 377 |
self.out, |
| 378 |
"{INDENT}return {RETURN_VARIABLE_NAME}.{ret_swizzle};" |
| 379 |
)?; |
| 380 |
|
| 381 |
// End of function body |
| 382 |
writeln!(self.out, "}}")?; |
| 383 |
// Write extra new line |
| 384 |
writeln!(self.out)?; |
| 385 |
|
| 386 |
Ok(()) |
| 387 |
} |
| 388 |
|
| 389 |
pub(super) fn write_wrapped_constructor_function_name( |
| 390 |
&mut self, |
| 391 |
module: &crate::Module, |
| 392 |
constructor: WrappedConstructor, |
| 393 |
) -> BackendResult { |
| 394 |
let name = crate::TypeInner::hlsl_type_id(constructor.ty, module.to_ctx(), &self.names)?; |
| 395 |
write!(self.out, "Construct{name}")?; |
| 396 |
Ok(()) |
| 397 |
} |
| 398 |
|
| 399 |
/// Helper function that write wrapped function for `Expression::Compose` for structures. |
| 400 |
fn write_wrapped_constructor_function( |
| 401 |
&mut self, |
| 402 |
module: &crate::Module, |
| 403 |
constructor: WrappedConstructor, |
| 404 |
) -> BackendResult { |
| 405 |
use crate::back::INDENT; |
| 406 |
|
| 407 |
const ARGUMENT_VARIABLE_NAME: &str = "arg"; |
| 408 |
const RETURN_VARIABLE_NAME: &str = "ret"; |
| 409 |
|
| 410 |
// Write function return type and name |
| 411 |
if let crate::TypeInner::Array { base, size, .. } = module.types[constructor.ty].inner { |
| 412 |
write!(self.out, "typedef ")?; |
| 413 |
self.write_type(module, constructor.ty)?; |
| 414 |
write!(self.out, " ret_")?; |
| 415 |
self.write_wrapped_constructor_function_name(module, constructor)?; |
| 416 |
self.write_array_size(module, base, size)?; |
| 417 |
writeln!(self.out, ";")?; |
| 418 |
|
| 419 |
write!(self.out, "ret_")?; |
| 420 |
self.write_wrapped_constructor_function_name(module, constructor)?; |
| 421 |
} else { |
| 422 |
self.write_type(module, constructor.ty)?; |
| 423 |
} |
| 424 |
write!(self.out, " ")?; |
| 425 |
self.write_wrapped_constructor_function_name(module, constructor)?; |
| 426 |
|
| 427 |
// Write function parameters |
| 428 |
write!(self.out, "(")?; |
| 429 |
|
| 430 |
let mut write_arg = |i, ty| -> BackendResult { |
| 431 |
if i != 0 { |
| 432 |
write!(self.out, ", ")?; |
| 433 |
} |
| 434 |
self.write_type(module, ty)?; |
| 435 |
write!(self.out, " {ARGUMENT_VARIABLE_NAME}{i}")?; |
| 436 |
if let crate::TypeInner::Array { base, size, .. } = module.types[ty].inner { |
| 437 |
self.write_array_size(module, base, size)?; |
| 438 |
} |
| 439 |
Ok(()) |
| 440 |
}; |
| 441 |
|
| 442 |
match module.types[constructor.ty].inner { |
| 443 |
crate::TypeInner::Struct { ref members, .. } => { |
| 444 |
for (i, member) in members.iter().enumerate() { |
| 445 |
write_arg(i, member.ty)?; |
| 446 |
} |
| 447 |
} |
| 448 |
crate::TypeInner::Array { |
| 449 |
base, |
| 450 |
size: crate::ArraySize::Constant(size), |
| 451 |
.. |
| 452 |
} => { |
| 453 |
for i in 0..size.get() as usize { |
| 454 |
write_arg(i, base)?; |
| 455 |
} |
| 456 |
} |
| 457 |
_ => unreachable!(), |
| 458 |
}; |
| 459 |
|
| 460 |
write!(self.out, ")")?; |
| 461 |
|
| 462 |
// Write function body |
| 463 |
writeln!(self.out, " {{")?; |
| 464 |
|
| 465 |
match module.types[constructor.ty].inner { |
| 466 |
crate::TypeInner::Struct { ref members, .. } => { |
| 467 |
let struct_name = &self.names[&NameKey::Type(constructor.ty)]; |
| 468 |
writeln!( |
| 469 |
self.out, |
| 470 |
"{INDENT}{struct_name} {RETURN_VARIABLE_NAME} = ({struct_name})0;" |
| 471 |
)?; |
| 472 |
for (i, member) in members.iter().enumerate() { |
| 473 |
let field_name = &self.names[&NameKey::StructMember(constructor.ty, i as u32)]; |
| 474 |
|
| 475 |
match module.types[member.ty].inner { |
| 476 |
crate::TypeInner::Matrix { |
| 477 |
columns, |
| 478 |
rows: crate::VectorSize::Bi, |
| 479 |
.. |
| 480 |
} if member.binding.is_none() => { |
| 481 |
for j in 0..columns as u8 { |
| 482 |
writeln!( |
| 483 |
self.out, |
| 484 |
"{INDENT}{RETURN_VARIABLE_NAME}.{field_name}_{j} = {ARGUMENT_VARIABLE_NAME}{i}[{j}];" |
| 485 |
)?; |
| 486 |
} |
| 487 |
} |
| 488 |
ref other => { |
| 489 |
// We cast arrays of native HLSL `floatCx2`s to arrays of `matCx2`s |
| 490 |
// (where the inner matrix is represented by a struct with C `float2` members). |
| 491 |
// See the module-level block comment in mod.rs for details. |
| 492 |
if let Some(super::writer::MatrixType { |
| 493 |
columns, |
| 494 |
rows: crate::VectorSize::Bi, |
| 495 |
width: 4, |
| 496 |
}) = super::writer::get_inner_matrix_data(module, member.ty) |
| 497 |
{ |
| 498 |
write!( |
| 499 |
self.out, |
| 500 |
"{}{}.{} = (__mat{}x2", |
| 501 |
INDENT, RETURN_VARIABLE_NAME, field_name, columns as u8 |
| 502 |
)?; |
| 503 |
if let crate::TypeInner::Array { base, size, .. } = *other { |
| 504 |
self.write_array_size(module, base, size)?; |
| 505 |
} |
| 506 |
writeln!(self.out, "){ARGUMENT_VARIABLE_NAME}{i};",)?; |
| 507 |
} else { |
| 508 |
writeln!( |
| 509 |
self.out, |
| 510 |
"{INDENT}{RETURN_VARIABLE_NAME}.{field_name} = {ARGUMENT_VARIABLE_NAME}{i};", |
| 511 |
)?; |
| 512 |
} |
| 513 |
} |
| 514 |
} |
| 515 |
} |
| 516 |
} |
| 517 |
crate::TypeInner::Array { |
| 518 |
base, |
| 519 |
size: crate::ArraySize::Constant(size), |
| 520 |
.. |
| 521 |
} => { |
| 522 |
write!(self.out, "{INDENT}")?; |
| 523 |
self.write_type(module, base)?; |
| 524 |
write!(self.out, " {RETURN_VARIABLE_NAME}")?; |
| 525 |
self.write_array_size(module, base, crate::ArraySize::Constant(size))?; |
| 526 |
write!(self.out, " = {{ ")?; |
| 527 |
for i in 0..size.get() { |
| 528 |
if i != 0 { |
| 529 |
write!(self.out, ", ")?; |
| 530 |
} |
| 531 |
write!(self.out, "{ARGUMENT_VARIABLE_NAME}{i}")?; |
| 532 |
} |
| 533 |
writeln!(self.out, " }};",)?; |
| 534 |
} |
| 535 |
_ => unreachable!(), |
| 536 |
} |
| 537 |
|
| 538 |
// Write return value |
| 539 |
writeln!(self.out, "{INDENT}return {RETURN_VARIABLE_NAME};")?; |
| 540 |
|
| 541 |
// End of function body |
| 542 |
writeln!(self.out, "}}")?; |
| 543 |
// Write extra new line |
| 544 |
writeln!(self.out)?; |
| 545 |
|
| 546 |
Ok(()) |
| 547 |
} |
| 548 |
|
| 549 |
/// Writes the conversion from a single length storage texture load to a vec4 with the loaded |
| 550 |
/// scalar in its `x` component, 1 in its `a` component and 0 everywhere else. |
| 551 |
fn write_loaded_scalar_to_storage_loaded_value( |
| 552 |
&mut self, |
| 553 |
scalar_type: crate::Scalar, |
| 554 |
) -> BackendResult { |
| 555 |
const ARGUMENT_VARIABLE_NAME: &str = "arg"; |
| 556 |
const RETURN_VARIABLE_NAME: &str = "ret"; |
| 557 |
|
| 558 |
let zero; |
| 559 |
let one; |
| 560 |
match scalar_type.kind { |
| 561 |
ScalarKind::Sint => { |
| 562 |
assert_eq!( |
| 563 |
scalar_type.width, 4, |
| 564 |
"Scalar {scalar_type:?} is not a result from any storage format" |
| 565 |
); |
| 566 |
zero = "0"; |
| 567 |
one = "1"; |
| 568 |
} |
| 569 |
ScalarKind::Uint => match scalar_type.width { |
| 570 |
4 => { |
| 571 |
zero = "0u"; |
| 572 |
one = "1u"; |
| 573 |
} |
| 574 |
8 => { |
| 575 |
zero = "0uL"; |
| 576 |
one = "1uL" |
| 577 |
} |
| 578 |
_ => unreachable!("Scalar {scalar_type:?} is not a result from any storage format"), |
| 579 |
}, |
| 580 |
ScalarKind::Float => { |
| 581 |
assert_eq!( |
| 582 |
scalar_type.width, 4, |
| 583 |
"Scalar {scalar_type:?} is not a result from any storage format" |
| 584 |
); |
| 585 |
zero = "0.0"; |
| 586 |
one = "1.0"; |
| 587 |
} |
| 588 |
_ => unreachable!("Scalar {scalar_type:?} is not a result from any storage format"), |
| 589 |
} |
| 590 |
|
| 591 |
let ty = scalar_type.to_hlsl_str()?; |
| 592 |
writeln!( |
| 593 |
self.out, |
| 594 |
"{ty}4 {IMAGE_STORAGE_LOAD_SCALAR_WRAPPER}{ty}({ty} {ARGUMENT_VARIABLE_NAME}) {{\ |
| 595 |
{ty}4 {RETURN_VARIABLE_NAME} = {ty}4({ARGUMENT_VARIABLE_NAME}, {zero}, {zero}, {one});\ |
| 596 |
return {RETURN_VARIABLE_NAME};\ |
| 597 |
}}" |
| 598 |
)?; |
| 599 |
|
| 600 |
Ok(()) |
| 601 |
} |
| 602 |
|
| 603 |
pub(super) fn write_wrapped_struct_matrix_get_function_name( |
| 604 |
&mut self, |
| 605 |
access: WrappedStructMatrixAccess, |
| 606 |
) -> BackendResult { |
| 607 |
let name = &self.names[&NameKey::Type(access.ty)]; |
| 608 |
let field_name = &self.names[&NameKey::StructMember(access.ty, access.index)]; |
| 609 |
write!(self.out, "GetMat{field_name}On{name}")?; |
| 610 |
Ok(()) |
| 611 |
} |
| 612 |
|
| 613 |
/// Writes a function used to get a matCx2 from within a structure. |
| 614 |
pub(super) fn write_wrapped_struct_matrix_get_function( |
| 615 |
&mut self, |
| 616 |
module: &crate::Module, |
| 617 |
access: WrappedStructMatrixAccess, |
| 618 |
) -> BackendResult { |
| 619 |
use crate::back::INDENT; |
| 620 |
|
| 621 |
const STRUCT_ARGUMENT_VARIABLE_NAME: &str = "obj"; |
| 622 |
|
| 623 |
// Write function return type and name |
| 624 |
let member = match module.types[access.ty].inner { |
| 625 |
crate::TypeInner::Struct { ref members, .. } => &members[access.index as usize], |
| 626 |
_ => unreachable!(), |
| 627 |
}; |
| 628 |
let ret_ty = &module.types[member.ty].inner; |
| 629 |
self.write_value_type(module, ret_ty)?; |
| 630 |
write!(self.out, " ")?; |
| 631 |
self.write_wrapped_struct_matrix_get_function_name(access)?; |
| 632 |
|
| 633 |
// Write function parameters |
| 634 |
write!(self.out, "(")?; |
| 635 |
let struct_name = &self.names[&NameKey::Type(access.ty)]; |
| 636 |
write!(self.out, "{struct_name} {STRUCT_ARGUMENT_VARIABLE_NAME}")?; |
| 637 |
|
| 638 |
// Write function body |
| 639 |
writeln!(self.out, ") {{")?; |
| 640 |
|
| 641 |
// Write return value |
| 642 |
write!(self.out, "{INDENT}return ")?; |
| 643 |
self.write_value_type(module, ret_ty)?; |
| 644 |
write!(self.out, "(")?; |
| 645 |
let field_name = &self.names[&NameKey::StructMember(access.ty, access.index)]; |
| 646 |
match module.types[member.ty].inner { |
| 647 |
crate::TypeInner::Matrix { columns, .. } => { |
| 648 |
for i in 0..columns as u8 { |
| 649 |
if i != 0 { |
| 650 |
write!(self.out, ", ")?; |
| 651 |
} |
| 652 |
write!(self.out, "{STRUCT_ARGUMENT_VARIABLE_NAME}.{field_name}_{i}")?; |
| 653 |
} |
| 654 |
} |
| 655 |
_ => unreachable!(), |
| 656 |
} |
| 657 |
writeln!(self.out, ");")?; |
| 658 |
|
| 659 |
// End of function body |
| 660 |
writeln!(self.out, "}}")?; |
| 661 |
// Write extra new line |
| 662 |
writeln!(self.out)?; |
| 663 |
|
| 664 |
Ok(()) |
| 665 |
} |
| 666 |
|
| 667 |
pub(super) fn write_wrapped_struct_matrix_set_function_name( |
| 668 |
&mut self, |
| 669 |
access: WrappedStructMatrixAccess, |
| 670 |
) -> BackendResult { |
| 671 |
let name = &self.names[&NameKey::Type(access.ty)]; |
| 672 |
let field_name = &self.names[&NameKey::StructMember(access.ty, access.index)]; |
| 673 |
write!(self.out, "SetMat{field_name}On{name}")?; |
| 674 |
Ok(()) |
| 675 |
} |
| 676 |
|
| 677 |
/// Writes a function used to set a matCx2 from within a structure. |
| 678 |
pub(super) fn write_wrapped_struct_matrix_set_function( |
| 679 |
&mut self, |
| 680 |
module: &crate::Module, |
| 681 |
access: WrappedStructMatrixAccess, |
| 682 |
) -> BackendResult { |
| 683 |
use crate::back::INDENT; |
| 684 |
|
| 685 |
const STRUCT_ARGUMENT_VARIABLE_NAME: &str = "obj"; |
| 686 |
const MATRIX_ARGUMENT_VARIABLE_NAME: &str = "mat"; |
| 687 |
|
| 688 |
// Write function return type and name |
| 689 |
write!(self.out, "void ")?; |
| 690 |
self.write_wrapped_struct_matrix_set_function_name(access)?; |
| 691 |
|
| 692 |
// Write function parameters |
| 693 |
write!(self.out, "(")?; |
| 694 |
let struct_name = &self.names[&NameKey::Type(access.ty)]; |
| 695 |
write!(self.out, "{struct_name} {STRUCT_ARGUMENT_VARIABLE_NAME}, ")?; |
| 696 |
let member = match module.types[access.ty].inner { |
| 697 |
crate::TypeInner::Struct { ref members, .. } => &members[access.index as usize], |
| 698 |
_ => unreachable!(), |
| 699 |
}; |
| 700 |
self.write_type(module, member.ty)?; |
| 701 |
write!(self.out, " {MATRIX_ARGUMENT_VARIABLE_NAME}")?; |
| 702 |
// Write function body |
| 703 |
writeln!(self.out, ") {{")?; |
| 704 |
|
| 705 |
let field_name = &self.names[&NameKey::StructMember(access.ty, access.index)]; |
| 706 |
|
| 707 |
match module.types[member.ty].inner { |
| 708 |
crate::TypeInner::Matrix { columns, .. } => { |
| 709 |
for i in 0..columns as u8 { |
| 710 |
writeln!( |
| 711 |
self.out, |
| 712 |
"{INDENT}{STRUCT_ARGUMENT_VARIABLE_NAME}.{field_name}_{i} = {MATRIX_ARGUMENT_VARIABLE_NAME}[{i}];" |
| 713 |
)?; |
| 714 |
} |
| 715 |
} |
| 716 |
_ => unreachable!(), |
| 717 |
} |
| 718 |
|
| 719 |
// End of function body |
| 720 |
writeln!(self.out, "}}")?; |
| 721 |
// Write extra new line |
| 722 |
writeln!(self.out)?; |
| 723 |
|
| 724 |
Ok(()) |
| 725 |
} |
| 726 |
|
| 727 |
pub(super) fn write_wrapped_struct_matrix_set_vec_function_name( |
| 728 |
&mut self, |
| 729 |
access: WrappedStructMatrixAccess, |
| 730 |
) -> BackendResult { |
| 731 |
let name = &self.names[&NameKey::Type(access.ty)]; |
| 732 |
let field_name = &self.names[&NameKey::StructMember(access.ty, access.index)]; |
| 733 |
write!(self.out, "SetMatVec{field_name}On{name}")?; |
| 734 |
Ok(()) |
| 735 |
} |
| 736 |
|
| 737 |
/// Writes a function used to set a vec2 on a matCx2 from within a structure. |
| 738 |
pub(super) fn write_wrapped_struct_matrix_set_vec_function( |
| 739 |
&mut self, |
| 740 |
module: &crate::Module, |
| 741 |
access: WrappedStructMatrixAccess, |
| 742 |
) -> BackendResult { |
| 743 |
use crate::back::INDENT; |
| 744 |
|
| 745 |
const STRUCT_ARGUMENT_VARIABLE_NAME: &str = "obj"; |
| 746 |
const VECTOR_ARGUMENT_VARIABLE_NAME: &str = "vec"; |
| 747 |
const MATRIX_INDEX_ARGUMENT_VARIABLE_NAME: &str = "mat_idx"; |
| 748 |
|
| 749 |
// Write function return type and name |
| 750 |
write!(self.out, "void ")?; |
| 751 |
self.write_wrapped_struct_matrix_set_vec_function_name(access)?; |
| 752 |
|
| 753 |
// Write function parameters |
| 754 |
write!(self.out, "(")?; |
| 755 |
let struct_name = &self.names[&NameKey::Type(access.ty)]; |
| 756 |
write!(self.out, "{struct_name} {STRUCT_ARGUMENT_VARIABLE_NAME}, ")?; |
| 757 |
let member = match module.types[access.ty].inner { |
| 758 |
crate::TypeInner::Struct { ref members, .. } => &members[access.index as usize], |
| 759 |
_ => unreachable!(), |
| 760 |
}; |
| 761 |
let vec_ty = match module.types[member.ty].inner { |
| 762 |
crate::TypeInner::Matrix { rows, scalar, .. } => { |
| 763 |
crate::TypeInner::Vector { size: rows, scalar } |
| 764 |
} |
| 765 |
_ => unreachable!(), |
| 766 |
}; |
| 767 |
self.write_value_type(module, &vec_ty)?; |
| 768 |
write!( |
| 769 |
self.out, |
| 770 |
" {VECTOR_ARGUMENT_VARIABLE_NAME}, uint {MATRIX_INDEX_ARGUMENT_VARIABLE_NAME}" |
| 771 |
)?; |
| 772 |
|
| 773 |
// Write function body |
| 774 |
writeln!(self.out, ") {{")?; |
| 775 |
|
| 776 |
writeln!( |
| 777 |
self.out, |
| 778 |
"{INDENT}switch({MATRIX_INDEX_ARGUMENT_VARIABLE_NAME}) {{" |
| 779 |
)?; |
| 780 |
|
| 781 |
let field_name = &self.names[&NameKey::StructMember(access.ty, access.index)]; |
| 782 |
|
| 783 |
match module.types[member.ty].inner { |
| 784 |
crate::TypeInner::Matrix { columns, .. } => { |
| 785 |
for i in 0..columns as u8 { |
| 786 |
writeln!( |
| 787 |
self.out, |
| 788 |
"{INDENT}case {i}: {{ {STRUCT_ARGUMENT_VARIABLE_NAME}.{field_name}_{i} = {VECTOR_ARGUMENT_VARIABLE_NAME}; break; }}" |
| 789 |
)?; |
| 790 |
} |
| 791 |
} |
| 792 |
_ => unreachable!(), |
| 793 |
} |
| 794 |
|
| 795 |
writeln!(self.out, "{INDENT}}}")?; |
| 796 |
|
| 797 |
// End of function body |
| 798 |
writeln!(self.out, "}}")?; |
| 799 |
// Write extra new line |
| 800 |
writeln!(self.out)?; |
| 801 |
|
| 802 |
Ok(()) |
| 803 |
} |
| 804 |
|
| 805 |
pub(super) fn write_wrapped_struct_matrix_set_scalar_function_name( |
| 806 |
&mut self, |
| 807 |
access: WrappedStructMatrixAccess, |
| 808 |
) -> BackendResult { |
| 809 |
let name = &self.names[&NameKey::Type(access.ty)]; |
| 810 |
let field_name = &self.names[&NameKey::StructMember(access.ty, access.index)]; |
| 811 |
write!(self.out, "SetMatScalar{field_name}On{name}")?; |
| 812 |
Ok(()) |
| 813 |
} |
| 814 |
|
| 815 |
/// Writes a function used to set a float on a matCx2 from within a structure. |
| 816 |
pub(super) fn write_wrapped_struct_matrix_set_scalar_function( |
| 817 |
&mut self, |
| 818 |
module: &crate::Module, |
| 819 |
access: WrappedStructMatrixAccess, |
| 820 |
) -> BackendResult { |
| 821 |
use crate::back::INDENT; |
| 822 |
|
| 823 |
const STRUCT_ARGUMENT_VARIABLE_NAME: &str = "obj"; |
| 824 |
const SCALAR_ARGUMENT_VARIABLE_NAME: &str = "scalar"; |
| 825 |
const MATRIX_INDEX_ARGUMENT_VARIABLE_NAME: &str = "mat_idx"; |
| 826 |
const VECTOR_INDEX_ARGUMENT_VARIABLE_NAME: &str = "vec_idx"; |
| 827 |
|
| 828 |
// Write function return type and name |
| 829 |
write!(self.out, "void ")?; |
| 830 |
self.write_wrapped_struct_matrix_set_scalar_function_name(access)?; |
| 831 |
|
| 832 |
// Write function parameters |
| 833 |
write!(self.out, "(")?; |
| 834 |
let struct_name = &self.names[&NameKey::Type(access.ty)]; |
| 835 |
write!(self.out, "{struct_name} {STRUCT_ARGUMENT_VARIABLE_NAME}, ")?; |
| 836 |
let member = match module.types[access.ty].inner { |
| 837 |
crate::TypeInner::Struct { ref members, .. } => &members[access.index as usize], |
| 838 |
_ => unreachable!(), |
| 839 |
}; |
| 840 |
let scalar_ty = match module.types[member.ty].inner { |
| 841 |
crate::TypeInner::Matrix { scalar, .. } => crate::TypeInner::Scalar(scalar), |
| 842 |
_ => unreachable!(), |
| 843 |
}; |
| 844 |
self.write_value_type(module, &scalar_ty)?; |
| 845 |
write!( |
| 846 |
self.out, |
| 847 |
" {SCALAR_ARGUMENT_VARIABLE_NAME}, uint {MATRIX_INDEX_ARGUMENT_VARIABLE_NAME}, uint {VECTOR_INDEX_ARGUMENT_VARIABLE_NAME}" |
| 848 |
)?; |
| 849 |
|
| 850 |
// Write function body |
| 851 |
writeln!(self.out, ") {{")?; |
| 852 |
|
| 853 |
writeln!( |
| 854 |
self.out, |
| 855 |
"{INDENT}switch({MATRIX_INDEX_ARGUMENT_VARIABLE_NAME}) {{" |
| 856 |
)?; |
| 857 |
|
| 858 |
let field_name = &self.names[&NameKey::StructMember(access.ty, access.index)]; |
| 859 |
|
| 860 |
match module.types[member.ty].inner { |
| 861 |
crate::TypeInner::Matrix { columns, .. } => { |
| 862 |
for i in 0..columns as u8 { |
| 863 |
writeln!( |
| 864 |
self.out, |
| 865 |
"{INDENT}case {i}: {{ {STRUCT_ARGUMENT_VARIABLE_NAME}.{field_name}_{i}[{VECTOR_INDEX_ARGUMENT_VARIABLE_NAME}] = {SCALAR_ARGUMENT_VARIABLE_NAME}; break; }}" |
| 866 |
)?; |
| 867 |
} |
| 868 |
} |
| 869 |
_ => unreachable!(), |
| 870 |
} |
| 871 |
|
| 872 |
writeln!(self.out, "{INDENT}}}")?; |
| 873 |
|
| 874 |
// End of function body |
| 875 |
writeln!(self.out, "}}")?; |
| 876 |
// Write extra new line |
| 877 |
writeln!(self.out)?; |
| 878 |
|
| 879 |
Ok(()) |
| 880 |
} |
| 881 |
|
| 882 |
/// Write functions to create special types. |
| 883 |
pub(super) fn write_special_functions(&mut self, module: &crate::Module) -> BackendResult { |
| 884 |
for (type_key, struct_ty) in module.special_types.predeclared_types.iter() { |
| 885 |
match type_key { |
| 886 |
&crate::PredeclaredType::ModfResult { size, scalar } |
| 887 |
| &crate::PredeclaredType::FrexpResult { size, scalar } => { |
| 888 |
let arg_type_name_owner; |
| 889 |
let arg_type_name = if let Some(size) = size { |
| 890 |
arg_type_name_owner = format!( |
| 891 |
"{}{}", |
| 892 |
if scalar.width == 8 { "double" } else { "float" }, |
| 893 |
size as u8 |
| 894 |
); |
| 895 |
&arg_type_name_owner |
| 896 |
} else if scalar.width == 8 { |
| 897 |
"double" |
| 898 |
} else { |
| 899 |
"float" |
| 900 |
}; |
| 901 |
|
| 902 |
let (defined_func_name, called_func_name, second_field_name, sign_multiplier) = |
| 903 |
if matches!(type_key, &crate::PredeclaredType::ModfResult { .. }) { |
| 904 |
(super::writer::MODF_FUNCTION, "modf", "whole", "") |
| 905 |
} else { |
| 906 |
( |
| 907 |
super::writer::FREXP_FUNCTION, |
| 908 |
"frexp", |
| 909 |
"exp_", |
| 910 |
"sign(arg) * ", |
| 911 |
) |
| 912 |
}; |
| 913 |
|
| 914 |
let struct_name = &self.names[&NameKey::Type(*struct_ty)]; |
| 915 |
|
| 916 |
writeln!( |
| 917 |
self.out, |
| 918 |
"{struct_name} {defined_func_name}({arg_type_name} arg) {{ |
| 919 |
{arg_type_name} other; |
| 920 |
{struct_name} result; |
| 921 |
result.fract = {sign_multiplier}{called_func_name}(arg, other); |
| 922 |
result.{second_field_name} = other; |
| 923 |
return result; |
| 924 |
}}" |
| 925 |
)?; |
| 926 |
writeln!(self.out)?; |
| 927 |
} |
| 928 |
&crate::PredeclaredType::AtomicCompareExchangeWeakResult { .. } => {} |
| 929 |
} |
| 930 |
} |
| 931 |
if module.special_types.ray_desc.is_some() { |
| 932 |
self.write_ray_desc_from_ray_desc_constructor_function(module)?; |
| 933 |
} |
| 934 |
|
| 935 |
Ok(()) |
| 936 |
} |
| 937 |
|
| 938 |
/// Helper function that writes wrapped functions for expressions in a function |
| 939 |
pub(super) fn write_wrapped_expression_functions( |
| 940 |
&mut self, |
| 941 |
module: &crate::Module, |
| 942 |
expressions: &crate::Arena<crate::Expression>, |
| 943 |
context: Option<&FunctionCtx>, |
| 944 |
) -> BackendResult { |
| 945 |
for (handle, _) in expressions.iter() { |
| 946 |
match expressions[handle] { |
| 947 |
crate::Expression::Compose { ty, .. } => { |
| 948 |
match module.types[ty].inner { |
| 949 |
crate::TypeInner::Struct { .. } | crate::TypeInner::Array { .. } => { |
| 950 |
let constructor = WrappedConstructor { ty }; |
| 951 |
if self.wrapped.insert(WrappedType::Constructor(constructor)) { |
| 952 |
self.write_wrapped_constructor_function(module, constructor)?; |
| 953 |
} |
| 954 |
} |
| 955 |
_ => {} |
| 956 |
}; |
| 957 |
} |
| 958 |
crate::Expression::ImageLoad { image, .. } => { |
| 959 |
// This can only happen in a function as this is not a valid const expression |
| 960 |
match *context.as_ref().unwrap().resolve_type(image, &module.types) { |
| 961 |
crate::TypeInner::Image { |
| 962 |
class: crate::ImageClass::Storage { format, .. }, |
| 963 |
.. |
| 964 |
} => { |
| 965 |
if format.single_component() { |
| 966 |
let scalar: crate::Scalar = format.into(); |
| 967 |
if self.wrapped.insert(WrappedType::ImageLoadScalar(scalar)) { |
| 968 |
self.write_loaded_scalar_to_storage_loaded_value(scalar)?; |
| 969 |
} |
| 970 |
} |
| 971 |
} |
| 972 |
_ => {} |
| 973 |
} |
| 974 |
} |
| 975 |
crate::Expression::RayQueryGetIntersection { committed, .. } => { |
| 976 |
if committed { |
| 977 |
if !self.written_committed_intersection { |
| 978 |
self.write_committed_intersection_function(module)?; |
| 979 |
self.written_committed_intersection = true; |
| 980 |
} |
| 981 |
} else if !self.written_candidate_intersection { |
| 982 |
self.write_candidate_intersection_function(module)?; |
| 983 |
self.written_candidate_intersection = true; |
| 984 |
} |
| 985 |
} |
| 986 |
_ => {} |
| 987 |
} |
| 988 |
} |
| 989 |
Ok(()) |
| 990 |
} |
| 991 |
|
| 992 |
// TODO: we could merge this with iteration in write_wrapped_expression_functions... |
| 993 |
// |
| 994 |
/// Helper function that writes zero value wrapped functions |
| 995 |
pub(super) fn write_wrapped_zero_value_functions( |
| 996 |
&mut self, |
| 997 |
module: &crate::Module, |
| 998 |
expressions: &crate::Arena<crate::Expression>, |
| 999 |
) -> BackendResult { |
| 1000 |
for (handle, _) in expressions.iter() { |
| 1001 |
if let crate::Expression::ZeroValue(ty) = expressions[handle] { |
| 1002 |
let zero_value = WrappedZeroValue { ty }; |
| 1003 |
if self.wrapped.insert(WrappedType::ZeroValue(zero_value)) { |
| 1004 |
self.write_wrapped_zero_value_function(module, zero_value)?; |
| 1005 |
} |
| 1006 |
} |
| 1007 |
} |
| 1008 |
Ok(()) |
| 1009 |
} |
| 1010 |
|
| 1011 |
pub(super) fn write_wrapped_math_functions( |
| 1012 |
&mut self, |
| 1013 |
module: &crate::Module, |
| 1014 |
func_ctx: &FunctionCtx, |
| 1015 |
) -> BackendResult { |
| 1016 |
for (_, expression) in func_ctx.expressions.iter() { |
| 1017 |
if let crate::Expression::Math { |
| 1018 |
fun, |
| 1019 |
arg, |
| 1020 |
arg1: _arg1, |
| 1021 |
arg2: _arg2, |
| 1022 |
arg3: _arg3, |
| 1023 |
} = *expression |
| 1024 |
{ |
| 1025 |
let arg_ty = func_ctx.resolve_type(arg, &module.types); |
| 1026 |
|
| 1027 |
match fun { |
| 1028 |
crate::MathFunction::ExtractBits => { |
| 1029 |
// The behavior of our extractBits polyfill is undefined if offset + count > bit_width. We need |
| 1030 |
// to first sanitize the offset and count first. If we don't do this, we will get out-of-spec |
| 1031 |
// values if the extracted range is not within the bit width. |
| 1032 |
// |
| 1033 |
// This encodes the exact formula specified by the wgsl spec: |
| 1034 |
// https://gpuweb.github.io/gpuweb/wgsl/#extractBits-unsigned-builtin |
| 1035 |
// |
| 1036 |
// w = sizeof(x) * 8 |
| 1037 |
// o = min(offset, w) |
| 1038 |
// c = min(count, w - o) |
| 1039 |
// |
| 1040 |
// bitfieldExtract(x, o, c) |
| 1041 |
let scalar = arg_ty.scalar().unwrap(); |
| 1042 |
let components = arg_ty.components(); |
| 1043 |
|
| 1044 |
let wrapped = WrappedMath { |
| 1045 |
fun, |
| 1046 |
scalar, |
| 1047 |
components, |
| 1048 |
}; |
| 1049 |
|
| 1050 |
if !self.wrapped.insert(WrappedType::Math(wrapped)) { |
| 1051 |
continue; |
| 1052 |
} |
| 1053 |
|
| 1054 |
// Write return type |
| 1055 |
self.write_value_type(module, arg_ty)?; |
| 1056 |
|
| 1057 |
let scalar_width: u8 = scalar.width * 8; |
| 1058 |
|
| 1059 |
// Write function name and parameters |
| 1060 |
writeln!(self.out, " {EXTRACT_BITS_FUNCTION}(")?; |
| 1061 |
write!(self.out, " ")?; |
| 1062 |
self.write_value_type(module, arg_ty)?; |
| 1063 |
writeln!(self.out, " e,")?; |
| 1064 |
writeln!(self.out, " uint offset,")?; |
| 1065 |
writeln!(self.out, " uint count")?; |
| 1066 |
writeln!(self.out, ") {{")?; |
| 1067 |
|
| 1068 |
// Write function body |
| 1069 |
writeln!(self.out, " uint w = {scalar_width};")?; |
| 1070 |
writeln!(self.out, " uint o = min(offset, w);")?; |
| 1071 |
writeln!(self.out, " uint c = min(count, w - o);")?; |
| 1072 |
writeln!( |
| 1073 |
self.out, |
| 1074 |
" return (c == 0 ? 0 : (e << (w - c - o)) >> (w - c));" |
| 1075 |
)?; |
| 1076 |
|
| 1077 |
// End of function body |
| 1078 |
writeln!(self.out, "}}")?; |
| 1079 |
} |
| 1080 |
crate::MathFunction::InsertBits => { |
| 1081 |
// The behavior of our insertBits polyfill has the same constraints as the extractBits polyfill. |
| 1082 |
|
| 1083 |
let scalar = arg_ty.scalar().unwrap(); |
| 1084 |
let components = arg_ty.components(); |
| 1085 |
|
| 1086 |
let wrapped = WrappedMath { |
| 1087 |
fun, |
| 1088 |
scalar, |
| 1089 |
components, |
| 1090 |
}; |
| 1091 |
|
| 1092 |
if !self.wrapped.insert(WrappedType::Math(wrapped)) { |
| 1093 |
continue; |
| 1094 |
} |
| 1095 |
|
| 1096 |
// Write return type |
| 1097 |
self.write_value_type(module, arg_ty)?; |
| 1098 |
|
| 1099 |
let scalar_width: u8 = scalar.width * 8; |
| 1100 |
let scalar_max: u64 = match scalar.width { |
| 1101 |
1 => 0xFF, |
| 1102 |
2 => 0xFFFF, |
| 1103 |
4 => 0xFFFFFFFF, |
| 1104 |
8 => 0xFFFFFFFFFFFFFFFF, |
| 1105 |
_ => unreachable!(), |
| 1106 |
}; |
| 1107 |
|
| 1108 |
// Write function name and parameters |
| 1109 |
writeln!(self.out, " {INSERT_BITS_FUNCTION}(")?; |
| 1110 |
write!(self.out, " ")?; |
| 1111 |
self.write_value_type(module, arg_ty)?; |
| 1112 |
writeln!(self.out, " e,")?; |
| 1113 |
write!(self.out, " ")?; |
| 1114 |
self.write_value_type(module, arg_ty)?; |
| 1115 |
writeln!(self.out, " newbits,")?; |
| 1116 |
writeln!(self.out, " uint offset,")?; |
| 1117 |
writeln!(self.out, " uint count")?; |
| 1118 |
writeln!(self.out, ") {{")?; |
| 1119 |
|
| 1120 |
// Write function body |
| 1121 |
writeln!(self.out, " uint w = {scalar_width}u;")?; |
| 1122 |
writeln!(self.out, " uint o = min(offset, w);")?; |
| 1123 |
writeln!(self.out, " uint c = min(count, w - o);")?; |
| 1124 |
|
| 1125 |
// The `u` suffix on the literals is _extremely_ important. Otherwise it will use |
| 1126 |
// i32 shifting instead of the intended u32 shifting. |
| 1127 |
writeln!( |
| 1128 |
self.out, |
| 1129 |
" uint mask = (({scalar_max}u >> ({scalar_width}u - c)) << o);" |
| 1130 |
)?; |
| 1131 |
writeln!( |
| 1132 |
self.out, |
| 1133 |
" return (c == 0 ? e : ((e & ~mask) | ((newbits << o) & mask)));" |
| 1134 |
)?; |
| 1135 |
|
| 1136 |
// End of function body |
| 1137 |
writeln!(self.out, "}}")?; |
| 1138 |
} |
| 1139 |
// Taking the absolute value of the minimum value of a two's |
| 1140 |
// complement signed integer type causes overflow, which is |
| 1141 |
// undefined behaviour in HLSL. To avoid this, when the value is |
| 1142 |
// negative we bitcast the value to unsigned and negate it, then |
| 1143 |
// bitcast back to signed. |
| 1144 |
// This adheres to the WGSL spec in that the absolute of the type's |
| 1145 |
// minimum value should equal to the minimum value. |
| 1146 |
// |
| 1147 |
// TODO(#7109): asint()/asuint() only support 32-bit integers, so we |
| 1148 |
// must find another solution for different bit-widths. |
| 1149 |
crate::MathFunction::Abs |
| 1150 |
if matches!(arg_ty.scalar(), Some(crate::Scalar::I32)) => |
| 1151 |
{ |
| 1152 |
let scalar = arg_ty.scalar().unwrap(); |
| 1153 |
let components = arg_ty.components(); |
| 1154 |
|
| 1155 |
let wrapped = WrappedMath { |
| 1156 |
fun, |
| 1157 |
scalar, |
| 1158 |
components, |
| 1159 |
}; |
| 1160 |
|
| 1161 |
if !self.wrapped.insert(WrappedType::Math(wrapped)) { |
| 1162 |
continue; |
| 1163 |
} |
| 1164 |
|
| 1165 |
self.write_value_type(module, arg_ty)?; |
| 1166 |
write!(self.out, " {ABS_FUNCTION}(")?; |
| 1167 |
self.write_value_type(module, arg_ty)?; |
| 1168 |
writeln!(self.out, " val) {{")?; |
| 1169 |
|
| 1170 |
let level = crate::back::Level(1); |
| 1171 |
writeln!( |
| 1172 |
self.out, |
| 1173 |
"{level}return val >= 0 ? val : asint(-asuint(val));" |
| 1174 |
)?; |
| 1175 |
writeln!(self.out, "}}")?; |
| 1176 |
writeln!(self.out)?; |
| 1177 |
} |
| 1178 |
_ => {} |
| 1179 |
} |
| 1180 |
} |
| 1181 |
} |
| 1182 |
|
| 1183 |
Ok(()) |
| 1184 |
} |
| 1185 |
|
| 1186 |
pub(super) fn write_wrapped_unary_ops( |
| 1187 |
&mut self, |
| 1188 |
module: &crate::Module, |
| 1189 |
func_ctx: &FunctionCtx, |
| 1190 |
) -> BackendResult { |
| 1191 |
for (_, expression) in func_ctx.expressions.iter() { |
| 1192 |
if let crate::Expression::Unary { op, expr } = *expression { |
| 1193 |
let expr_ty = func_ctx.resolve_type(expr, &module.types); |
| 1194 |
let Some((vector_size, scalar)) = expr_ty.vector_size_and_scalar() else { |
| 1195 |
continue; |
| 1196 |
}; |
| 1197 |
let wrapped = WrappedUnaryOp { |
| 1198 |
op, |
| 1199 |
ty: (vector_size, scalar), |
| 1200 |
}; |
| 1201 |
|
| 1202 |
// Negating the minimum value of a two's complement signed integer type |
| 1203 |
// causes overflow, which is undefined behaviour in HLSL. To avoid this |
| 1204 |
// we bitcast the value to unsigned and negate it, then bitcast back to |
| 1205 |
// signed. This adheres to the WGSL spec in that the negative of the |
| 1206 |
// type's minimum value should equal to the minimum value. |
| 1207 |
// |
| 1208 |
// TODO(#7109): asint()/asuint() only support 32-bit integers, so we must |
| 1209 |
// find another solution for different bit-widths. |
| 1210 |
match (op, scalar) { |
| 1211 |
(crate::UnaryOperator::Negate, crate::Scalar::I32) => { |
| 1212 |
if !self.wrapped.insert(WrappedType::UnaryOp(wrapped)) { |
| 1213 |
continue; |
| 1214 |
} |
| 1215 |
|
| 1216 |
self.write_value_type(module, expr_ty)?; |
| 1217 |
write!(self.out, " {NEG_FUNCTION}(")?; |
| 1218 |
self.write_value_type(module, expr_ty)?; |
| 1219 |
writeln!(self.out, " val) {{")?; |
| 1220 |
|
| 1221 |
let level = crate::back::Level(1); |
| 1222 |
writeln!(self.out, "{level}return asint(-asuint(val));",)?; |
| 1223 |
writeln!(self.out, "}}")?; |
| 1224 |
writeln!(self.out)?; |
| 1225 |
} |
| 1226 |
_ => {} |
| 1227 |
} |
| 1228 |
} |
| 1229 |
} |
| 1230 |
|
| 1231 |
Ok(()) |
| 1232 |
} |
| 1233 |
|
| 1234 |
pub(super) fn write_wrapped_binary_ops( |
| 1235 |
&mut self, |
| 1236 |
module: &crate::Module, |
| 1237 |
func_ctx: &FunctionCtx, |
| 1238 |
) -> BackendResult { |
| 1239 |
for (expr_handle, expression) in func_ctx.expressions.iter() { |
| 1240 |
if let crate::Expression::Binary { op, left, right } = *expression { |
| 1241 |
let expr_ty = func_ctx.resolve_type(expr_handle, &module.types); |
| 1242 |
let left_ty = func_ctx.resolve_type(left, &module.types); |
| 1243 |
let right_ty = func_ctx.resolve_type(right, &module.types); |
| 1244 |
|
| 1245 |
match (op, expr_ty.scalar()) { |
| 1246 |
// Signed integer division of the type's minimum representable value |
| 1247 |
// divided by -1, or signed or unsigned division by zero, is |
| 1248 |
// undefined behaviour in HLSL. We override the divisor to 1 in these |
| 1249 |
// cases. |
| 1250 |
// This adheres to the WGSL spec in that: |
| 1251 |
// * TYPE_MIN / -1 == TYPE_MIN |
| 1252 |
// * x / 0 == x |
| 1253 |
( |
| 1254 |
crate::BinaryOperator::Divide, |
| 1255 |
Some( |
| 1256 |
scalar @ crate::Scalar { |
| 1257 |
kind: ScalarKind::Sint | ScalarKind::Uint, |
| 1258 |
.. |
| 1259 |
}, |
| 1260 |
), |
| 1261 |
) => { |
| 1262 |
let Some(left_wrapped_ty) = left_ty.vector_size_and_scalar() else { |
| 1263 |
continue; |
| 1264 |
}; |
| 1265 |
let Some(right_wrapped_ty) = right_ty.vector_size_and_scalar() else { |
| 1266 |
continue; |
| 1267 |
}; |
| 1268 |
let wrapped = WrappedBinaryOp { |
| 1269 |
op, |
| 1270 |
left_ty: left_wrapped_ty, |
| 1271 |
right_ty: right_wrapped_ty, |
| 1272 |
}; |
| 1273 |
if !self.wrapped.insert(WrappedType::BinaryOp(wrapped)) { |
| 1274 |
continue; |
| 1275 |
} |
| 1276 |
|
| 1277 |
self.write_value_type(module, expr_ty)?; |
| 1278 |
write!(self.out, " {DIV_FUNCTION}(")?; |
| 1279 |
self.write_value_type(module, left_ty)?; |
| 1280 |
write!(self.out, " lhs, ")?; |
| 1281 |
self.write_value_type(module, right_ty)?; |
| 1282 |
writeln!(self.out, " rhs) {{")?; |
| 1283 |
let level = crate::back::Level(1); |
| 1284 |
match scalar.kind { |
| 1285 |
ScalarKind::Sint => { |
| 1286 |
let min_val = match scalar.width { |
| 1287 |
4 => crate::Literal::I32(i32::MIN), |
| 1288 |
8 => crate::Literal::I64(i64::MIN), |
| 1289 |
_ => { |
| 1290 |
return Err(super::Error::UnsupportedScalar(scalar)); |
| 1291 |
} |
| 1292 |
}; |
| 1293 |
write!(self.out, "{level}return lhs / (((lhs == ")?; |
| 1294 |
self.write_literal(min_val)?; |
| 1295 |
writeln!(self.out, " & rhs == -1) | (rhs == 0)) ? 1 : rhs);")? |
| 1296 |
} |
| 1297 |
ScalarKind::Uint => { |
| 1298 |
writeln!(self.out, "{level}return lhs / (rhs == 0u ? 1u : rhs);")? |
| 1299 |
} |
| 1300 |
_ => unreachable!(), |
| 1301 |
} |
| 1302 |
writeln!(self.out, "}}")?; |
| 1303 |
writeln!(self.out)?; |
| 1304 |
} |
| 1305 |
// The modulus operator is only defined for integers in HLSL when |
| 1306 |
// either both sides are positive or both sides are negative. To |
| 1307 |
// avoid this undefined behaviour we use the following equation: |
| 1308 |
// |
| 1309 |
// dividend - (dividend / divisor) * divisor |
| 1310 |
// |
| 1311 |
// overriding the divisor to 1 if either it is 0, or it is -1 |
| 1312 |
// and the dividend is the minimum representable value. |
| 1313 |
// |
| 1314 |
// This adheres to the WGSL spec in that: |
| 1315 |
// * min_value % -1 == 0 |
| 1316 |
// * x % 0 == 0 |
| 1317 |
( |
| 1318 |
crate::BinaryOperator::Modulo, |
| 1319 |
Some( |
| 1320 |
scalar @ crate::Scalar { |
| 1321 |
kind: ScalarKind::Sint | ScalarKind::Uint, |
| 1322 |
.. |
| 1323 |
}, |
| 1324 |
), |
| 1325 |
) => { |
| 1326 |
let Some(left_wrapped_ty) = left_ty.vector_size_and_scalar() else { |
| 1327 |
continue; |
| 1328 |
}; |
| 1329 |
let Some(right_wrapped_ty) = right_ty.vector_size_and_scalar() else { |
| 1330 |
continue; |
| 1331 |
}; |
| 1332 |
let wrapped = WrappedBinaryOp { |
| 1333 |
op, |
| 1334 |
left_ty: left_wrapped_ty, |
| 1335 |
right_ty: right_wrapped_ty, |
| 1336 |
}; |
| 1337 |
if !self.wrapped.insert(WrappedType::BinaryOp(wrapped)) { |
| 1338 |
continue; |
| 1339 |
} |
| 1340 |
|
| 1341 |
self.write_value_type(module, expr_ty)?; |
| 1342 |
write!(self.out, " {MOD_FUNCTION}(")?; |
| 1343 |
self.write_value_type(module, left_ty)?; |
| 1344 |
write!(self.out, " lhs, ")?; |
| 1345 |
self.write_value_type(module, right_ty)?; |
| 1346 |
writeln!(self.out, " rhs) {{")?; |
| 1347 |
let level = crate::back::Level(1); |
| 1348 |
match scalar.kind { |
| 1349 |
ScalarKind::Sint => { |
| 1350 |
let min_val = match scalar.width { |
| 1351 |
4 => crate::Literal::I32(i32::MIN), |
| 1352 |
8 => crate::Literal::I64(i64::MIN), |
| 1353 |
_ => { |
| 1354 |
return Err(super::Error::UnsupportedScalar(scalar)); |
| 1355 |
} |
| 1356 |
}; |
| 1357 |
write!(self.out, "{level}")?; |
| 1358 |
self.write_value_type(module, right_ty)?; |
| 1359 |
write!(self.out, " divisor = ((lhs == ")?; |
| 1360 |
self.write_literal(min_val)?; |
| 1361 |
writeln!(self.out, " & rhs == -1) | (rhs == 0)) ? 1 : rhs;")?; |
| 1362 |
writeln!( |
| 1363 |
self.out, |
| 1364 |
"{level}return lhs - (lhs / divisor) * divisor;" |
| 1365 |
)? |
| 1366 |
} |
| 1367 |
ScalarKind::Uint => { |
| 1368 |
writeln!(self.out, "{level}return lhs % (rhs == 0u ? 1u : rhs);")? |
| 1369 |
} |
| 1370 |
_ => unreachable!(), |
| 1371 |
} |
| 1372 |
writeln!(self.out, "}}")?; |
| 1373 |
writeln!(self.out)?; |
| 1374 |
} |
| 1375 |
_ => {} |
| 1376 |
} |
| 1377 |
} |
| 1378 |
} |
| 1379 |
|
| 1380 |
Ok(()) |
| 1381 |
} |
| 1382 |
|
| 1383 |
fn write_wrapped_cast_functions( |
| 1384 |
&mut self, |
| 1385 |
module: &crate::Module, |
| 1386 |
func_ctx: &FunctionCtx, |
| 1387 |
) -> BackendResult { |
| 1388 |
for (_, expression) in func_ctx.expressions.iter() { |
| 1389 |
if let crate::Expression::As { |
| 1390 |
expr, |
| 1391 |
kind, |
| 1392 |
convert: Some(width), |
| 1393 |
} = *expression |
| 1394 |
{ |
| 1395 |
// Avoid undefined behaviour when casting from a float to integer |
| 1396 |
// when the value is out of range for the target type. Additionally |
| 1397 |
// ensure we clamp to the correct value as per the WGSL spec. |
| 1398 |
// |
| 1399 |
// https://www.w3.org/TR/WGSL/#floating-point-conversion: |
| 1400 |
// * If X is exactly representable in the target type T, then the |
| 1401 |
// result is that value. |
| 1402 |
// * Otherwise, the result is the value in T closest to |
| 1403 |
// truncate(X) and also exactly representable in the original |
| 1404 |
// floating point type. |
| 1405 |
let src_ty = func_ctx.resolve_type(expr, &module.types); |
| 1406 |
let Some((vector_size, src_scalar)) = src_ty.vector_size_and_scalar() else { |
| 1407 |
continue; |
| 1408 |
}; |
| 1409 |
let dst_scalar = crate::Scalar { kind, width }; |
| 1410 |
if src_scalar.kind != ScalarKind::Float |
| 1411 |
|| (dst_scalar.kind != ScalarKind::Sint && dst_scalar.kind != ScalarKind::Uint) |
| 1412 |
{ |
| 1413 |
continue; |
| 1414 |
} |
| 1415 |
|
| 1416 |
let wrapped = WrappedCast { |
| 1417 |
src_scalar, |
| 1418 |
vector_size, |
| 1419 |
dst_scalar, |
| 1420 |
}; |
| 1421 |
if !self.wrapped.insert(WrappedType::Cast(wrapped)) { |
| 1422 |
continue; |
| 1423 |
} |
| 1424 |
|
| 1425 |
let (src_ty, dst_ty) = match vector_size { |
| 1426 |
None => ( |
| 1427 |
crate::TypeInner::Scalar(src_scalar), |
| 1428 |
crate::TypeInner::Scalar(dst_scalar), |
| 1429 |
), |
| 1430 |
Some(vector_size) => ( |
| 1431 |
crate::TypeInner::Vector { |
| 1432 |
scalar: src_scalar, |
| 1433 |
size: vector_size, |
| 1434 |
}, |
| 1435 |
crate::TypeInner::Vector { |
| 1436 |
scalar: dst_scalar, |
| 1437 |
size: vector_size, |
| 1438 |
}, |
| 1439 |
), |
| 1440 |
}; |
| 1441 |
let (min, max) = |
| 1442 |
crate::proc::min_max_float_representable_by(src_scalar, dst_scalar); |
| 1443 |
let cast_str = format!( |
| 1444 |
"{}{}", |
| 1445 |
dst_scalar.to_hlsl_str()?, |
| 1446 |
vector_size |
| 1447 |
.map(crate::common::vector_size_str) |
| 1448 |
.unwrap_or(""), |
| 1449 |
); |
| 1450 |
let fun_name = match dst_scalar { |
| 1451 |
crate::Scalar::I32 => F2I32_FUNCTION, |
| 1452 |
crate::Scalar::U32 => F2U32_FUNCTION, |
| 1453 |
crate::Scalar::I64 => F2I64_FUNCTION, |
| 1454 |
crate::Scalar::U64 => F2U64_FUNCTION, |
| 1455 |
_ => unreachable!(), |
| 1456 |
}; |
| 1457 |
self.write_value_type(module, &dst_ty)?; |
| 1458 |
write!(self.out, " {fun_name}(")?; |
| 1459 |
self.write_value_type(module, &src_ty)?; |
| 1460 |
writeln!(self.out, " value) {{")?; |
| 1461 |
let level = crate::back::Level(1); |
| 1462 |
write!(self.out, "{level}return {cast_str}(clamp(value, ")?; |
| 1463 |
self.write_literal(min)?; |
| 1464 |
write!(self.out, ", ")?; |
| 1465 |
self.write_literal(max)?; |
| 1466 |
writeln!(self.out, "));",)?; |
| 1467 |
writeln!(self.out, "}}")?; |
| 1468 |
writeln!(self.out)?; |
| 1469 |
} |
| 1470 |
} |
| 1471 |
Ok(()) |
| 1472 |
} |
| 1473 |
|
| 1474 |
/// Helper function that writes various wrapped functions |
| 1475 |
pub(super) fn write_wrapped_functions( |
| 1476 |
&mut self, |
| 1477 |
module: &crate::Module, |
| 1478 |
func_ctx: &FunctionCtx, |
| 1479 |
) -> BackendResult { |
| 1480 |
self.write_wrapped_math_functions(module, func_ctx)?; |
| 1481 |
self.write_wrapped_unary_ops(module, func_ctx)?; |
| 1482 |
self.write_wrapped_binary_ops(module, func_ctx)?; |
| 1483 |
self.write_wrapped_expression_functions(module, func_ctx.expressions, Some(func_ctx))?; |
| 1484 |
self.write_wrapped_zero_value_functions(module, func_ctx.expressions)?; |
| 1485 |
self.write_wrapped_cast_functions(module, func_ctx)?; |
| 1486 |
|
| 1487 |
for (handle, _) in func_ctx.expressions.iter() { |
| 1488 |
match func_ctx.expressions[handle] { |
| 1489 |
crate::Expression::ArrayLength(expr) => { |
| 1490 |
let global_expr = match func_ctx.expressions[expr] { |
| 1491 |
crate::Expression::GlobalVariable(_) => expr, |
| 1492 |
crate::Expression::AccessIndex { base, index: _ } => base, |
| 1493 |
ref other => unreachable!("Array length of {:?}", other), |
| 1494 |
}; |
| 1495 |
let global_var = match func_ctx.expressions[global_expr] { |
| 1496 |
crate::Expression::GlobalVariable(var_handle) => { |
| 1497 |
&module.global_variables[var_handle] |
| 1498 |
} |
| 1499 |
ref other => { |
| 1500 |
return Err(super::Error::Unimplemented(format!( |
| 1501 |
"Array length of base {other:?}" |
| 1502 |
))) |
| 1503 |
} |
| 1504 |
}; |
| 1505 |
let storage_access = match global_var.space { |
| 1506 |
crate::AddressSpace::Storage { access } => access, |
| 1507 |
_ => crate::StorageAccess::default(), |
| 1508 |
}; |
| 1509 |
let wal = WrappedArrayLength { |
| 1510 |
writable: storage_access.contains(crate::StorageAccess::STORE), |
| 1511 |
}; |
| 1512 |
|
| 1513 |
if self.wrapped.insert(WrappedType::ArrayLength(wal)) { |
| 1514 |
self.write_wrapped_array_length_function(wal)?; |
| 1515 |
} |
| 1516 |
} |
| 1517 |
crate::Expression::ImageQuery { image, query } => { |
| 1518 |
let wiq = match *func_ctx.resolve_type(image, &module.types) { |
| 1519 |
crate::TypeInner::Image { |
| 1520 |
dim, |
| 1521 |
arrayed, |
| 1522 |
class, |
| 1523 |
} => WrappedImageQuery { |
| 1524 |
dim, |
| 1525 |
arrayed, |
| 1526 |
class, |
| 1527 |
query: query.into(), |
| 1528 |
}, |
| 1529 |
_ => unreachable!("we only query images"), |
| 1530 |
}; |
| 1531 |
|
| 1532 |
if self.wrapped.insert(WrappedType::ImageQuery(wiq)) { |
| 1533 |
self.write_wrapped_image_query_function(module, wiq, handle, func_ctx)?; |
| 1534 |
} |
| 1535 |
} |
| 1536 |
// Write `WrappedConstructor` for structs that are loaded from `AddressSpace::Storage` |
| 1537 |
// since they will later be used by the fn `write_storage_load` |
| 1538 |
crate::Expression::Load { pointer } => { |
| 1539 |
let pointer_space = func_ctx |
| 1540 |
.resolve_type(pointer, &module.types) |
| 1541 |
.pointer_space(); |
| 1542 |
|
| 1543 |
if let Some(crate::AddressSpace::Storage { .. }) = pointer_space { |
| 1544 |
if let Some(ty) = func_ctx.info[handle].ty.handle() { |
| 1545 |
write_wrapped_constructor(self, ty, module)?; |
| 1546 |
} |
| 1547 |
} |
| 1548 |
|
| 1549 |
fn write_wrapped_constructor<W: Write>( |
| 1550 |
writer: &mut super::Writer<'_, W>, |
| 1551 |
ty: Handle<crate::Type>, |
| 1552 |
module: &crate::Module, |
| 1553 |
) -> BackendResult { |
| 1554 |
match module.types[ty].inner { |
| 1555 |
crate::TypeInner::Struct { ref members, .. } => { |
| 1556 |
for member in members { |
| 1557 |
write_wrapped_constructor(writer, member.ty, module)?; |
| 1558 |
} |
| 1559 |
|
| 1560 |
let constructor = WrappedConstructor { ty }; |
| 1561 |
if writer.wrapped.insert(WrappedType::Constructor(constructor)) { |
| 1562 |
writer |
| 1563 |
.write_wrapped_constructor_function(module, constructor)?; |
| 1564 |
} |
| 1565 |
} |
| 1566 |
crate::TypeInner::Array { base, .. } => { |
| 1567 |
write_wrapped_constructor(writer, base, module)?; |
| 1568 |
|
| 1569 |
let constructor = WrappedConstructor { ty }; |
| 1570 |
if writer.wrapped.insert(WrappedType::Constructor(constructor)) { |
| 1571 |
writer |
| 1572 |
.write_wrapped_constructor_function(module, constructor)?; |
| 1573 |
} |
| 1574 |
} |
| 1575 |
_ => {} |
| 1576 |
}; |
| 1577 |
|
| 1578 |
Ok(()) |
| 1579 |
} |
| 1580 |
} |
| 1581 |
// We treat matrices of the form `matCx2` as a sequence of C `vec2`s |
| 1582 |
// (see top level module docs for details). |
| 1583 |
// |
| 1584 |
// The functions injected here are required to get the matrix accesses working. |
| 1585 |
crate::Expression::AccessIndex { base, index } => { |
| 1586 |
let base_ty_res = &func_ctx.info[base].ty; |
| 1587 |
let mut resolved = base_ty_res.inner_with(&module.types); |
| 1588 |
let base_ty_handle = match *resolved { |
| 1589 |
crate::TypeInner::Pointer { base, .. } => { |
| 1590 |
resolved = &module.types[base].inner; |
| 1591 |
Some(base) |
| 1592 |
} |
| 1593 |
_ => base_ty_res.handle(), |
| 1594 |
}; |
| 1595 |
if let crate::TypeInner::Struct { ref members, .. } = *resolved { |
| 1596 |
let member = &members[index as usize]; |
| 1597 |
|
| 1598 |
match module.types[member.ty].inner { |
| 1599 |
crate::TypeInner::Matrix { |
| 1600 |
rows: crate::VectorSize::Bi, |
| 1601 |
.. |
| 1602 |
} if member.binding.is_none() => { |
| 1603 |
let ty = base_ty_handle.unwrap(); |
| 1604 |
let access = WrappedStructMatrixAccess { ty, index }; |
| 1605 |
|
| 1606 |
if self.wrapped.insert(WrappedType::StructMatrixAccess(access)) { |
| 1607 |
self.write_wrapped_struct_matrix_get_function(module, access)?; |
| 1608 |
self.write_wrapped_struct_matrix_set_function(module, access)?; |
| 1609 |
self.write_wrapped_struct_matrix_set_vec_function( |
| 1610 |
module, access, |
| 1611 |
)?; |
| 1612 |
self.write_wrapped_struct_matrix_set_scalar_function( |
| 1613 |
module, access, |
| 1614 |
)?; |
| 1615 |
} |
| 1616 |
} |
| 1617 |
_ => {} |
| 1618 |
} |
| 1619 |
} |
| 1620 |
} |
| 1621 |
_ => {} |
| 1622 |
}; |
| 1623 |
} |
| 1624 |
|
| 1625 |
Ok(()) |
| 1626 |
} |
| 1627 |
|
| 1628 |
/// Writes out the sampler heap declarations if they haven't been written yet. |
| 1629 |
pub(super) fn write_sampler_heaps(&mut self) -> BackendResult { |
| 1630 |
if self.wrapped.sampler_heaps { |
| 1631 |
return Ok(()); |
| 1632 |
} |
| 1633 |
|
| 1634 |
writeln!( |
| 1635 |
self.out, |
| 1636 |
"SamplerState {}[2048]: register(s{}, space{});", |
| 1637 |
super::writer::SAMPLER_HEAP_VAR, |
| 1638 |
self.options.sampler_heap_target.standard_samplers.register, |
| 1639 |
self.options.sampler_heap_target.standard_samplers.space |
| 1640 |
)?; |
| 1641 |
writeln!( |
| 1642 |
self.out, |
| 1643 |
"SamplerComparisonState {}[2048]: register(s{}, space{});", |
| 1644 |
super::writer::COMPARISON_SAMPLER_HEAP_VAR, |
| 1645 |
self.options |
| 1646 |
.sampler_heap_target |
| 1647 |
.comparison_samplers |
| 1648 |
.register, |
| 1649 |
self.options.sampler_heap_target.comparison_samplers.space |
| 1650 |
)?; |
| 1651 |
|
| 1652 |
self.wrapped.sampler_heaps = true; |
| 1653 |
|
| 1654 |
Ok(()) |
| 1655 |
} |
| 1656 |
|
| 1657 |
/// Writes out the sampler index buffer declaration if it hasn't been written yet. |
| 1658 |
pub(super) fn write_wrapped_sampler_buffer( |
| 1659 |
&mut self, |
| 1660 |
key: super::SamplerIndexBufferKey, |
| 1661 |
) -> BackendResult { |
| 1662 |
// The astute will notice that we do a double hash lookup, but we do this to avoid |
| 1663 |
// holding a mutable reference to `self` while trying to call `write_sampler_heaps`. |
| 1664 |
// |
| 1665 |
// We only pay this double lookup cost when we actually need to write out the sampler |
| 1666 |
// buffer, which should be not be common. |
| 1667 |
|
| 1668 |
if self.wrapped.sampler_index_buffers.contains_key(&key) { |
| 1669 |
return Ok(()); |
| 1670 |
}; |
| 1671 |
|
| 1672 |
self.write_sampler_heaps()?; |
| 1673 |
|
| 1674 |
// Because the group number can be arbitrary, we use the namer to generate a unique name |
| 1675 |
// instead of adding it to the reserved name list. |
| 1676 |
let sampler_array_name = self |
| 1677 |
.namer |
| 1678 |
.call(&format!("nagaGroup{}SamplerIndexArray", key.group)); |
| 1679 |
|
| 1680 |
let bind_target = match self.options.sampler_buffer_binding_map.get(&key) { |
| 1681 |
Some(&bind_target) => bind_target, |
| 1682 |
None if self.options.fake_missing_bindings => super::BindTarget { |
| 1683 |
space: u8::MAX, |
| 1684 |
register: key.group, |
| 1685 |
binding_array_size: None, |
| 1686 |
dynamic_storage_buffer_offsets_index: None, |
| 1687 |
restrict_indexing: false, |
| 1688 |
}, |
| 1689 |
None => { |
| 1690 |
unreachable!("Sampler buffer of group {key:?} not bound to a register"); |
| 1691 |
} |
| 1692 |
}; |
| 1693 |
|
| 1694 |
writeln!( |
| 1695 |
self.out, |
| 1696 |
"StructuredBuffer<uint> {sampler_array_name} : register(t{}, space{});", |
| 1697 |
bind_target.register, bind_target.space |
| 1698 |
)?; |
| 1699 |
|
| 1700 |
self.wrapped |
| 1701 |
.sampler_index_buffers |
| 1702 |
.insert(key, sampler_array_name); |
| 1703 |
|
| 1704 |
Ok(()) |
| 1705 |
} |
| 1706 |
|
| 1707 |
pub(super) fn write_texture_coordinates( |
| 1708 |
&mut self, |
| 1709 |
kind: &str, |
| 1710 |
coordinate: Handle<crate::Expression>, |
| 1711 |
array_index: Option<Handle<crate::Expression>>, |
| 1712 |
mip_level: Option<Handle<crate::Expression>>, |
| 1713 |
module: &crate::Module, |
| 1714 |
func_ctx: &FunctionCtx, |
| 1715 |
) -> BackendResult { |
| 1716 |
// HLSL expects the array index to be merged with the coordinate |
| 1717 |
let extra = array_index.is_some() as usize + (mip_level.is_some()) as usize; |
| 1718 |
if extra == 0 { |
| 1719 |
self.write_expr(module, coordinate, func_ctx)?; |
| 1720 |
} else { |
| 1721 |
let num_coords = match *func_ctx.resolve_type(coordinate, &module.types) { |
| 1722 |
crate::TypeInner::Scalar { .. } => 1, |
| 1723 |
crate::TypeInner::Vector { size, .. } => size as usize, |
| 1724 |
_ => unreachable!(), |
| 1725 |
}; |
| 1726 |
write!(self.out, "{}{}(", kind, num_coords + extra)?; |
| 1727 |
self.write_expr(module, coordinate, func_ctx)?; |
| 1728 |
if let Some(expr) = array_index { |
| 1729 |
write!(self.out, ", ")?; |
| 1730 |
self.write_expr(module, expr, func_ctx)?; |
| 1731 |
} |
| 1732 |
if let Some(expr) = mip_level { |
| 1733 |
// Explicit cast if needed |
| 1734 |
let cast_to_int = matches!( |
| 1735 |
*func_ctx.resolve_type(expr, &module.types), |
| 1736 |
crate::TypeInner::Scalar(crate::Scalar { |
| 1737 |
kind: ScalarKind::Uint, |
| 1738 |
.. |
| 1739 |
}) |
| 1740 |
); |
| 1741 |
|
| 1742 |
write!(self.out, ", ")?; |
| 1743 |
|
| 1744 |
if cast_to_int { |
| 1745 |
write!(self.out, "int(")?; |
| 1746 |
} |
| 1747 |
|
| 1748 |
self.write_expr(module, expr, func_ctx)?; |
| 1749 |
|
| 1750 |
if cast_to_int { |
| 1751 |
write!(self.out, ")")?; |
| 1752 |
} |
| 1753 |
} |
| 1754 |
write!(self.out, ")")?; |
| 1755 |
} |
| 1756 |
Ok(()) |
| 1757 |
} |
| 1758 |
|
| 1759 |
pub(super) fn write_mat_cx2_typedef_and_functions( |
| 1760 |
&mut self, |
| 1761 |
WrappedMatCx2 { columns }: WrappedMatCx2, |
| 1762 |
) -> BackendResult { |
| 1763 |
use crate::back::INDENT; |
| 1764 |
|
| 1765 |
// typedef |
| 1766 |
write!(self.out, "typedef struct {{ ")?; |
| 1767 |
for i in 0..columns as u8 { |
| 1768 |
write!(self.out, "float2 _{i}; ")?; |
| 1769 |
} |
| 1770 |
writeln!(self.out, "}} __mat{}x2;", columns as u8)?; |
| 1771 |
|
| 1772 |
// __get_col_of_mat |
| 1773 |
writeln!( |
| 1774 |
self.out, |
| 1775 |
"float2 __get_col_of_mat{}x2(__mat{}x2 mat, uint idx) {{", |
| 1776 |
columns as u8, columns as u8 |
| 1777 |
)?; |
| 1778 |
writeln!(self.out, "{INDENT}switch(idx) {{")?; |
| 1779 |
for i in 0..columns as u8 { |
| 1780 |
writeln!(self.out, "{INDENT}case {i}: {{ return mat._{i}; }}")?; |
| 1781 |
} |
| 1782 |
writeln!(self.out, "{INDENT}default: {{ return (float2)0; }}")?; |
| 1783 |
writeln!(self.out, "{INDENT}}}")?; |
| 1784 |
writeln!(self.out, "}}")?; |
| 1785 |
|
| 1786 |
// __set_col_of_mat |
| 1787 |
writeln!( |
| 1788 |
self.out, |
| 1789 |
"void __set_col_of_mat{}x2(__mat{}x2 mat, uint idx, float2 value) {{", |
| 1790 |
columns as u8, columns as u8 |
| 1791 |
)?; |
| 1792 |
writeln!(self.out, "{INDENT}switch(idx) {{")?; |
| 1793 |
for i in 0..columns as u8 { |
| 1794 |
writeln!(self.out, "{INDENT}case {i}: {{ mat._{i} = value; break; }}")?; |
| 1795 |
} |
| 1796 |
writeln!(self.out, "{INDENT}}}")?; |
| 1797 |
writeln!(self.out, "}}")?; |
| 1798 |
|
| 1799 |
// __set_el_of_mat |
| 1800 |
writeln!( |
| 1801 |
self.out, |
| 1802 |
"void __set_el_of_mat{}x2(__mat{}x2 mat, uint idx, uint vec_idx, float value) {{", |
| 1803 |
columns as u8, columns as u8 |
| 1804 |
)?; |
| 1805 |
writeln!(self.out, "{INDENT}switch(idx) {{")?; |
| 1806 |
for i in 0..columns as u8 { |
| 1807 |
writeln!( |
| 1808 |
self.out, |
| 1809 |
"{INDENT}case {i}: {{ mat._{i}[vec_idx] = value; break; }}" |
| 1810 |
)?; |
| 1811 |
} |
| 1812 |
writeln!(self.out, "{INDENT}}}")?; |
| 1813 |
writeln!(self.out, "}}")?; |
| 1814 |
|
| 1815 |
writeln!(self.out)?; |
| 1816 |
|
| 1817 |
Ok(()) |
| 1818 |
} |
| 1819 |
|
| 1820 |
pub(super) fn write_all_mat_cx2_typedefs_and_functions( |
| 1821 |
&mut self, |
| 1822 |
module: &crate::Module, |
| 1823 |
) -> BackendResult { |
| 1824 |
for (handle, _) in module.global_variables.iter() { |
| 1825 |
let global = &module.global_variables[handle]; |
| 1826 |
|
| 1827 |
if global.space == crate::AddressSpace::Uniform { |
| 1828 |
if let Some(super::writer::MatrixType { |
| 1829 |
columns, |
| 1830 |
rows: crate::VectorSize::Bi, |
| 1831 |
width: 4, |
| 1832 |
}) = super::writer::get_inner_matrix_data(module, global.ty) |
| 1833 |
{ |
| 1834 |
let entry = WrappedMatCx2 { columns }; |
| 1835 |
if self.wrapped.insert(WrappedType::MatCx2(entry)) { |
| 1836 |
self.write_mat_cx2_typedef_and_functions(entry)?; |
| 1837 |
} |
| 1838 |
} |
| 1839 |
} |
| 1840 |
} |
| 1841 |
|
| 1842 |
for (_, ty) in module.types.iter() { |
| 1843 |
if let crate::TypeInner::Struct { ref members, .. } = ty.inner { |
| 1844 |
for member in members.iter() { |
| 1845 |
if let crate::TypeInner::Array { .. } = module.types[member.ty].inner { |
| 1846 |
if let Some(super::writer::MatrixType { |
| 1847 |
columns, |
| 1848 |
rows: crate::VectorSize::Bi, |
| 1849 |
width: 4, |
| 1850 |
}) = super::writer::get_inner_matrix_data(module, member.ty) |
| 1851 |
{ |
| 1852 |
let entry = WrappedMatCx2 { columns }; |
| 1853 |
if self.wrapped.insert(WrappedType::MatCx2(entry)) { |
| 1854 |
self.write_mat_cx2_typedef_and_functions(entry)?; |
| 1855 |
} |
| 1856 |
} |
| 1857 |
} |
| 1858 |
} |
| 1859 |
} |
| 1860 |
} |
| 1861 |
|
| 1862 |
Ok(()) |
| 1863 |
} |
| 1864 |
|
| 1865 |
pub(super) fn write_wrapped_zero_value_function_name( |
| 1866 |
&mut self, |
| 1867 |
module: &crate::Module, |
| 1868 |
zero_value: WrappedZeroValue, |
| 1869 |
) -> BackendResult { |
| 1870 |
let name = crate::TypeInner::hlsl_type_id(zero_value.ty, module.to_ctx(), &self.names)?; |
| 1871 |
write!(self.out, "ZeroValue{name}")?; |
| 1872 |
Ok(()) |
| 1873 |
} |
| 1874 |
|
| 1875 |
/// Helper function that write wrapped function for `Expression::ZeroValue` |
| 1876 |
/// |
| 1877 |
/// This is necessary since we might have a member access after the zero value expression, e.g. |
| 1878 |
/// `.y` (in practice this can come up when consuming SPIRV that's been produced by glslc). |
| 1879 |
/// |
| 1880 |
/// So we can't just write `(float4)0` since `(float4)0.y` won't parse correctly. |
| 1881 |
/// |
| 1882 |
/// Parenthesizing the expression like `((float4)0).y` would work... except DXC can't handle |
| 1883 |
/// cases like: |
| 1884 |
/// |
| 1885 |
/// ```text |
| 1886 |
/// tests\out\hlsl\access.hlsl:183:41: error: cannot compile this l-value expression yet |
| 1887 |
/// t_1.am = (__mat4x2[2])((float4x2[2])0); |
| 1888 |
/// ^ |
| 1889 |
/// ``` |
| 1890 |
fn write_wrapped_zero_value_function( |
| 1891 |
&mut self, |
| 1892 |
module: &crate::Module, |
| 1893 |
zero_value: WrappedZeroValue, |
| 1894 |
) -> BackendResult { |
| 1895 |
use crate::back::INDENT; |
| 1896 |
|
| 1897 |
// Write function return type and name |
| 1898 |
if let crate::TypeInner::Array { base, size, .. } = module.types[zero_value.ty].inner { |
| 1899 |
write!(self.out, "typedef ")?; |
| 1900 |
self.write_type(module, zero_value.ty)?; |
| 1901 |
write!(self.out, " ret_")?; |
| 1902 |
self.write_wrapped_zero_value_function_name(module, zero_value)?; |
| 1903 |
self.write_array_size(module, base, size)?; |
| 1904 |
writeln!(self.out, ";")?; |
| 1905 |
|
| 1906 |
write!(self.out, "ret_")?; |
| 1907 |
self.write_wrapped_zero_value_function_name(module, zero_value)?; |
| 1908 |
} else { |
| 1909 |
self.write_type(module, zero_value.ty)?; |
| 1910 |
} |
| 1911 |
write!(self.out, " ")?; |
| 1912 |
self.write_wrapped_zero_value_function_name(module, zero_value)?; |
| 1913 |
|
| 1914 |
// Write function parameters (none) and start function body |
| 1915 |
writeln!(self.out, "() {{")?; |
| 1916 |
|
| 1917 |
// Write `ZeroValue` function. |
| 1918 |
write!(self.out, "{INDENT}return ")?; |
| 1919 |
self.write_default_init(module, zero_value.ty)?; |
| 1920 |
writeln!(self.out, ";")?; |
| 1921 |
|
| 1922 |
// End of function body |
| 1923 |
writeln!(self.out, "}}")?; |
| 1924 |
// Write extra new line |
| 1925 |
writeln!(self.out)?; |
| 1926 |
|
| 1927 |
Ok(()) |
| 1928 |
} |
| 1929 |
} |
| 1930 |
|
| 1931 |
impl crate::StorageFormat { |
| 1932 |
/// Returns `true` if there is just one component, otherwise `false` |
| 1933 |
pub(super) const fn single_component(&self) -> bool { |
| 1934 |
match *self { |
| 1935 |
crate::StorageFormat::R16Float |
| 1936 |
| crate::StorageFormat::R32Float |
| 1937 |
| crate::StorageFormat::R8Unorm |
| 1938 |
| crate::StorageFormat::R16Unorm |
| 1939 |
| crate::StorageFormat::R8Snorm |
| 1940 |
| crate::StorageFormat::R16Snorm |
| 1941 |
| crate::StorageFormat::R8Uint |
| 1942 |
| crate::StorageFormat::R16Uint |
| 1943 |
| crate::StorageFormat::R32Uint |
| 1944 |
| crate::StorageFormat::R8Sint |
| 1945 |
| crate::StorageFormat::R16Sint |
| 1946 |
| crate::StorageFormat::R32Sint |
| 1947 |
| crate::StorageFormat::R64Uint => true, |
| 1948 |
_ => false, |
| 1949 |
} |
| 1950 |
} |
| 1951 |
} |