Shader
Description
Section titled “Description”The Shader object is the main building block in FragmentColor.
It takes a WGSL or GLSL shader source as input, parses it, validates it, and exposes the uniforms as keys.
Shader::new refuses a source that no device FragmentColor opens can run, with a ShaderError that names the problem: a feature outside the set FragmentColor requests (such as ray queries or f64), two globals on one @group and @binding (a lights root included), writable storage in a @vertex entry point, an immediate root that breaks the uniform layout rules, a filtering sampler that samples a depth texture, and two vertex inputs with one name, which would read one mesh attribute. A shader that passes can still be one a given device can’t run, which Renderer::render refuses, as Device limits describes.
Shader::new accepts a source string, a registry slug like "sdf2d/circle", an https:// URL, a local file path, or an array mixing any of those. Array parts are deduplicated by hash and concatenated in order, so you can pull pure helper functions from the public registry at https://fragmentcolor.org/shaders/ into your own shader without copy-pasting. Override the registry base with Shader::set_registry.
To draw your shader, you must use your Shader instance as input to a Renderer.
You can compose Shader instances into a Pass object to create more complex rendering pipelines.
You can also create renderings with multiple Render Passes by passing an array of Pass instances to Renderer::render.
Uniforms
Section titled “Uniforms”Classic uniforms are declared with var<uniform> and can be nested structs/arrays.
FragmentColor exposes every root and nested field as addressable keys using dot and index notation:
- Set a field:
shader.set("u.color", [r, g, b, a]) - Index arrays:
shader.set("u.arr[1]", value)
WGSL example
Section titled “WGSL example”struct MyUniform { color: vec4<f32>, arr: array<vec4<f32>, 2>};
@group(0) @binding(0) var<uniform> u: MyUniform;FragmentColor handles std140-style 16-byte alignment for you, and large uniform blobs are pooled internally. There is nothing to configure.
Textures and Samplers
Section titled “Textures and Samplers”Sampled textures and samplers are supported via texture_* and sampler declarations.
You can bind a Texture object created by the Renderer directly to a texture uniform (e.g., shader.set("tex", &texture));
samplers are provided automatically:
- If a texture is bound in the same group, the sampler defaults to that texture’s sampler.
- Otherwise, a reasonable default sampler is used.
WGSL example
Section titled “WGSL example”@group(0) @binding(0) var tex: texture_2d<f32>;@group(0) @binding(1) var samp: sampler;1D, 2D and 3D textures bind with the view dimension the WGSL declaration gives. A FragmentColor texture’s view always covers all of it, so a cube, cube array or 2D array slot takes no texture yet, and Renderer::render refuses one with RendererError::BindingError. Integer textures map to Sint / Uint sample types; float textures use filterable float when the device allows it. A filtering sampler never samples a depth texture: use a sampler_comparison with textureSampleCompare, or textureLoad.
Storage Textures
Section titled “Storage Textures”Writeable/readable image surfaces are supported via storage textures (texture_storage_*).
Access flags are preserved from WGSL and mapped to the device:
read-> read-only storage accesswrite-> write-only storage accessread_write-> read+write (when supported)atomic-> read, write and the texture atomics below, onr32uintandr32sint
WGSL example
Section titled “WGSL example”@group(0) @binding(0) var img: texture_storage_2d<rgba8unorm, write>;Every storage format binds as the format the shader declares. A format or access the device can’t bind fails in Renderer::render before it takes a frame, and so does a bound texture of another format, one without STORAGE_BINDING usage, or one with more than one mip level.
Texture atomics
Section titled “Texture atomics”An r32uint or r32sint storage texture with atomic access takes texture atomics: textureAtomicAdd, textureAtomicMin, textureAtomicMax, textureAtomicAnd, textureAtomicOr and textureAtomicXor. Each call changes one texel in a single step, however many invocations reach it at once, and returns no value. Exchange and compare-exchange on textures aren’t in naga, and textureLoad and textureStore work on an atomic texture as on any other storage texture.
@group(0) @binding(0) var counts: texture_storage_2d<r32uint, atomic>;
@compute @workgroup_size(8, 8)fn cs_main(@builtin(global_invocation_id) id: vec3<u32>) { textureAtomicAdd(counts, id.xy / 16u, 1u);}Shader::new takes such a shader on every platform, and it runs where the device has TEXTURE_ATOMIC: Vulkan, DX12, and Metal from macOS 14 and iOS 17. The browser’s WebGPU, WebGL2 and native GL have no texture atomics, so Renderer::render refuses the shader there with RendererError::FeatureError, whose feature names TEXTURE_ATOMIC. Bind an R32Uint or R32Sint texture from Renderer::create_storage_texture, which takes no extra usage flag for atomics. An r64uint storage texture needs TEXTURE_INT64_ATOMIC, a feature FragmentColor doesn’t request, so Shader::new refuses it.
External textures
Section titled “External textures”WGSL reads video frames through texture_external, and FragmentColor fills that slot with an ordinary Texture: shader.set("video", &texture), as for any texture uniform. The shader reads it with textureSampleBaseClampToEdge, textureLoad and textureDimensions.
@group(0) @binding(0) var video: texture_external;@group(0) @binding(1) var soft: sampler;
@fragmentfn fs_main(@builtin(position) pixel: vec4<f32>) -> @location(0) vec4<f32> { let size = vec2<f32>(textureDimensions(video)); let filtered = textureSampleBaseClampToEdge(video, soft, pixel.xy / size); let exact = textureLoad(video, vec2<u32>(pixel.xy)); return mix(filtered, exact, 0.5);}Every platform accepts such a shader at Shader::new. It draws on devices with EXTERNAL_TEXTURE, which wgpu offers on Metal and DX12. On Vulkan, OpenGL, WebGL2 and the browser’s WebGPU, Renderer::render refuses the shader with RendererError::FeatureError before it takes a frame, and the error’s feature names EXTERNAL_TEXTURE.
The slot takes a single-sampled 2D texture in Rgba8Unorm, Bgra8Unorm or Rgba16Float and reads its base mip level, which lets a texture with a mip chain bind too. Raw bytes with a size upload as Rgba8Unorm. An 8-bit color image, such as a PNG or a JPEG, decodes into Rgba8UnormSrgb, which the slot refuses with RendererError::BindingError. Name the format when you create the texture from one: renderer.create_texture((bytes, TextureFormat::Rgba8Unorm)).
wgpu counts one external slot as four sampled textures, a sampler and a uniform buffer in each stage that reads it, and Renderer::render counts it the same way against the device’s limits. A stage that reads four external slots counts 16 sampled textures against max_sampled_textures_per_shader_stage.
Storage Buffers
Section titled “Storage Buffers”Structured buffers are supported via var<storage, read> or var<storage, read_write>
and can contain nested structs/arrays. FragmentColor preserves and applies the WGSL access flags
when creating binding layouts and setting visibility.
WGSL example
Section titled “WGSL example”struct Buf { a: vec4<f32> };@group(0) @binding(0) var<storage, read> ssbo: Buf;Read-only buffers bind with read-only storage access; read_write allows writes where the device supports it. Each binding is visible to the stages whose entry points use it, so a fragment entry point can write a storage buffer or texture on a device with writable fragment storage. CPU-side updates use the same shader.set("path", value) API as uniforms, with array indexing (e.g. buf.items[2].v). Buffer byte spans are computed from the WGSL shape (arrays and structs honor stride and alignment automatically) and large buffers are pooled internally.
Explicit layouts
Section titled “Explicit layouts”@size and @align on the members of a uniform, storage or immediate struct keep their layout on Vulkan, Metal, DX12 and the browser’s WebGPU. The WGSL that wgpu writes for the browser drops both attributes, so FragmentColor hands the browser WGSL with a @size on each member of such a struct, which pins every offset and the struct’s size. The GL backends, WebGL2 and native GL, write a struct into a std140 block member by member and can’t keep such a layout, so Renderer::render refuses it there with RendererError::FeatureError. Spelling the padding out as members works everywhere, as the built-in PBR shader does.
Immediate data
Section titled “Immediate data”Immediate data, declared with var<immediate>, works on every platform, in render and compute shaders. One root that fits the device’s max_immediate_size takes native immediates. It becomes a classic uniform buffer instead on the web, on the GL backends, on a device without immediates, and when the shader declares more than one root, with one binding per root in the lowest bind group the shader leaves free. On WebGL2 and native GL the uniform is padded to a multiple of 16 bytes, as those backends take it. A root must therefore also follow the uniform layout rules, such as a 16-byte array stride, and Shader::new refuses one that doesn’t. An entry point reads at most one root.
A root that isn’t a struct takes its bytes whole through set, as a storage root does. A struct root also takes each field by name, as in pc.color.
Subgroups and primitive index
Section titled “Subgroups and primitive index”Shader::new takes subgroup built-ins and functions, such as @builtin(subgroup_size) and subgroupAdd, and @builtin(primitive_index) after enable primitive_index;, on every platform. Each runs where the device has its wgpu feature. Elsewhere Renderer::render refuses the shader with RendererError::FeatureError, whose feature names the flag the device lacks.
- Subgroup operations need
SUBGROUPin compute and fragment shaders andSUBGROUP_VERTEXin vertex shaders, andsubgroupBarrieralso needsSUBGROUP_BARRIER. Vulkan devices with the full set of subgroup operations offer them, as do Metal GPUs of the Apple7, Mac2 and Metal 3 families and DX12 devices with Shader Model 6.0 wave operations. Only Vulkan offersSUBGROUP_VERTEX, and DX12 has noSUBGROUP_BARRIER. primitive_indexneedsPRIMITIVE_INDEX, which DX12, Vulkan devices with geometry shaders, the same Metal GPU families, OpenGL 3.2 and OpenGL ES 3.2 offer.
Neither runs on the web. Chrome’s WebGPU offers subgroups, but wgpu 30 doesn’t request them for the device it opens there, and WebGL2 has neither. Native GL offers no subgroups. Write subgroup code in WGSL and leave out enable subgroups;, which naga doesn’t take yet:
@group(0) @binding(0) var<storage, read_write> sums: array<u32, 64>;
@compute @workgroup_size(64)fn cs_main(@builtin(local_invocation_index) index: u32) { sums[index] = subgroupAdd(1u);}Half precision
Section titled “Half precision”After enable f16;, a shader holds 16-bit floats: f16, its vectors and its square matrices, in uniforms, storage buffers and vertex inputs. The directive opens the source, or the part that needs it when Shader::new joins several parts.
enable f16;
struct Light { color: vec3<f16>, power: f16 };@group(0) @binding(0) var<uniform> light: Light;@group(0) @binding(1) var<uniform> gain: f16;
@fragmentfn fs_main() -> @location(0) vec4<f32> { let color = light.color * light.power * gain; return vec4<f32>(vec3<f32>(color), 1.0);}set takes plain numbers for an f16 key, as it does for an f32 one, and rounds each to the nearest f16. NaN, infinities and numbers past ±65504 that don’t round back to it throw, and the key keeps its value. get returns the rounded value as f32 numbers in every language, so 0.1 reads back as 0.0999755859375. Past 2048, an f16 skips some whole numbers, as an f32 does past 2^24, and rounding one raises no error.
A Camera or Scene::ambient value that an f16 field can’t hold leaves the field as it was, and Renderer::render returns the same error until a later value fits.
A vertex input declared as f16 or vec4<f16> reads the mesh’s 32-bit floats, which the GPU converts, so one mesh feeds f32 and f16 shaders alike. An attach error names the type the shader declares, such as vec2<f16>.
Values take WGSL’s f16 layout: 2 bytes for each component, a vec3<f16> aligned to 8 bytes, and the columns of a mat3x3<f16> 8 bytes apart. A root such as var<uniform> gain: f16 spans 2 bytes, and Renderer::read_storage returns exactly as many bytes as a storage root spans. Immediate data can’t hold f16, which Shader::new refuses.
A color output must be vec4<f32>, never vec4<f16>, since wgpu refuses a narrower float at @location(0). Convert the result before the fragment shader returns it, as vec4<f32>(vec3<f32>(color), 1.0) does above.
Every platform accepts such a shader at Shader::new. It draws where the device has SHADER_F16: every Metal device, DX12 with Shader Model 6.2, Vulkan devices with f16 arithmetic and 16-bit storage, and the browser’s WebGPU where the browser offers shader-f16. On WebGL2, OpenGL and every other device, Renderer::render refuses the shader with RendererError::FeatureError before it takes a frame, and the error’s feature names SHADER_F16.
Device limits
Section titled “Device limits”Renderer::render checks each shader against the device before it takes a frame, so every platform returns the same error from the call that caused it, the web included. Each refusal has a typed error with fields:
RendererError::LimitError { item, limit, value, max }for a group pastmax_bind_groups, a binding pastmax_bindings_per_bind_group, more bindings of a kind in one stage than the device takes, a uniform or storage buffer past its binding size limit, a workgroup past the device’s sizes, invocations or workgroup memory, and a vertex input at a location pastmax_vertex_attributes. A mesh whose stride or buffers pass the device’s limits gets it too.RendererError::FeatureError { item, feature }for a compute shader on a device without compute, storage a stage of the device can’t bind, a storage format or access the device lacks, such as an atomic storage texture on a device withoutTEXTURE_ATOMIC, an external texture on a device withoutEXTERNAL_TEXTURE, an explicit layout on a GL backend, a shader that measures its light roots witharrayLengthon a device that takes lights through a uniform block, a shader feature the device lacks, such as subgroups orf16, whosefeaturenames the wgpu flag, and anything else the device’s shader validator refuses.RendererError::BindingError { uniform, expected, found }for a texture uniform that was never set, or whose texture its slot can’t take by format, usage, dimension, sample count or mip levels.RendererError::EntryError { stage }for a render shader without its@vertexor@fragmententry point.
JavaScript throws an Error named after the class Python raises, such as LimitError, with the same fields as properties. Python raises LimitError, FeatureError, BindingError and EntryError, each a FragmentColorError with the fields as attributes. Swift throws FragmentColorError.Limit, .Feature, .Binding and .Entry, and Kotlin the FragmentColorException subclasses of the same names.
An unset PBR map slot, such as base_color_map, binds a 1x1 default in a render shader, when the slot takes a 2D float texture. One set to a texture unregister_texture removed, or one another Renderer created, returns RendererError::TextureNotFoundError. A Material map that this Renderer holds no copy of yet binds the PBR default when its slot has one of the five PBR names, sits in a render shader and takes a 2D float texture, as an unset slot does, and returns RendererError::BindingError otherwise. That happens on the web before load, where the error asks for load, and on native for a map that another thread sets while render runs, which the next render uploads.
Example
Section titled “Example”use fragmentcolor::{Shader, Renderer};
let shader = Shader::new(r#" @vertex fn vs_main(@builtin(vertex_index) index: u32) -> @builtin(position) vec4<f32> { var pos = array<vec2<f32>, 3>( vec2<f32>(-1.0, -1.0), vec2<f32>( 3.0, -1.0), vec2<f32>(-1.0, 3.0) ); return vec4<f32>(pos[index], 0.0, 1.0); }
@group(0) @binding(0) var<uniform> resolution: vec2<f32>;
@fragment fn fs_main() -> @location(0) vec4<f32> { return vec4<f32>(1.0, 0.0, 0.0, 1.0); // Red }"#)?;
// Set the "resolution" uniformshader.set("resolution", [800.0, 600.0])?;let res: [f32; 2] = shader.get("resolution")?;
let renderer = Renderer::new();let target = renderer.create_texture_target([16, 16]).await?;renderer.render(&shader, &target)?;import { Shader, Renderer } from "fragmentcolor";
const shader = new Shader(`
@vertex fn vs_main(@builtin(vertex_index) index: u32) -> @builtin(position) vec4<f32> { var pos = array<vec2<f32>, 3>( vec2<f32>(-1.0, -1.0), vec2<f32>( 3.0, -1.0), vec2<f32>(-1.0, 3.0) ); return vec4<f32>(pos[index], 0.0, 1.0); }
@group(0) @binding(0) var<uniform> resolution: vec2<f32>;
@fragment fn fs_main() -> @location(0) vec4<f32> { return vec4<f32>(1.0, 0.0, 0.0, 1.0); // Red }
`);
// Set the "resolution" uniformshader.set("resolution", [800.0, 600.0]);const res = shader.get("resolution");
const renderer = new Renderer();const target = await renderer.createTextureTarget([16, 16]);renderer.render(shader, target);from fragmentcolor import Shader, Renderer
shader = Shader(""" @vertex fn vs_main(@builtin(vertex_index) index: u32) -> @builtin(position) vec4<f32> { var pos = array<vec2<f32>, 3>( vec2<f32>(-1.0, -1.0), vec2<f32>( 3.0, -1.0), vec2<f32>(-1.0, 3.0) ); return vec4<f32>(pos[index], 0.0, 1.0); }
@group(0) @binding(0) var<uniform> resolution: vec2<f32>;
@fragment fn fs_main() -> @location(0) vec4<f32> { return vec4<f32>(1.0, 0.0, 0.0, 1.0); // Red }
""")
# Set the "resolution" uniformshader.set("resolution", [800.0, 600.0])res = shader.get("resolution")
renderer = Renderer()target = renderer.create_texture_target([16, 16])renderer.render(shader, target)import FragmentColor
let shader = try Shader(""" @vertex fn vs_main(@builtin(vertex_index) index: u32) -> @builtin(position) vec4<f32> { var pos = array<vec2<f32>, 3>( vec2<f32>(-1.0, -1.0), vec2<f32>( 3.0, -1.0), vec2<f32>(-1.0, 3.0) ); return vec4<f32>(pos[index], 0.0, 1.0); }
@group(0) @binding(0) var<uniform> resolution: vec2<f32>;
@fragment fn fs_main() -> @location(0) vec4<f32> { return vec4<f32>(1.0, 0.0, 0.0, 1.0); // Red }
""")
// Set the "resolution" uniformtry shader.set("resolution", [800.0, 600.0])let res = try shader.get("resolution")
let renderer = Renderer()let target = try await renderer.createTextureTarget([16, 16])try renderer.render(shader, target)import org.fragmentcolor.*
val shader = Shader(""" @vertex fn vs_main(@builtin(vertex_index) index: u32) -> @builtin(position) vec4<f32> { var pos = array<vec2<f32>, 3>( vec2<f32>(-1.0, -1.0), vec2<f32>( 3.0, -1.0), vec2<f32>(-1.0, 3.0) ); return vec4<f32>(pos[index], 0.0, 1.0); }
@group(0) @binding(0) var<uniform> resolution: vec2<f32>;
@fragment fn fs_main() -> @location(0) vec4<f32> { return vec4<f32>(1.0, 0.0, 0.0, 1.0); // Red }
""")
// Set the "resolution" uniformshader.set("resolution", listOf(800.0f, 600.0f))val res = shader.get("resolution")
val renderer = Renderer()val target = renderer.createTextureTarget(listOf(16u, 16u))renderer.render(shader, target)Methods
Section titled “Methods”Shader::new(input: string | string[])
Section titled “Shader::new(input: string | string[])”Creates a new Shader. The input is a single string, or an array of strings, of any of these shapes:
- a raw WGSL source string
- a registry slug like
"sdf2d/circle", which pulls a helper function from the public registry athttps://fragmentcolor.org/shaders/ - an
https://URL pointing at a.wgslfile - a local file path ending in
.wgsl,.glsl,.frag, or.vert
When you pass an array, parts are deduplicated by source hash and concatenated
in order before validation, so you can compose pure helper functions from the
registry with your own source. The enable, requires and diagnostic
directives a later part opens with move to the top, the only place WGSL takes
them, so a helper can carry the enable it needs.
If validation fails, the error message points at the line and column in the
parts as written, joined in order by two line breaks. A shader that passes is
one some device can run: Renderer::render still checks it against its own
device, and refuses one past that device’s limits or features with a typed
error. All uniforms are initialized to zero.
GLSL is supported only as a single part (a .vert, .frag, or .glsl
file). Mixing GLSL with other parts is rejected.
An empty string, or an empty array, gives the default shader.
Where each input resolves
Section titled “Where each input resolves”| Platform | Registry slugs and registry URLs | Other https:// URLs |
File paths |
|---|---|---|---|
| Rust (desktop) | Bundled shader library, offline | Fetched with the network feature, an error without it |
Read from disk |
| Python | Bundled shader library, offline | Fetched by a wheel built with the network feature, an error otherwise |
Read from disk |
| Swift / Kotlin | Bundled shader library, offline | Not fetched; a network error | Read from disk |
Web, Shader.fetch |
The browser’s fetch() |
The browser’s fetch() |
Fetched relative to the page’s origin |
Web, new Shader |
Not fetched; an error that points at Shader.fetch |
Not fetched; an error | Not fetched; an error |
After Shader::set_registry, slugs and registry URLs are fetched first on
every platform, and the bundled copy stands in when the fetch fails. A slug
resolves against the new registry. A registry URL is fetched as written, so
https://fragmentcolor.org/shaders/sdf2d/circle.wgsl still asks the default registry.
Example
Section titled “Example”use fragmentcolor::Shader;
let shader = Shader::new(r#" @vertex fn vs_main(@builtin(vertex_index) index: u32) -> @builtin(position) vec4<f32> { var pos = array<vec2<f32>, 3>( vec2<f32>(-1.0, -1.0), vec2<f32>( 3.0, -1.0), vec2<f32>(-1.0, 3.0) ); return vec4<f32>(pos[index], 0.0, 1.0); }
@group(0) @binding(0) var<uniform> resolution: vec2<f32>;
@fragment fn fs_main() -> @location(0) vec4<f32> { return vec4<f32>(1.0, 0.0, 0.0, 1.0); // Red }"#)?;
use fragmentcolor::Shader;
let main = r#" @vertex fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4<f32> { let p = array<vec2<f32>,3>(vec2f(-1.,-1.), vec2f(3.,-1.), vec2f(-1.,3.)); return vec4<f32>(p[i], 0.0, 1.0); }
@fragment fn fs(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> { let d = circle(pos.xy - vec2<f32>(400.0, 300.0), 100.0); let n = simplex2(pos.xy * 0.01); return vec4<f32>(vec3<f32>(step(0.0, d) + n * 0.1), 1.0); }"#;
let shader = Shader::new([ "sdf2d/circle", // pure function: fn circle(p: vec2<f32>, r: f32) -> f32 "noise/simplex2", // pure function: fn simplex2(v: vec2<f32>) -> f32 main,])?;import { Shader } from "fragmentcolor";
const shader = new Shader(` @vertex fn vs_main(@builtin(vertex_index) index: u32) -> @builtin(position) vec4<f32> { var pos = array<vec2<f32>, 3>( vec2<f32>(-1.0, -1.0), vec2<f32>( 3.0, -1.0), vec2<f32>(-1.0, 3.0) ); return vec4<f32>(pos[index], 0.0, 1.0); }
@group(0) @binding(0) var<uniform> resolution: vec2<f32>;
@fragment fn fs_main() -> @location(0) vec4<f32> { return vec4<f32>(1.0, 0.0, 0.0, 1.0); // Red }`);
// Compose pure helpers from the registry with your own source.const main = ` @vertex fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4<f32> { let p = array<vec2<f32>,3>(vec2f(-1.,-1.), vec2f(3.,-1.), vec2f(-1.,3.)); return vec4<f32>(p[i], 0.0, 1.0); }
@fragment fn fs(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> { let d = circle(pos.xy - vec2<f32>(400.0, 300.0), 100.0); let n = simplex2(pos.xy * 0.01); return vec4<f32>(vec3<f32>(step(0.0, d) + n * 0.1), 1.0); }`;const composed = await Shader.fetch(["sdf2d/circle", "noise/simplex2", main]);from fragmentcolor import Shader
# Simple WGSL fragment shadershader = Shader("""@vertex fn vs_main(@builtin(vertex_index) i: u32) -> @builtin(position) vec4<f32> {let p = array<vec2<f32>,3>(vec2f(-1.,-1.), vec2f(3.,-1.), vec2f(-1.,3.));return vec4f(p[i], 0., 1.);}@fragment fn fs_main() -> @location(0) vec4<f32> { return vec4f(1., 0., 0., 1.); }""")
# Compose pure helpers from the registry with your own source.main = """@vertex fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4<f32> {let p = array<vec2<f32>,3>(vec2f(-1.,-1.), vec2f(3.,-1.), vec2f(-1.,3.));return vec4<f32>(p[i], 0.0, 1.0);}@fragment fn fs(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {let d = circle(pos.xy - vec2<f32>(400.0, 300.0), 100.0);let n = simplex2(pos.xy * 0.01);return vec4<f32>(vec3<f32>(step(0.0, d) + n * 0.1), 1.0);}"""composed = Shader(["sdf2d/circle", "noise/simplex2", main])import FragmentColor
let shader = try Shader(""" @vertex fn vs_main(@builtin(vertex_index) index: u32) -> @builtin(position) vec4<f32> { var pos = array<vec2<f32>, 3>( vec2<f32>(-1.0, -1.0), vec2<f32>( 3.0, -1.0), vec2<f32>(-1.0, 3.0) ); return vec4<f32>(pos[index], 0.0, 1.0); }
@group(0) @binding(0) var<uniform> resolution: vec2<f32>;
@fragment fn fs_main() -> @location(0) vec4<f32> { return vec4<f32>(1.0, 0.0, 0.0, 1.0); // Red }
""")
let main = """ @vertex fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4<f32> { let p = array<vec2<f32>,3>(vec2f(-1.,-1.), vec2f(3.,-1.), vec2f(-1.,3.)); return vec4<f32>(p[i], 0.0, 1.0); }
@fragment fn fs(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> { let d = circle(pos.xy - vec2<f32>(400.0, 300.0), 100.0); let n = simplex2(pos.xy * 0.01); return vec4<f32>(vec3<f32>(step(0.0, d) + n * 0.1), 1.0); }
"""
let shader2 = try Shader([ "sdf2d/circle", // pure function: fn circle(p: vec2<f32>, r: f32) -> f32 "noise/simplex2", // pure function: fn simplex2(v: vec2<f32>) -> f32 main,])import org.fragmentcolor.*
val shader = Shader(""" @vertex fn vs_main(@builtin(vertex_index) index: u32) -> @builtin(position) vec4<f32> { var pos = array<vec2<f32>, 3>( vec2<f32>(-1.0, -1.0), vec2<f32>( 3.0, -1.0), vec2<f32>(-1.0, 3.0) ); return vec4<f32>(pos[index], 0.0, 1.0); }
@group(0) @binding(0) var<uniform> resolution: vec2<f32>;
@fragment fn fs_main() -> @location(0) vec4<f32> { return vec4<f32>(1.0, 0.0, 0.0, 1.0); // Red }
""")
val main = """ @vertex fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4<f32> { let p = array<vec2<f32>,3>(vec2f(-1.,-1.), vec2f(3.,-1.), vec2f(-1.,3.)); return vec4<f32>(p[i], 0.0, 1.0); }
@fragment fn fs(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> { let d = circle(pos.xy - vec2<f32>(400.0, 300.0), 100.0); let n = simplex2(pos.xy * 0.01); return vec4<f32>(vec3<f32>(step(0.0, d) + n * 0.1), 1.0); }
"""
val shader2 = Shader(listOf( "sdf2d/circle", // pure function: fn circle(p: vec2<f32>, r: f32) -> f32 "noise/simplex2", // pure function: fn simplex2(v: vec2<f32>) -> f32 main,))Shader::fetch(input)
Section titled “Shader::fetch(input)”Async constructor that returns a compiled Shader from one or more parts.
Each part can be:
- a raw WGSL source string
- a registry slug like
"sdf2d/circle" - an
https://URL pointing at a.wgslfile - a local file path ending in
.wgsl,.glsl,.frag, or.vert
Parts are deduplicated by source hash and concatenated in order before
compilation. fetch is the async path used when any part needs network or
file I/O. Shader::new covers the same shapes for callers that prefer a
synchronous constructor.
Platforms
Section titled “Platforms”| Platform | Spelling | Async mechanism |
|---|---|---|
| Web (JS) | await Shader.fetch(input) |
Promise via wasm_bindgen async |
| Python | Shader.fetch(input) |
Blocks the calling thread via pollster::block_on |
| Swift | try await Shader.fetch(input) |
async throws via uniffi async method |
| Kotlin | Shader.fetch(input) |
suspend fun via uniffi async method |
Note (Swift / Kotlin): the underlying uniffi binding is an
asyncinstance method. The Swift and KotlinShader.fetch(...)extensions call it on a throwaway default shader, so callers see a static factory.
Where each input resolves
Section titled “Where each input resolves”| Platform | Registry slugs and registry URLs | Other https:// URLs |
File paths |
|---|---|---|---|
| Rust (desktop) | Bundled shader library, offline | Fetched with the network feature, an error without it |
Read from disk |
| Python | Bundled shader library, offline | Fetched by a wheel built with the network feature, an error otherwise |
Read from disk |
| Swift / Kotlin | Bundled shader library, offline | Not fetched; a network error | Read from disk |
Web, Shader.fetch |
The browser’s fetch() |
The browser’s fetch() |
Fetched relative to the page’s origin |
Web, new Shader |
Not fetched; an error that points at Shader.fetch |
Not fetched; an error | Not fetched; an error |
After Shader::set_registry, slugs and registry URLs are fetched first on
every platform, and the bundled copy stands in when the fetch fails. A slug
resolves against the new registry. A registry URL is fetched as written, so
https://fragmentcolor.org/shaders/sdf2d/circle.wgsl still asks the default registry.
Example
Section titled “Example”use fragmentcolor::Shader;
// Full registry URL.let shader = Shader::fetch("https://fragmentcolor.org/shaders/sdf2d/circle.wgsl").await?;
// Equivalent shorthand using the registry slug.let shader2 = Shader::fetch("sdf2d/circle").await?;import { Shader } from "fragmentcolor";
// Full registry URL.const shader = await Shader.fetch("https://fragmentcolor.org/shaders/sdf2d/circle.wgsl");
// Equivalent shorthand using the registry slug.const shader2 = await Shader.fetch("sdf2d/circle");from fragmentcolor import Shader
# Full registry URL.shader = Shader.fetch("https://fragmentcolor.org/shaders/sdf2d/circle.wgsl")
# Equivalent shorthand using the registry slug.shader2 = Shader.fetch("sdf2d/circle")import FragmentColor
// Full registry URL.let shader = try await Shader.fetch("https://fragmentcolor.org/shaders/sdf2d/circle.wgsl")
// Equivalent shorthand using the registry slug.let shader2 = try await Shader.fetch("sdf2d/circle")import org.fragmentcolor.*
// Full registry URL.val shader = Shader.fetch("https://fragmentcolor.org/shaders/sdf2d/circle.wgsl")
// Equivalent shorthand using the registry slug.val shader2 = Shader.fetch("sdf2d/circle")Shader::set(key: string, value: any)
Section titled “Shader::set(key: string, value: any)”Sets the value of the uniform identified by the given key.
If the key does not exist or the value format is incorrect, the set method throws an exception. The shader remains valid, and if the exception is caught, the shader can still be used with the renderer.
set never waits for a draw. When another thread holds the shader’s storage, the value is queued and applied before the next draw. A texture can wait a moment while another thread binds a texture to the same shader, or while the renderer applies the shader’s queued values, so the latest one wins. A bad value that can’t be checked right away is dropped later with a logged warning instead of throwing.
The uniform’s declared WGSL type decides how the value is read, so a call behaves the same in every language:
- A number fits an
f32,f16,i32, oru32uniform. Integer uniforms take whole numbers in range. A float uniform rounds the number to its type, so anf16one keeps the nearestf16, and NaN, infinities and numbers past the type’s range throw. - A vector takes exactly as many numbers as it has components. A
mat2x2,mat3x3, ormat4x4takes 4, 9, or 16. - A
Texturecreated by aRendererbinds to a texture uniform, atexture_externalone included. - Raw bytes replace a whole storage-buffer or push-constant root: a byte slice in Rust, a
Uint8Arrayin JavaScript,bytes(or abytearrayormemoryview) in Python,Datain Swift, or aByteArrayin Kotlin. The byte count must equal the root’s size, and any other length throws.
Setting one field of a storage root uploads the whole root from the shader’s CPU copy at the next render that binds it, which overwrites everything a compute pass wrote to that root.
Example
Section titled “Example”use fragmentcolor::{Renderer, Shader};let r = Renderer::new();let shader = Shader::new(r#"enable f16;@group(0) @binding(0) var<uniform> resolution: vec2<f32>;@group(0) @binding(1) var<uniform> gain: f16;
struct VOut { @builtin(position) pos: vec4<f32> };@vertex fn vs_main(@builtin(vertex_index) i: u32) -> VOut {var p = array<vec2<f32>, 3>(vec2<f32>(-1.,-1.), vec2<f32>(3.,-1.), vec2<f32>(-1.,3.));var out: VOut;out.pos = vec4<f32>(p[i], 0., 1.);return out;}@fragment fn main() -> @location(0) vec4<f32> { return vec4<f32>(f32(gain), 0., 0., 1.); }"#)?;
// Set scalars/vectors on declared uniformsshader.set("resolution", [800.0, 600.0])?;shader.set("gain", 0.5)?;import { Renderer, Shader } from "fragmentcolor";const r = new Renderer();const shader = new Shader(`
enable f16;@group(0) @binding(0) var<uniform> resolution: vec2<f32>;@group(0) @binding(1) var<uniform> gain: f16;
struct VOut { @builtin(position) pos: vec4<f32> };@vertex fn vs_main(@builtin(vertex_index) i: u32) -> VOut {var p = array<vec2<f32>, 3>(vec2<f32>(-1.,-1.), vec2<f32>(3.,-1.), vec2<f32>(-1.,3.));var out: VOut;out.pos = vec4<f32>(p[i], 0., 1.);return out;}@fragment fn main() -> @location(0) vec4<f32> { return vec4<f32>(f32(gain), 0., 0., 1.); }
`);
// Set scalars/vectors on declared uniformsshader.set("resolution", [800.0, 600.0]);shader.set("gain", 0.5);from fragmentcolor import Renderer, Shaderr = Renderer()shader = Shader("""enable f16;@group(0) @binding(0) var<uniform> resolution: vec2<f32>;@group(0) @binding(1) var<uniform> gain: f16;
struct VOut { @builtin(position) pos: vec4<f32> };@vertex fn vs_main(@builtin(vertex_index) i: u32) -> VOut {var p = array<vec2<f32>, 3>(vec2<f32>(-1.,-1.), vec2<f32>(3.,-1.), vec2<f32>(-1.,3.));var out: VOut;out.pos = vec4<f32>(p[i], 0., 1.);return out;}@fragment fn main() -> @location(0) vec4<f32> { return vec4<f32>(f32(gain), 0., 0., 1.); }
""")
# Set scalars/vectors on declared uniformsshader.set("resolution", [800.0, 600.0])shader.set("gain", 0.5)import FragmentColorlet r = Renderer()let shader = try Shader("""enable f16;@group(0) @binding(0) var<uniform> resolution: vec2<f32>;@group(0) @binding(1) var<uniform> gain: f16;
struct VOut { @builtin(position) pos: vec4<f32> };@vertex fn vs_main(@builtin(vertex_index) i: u32) -> VOut {var p = array<vec2<f32>, 3>(vec2<f32>(-1.,-1.), vec2<f32>(3.,-1.), vec2<f32>(-1.,3.));var out: VOut;out.pos = vec4<f32>(p[i], 0., 1.);return out;}@fragment fn main() -> @location(0) vec4<f32> { return vec4<f32>(f32(gain), 0., 0., 1.); }
""")
// Set scalars/vectors on declared uniformstry shader.set("resolution", [800.0, 600.0])try shader.set("gain", 0.5)import org.fragmentcolor.*val r = Renderer()val shader = Shader("""enable f16;@group(0) @binding(0) var<uniform> resolution: vec2<f32>;@group(0) @binding(1) var<uniform> gain: f16;
struct VOut { @builtin(position) pos: vec4<f32> };@vertex fn vs_main(@builtin(vertex_index) i: u32) -> VOut {var p = array<vec2<f32>, 3>(vec2<f32>(-1.,-1.), vec2<f32>(3.,-1.), vec2<f32>(-1.,3.));var out: VOut;out.pos = vec4<f32>(p[i], 0., 1.);return out;}@fragment fn main() -> @location(0) vec4<f32> { return vec4<f32>(f32(gain), 0., 0., 1.); }
""")
// Set scalars/vectors on declared uniformsshader.set("resolution", listOf(800.0f, 600.0f))shader.set("gain", 0.5f)Shader::get(key: string) -> any
Section titled “Shader::get(key: string) -> any”Returns the current value of the uniform identified by the given key.
A struct or array root reads back as its bytes, and set doesn’t take
those bytes back for that root. Set a struct one field at a time
("light.color") and an array one element at a time ("weights[0]").
Only a storage-buffer or push-constant root takes its whole bytes.
An f16 uniform reads back as f32 numbers that hold the value rounded to f16, so 0.1 reads back as 0.0999755859375.
A texture slot reads back the id of what it binds. A Material map’s slot
holds the map’s id from the setter call on, before any Renderer loads it.
Example
Section titled “Example”use fragmentcolor::Shader;
let shader = Shader::default();shader.set("resolution", [800.0, 600.0])?;let res: [f32; 2] = shader.get("resolution")?;import { Shader } from "fragmentcolor";
const shader = Shader.default();shader.set("resolution", [800.0, 600.0]);const res = shader.get("resolution");from fragmentcolor import Shader
shader = Shader.default()shader.set("resolution", [800.0, 600.0])res = shader.get("resolution")import FragmentColor
let shader = Shader.default()try shader.set("resolution", [800.0, 600.0])let res = try shader.get("resolution")import org.fragmentcolor.*
val shader = Shader.default()shader.set("resolution", listOf(800.0f, 600.0f))val res = shader.get("resolution")Shader::list_uniforms() -> [string]
Section titled “Shader::list_uniforms() -> [string]”Returns a list of all uniform names in the Shader (excluding struct fields).
Example
Section titled “Example”use fragmentcolor::Shader;
let shader = Shader::default();let list = shader.list_uniforms();import { Shader } from "fragmentcolor";
const shader = Shader.default();const list = shader.listUniforms();from fragmentcolor import Shader
shader = Shader.default()list = shader.list_uniforms()import FragmentColor
let shader = Shader.default()let list = shader.listUniforms()import org.fragmentcolor.*
val shader = Shader.default()val list = shader.listUniforms()Shader::list_keys() -> [string]
Section titled “Shader::list_keys() -> [string]”Returns a list of all keys in the Shader, including uniform names and struct fields using the dot notation. Array elements aren’t listed, and set and get still take them by index, as in u.items[2].v.
list_keys never blocks. When another thread holds the shader’s storage, it returns an empty list and logs a warning.
Example
Section titled “Example”use fragmentcolor::Shader;
let shader = Shader::default();let keys = shader.list_keys();import { Shader } from "fragmentcolor";
const shader = Shader.default();const keys = shader.listKeys();from fragmentcolor import Shader
shader = Shader.default()keys = shader.list_keys()import FragmentColor
let shader = Shader.default()let keys = shader.listKeys()import org.fragmentcolor.*
val shader = Shader.default()val keys = shader.listKeys()Shader::from_vertex
Section titled “Shader::from_vertex”Build a basic WGSL shader source from a single Vertex layout.
This inspects the vertex position dimensionality (2D or 3D) and optional properties.
It generates a minimal vertex shader that consumes @location(0) position and a fragment shader that returns a flat color by default.
If a color: vec4<f32> property exists, the shader reads it at @location(1), whatever its place among the vertex’s properties, and uses it as the output.
This is intended as a fallback and for quick debugging. Canonical usage is the opposite: write your own shader and then build Meshes that match it.
It returns Result<Shader, ShaderError>, like Shader::new.
Example
Section titled “Example”use fragmentcolor::{Shader, Vertex};
let vertex = Vertex::new([0.0, 0.0, 0.0]);let shader = Shader::from_vertex(&vertex)?;import { Shader, Vertex } from "fragmentcolor";
const vertex = new Vertex([0.0, 0.0, 0.0]);const shader = Shader.fromVertex(vertex);from fragmentcolor import Shader, Vertex
vertex = Vertex([0.0, 0.0, 0.0])shader = Shader.from_vertex(vertex)import FragmentColor
let vertex = try Vertex([0.0, 0.0, 0.0])let shader = try Shader.fromVertex(vertex)import org.fragmentcolor.*
val vertex = Vertex(listOf(0.0f, 0.0f, 0.0f))val shader = Shader.fromVertex(vertex)Shader::from_mesh
Section titled “Shader::from_mesh”Build a basic WGSL shader source from the first vertex in a Mesh.
The resulting shader automatically adds the provided Mesh to its internal list of Meshes to render,
so the user doesn’t need to call Shader::add_mesh manually.
This function uses the first Vertex to infer position dimensionality and optional properties.
It generates a minimal vertex shader that consumes @location(0) position and a fragment shader that returns a flat color by default. If a color: vec4<f32> property exists, it is passed through to the fragment stage and used as output.
Errors
Section titled “Errors”from_mesh returns Result<Shader, ShaderError>. A mesh with no vertices returns
ShaderError::InvalidKey, since there is no first vertex to build from. A mesh the new
shader refuses returns the error Shader::add_mesh gives, such as a vertex whose position
has another dimension than the first one’s.
Example
Section titled “Example”use fragmentcolor::{Mesh, Shader};
let mut mesh = Mesh::new();mesh.add_vertices([ [-0.5, -0.5, 0.0], [0.5, -0.5, 0.0], [0.0, 0.5, 0.0],]);let shader = Shader::from_mesh(&mesh)?;import { Mesh, Shader } from "fragmentcolor";
const mesh = new Mesh();mesh.addVertices([ [-0.5, -0.5, 0.0], [0.5, -0.5, 0.0], [0.0, 0.5, 0.0], ]);const shader = Shader.fromMesh(mesh);from fragmentcolor import Mesh, Shader
mesh = Mesh()mesh.add_vertices([ [-0.5, -0.5, 0.0], [0.5, -0.5, 0.0], [0.0, 0.5, 0.0],])shader = Shader.from_mesh(mesh)import FragmentColor
let mesh = Mesh()try mesh.addVertices([ [-0.5, -0.5, 0.0], [0.5, -0.5, 0.0], [0.0, 0.5, 0.0],])let shader = try Shader.fromMesh(mesh)import org.fragmentcolor.*
val mesh = Mesh()mesh.addVertices(listOf(listOf(-0.5f, -0.5f, 0.0f), listOf(0.5f, -0.5f, 0.0f), listOf(0.0f, 0.5f, 0.0f)))val shader = Shader.fromMesh(mesh)Shader::add_mesh
Section titled “Shader::add_mesh”Attach a Mesh to this Shader. The Renderer draws every mesh attached to it, one draw call per mesh. Meshes that lay out their data alike share one pipeline, and a mesh whose stride, attribute offsets or instance stream differ draws with a pipeline of its own.
add_mesh checks every vertex and instance of the mesh against the shader’s @location inputs and returns Result<(), ShaderError>.
- An attribute set from numbers takes the type the shader declares at its location: floats for
f32,f16and their vectors, integers foru32,i32and their vectors when every value is whole and fits. The mesh holds 32-bit floats for anf16input, and the GPU converts them. A float takes a number only when it stays finite after rounding to the declared type, so NaN, infinities, numbers past thef32range, and numbers past ±65504 for anf16input, its position included, fail. - On success, the mesh is attached, its attributes keep those types for as long as the mesh lives, and it is drawn when this shader renders.
- On a missing attribute or a value that doesn’t fit, the error names the attribute, the declared type and the value, or the vertex or instance that lacks it. The mesh isn’t attached and records no type.
- A shader that declares another type for an attribute an earlier shader already typed on this mesh fails to attach.
- A vertex that sets a property named
positionfails withShaderError::InvalidKey, since its position comes fromVertex::new. - A vertex or instance added after the attach must hold every attribute the shader reads, each value in the range of the type the shader declares,
f16included.Renderer.renderreturnsMeshError::InvalidVertexorMeshError::InvalidInstancenaming the attribute and that type otherwise. - The
@locationmembers of a struct argument are inputs too, each read from the attribute of its own name, sostruct VIn { @location(1) color: vec4<f32> }readscolor. Built-in members such as@builtin(vertex_index)read nothing from the mesh. - A shader with no
@locationinputs, in its arguments or their members, draws fullscreen and rejects every mesh withShaderError::InvalidKey.
See also
Section titled “See also”Use Shader::validate_mesh for performing a compatibility check without attaching.
Example
Section titled “Example”use fragmentcolor::{Shader, Mesh};
let shader = Shader::new(r#"@vertex fn vs_main(@location(0) pos: vec3<f32>) -> @builtin(position) vec4<f32> { return vec4<f32>(pos, 1.0);}@fragment fn fs_main() -> @location(0) vec4<f32> { return vec4<f32>(1.,0.,0.,1.); }"#)?;
let mesh = Mesh::new();mesh.add_vertices([ [-0.5, -0.5, 0.0], [0.5, -0.5, 0.0], [0.0, 0.5, 0.0],]);
// Attach mesh to this shader (errors if incompatible)shader.add_mesh(&mesh)?;
// Renderer will draw the mesh when rendering this pass.// Meshes that lay out their vertices alike draw with one// RenderPipeline, and each other layout gets one of its own.import { Shader, Mesh } from "fragmentcolor";
const shader = new Shader(`
@vertex fn vs_main(@location(0) pos: vec3<f32>) -> @builtin(position) vec4<f32> { return vec4<f32>(pos, 1.0);}@fragment fn fs_main() -> @location(0) vec4<f32> { return vec4<f32>(1.,0.,0.,1.); }
`);
const mesh = new Mesh();mesh.addVertices([ [-0.5, -0.5, 0.0], [0.5, -0.5, 0.0], [0.0, 0.5, 0.0], ]);
// Attach mesh to this shader (errors if incompatible)shader.addMesh(mesh);
// Renderer will draw the mesh when rendering this pass.// Meshes that lay out their vertices alike draw with one// RenderPipeline, and each other layout gets one of its own.from fragmentcolor import Shader, Mesh
shader = Shader("""@vertex fn vs_main(@location(0) pos: vec3<f32>) -> @builtin(position) vec4<f32> { return vec4<f32>(pos, 1.0);}@fragment fn fs_main() -> @location(0) vec4<f32> { return vec4<f32>(1.,0.,0.,1.); }
""")
mesh = Mesh()mesh.add_vertices([ [-0.5, -0.5, 0.0], [0.5, -0.5, 0.0], [0.0, 0.5, 0.0],])
# Attach mesh to this shader (errors if incompatible)shader.add_mesh(mesh)
# Renderer will draw the mesh when rendering this pass.# Meshes that lay out their vertices alike draw with one# RenderPipeline, and each other layout gets one of its own.import FragmentColor
let shader = try Shader("""@vertex fn vs_main(@location(0) pos: vec3<f32>) -> @builtin(position) vec4<f32> { return vec4<f32>(pos, 1.0);}@fragment fn fs_main() -> @location(0) vec4<f32> { return vec4<f32>(1.,0.,0.,1.); }
""")
let mesh = Mesh()try mesh.addVertices([ [-0.5, -0.5, 0.0], [0.5, -0.5, 0.0], [0.0, 0.5, 0.0],])
// Attach mesh to this shader (errors if incompatible)try shader.addMesh(mesh)
// Renderer will draw the mesh when rendering this pass.// Meshes that lay out their vertices alike draw with one// RenderPipeline, and each other layout gets one of its own.import org.fragmentcolor.*
val shader = Shader("""@vertex fn vs_main(@location(0) pos: vec3<f32>) -> @builtin(position) vec4<f32> { return vec4<f32>(pos, 1.0);}@fragment fn fs_main() -> @location(0) vec4<f32> { return vec4<f32>(1.,0.,0.,1.); }
""")
val mesh = Mesh()mesh.addVertices(listOf(listOf(-0.5f, -0.5f, 0.0f), listOf(0.5f, -0.5f, 0.0f), listOf(0.0f, 0.5f, 0.0f)))
// Attach mesh to this shader (errors if incompatible)shader.addMesh(mesh)
// Renderer will draw the mesh when rendering this pass.// Meshes that lay out their vertices alike draw with one// RenderPipeline, and each other layout gets one of its own.Shader::remove_mesh
Section titled “Shader::remove_mesh”Remove a single Mesh previously attached to this Shader. If the Mesh is attached multiple times, removes the first match. Once the shader holds the mesh no more, a vertex or instance added to the mesh may leave out what this shader reads.
Example
Section titled “Example”use fragmentcolor::{Shader, Mesh};
let shader = Shader::new(r#"struct VOut { @builtin(position) pos: vec4<f32> };@vertexfn vs_main(@location(0) pos: vec2<f32>) -> VOut { var out: VOut; out.pos = vec4<f32>(pos, 0.0, 1.0); return out;}@fragmentfn fs_main(_v: VOut) -> @location(0) vec4<f32> { return vec4<f32>(1.0,0.0,0.0,1.0); }"#)?;
let mesh = Mesh::new();mesh.add_vertices([ [-0.5, -0.5], [0.5, -0.5], [0.0, 0.5],]);shader.add_mesh(&mesh)?;
// Detach the meshshader.remove_mesh(&mesh);import { Shader, Mesh } from "fragmentcolor";
const shader = new Shader(`
struct VOut { @builtin(position) pos: vec4<f32> };@vertexfn vs_main(@location(0) pos: vec2<f32>) -> VOut { var out: VOut; out.pos = vec4<f32>(pos, 0.0, 1.0); return out;}@fragmentfn fs_main(_v: VOut) -> @location(0) vec4<f32> { return vec4<f32>(1.0,0.0,0.0,1.0); }
`);
const mesh = new Mesh();mesh.addVertices([ [-0.5, -0.5], [0.5, -0.5], [0.0, 0.5], ]);shader.addMesh(mesh);
// Detach the meshshader.removeMesh(mesh);from fragmentcolor import Shader, Mesh
shader = Shader("""struct VOut { @builtin(position) pos: vec4<f32> };@vertexfn vs_main(@location(0) pos: vec2<f32>) -> VOut { var out: VOut; out.pos = vec4<f32>(pos, 0.0, 1.0); return out;}@fragmentfn fs_main(_v: VOut) -> @location(0) vec4<f32> { return vec4<f32>(1.0,0.0,0.0,1.0); }
""")
mesh = Mesh()mesh.add_vertices([ [-0.5, -0.5], [0.5, -0.5], [0.0, 0.5],])shader.add_mesh(mesh)
# Detach the meshshader.remove_mesh(mesh)import FragmentColor
let shader = try Shader("""struct VOut { @builtin(position) pos: vec4<f32> };@vertexfn vs_main(@location(0) pos: vec2<f32>) -> VOut { var out: VOut; out.pos = vec4<f32>(pos, 0.0, 1.0); return out;}@fragmentfn fs_main(_v: VOut) -> @location(0) vec4<f32> { return vec4<f32>(1.0,0.0,0.0,1.0); }
""")
let mesh = Mesh()try mesh.addVertices([ [-0.5, -0.5], [0.5, -0.5], [0.0, 0.5],])try shader.addMesh(mesh)
// Detach the meshshader.removeMesh(mesh)import org.fragmentcolor.*
val shader = Shader("""struct VOut { @builtin(position) pos: vec4<f32> };@vertexfn vs_main(@location(0) pos: vec2<f32>) -> VOut { var out: VOut; out.pos = vec4<f32>(pos, 0.0, 1.0); return out;}@fragmentfn fs_main(_v: VOut) -> @location(0) vec4<f32> { return vec4<f32>(1.0,0.0,0.0,1.0); }
""")
val mesh = Mesh()mesh.addVertices(listOf(listOf(-0.5f, -0.5f), listOf(0.5f, -0.5f), listOf(0.0f, 0.5f)))shader.addMesh(mesh)
// Detach the meshshader.removeMesh(mesh)Shader::remove_meshes
Section titled “Shader::remove_meshes”Remove multiple meshes from this Shader.
Example
Section titled “Example”use fragmentcolor::{Shader, Mesh};
let shader = Shader::new(r#"struct VOut { @builtin(position) pos: vec4<f32> };@vertexfn vs_main(@location(0) pos: vec2<f32>) -> VOut { var out: VOut; out.pos = vec4<f32>(pos, 0.0, 1.0); return out;}@fragmentfn fs_main(_v: VOut) -> @location(0) vec4<f32> { return vec4<f32>(1.0,0.0,0.0,1.0); }"#)?;
let m1 = Mesh::new();m1.add_vertices([ [-0.5, -0.5], [0.0, -0.5], [-0.5, 0.0],]);let m2 = Mesh::new();m2.add_vertices([ [0.0, 0.0], [0.5, 0.0], [0.0, 0.5],]);
shader.add_mesh(&m1)?;shader.add_mesh(&m2)?;
shader.remove_meshes([&m1, &m2]);import { Shader, Mesh } from "fragmentcolor";
const shader = new Shader(`
struct VOut { @builtin(position) pos: vec4<f32> };@vertexfn vs_main(@location(0) pos: vec2<f32>) -> VOut { var out: VOut; out.pos = vec4<f32>(pos, 0.0, 1.0); return out;}@fragmentfn fs_main(_v: VOut) -> @location(0) vec4<f32> { return vec4<f32>(1.0,0.0,0.0,1.0); }
`);
const m1 = new Mesh();m1.addVertices([ [-0.5, -0.5], [0.0, -0.5], [-0.5, 0.0], ]);const m2 = new Mesh();m2.addVertices([ [0.0, 0.0], [0.5, 0.0], [0.0, 0.5], ]);
shader.addMesh(m1);shader.addMesh(m2);
shader.removeMeshes([m1, m2]);from fragmentcolor import Shader, Mesh
shader = Shader("""struct VOut { @builtin(position) pos: vec4<f32> };@vertexfn vs_main(@location(0) pos: vec2<f32>) -> VOut { var out: VOut; out.pos = vec4<f32>(pos, 0.0, 1.0); return out;}@fragmentfn fs_main(_v: VOut) -> @location(0) vec4<f32> { return vec4<f32>(1.0,0.0,0.0,1.0); }
""")
m1 = Mesh()m1.add_vertices([ [-0.5, -0.5], [0.0, -0.5], [-0.5, 0.0],])m2 = Mesh()m2.add_vertices([ [0.0, 0.0], [0.5, 0.0], [0.0, 0.5],])
shader.add_mesh(m1)shader.add_mesh(m2)
shader.remove_meshes([m1, m2])import FragmentColor
let shader = try Shader("""struct VOut { @builtin(position) pos: vec4<f32> };@vertexfn vs_main(@location(0) pos: vec2<f32>) -> VOut { var out: VOut; out.pos = vec4<f32>(pos, 0.0, 1.0); return out;}@fragmentfn fs_main(_v: VOut) -> @location(0) vec4<f32> { return vec4<f32>(1.0,0.0,0.0,1.0); }
""")
let m1 = Mesh()try m1.addVertices([ [-0.5, -0.5], [0.0, -0.5], [-0.5, 0.0],])let m2 = Mesh()try m2.addVertices([ [0.0, 0.0], [0.5, 0.0], [0.0, 0.5],])
try shader.addMesh(m1)try shader.addMesh(m2)
shader.removeMeshes([m1, m2])import org.fragmentcolor.*
val shader = Shader("""struct VOut { @builtin(position) pos: vec4<f32> };@vertexfn vs_main(@location(0) pos: vec2<f32>) -> VOut { var out: VOut; out.pos = vec4<f32>(pos, 0.0, 1.0); return out;}@fragmentfn fs_main(_v: VOut) -> @location(0) vec4<f32> { return vec4<f32>(1.0,0.0,0.0,1.0); }
""")
val m1 = Mesh()m1.addVertices(listOf(listOf(-0.5f, -0.5f), listOf(0.0f, -0.5f), listOf(-0.5f, 0.0f)))val m2 = Mesh()m2.addVertices(listOf(listOf(0.0f, 0.0f), listOf(0.5f, 0.0f), listOf(0.0f, 0.5f)))
shader.addMesh(m1)shader.addMesh(m2)
shader.removeMeshes(listOf(m1, m2))Shader::clear_meshes
Section titled “Shader::clear_meshes”Remove all meshes attached to this Shader. A vertex or instance added to one of them afterwards may leave out what this shader reads.
Example
Section titled “Example”use fragmentcolor::{Shader, Mesh};
let shader = Shader::new(r#"struct VOut { @builtin(position) pos: vec4<f32> };@vertexfn vs_main(@location(0) pos: vec2<f32>) -> VOut { var out: VOut; out.pos = vec4<f32>(pos, 0.0, 1.0); return out;}@fragmentfn fs_main(_v: VOut) -> @location(0) vec4<f32> { return vec4<f32>(1.0,0.0,0.0,1.0); }"#)?;
let mesh = Mesh::new();mesh.add_vertices([ [-0.5, -0.5], [0.5, -0.5], [0.0, 0.5],]);shader.add_mesh(&mesh)?;
// Clear allshader.clear_meshes();import { Shader, Mesh } from "fragmentcolor";
const shader = new Shader(`
struct VOut { @builtin(position) pos: vec4<f32> };@vertexfn vs_main(@location(0) pos: vec2<f32>) -> VOut { var out: VOut; out.pos = vec4<f32>(pos, 0.0, 1.0); return out;}@fragmentfn fs_main(_v: VOut) -> @location(0) vec4<f32> { return vec4<f32>(1.0,0.0,0.0,1.0); }
`);
const mesh = new Mesh();mesh.addVertices([ [-0.5, -0.5], [0.5, -0.5], [0.0, 0.5], ]);shader.addMesh(mesh);
// Clear allshader.clearMeshes();from fragmentcolor import Shader, Mesh
shader = Shader("""struct VOut { @builtin(position) pos: vec4<f32> };@vertexfn vs_main(@location(0) pos: vec2<f32>) -> VOut { var out: VOut; out.pos = vec4<f32>(pos, 0.0, 1.0); return out;}@fragmentfn fs_main(_v: VOut) -> @location(0) vec4<f32> { return vec4<f32>(1.0,0.0,0.0,1.0); }
""")
mesh = Mesh()mesh.add_vertices([ [-0.5, -0.5], [0.5, -0.5], [0.0, 0.5],])shader.add_mesh(mesh)
# Clear allshader.clear_meshes()import FragmentColor
let shader = try Shader("""struct VOut { @builtin(position) pos: vec4<f32> };@vertexfn vs_main(@location(0) pos: vec2<f32>) -> VOut { var out: VOut; out.pos = vec4<f32>(pos, 0.0, 1.0); return out;}@fragmentfn fs_main(_v: VOut) -> @location(0) vec4<f32> { return vec4<f32>(1.0,0.0,0.0,1.0); }
""")
let mesh = Mesh()try mesh.addVertices([ [-0.5, -0.5], [0.5, -0.5], [0.0, 0.5],])try shader.addMesh(mesh)
// Clear allshader.clearMeshes()import org.fragmentcolor.*
val shader = Shader("""struct VOut { @builtin(position) pos: vec4<f32> };@vertexfn vs_main(@location(0) pos: vec2<f32>) -> VOut { var out: VOut; out.pos = vec4<f32>(pos, 0.0, 1.0); return out;}@fragmentfn fs_main(_v: VOut) -> @location(0) vec4<f32> { return vec4<f32>(1.0,0.0,0.0,1.0); }
""")
val mesh = Mesh()mesh.addVertices(listOf(listOf(-0.5f, -0.5f), listOf(0.5f, -0.5f), listOf(0.0f, 0.5f)))shader.addMesh(mesh)
// Clear allshader.clearMeshes()Shader::validate_mesh
Section titled “Shader::validate_mesh”Validate that a Mesh is compatible with this Shader’s vertex inputs.
- Checks that every
@locationinput of the vertex entry point finds an attribute, that every vertex and instance holds each attribute the shader reads, and that every value fits the type the input declares. The@locationmembers of a struct argument count as inputs, each under its member name. - Matches each input in this order:
- by name, instance attributes first, then vertex attributes (
positionincluded) - the position, at
@location(0) - by the attribute’s own location, instance attributes first, then vertex attributes
- by name, instance attributes first, then vertex attributes (
- A number fills a float input unless the shader declares an integer type there. An integer input takes whole numbers that fit its type.
- Returns
Ok(())when every input matches; returns the same errorShader::add_meshwould otherwise.
Shader::add_meshandPass::add_meshrun the same check. Callvalidate_meshto test a mesh without attaching it.- It changes nothing: the mesh isn’t attached and its attributes take no type.
- If the Shader has no
@locationinputs, as arguments or struct members, it draws fullscreen and attaching a Mesh is rejected. A struct of built-ins only, such as@builtin(vertex_index), still counts as no input. - This method does not allocate GPU buffers; it inspects CPU-side vertex/instance data only.
Example
Section titled “Example”use fragmentcolor::{Shader, Pass, Mesh};
let shader = Shader::new(r#"struct VOut { @builtin(position) pos: vec4<f32> };@vertex fn vs_main(@location(0) pos: vec3<f32>) -> VOut {var out: VOut;out.pos = vec4<f32>(pos, 1.0);return out;}@fragment fn fs_main(_v: VOut) -> @location(0) vec4<f32> { return vec4<f32>(1.,0.,0.,1.); }"#)?;let pass = Pass::from_shader("p", &shader);
let mesh = Mesh::new();mesh.add_vertices([[-0.5, -0.5, 0.0],[ 0.5, -0.5, 0.0],[ 0.0, 0.5, 0.0],]);
shader.validate_mesh(&mesh)?; // Okpass.add_mesh(&mesh)?;import { Shader, Pass, Mesh } from "fragmentcolor";
const shader = new Shader(`
struct VOut { @builtin(position) pos: vec4<f32> };@vertex fn vs_main(@location(0) pos: vec3<f32>) -> VOut {var out: VOut;out.pos = vec4<f32>(pos, 1.0);return out;}@fragment fn fs_main(_v: VOut) -> @location(0) vec4<f32> { return vec4<f32>(1.,0.,0.,1.); }
`);const pass = Pass.fromShader("p", shader);
const mesh = new Mesh();mesh.addVertices([ [-0.5, -0.5, 0.0], [ 0.5, -0.5, 0.0], [ 0.0, 0.5, 0.0], ]);
shader.validateMesh(mesh); // Okpass.addMesh(mesh);from fragmentcolor import Shader, Pass, Mesh
shader = Shader("""struct VOut { @builtin(position) pos: vec4<f32> };@vertex fn vs_main(@location(0) pos: vec3<f32>) -> VOut {var out: VOut;out.pos = vec4<f32>(pos, 1.0);return out;}@fragment fn fs_main(_v: VOut) -> @location(0) vec4<f32> { return vec4<f32>(1.,0.,0.,1.); }
""")rpass = Pass.from_shader("p", shader)
mesh = Mesh()mesh.add_vertices([[-0.5, -0.5, 0.0],[ 0.5, -0.5, 0.0],[ 0.0, 0.5, 0.0],])
shader.validate_mesh(mesh) # Okrpass.add_mesh(mesh)import FragmentColor
let shader = try Shader("""struct VOut { @builtin(position) pos: vec4<f32> };@vertex fn vs_main(@location(0) pos: vec3<f32>) -> VOut {var out: VOut;out.pos = vec4<f32>(pos, 1.0);return out;}@fragment fn fs_main(_v: VOut) -> @location(0) vec4<f32> { return vec4<f32>(1.,0.,0.,1.); }
""")let pass = Pass.fromShader("p", shader)
let mesh = Mesh()try mesh.addVertices([[-0.5, -0.5, 0.0],[ 0.5, -0.5, 0.0],[ 0.0, 0.5, 0.0],])
try shader.validateMesh(mesh) // Oktry pass.addMesh(mesh)import org.fragmentcolor.*
val shader = Shader("""struct VOut { @builtin(position) pos: vec4<f32> };@vertex fn vs_main(@location(0) pos: vec3<f32>) -> VOut {var out: VOut;out.pos = vec4<f32>(pos, 1.0);return out;}@fragment fn fs_main(_v: VOut) -> @location(0) vec4<f32> { return vec4<f32>(1.,0.,0.,1.); }
""")val pass = Pass.fromShader("p", shader)
val mesh = Mesh()mesh.addVertices(listOf(listOf(-0.5f, -0.5f, 0.0f), listOf(0.5f, -0.5f, 0.0f), listOf(0.0f, 0.5f, 0.0f)))
shader.validateMesh(mesh) // Okpass.addMesh(mesh)Shader::is_compute
Section titled “Shader::is_compute”Returns true if this Shader is a compute shader (has a compute entry point).
Example
Section titled “Example”use fragmentcolor::Shader;
let shader = Shader::new(r#"@compute @workgroup_size(1)fn cs_main() { }"#)?;
// Call the methodlet is_compute = shader.is_compute();import { Shader } from "fragmentcolor";
const shader = new Shader(`
@compute @workgroup_size(1)fn cs_main() { }
`);
// Call the methodconst is_compute = shader.isCompute();from fragmentcolor import Shader
shader = Shader("""@compute @workgroup_size(1)fn cs_main() { }
""")
# Call the methodis_compute = shader.is_compute()import FragmentColor
let shader = try Shader("""@compute @workgroup_size(1)fn cs_main() { }
""")
// Call the methodlet is_compute = shader.isCompute()import org.fragmentcolor.*
val shader = Shader("""@compute @workgroup_size(1)fn cs_main() { }
""")
// Call the methodval is_compute = shader.isCompute()Shader::set_registry(base_url: string)
Section titled “Shader::set_registry(base_url: string)”Override the base URL used to resolve shader slugs (e.g. "sdf2d/circle").
When a slug is passed to Shader::new, it is expanded to:
<base_url>/<slug>.wgslThe default base URL is https://fragmentcolor.org/shaders/, which serves the public shader registry. Override it to point at your own collection (a CDN, a local dev server, or a mirror) without changing the rest of your code.
The base may end with or without a trailing slash; both are normalized at lookup time.
This setting is process-wide. It applies to every subsequent call to Shader::new(...) until overridden again.
A full URL into the default registry keeps pointing there. After set_registry, https://fragmentcolor.org/shaders/sdf2d/circle.wgsl is fetched as written, and the bundled shader library stands in when the fetch fails. Builds without the network feature, such as the Swift and Kotlin packages, always take the bundled copy.
Example
Section titled “Example”use fragmentcolor::Shader;
// Point at your own mirror of the registryShader::set_registry("https://cdn.example.com/shaders/");
// Now the slug "sdf2d/circle" resolves to https://cdn.example.com/shaders/sdf2d/circle.wgsl// (Skipping the actual fetch in this doctest)import { Shader } from "fragmentcolor";
// Point at your own mirror of the registryShader.setRegistry("https://cdn.example.com/shaders/");
// Now the slug "sdf2d/circle" resolves to https://cdn.example.com/shaders/sdf2d/circle.wgsl// (Skipping the actual fetch in this doctest)from fragmentcolor import Shader
# Point at your own mirror of the registryShader.set_registry("https://cdn.example.com/shaders/")
# Now the slug "sdf2d/circle" resolves to https://cdn.example.com/shaders/sdf2d/circle.wgsl# (Skipping the actual fetch in this doctest)import FragmentColor
// Point at your own mirror of the registryShader.setRegistry("https://cdn.example.com/shaders/")
// Now the slug "sdf2d/circle" resolves to https://cdn.example.com/shaders/sdf2d/circle.wgsl// (Skipping the actual fetch in this doctest)import org.fragmentcolor.*
// Point at your own mirror of the registryShader.setRegistry("https://cdn.example.com/shaders/")
// Now the slug "sdf2d/circle" resolves to https://cdn.example.com/shaders/sdf2d/circle.wgsl// (Skipping the actual fetch in this doctest)Shader::default()
Section titled “Shader::default()”Creates a new Shader from the default shader source.
Useful for examples and quick demos. Includes a “resolution” uniform.
struct VertexOutput { @builtin(position) coords: vec4<f32>,}
@group(0) @binding(0)var<uniform> resolution: vec2<f32>;
@vertexfn vs_main(@builtin(vertex_index) in_vertex_index: u32) -> VertexOutput { let x = f32(i32(in_vertex_index) - 1); let y = f32(i32(in_vertex_index & 1u) * 2 - 1); return VertexOutput(vec4<f32>(x, y, 0.0, 1.0));}
@fragmentfn fs_main(pixel: VertexOutput) -> @location(0) vec4<f32> { let _dummy = resolution.x + resolution.y * 0.0; return vec4<f32>(1.0, 0.0, 0.0, 1.0);}Example
Section titled “Example”use fragmentcolor::{Shader};
let shader = Shader::default();
// The default shader includes a "resolution" uniformshader.set("resolution", [800.0, 600.0])?;let res: [f32; 2] = shader.get("resolution")?;import { Shader } from "fragmentcolor";
const shader = Shader.default();
// The default shader includes a "resolution" uniformshader.set("resolution", [800.0, 600.0]);const res = shader.get("resolution");from fragmentcolor import Shader
shader = Shader.default()
# The default shader includes a "resolution" uniformshader.set("resolution", [800.0, 600.0])res = shader.get("resolution")import FragmentColor
let shader = Shader.default()
// The default shader includes a "resolution" uniformtry shader.set("resolution", [800.0, 600.0])let res = try shader.get("resolution")import org.fragmentcolor.*
val shader = Shader.default()
// The default shader includes a "resolution" uniformshader.set("resolution", listOf(800.0f, 600.0f))val res = shader.get("resolution")