Skip to main content

Shader

Struct Shader 

Source
pub struct Shader {
    pub asset_id: AssetId,
    pub fragment: String,
    pub vertex: Option<String>,
    pub locator: Option<PayloadLocator>,
}
Expand description

Replaces how surfaces are shaded, and optionally how vertices are placed, with functions of your own. Written in Slang, one source for every backend.

A Shader is entirely optional. The engine ships its own lighting and projection and uses them for every draw a Shader does not claim, so a world that wants standard lighting declares no Shader at all. The shadow pass and the depth pre-pass are engine-internal and take no Shader stage; enable or size shadows with shadow_map_size in GraphicsConfig.

// Custom shading only; the engine still places every vertex.
let water = Shader {
    fragment: "assets/shaders/water.slang".into(),
    ..Default::default()
};
// Both hooks: a sway displacement, then the surface.
let reeds = Shader {
    vertex: Some("assets/shaders/reeds_sway.slang".into()),
    fragment: "assets/shaders/reeds.slang".into(),
    ..Default::default()
};
assert!(water.vertex.is_none() && reeds.vertex.is_some());

§The two hooks

A Shader file defines a function, not an entry point. The engine owns every entry point, binding and pipeline on every backend, and calls the world’s functions from inside its own:

// the `fragment` file, required
float4 shade(VertexOut in, GpuObjectData od);

// the `vertex` file, optional; without one the engine projects the vertex itself
VertexOut transform(float4x4 model, float3 pos, float3 normal, float3 tangent,
                    float3 color, float2 uv);

shade returns the surface’s linear-light colour with alpha. od is the surface’s material record whichever path drew it: tint_roughness, emissive_metallic, albedo_index, normal_index, emissive_map_index, orm_map_index and bb_max_alpha_cutoff.w are the fields a surface reads. transform receives the model matrix and the model-space attributes, after skinning for a SkinnedMesh and per instance for an InstancedProp, and returns the projected vertex; the engine’s own is project_vertex, so a displacement is return project_vertex(model, pos + offset, normal, tangent, color, uv);.

Both files are compiled inside the engine’s own main-pass source, so they see the same vocabulary the engine’s shading uses and declare no layout, binding, register, attribute or varying of their own:

  • shade_surface(in, od): the engine’s PBR lighting, so return shade_surface(in, od) * tint; starts from it.
  • project_vertex(model, pos, normal, tangent, color, uv): the engine’s projection.
  • pool_sample(index, uv): a texture from the world’s pool by the record’s index.
  • decode_normal_map(rg): a tangent-space normal from a normal-map texel.
  • shadow_factor_cascaded(world_pos, view_depth, screen_xy): the sun’s cascaded shadow term.
  • environment_specular(world_pos, reflected, lod): the reflection environment.
  • irradiance_sample(normal): the diffuse environment.
  • VIEW: the view block, with vp, view_mat, elapsed, cam_x / cam_y / cam_z and sky_rot.
  • LIGHTS: the light block, with dir[], pt[], num_dir, num_pt and ambient_intensity.
  • SKY_DIR(d): a world direction in the environment map’s frame.

VertexOut is the engine’s varying block: position (clip), world_pos, normal, tangent, bitangent, uv, view_depth and color. A shade must not read in.object_id; the record is od.

§More than one Shader

The first declared Shader is the world’s default: everything renders with it unless a Material names another one through its shader field. A world may declare up to 8 Shaders in total.

  • Instanced, skinned, and voxel-chunk draws always use the world default. A Material naming a Shader cannot be used by an InstancedProp, a SkinnedMesh, or a VoxelWorld; give those a Material without one.
  • At most 8 Shaders, the world default included.

Planar reflections are the one case with no build-time signal: a surface reflected in a mirror is drawn with the world default Shader regardless of its Material. Reflection probe cubes capture it the same way.

A Shader referenced only by materials belonging to one Scene is owned by that scene: its pipeline is built when the scene loads (behind the loading screen, alongside that scene’s textures and meshes) and released when the scene unloads. A Shader used across scenes, or by the world default, loads at startup.

§Compilation

cn build compiles both files for the backend it cooks for and stores the result in the world; a player needs no shader compiler. A file that fails to compile, or omits its hook, fails the build naming the Shader and the hook. Under cn debug a save to either file recompiles it and swaps the live pipelines.

Fields§

§asset_id: AssetId

Asset identity; injected via inject_name. Not part of args.

§fragment: String

Path to the .slang file defining shade. Required.

§vertex: Option<String>

Path to the .slang file defining transform. Omit to keep the engine’s own projection.

§locator: Option<PayloadLocator>

Injected at load time from BlobAssetDef::payload.

Implementations§

Source§

impl Shader

Source

pub fn stage(&self, stage: ShaderStage) -> Option<&str>

The declared path for stage, if that file is present.

Trait Implementations§

Source§

impl Clone for Shader

Source§

fn clone(&self) -> Shader

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Component for Shader

Source§

const NAME: &'static str = "Shader"

The registry name a world authors this component under.
Source§

fn from_baked(bytes: &[u8]) -> Result<Shader, CnResult>

Reconstruct this component from a blob record, whose bytes are the serialized runtime component (cook already ran the asset -> component translation). The default rejects: runtime-only components are never stored in a blob, so only loadable types provide an implementation.
Source§

fn inject_locator(&mut self, locator: PayloadLocator)

Called after construction to inject the payload locator from the blob def. Only meaningful for components with a compiled payload. The default implementation does nothing (correct for most components).
Source§

fn inject_name(&mut self, id: AssetId)

Called after construction to inject the asset’s identity from the blob def. Only meaningful for components that look themselves up by id at runtime. The default implementation does nothing.
Source§

impl ComponentSlot for Shader

Source§

const DISCRIMINANT: u8

The component type’s stable id, used as its ComponentId.
Source§

fn slot(s: &ComponentStorage) -> &Column<Shader>

Borrow this type’s column out of the storage.
Source§

fn slot_mut(s: &mut ComponentStorage) -> &mut Column<Shader>

Mutably borrow this type’s column out of the storage.
Source§

impl Debug for Shader

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Default for Shader

Source§

fn default() -> Shader

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for Shader

Source§

fn deserialize<__D>( __deserializer: __D, ) -> Result<Shader, <__D as Deserializer<'de>>::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl From<Shader> for ComponentAsset

Source§

fn from(c: Shader) -> ComponentAsset

Converts to this type from the input type.
Source§

impl RuntimeComponent for Shader

Source§

impl Serialize for Shader

Source§

fn serialize<__S>( &self, __serializer: __S, ) -> Result<<__S as Serializer>::Ok, <__S as Serializer>::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<S, T> Duplex<S> for T
where T: FromSample<S> + ToSample<S>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<S> FromSample<S> for S

Source§

fn from_sample_(s: S) -> S

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<F, T> IntoSample<T> for F
where T: FromSample<F>,

Source§

fn into_sample(self) -> T

Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<R, P> ReadPrimitive<R> for P
where R: Read + ReadEndian<P>, P: Default,

Source§

fn read_from_little_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_little_endian().
Source§

fn read_from_big_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_big_endian().
Source§

fn read_from_native_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_native_endian().
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> ToSample<U> for T
where U: FromSample<T>,

Source§

fn to_sample_(self) -> U

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more