Crate naga

Crate naga 

Available on crate feature unstable-wgpu-26 only.
Expand description

Naga can be used to translate source code written in one shading language to another.

§Example

The following example translates WGSL to GLSL. It requires the features "wgsl-in" and "glsl-out" to be enabled.

let wgsl_source = "
@fragment
fn main_fs() -> @location(0) vec4<f32> {
    return vec4<f32>(1.0, 1.0, 1.0, 1.0);
}
";

// Parse the source into a Module.
let module: naga::Module = naga::front::wgsl::parse_str(wgsl_source)?;

// Validate the module.
// Validation can be made less restrictive by changing the ValidationFlags.
let module_info: naga::valid::ModuleInfo =
    naga::valid::Validator::new(
        naga::valid::ValidationFlags::all(),
        naga::valid::Capabilities::all(),
    )
    .subgroup_stages(naga::valid::ShaderStages::all())
    .subgroup_operations(naga::valid::SubgroupOperationSet::all())
    .validate(&module)?;

// Translate the module.
use naga::back::glsl;
let mut glsl_source = String::new();
glsl::Writer::new(
    &mut glsl_source,
    &module,
    &module_info,
    &glsl::Options::default(),
    &glsl::PipelineOptions {
        entry_point: "main_fs".into(),
        shader_stage: naga::ShaderStage::Fragment,
        multiview: None,
    },
    naga::proc::BoundsCheckPolicies::default(),
)?.write()?;

assert_eq!(glsl_source, "\
#version 310 es

precision highp float;
precision highp int;

layout(location = 0) out vec4 _fs2p_location0;

void main() {
    _fs2p_location0 = vec4(1.0, 1.0, 1.0, 1.0);
    return;
}

");

Modules§

back
Backend functions that export shader Modules into binary and text formats.
common
Code common to the front and backends for specific languages.
compact
diagnostic_filter
DiagnosticFilters and supporting functionality.
error
front
Frontend parsers that consume binary and text shaders and load them into Modules.
ir
The Intermediate Representation shared by all frontends and backends.
keywords
Lists of reserved keywords for each shading language with a frontend or backend.
proc
Module processing functionality.
valid
Shader validator.

Structs§

Arena
An arena holding some kind of component (e.g., type, constant, instruction, etc.) that can be referenced.
Barrier
Memory barrier flags.
Block
A code block is a vector of statements, with maybe a vector of spans.
Constant
Constant value.
DocComments
Doc comments preceding items.
EntryPoint
The main function for a pipeline stage.
Function
A function defined in the module.
FunctionArgument
A function argument.
FunctionResult
A function result.
GlobalVariable
Variable defined at module level.
Handle
A strongly typed reference to an arena item.
LocalVariable
Variable defined at function level.
Module
Shader module.
Override
Pipeline-overridable constant.
Range
A strongly typed range of handles.
RayFlag
Ray flags used when casting rays. Matching vulkan constants can be found in https://github.com/KhronosGroup/SPIRV-Registry/blob/main/extensions/KHR/ray_common/ray_flags_section.txt
ResourceBinding
Pipeline binding information for global resources.
Scalar
Characteristics of a scalar type.
SourceLocation
A human-readable representation for a span, tailored for text source.
Span
A source code span, used for error reporting.
SpecialTypes
Set of special types that can be optionally generated by the frontends.
StorageAccess
Flags describing an image.
StructMember
Member of a user-defined structure.
SwitchCase
A case for a switch statement.
Type
A data type declared in the module.
UniqueArena
An arena whose elements are guaranteed to be unique.
WithSpan
Wrapper class for Error, augmenting it with a list of SpanContexts.

Enums§

AddressSpace
Addressing space of variables.
ArraySize
Size of an array.
AtomicFunction
Function on an atomic value.
BinaryOperator
Operation that can be applied on two values.
Binding
Describes how an input/output variable is to be bound.
BuiltIn
Built-in inputs and outputs.
CollectiveOperation
ConservativeDepth
Enables adjusting depth without disabling early Z.
DerivativeAxis
Axis on which to compute a derivative.
DerivativeControl
Hint at which precision to compute a derivative.
Direction
EarlyDepthTest
Explicitly allows early depth/stencil tests.
Expression
An expression that can be evaluated to obtain a value.
GatherMode
The specific behavior of a SubgroupGather statement.
ImageClass
Sub-class of the image type.
ImageDimension
The number of dimensions an image has.
ImageQuery
Type of an image query.
Interpolation
The interpolation qualifier of a binding or struct field.
Literal
MathFunction
Built-in shader function for math.
PredeclaredType
Return types predeclared for the frexp, modf, and atomicCompareExchangeWeak built-in functions.
RayQueryFunction
An operation that a RayQuery statement applies to its query operand.
RayQueryIntersection
Type of a ray query intersection. Matching vulkan constants can be found in https://github.com/KhronosGroup/SPIRV-Registry/blob/main/extensions/KHR/SPV_KHR_ray_query.asciidoc but the actual values are different for candidate intersections.
RelationalFunction
Built-in shader function for testing relation between values.
SampleLevel
Sampling modifier to control the level of detail.
Sampling
The sampling qualifiers of a binding or struct field.
ScalarKind
Primitive type for a scalar.
ShaderStage
Stage of the programmable pipeline.
Statement
Instructions which make up an executable block.
StorageFormat
Image storage format.
SubgroupOperation
SwitchValue
The value of the switch case.
SwizzleComponent
Component selection for a vector swizzle.
TypeInner
Enum with additional information, depending on the kind of type.
UnaryOperator
Operation that can be applied on a single value.
VectorSize
Number of components in a vector.

Constants§

ABSTRACT_WIDTH
Width of abstract types, in bytes.
BOOL_WIDTH
Width of a boolean type, in bytes.

Type Aliases§

Bytes
Number of bytes per scalar.
FastHashMap
Hash map that is faster but not resilient to DoS attacks. (Similar to rustc_hash::FxHashMap but using hashbrown::HashMap instead of alloc::collections::HashMap.) To construct a new instance: FastHashMap::default()
FastHashSet
Hash set that is faster but not resilient to DoS attacks. (Similar to rustc_hash::FxHashSet but using hashbrown::HashSet instead of alloc::collections::HashMap.)
FastIndexMap
Insertion-order-preserving hash map (IndexMap<K, V>), but with the same hasher as FastHashMap<K, V> (faster but not resilient to DoS attacks).
FastIndexSet
Insertion-order-preserving hash set (IndexSet<K>), but with the same hasher as FastHashSet<K> (faster but not resilient to DoS attacks).
SpanContext
A source code span together with “context”, a user-readable description of what part of the error it refers to.