module CrShader::Language::PreProcessors

Overview

Compiler directives, storage qualifiers, uniform options, and pipeline flags.

This module defines the top-level declarative syntax used in .crshader files. During compilation, these directives configure shader targets, memory layouts, and expose properties to the Godot Inspector.

Basic Example

shader_type :canvas_item
render_mode :unshaded, :blend_mix

uniform screen_texture : Sampler2D, hint: :screen_texture, filter: :linear
uniform intensity : Float32 = 1.0, hint: hint_range(0.0, 5.0)

def fragment
  col = screen_texture.sample(SCREEN_UV).rgb
  COLOR = vec4(col * intensity, 1.0)
end

Extended Modules

Direct including types

Defined in:

crshader/language/preprocessors.cr

Macro Summary

Instance Method Summary

Macro Detail

macro buffer(name, **options, &block) #

Shader Storage Buffer (SSBO): Declares a structured storage buffer for compute and storage.

Transpiled to Vulkan GLSL layout(std430, set = X, binding = Y) buffer ....

Options:

  • set: Vulkan descriptor set index (default: 0).
  • binding: Vulkan descriptor binding slot index (default: 0).
  • std: Memory layout standard ("std430" or "std140", default: "std430").
  • restrict: Informs compiler that memory does not alias other pointers.
  • readonly: Marks the buffer as read-only for hardware caching optimizations.

Example:

buffer ParticleBuffer, set: 0, binding: 0, std: "std430" do
  particles : ParticleData[]
end

macro const(declaration) #

Compile-Time Constant: Declares a static compile-time constant.

Evaluated and emitted as a const expression in the target shader.

Example:

const PI = 3.14159265359_f32
const MAX_LIGHTS = 8

macro constant(declaration) #

Alias for const.


macro global_uniform(declaration, **options) #

Global Uniform: Declares a project-wide global uniform registered in Project Settings.

Global uniforms (Godot 4.x) are shared across all materials in the game simultaneously with zero CPU overhead. Useful for wind direction, player position, or time of day.

Transpiled to Godot's global uniform ....

Example:

global_uniform global_wind_dir : Vec3
global_uniform global_water_level : Float32

macro image2d(name, **options) #

Image Uniform: Declares a direct read/write texture image binding for compute shaders.

Enables direct pixel access via imageLoad and imageStore.

Options:

  • format: Vulkan pixel format (:rgba32f, :rgba16f, :r32f, :r32ui, default: :rgba32f).
  • set: Vulkan descriptor set index (default: 0).
  • binding: Vulkan descriptor binding index (default: 0).

Example:

image2d input_tex, format: :rgba32f, set: 0, binding: 0
image2d output_tex, format: :rgba32f, set: 0, binding: 1

macro include(path) #

Alias for require.


macro instance_uniform(declaration, **options) #

Instance Uniform: Declares a per-instance uniform stored in InstanceData.

Instance uniforms allow multiple nodes sharing the same material (e.g. MultiMeshInstance3D or multiple MeshInstance3D nodes) to have unique values without duplicating the material.

Transpiled to Godot's instance uniform ....

Example:

instance_uniform custom_tint : Color = Color.new(1.0, 1.0, 1.0, 1.0), hint: :source_color
instance_uniform instance_offset : Vec3 = vec3(0.0, 0.0, 0.0)

macro push_constant(name, **options, &block) #

Push Constant Block: Declares a low-latency Vulkan push constant block.

Push constants are stored directly in GPU command registers for maximum transmission speed.

Example:

push_constant FrameUniforms do
  delta_time : Float32
  screen_size : Vec2
end

macro require(path) #

Module Inclusion: Imports standard library routines or local shader definitions.

Available Standard Library Modules:

Module Path Included Features
"std/math"saturate, lerp, remap, rotate_2d, fresnel, rand
"std/noise"hash11..33, value_noise, voronoi, simplex_noise_2d, fbm
"std/color"hsv2rgb, rgb2hsv, grayscale, adjust_contrast, adjust_saturation
"std/lighting"cel_shade, blinn_phong
"std/sdf"sdf_sphere, sdf_box, smin, smax
"std/tonemap"aces_tonemap, reinhard_tonemap
"std/triplanar"triplanar_weights
"std/post_processing"linear_depth, luminance, barrel_distortion, vignette

Example:

require "std/noise"
require "std/lighting"

macro shared(declaration) #

Workgroup Shared Memory: Declares memory shared among compute threads in a workgroup.

Accessible to all invocations in the current local workgroup. Much faster than VRAM.

Example:

shared tile_cache : UInt32[256]

macro uniform(declaration, **options) #

Material Uniform: Declares a variable exposed to the Godot Inspector and script API.

Uniforms allow runtime scripts and material properties in the editor to pass values into the shader.

Inspector Hints & Options:

Option Type Description
hint: :source_colorColor / Vec4Displays a color picker and converts sRGB to linear color space.
hint: hint_range(min, max, step)Float32 / Int32Renders a slider with custom bounds and step granularity.
hint: :screen_textureSampler2DBinds the current viewport rendered screen texture.
hint: :depth_textureSampler2DBinds the linear / non-linear depth buffer texture.
hint: :normal_roughness_textureSampler2DBinds the screen-space normal and roughness buffer.
hint: :white / :blackSampler2DProvides a fallback solid white or solid black texture if unassigned.
filter: :nearest / :linearSampler2DSpecifies texture pixel interpolation mode.
filter: :nearest_mipmap / :linear_mipmapSampler2DEnables mipmap sampling for textures.
repeat: :enable / :disableSampler2DSpecifies texture UV tiling and repeating mode.
group: "Name"StringPlaces the property inside an inspector accordion group.
subgroup: "Name"StringPlaces the property inside an inspector subgroup.

Examples:

uniform albedo : Color = Color.new(1.0, 0.5, 0.2, 1.0), hint: :source_color
uniform wave_speed : Float32 = 2.5, hint: hint_range(0.0, 10.0, 0.1)
uniform roughness : Float32 = 0.5, hint: hint_range(0.0, 1.0)
uniform base_texture : Sampler2D, filter: :linear_mipmap, repeat: :enable
uniform bone_matrices : Mat4[64] # Array uniform

macro varying(declaration, **options) #

Varying Variable: Declares an interpolated variable passed between shader stages.

Varying variables are calculated in the vertex processor and smoothly interpolated across polygon faces before arriving at the fragment or light processors.

Interpolation Qualifiers:

  • :smooth: Standard perspective-correct interpolation (default).
  • :flat: No interpolation; uses the value from the primitive's first vertex.

Example:

varying v_world_pos : Vec3
varying v_normal : Vec3, qualifier: :smooth
varying v_tile_id : Int32, qualifier: :flat

def vertex
  v_world_pos = (MODEL_MATRIX * vec4(VERTEX, 1.0)).xyz
  v_normal = (MODEL_MATRIX * vec4(NORMAL, 0.0)).xyz
end

def fragment
  dist = length(v_world_pos)
end

Instance Method Detail

def group(name : String) : Nil #

Inspector Group: Groups subsequent uniforms under a categorized accordion section.

Example:

group "Water Dynamics"
uniform wave_height : Float32 = 0.5
uniform wave_speed : Float32 = 1.0

def local_size(x : Int32 = 8, y : Int32 = 8, z : Int32 = 1) : Nil #

Workgroup Layout: Specifies compute shader local invocation workgroup size.

Transpiled to GLSL layout(local_size_x = X, local_size_y = Y, local_size_z = Z) in;.

Parameters:

  • x: Number of invocations in the X dimension (default: 8).
  • y: Number of invocations in the Y dimension (default: 8).
  • z: Number of invocations in the Z dimension (default: 1).

Example:

shader_type :compute
local_size 16, 16, 1

def render_mode(*modes : Symbol) : Nil #

Render Modes: Specifies engine pipeline flags and rendering optimizations.

Render modes tell Godot how to configure the hardware rasterizer, blend states, face culling, and depth testing before executing shader stages.

Spatial Render Modes (:spatial):

Mode Description
:unshadedDisables all lighting calculations; ALBEDO is drawn directly.
:wireframeRenders geometry in wireframe mode (debug / stylized).
:cull_disabledDisables backface culling; renders both sides of triangles.
:cull_frontCulls front faces (renders back faces only, useful for outlines).
:cull_backCulls back faces (standard default).
:depth_draw_opaqueDraws depth only for opaque pixels (default).
:depth_draw_alwaysAlways writes depth buffer, even for transparent surfaces.
:depth_draw_neverNever writes depth buffer.
:depth_prepass_alphaPerforms an early depth prepass for alpha testing.
:blend_mixStandard alpha blending: src * alpha + dst * (1 - alpha).
:blend_addAdditive blending: src + dst (fire, lasers, magic effects).
:blend_subSubtractive blending: dst - src.
:blend_mulMultiplicative blending: src * dst (shadows, decals).
:fog_disabledIgnores volumetric and environmental fog.
:shadows_disabledSurface neither receives nor casts real-time shadows.

CanvasItem Render Modes (:canvas_item):

Mode Description
:unshadedDisables 2D canvas lighting.
:blend_mixStandard 2D alpha blending.
:blend_add2D additive glow blending.
:blend_sub2D subtractive blending.
:blend_mul2D multiplicative blending.
:blend_premul_alphaPre-multiplied alpha blending.
:skip_vertex_transformBypasses engine modelview transformation in vertex stage.

Example:

render_mode :unshaded, :cull_disabled, :depth_draw_always

def setup_gdshader : Nil #

Compatibility Setup: Enables standard Godot GDShader macros and compatibility helpers.

Synthesizes helper definitions allowing smooth interoperation with legacy Godot shaders.


def shader_type(mode : Symbol) : Nil #

Shader Target: Specifies the operating mode of the shader pipeline.

Godot divides shaders into distinct operational categories. Setting #shader_type selects which built-in variables are accessible and which renderer pipeline executes the code.

Supported Shader Modes:

Mode Symbol Target Pipeline Applicable Nodes
:spatial 3D spatial rendering pipeline (PBR lighting, vertex displacement) MeshInstance3D, CSGShape3D, GPUParticles3D
:canvas_item 2D canvas rendering pipeline (screen-space, UI, sprites) Sprite2D, Control, ColorRect, TextureRect, SubViewport
:particles GPU particle simulation and update step GPUParticles2D, GPUParticles3D
:sky Background radiance and panoramic sky dome renderer Sky, Environment, WorldEnvironment
:fog 3D volumetric fog density and scattering voxel renderer FogVolume
:compute Vulkan compute shader (GPGPU computation, image processing) RenderingDevice, Compute pipelines

Example:

shader_type :spatial

def subgroup(name : String) : Nil #

Inspector Subgroup: Groups subsequent uniforms under an inspector subsection.

Example:

subgroup "Foam Parameters"
uniform foam_color : Color = Color.new(1.0, 1.0, 1.0, 1.0)
uniform foam_threshold : Float32 = 0.8