module
CrShader::Docs::E_OUTPUT_COMPARISONS::A_SIDE_BY_SIDE_COMPARISONS
Overview
Complete CRShader Side-by-Side Output Atlas
This atlas showcases every special language, optimizer, debugging, and code-generation feature of CRShader alongside the exact code emitted by its transpiler backends:
- Godot 4 GDShader (
.gdshader) forspatial,canvas_item,particles,sky, andfogpipelines. - Godot 4 Header Libraries (
.gdshaderinc) with#ifndefguards and shared structs/classes/helpers. - Vulkan GLSL 450 (
.glsl) for Godot 4.8CompositorEffectpost-processing passes and parallelRenderingDevicecompute kernels. - Production Specialized & Minified Outputs (
--release -O/-D) demonstrating dead-uniform tree-shaking and zero-costinspect()probe stripping. - Lapis
@[Tool]Host Nodes (.cr) synthesized automatically viagenerate_node.
Executive Summary & Key Topics
| Topic | Method / Anchor | Description |
|---|---|---|
| Classes, Structs, Constructors & Instance Methods | .topic_01_classes_and_methods |
Encapsulating shader data and behavior with Crystal class, struct, and record blocks lowered to GDShader, GDShaderInc, and GLSL. |
| Type Inference, Branch Hoisting, Expressions & Loops | .topic_02_type_inference_and_control_flow |
How Crystal assignments, if/else variable scoping, range iterators, case/when, and implicit returns transpile to C-family shader syntax. |
| Fluent UFCS & Artist Method Chains | .topic_03_fluent_ufcs_and_artist_chains |
Left-to-right method chaining for UV warping, texture sampling, Photoshop-style blend modes, color grading, and IEEE-754 bitcasts. |
| Typed Uniforms, Inspector Groups, Palettes & Vulkan Layout Packing | .topic_04_uniforms_groups_palettes_and_packing |
How nested uniform groups, doc comments, hex colors, palette arrays, and Vulkan std430/std140 layouts compile across GDShader and GLSL. |
| Declarative Shader Archetypes | .topic_05_shader_archetypes |
Zero-boilerplate domain blocks (sprite_effect, ui_effect, screen_effect, surface_material) that hoist uniforms and synthesize pipeline boilerplate. |
| Composable shader_trait & Hygienic use_trait Fusion | .topic_06_traits_and_cross_target_fusion |
Fusing reusable vertex, fragment, light, and cross-target pixel traits with automatic prefix namespacing and AST local-variable hygiene. |
| Compile-Time Macros, feature Specialization & Dead-Uniform Tree-Shaking | .topic_07_macros_features_and_tree_shaking |
Unrolling loops with Crystal macros, specializing variants with feature/when_feature, and automatically pruning unreachable uniforms and helpers. |
| Analytical Perceptual Oklab Gradients & Smooth Curves | .topic_08_gradients_and_curves |
Compiling multi-stop color ramps (sRGB, Linear, Oklab) and easing curves into zero-texture, branchless GPU functions. |
| One-Line inspect() Visual Debugger vs --release -O Stripping | .topic_09_visual_inspector_and_release_stripping |
Live in-viewport variable heatmaps and NaN/Inf detection during development, stripped to zero GPU cost in production release builds. |
| Godot 4.8 compositor_effect, compute_kernel & particle_simulation | .topic_10_compositor_compute_and_particles |
High-level DSLs for RenderingDevice post-processing passes, scene camera UBOs, and std430 GPU particle simulations. |
| Reusable .gdshaderinc Headers & Multi-Target emit_target | .topic_11_gdshaderinc_and_multi_target_emit |
Emitting #ifndef-guarded .gdshaderinc libraries and multiple feature-specialized shader files from a single .crshader source. |
| Automatic Lapis @[Tool] Host Node Synthesis (generate_node) | .topic_12_host_node_generation |
Synthesizing complete Crystal Godot 4 nodes (CompositorEffect, MeshInstance3D, CanvasLayer, ComputeParticles) directly from .crshader uniforms. |
Related Guides & Source References
- src/crshader/compiler.cr
- src/crshader/parser/class_lowering.cr
- src/crshader/parser/archetypes.cr
- src/crshader/composer/trait_fuser.cr
- src/crshader/language/gradients_and_curves.cr
- src/crshader/extensions/visual_inspector_extension.cr
- src/crshader/generator/node_generator.cr
Defined in:
docs/e_output_comparisons/a_side_by_side_comparisons.crClass Method Summary
-
.topic_01_classes_and_methods : Nil
Classes, Structs, Constructors & Instance Methods: Encapsulating shader data and behavior with Crystal class, struct, and record blocks lowered to GDShader, GDShaderInc, and GLSL.
-
.topic_02_type_inference_and_control_flow : Nil
Type Inference, Branch Hoisting, Expressions & Loops: How Crystal assignments, if/else variable scoping, range iterators, case/when, and implicit returns transpile to C-family shader syntax.
-
.topic_03_fluent_ufcs_and_artist_chains : Nil
Fluent UFCS & Artist Method Chains: Left-to-right method chaining for UV warping, texture sampling, Photoshop-style blend modes, color grading, and IEEE-754 bitcasts.
-
.topic_04_uniforms_groups_palettes_and_packing : Nil
Typed Uniforms, Inspector Groups, Palettes & Vulkan Layout Packing: How nested uniform groups, doc comments, hex colors, palette arrays, and Vulkan std430/std140 layouts compile across GDShader and GLSL.
-
.topic_05_shader_archetypes : Nil
Declarative Shader Archetypes: Zero-boilerplate domain blocks (sprite_effect, ui_effect, screen_effect, surface_material) that hoist uniforms and synthesize pipeline boilerplate.
-
.topic_06_traits_and_cross_target_fusion : Nil
Composable shader_trait & Hygienic use_trait Fusion: Fusing reusable vertex, fragment, light, and cross-target pixel traits with automatic prefix namespacing and AST local-variable hygiene.
-
.topic_07_macros_features_and_tree_shaking : Nil
Compile-Time Macros, feature Specialization & Dead-Uniform Tree-Shaking: Unrolling loops with Crystal macros, specializing variants with feature/when_feature, and automatically pruning unreachable uniforms and helpers.
-
.topic_08_gradients_and_curves : Nil
Analytical Perceptual Oklab Gradients & Smooth Curves: Compiling multi-stop color ramps (sRGB, Linear, Oklab) and easing curves into zero-texture, branchless GPU functions.
-
.topic_09_visual_inspector_and_release_stripping : Nil
One-Line inspect() Visual Debugger vs --release -O Stripping: Live in-viewport variable heatmaps and NaN/Inf detection during development, stripped to zero GPU cost in production release builds.
-
.topic_10_compositor_compute_and_particles : Nil
Godot 48 compositor_effect, compute_kernel & particle_simulation: High-level DSLs for RenderingDevice post-processing passes, scene camera UBOs, and std430 GPU particle simulations.
-
.topic_11_gdshaderinc_and_multi_target_emit : Nil
Reusable gdshaderinc Headers & Multi-Target emit_target: Emitting #ifndef-guarded .gdshaderinc libraries and multiple feature-specialized shader files from a single .crshader source.
-
.topic_12_host_node_generation : Nil
Automatic Lapis @[Tool] Host Node Synthesis (generate_node): Synthesizing complete Crystal Godot 4 nodes (CompositorEffect, MeshInstance3D, CanvasLayer, ComputeParticles) directly from .crshader uniforms.
Class Method Detail
Classes, Structs, Constructors & Instance Methods: Encapsulating shader data and behavior with Crystal class, struct, and record blocks lowered to GDShader, GDShaderInc, and GLSL.
CRShader lets you author object-oriented class, struct, and one-line record types with typed fields, custom initialize constructors, def self.* static factory methods, predicate ? methods, and mutating ! methods.
Because GPU shading languages lack heap allocations and struct member functions, ClassLoweringPass compiles every class or struct into a native value struct plus tree-shaken free functions:
- Read-only methods pass
_selfby value (FresnelRim _self). - Mutating methods (writing
@field = ...,@field *= ..., or calling another mutating sibling) automatically emitinout FresnelRim _self. - Crystal
?and!suffixes sanitize cleanly to C-valid identifiers (active?->LightProbe_is_active,boost!->FresnelRim_boost). - Default arguments &
initializeexpand at call sites so GDShader and GLSL never see unsupported default parameter syntax.
Side-by-Side Output Comparison
boost! automatically acquires inout FresnelRim _self, while the unreferenced debug_luma method is stripped from both .gdshader and .glsl.- Inside instance methods, both
@colorinstance-variable syntax and barecolorgetter syntax resolve to_self.color. - In GLSL 450 compute kernels,
uniform rim_boostis automatically packed intolayout(push_constant, std430) uniform CrShaderParams.
shader :gdshaderinc retains all public structs and lowered class helpers inside an #ifndef include guard.- Omitted default arguments (
LightProbe.newandprobe.scaled) are filled at each call site (LightProbe__new(1.0)andLightProbe_scaled(probe, 2.0)).
Type Inference, Branch Hoisting, Expressions & Loops: How Crystal assignments, if/else variable scoping, range iterators, case/when, and implicit returns transpile to C-family shader syntax.
In Crystal, variables do not require explicit type keywords on first assignment, variables assigned inside if/else branches remain in scope afterward, and the last expression of a typed def is returned implicitly. CRShader's SymbolTable and BaseVisitor bridge all of these idioms cleanly to strict C-style shader scopes:
- First-assignment inference:
sum = 0.0emitsfloat sum = 0.0;, while subsequent writes emitsum = ...;. - Branch variable hoisting: Assigning a new local variable (
band) inside anif/elsestatement hoistsfloat band;above theifblock so C/GLSL block scoping never hides it. - **Idiomatic loops & control flow**: `(0...4).each` and `n.times` become `for` loops, `unless` / `until` negate cleanly, `case`/`when` emits `switch`/`case` with automatic `break;
, andx ** ylowers topow(x, y)`.
Side-by-Side Output Comparison
canvas_item GDShader and Vulkan GLSL 450.InOut(Vec2)andOut(T)parameter wrappers emitinout vec2andout Tacross all backends.- Type cast methods
.to_f,.to_i,.to_u, and.to_bmap directly tofloat(...),int(...),uint(...), andbool(...).
Fluent UFCS & Artist Method Chains: Left-to-right method chaining for UV warping, texture sampling, Photoshop-style blend modes, color grading, and IEEE-754 bitcasts.
Deeply nested shader calls like blend_overlay_rgba(hue_shift_rgba(adjust_contrast_rgba(texture(tex, uv), 1.15), 0.08), tint, 0.65) are hard to read and edit. CRShader supports left-to-right fluent method chains backed by automatic TreeShaker dependency injection:
- Texture methods:
.sample(uv),.sample_lod(uv, lod),.fetch(coord, lod),.size. - UV transforms:
.tile(scale),.scroll(vx, vy[, t]),.offset(dx, dy),.rotate(angle[, pivot]),.pixelate(steps),.polar([center]),.wave(freq, amp[, phase]). - Color & blend pipelines:
.contrast(k),.saturate_color(s),.hue_shift(a),.luminance,.posterize(steps),.one_minus, and.blend(:multiply | :screen | :overlay | :hard_light | :soft_light | :color_dodge | :color_burn | :difference | :exclusion | :add, top, opacity). - Math & bitcasts:
.saturate,.lerp(b, t),.remap(in0, in1, out0, out1),.to_bits_u32,.to_bits_i32,.from_bits_f32.
Side-by-Side Output Comparison
uv_wave, adjust_contrast_rgba, hue_shift_rgba, blend_overlay_rgba, remap) are emitted.- Receiver type inference (
vec3vsvec4) automatically selects RGB vs alpha-preserving RGBA helpers (e.g.blend_overlay_rgbavsblend_overlay_opacity).
Typed Uniforms, Inspector Groups, Palettes & Vulkan Layout Packing: How nested uniform groups, doc comments, hex colors, palette arrays, and Vulkan std430/std140 layouts compile across GDShader and GLSL.
CRShader unifies Godot Inspector ergonomics with Vulkan RenderingDevice descriptor layout rules from a single declaration syntax:
- Inspector Groups & Doc Harvesting**: `group` / `subgroup` blocks emit balanced `group_uniforms Group.Subgroup;
directives, and# commentsdirectly above uniforms emit/ ... */` Godot Inspector tooltips. - **Hex & Palette Resources**: `Color.hex("#rrggbb")` converts hex strings to normalized floats at compile time;
PackedColorArray[...]andresource("res://palette.tres")synthesizeconst int <name>_size = N;plus typed uniform arrays. - Deterministic GLSL Layout Packing (
GLSLLayoutPacker): When compiling to.glsl, opaque samplers receive non-collidingset = 0, binding = Nslots, compact scalar/vector blocks (<= 128bytes, no arrays) pack intolayout(push_constant, std430) uniform CrShaderParams, and array/large blocks automatically upgrade tolayout(set = 1, binding = 0, std140) uniform CrShaderUniforms.
Side-by-Side Output Comparison
push_constant block when targeting GLSL.PackedColorArray synthesizes palette_size and automatically promotes the GLSL block to set = 1, binding = 0, std140.Declarative Shader Archetypes: Zero-boilerplate domain blocks (sprite_effect, ui_effect, screen_effect, surface_material) that hoist uniforms and synthesize pipeline boilerplate.
Archetypes eliminate repetitive Godot setup code while allowing property, sampler, class, and def declarations right inside the block:
sprite_effect: Setsshader_type canvas_item, samplesTEXTURE * COLOR, optionally exposesTEXTURE_PIXEL_SIZE, and binds the final expression toCOLOR.ui_effect: Computes screen-space UV derivatives (dFdx/dFdy) so SDF circles, rings, and borders stay circular even on stretched non-squareControlnodes.screen_effect: Supports both 2Dcanvas_itemand 3Dmode: :spatial, depth: truefull-screen post-process quads (auto-emittingPOSITION = vec4(VERTEX.xy, 1.0, 1.0),screen_texture, anddepth_texture).surface_material: Configures curated 3Drender_modepresets (:pbr,:toon,:glass,:foliage,:unshaded).
Side-by-Side Output Comparison
sprite_effect and aspect-corrected ui_effect GDShader outputs.screen_effect mode: :spatial, depth: true automatically generates the clip-space quad vertex() stage, render modes, and screen/depth samplers.Composable shader_trait & Hygienic use_trait Fusion: Fusing reusable vertex, fragment, light, and cross-target pixel traits with automatic prefix namespacing and AST local-variable hygiene.
Unlike #include files (which cannot merge logic into vertex() or fragment() and collide when included twice), shader_trait and use_trait fuse modular effects at the AST level:
- Cross-Target
on_pixelHooks: Built-in post-processing traits (vignette,chromatic_aberration,color_grade,film_grain,shockwave_ripple) compile seamlessly into both 2D/3D.gdshaderscreen passes (texture(screen_texture, ...)) and Godot 4.8 Vulkan.glslcompositor passes (imageLoad(color_image, ...)). - Multi-Instance
prefix:Namespacing & Hygiene: Applying the same trait twice (prefix: :keyandprefix: :fill) namespaces every uniform, group, constant, struct, helper, and stage-local variable (_key_rim_fresnel_f1_0_ndotv) so local declarations never collide.
Side-by-Side Output Comparison
chromatic_aberration and prefixed vignette fuse cleanly into both a CanvasItem screen shader and a RenderingDevice compute compositor pass.rim_fresnel twice with prefix: :key and prefix: :fill creates isolated Inspector groups (Key_RimFresnel, Fill_RimFresnel) and collision-free locals.Compile-Time Macros, feature Specialization & Dead-Uniform Tree-Shaking: Unrolling loops with Crystal macros, specializing variants with feature/when_feature, and automatically pruning unreachable uniforms and helpers.
Traditional uber-shaders litter code with #ifdef tangles and keep dead uniforms bound in the material inspector even when features are disabled. CRShader evaluates macro, {% for %}, {% if IS_GLSL %}, feature, and when_feature / unless_feature at compile time, and then runs TreeShaker to strip both unreachable helper functions and unused uniforms/samplers!
Side-by-Side Output Comparison
-D rim=false -D quality=low), sample_detail, detail_tex, AND rim_color are completely eliminated from the compiled shader.- Run
crshader matrix shader.crshader -o variants/to precompile the Cartesian product of all boolean and enumfeaturecombinations.
Analytical Perceptual Oklab Gradients & Smooth Curves: Compiling multi-stop color ramps (sRGB, Linear, Oklab) and easing curves into zero-texture, branchless GPU functions.
Sampling 1D GradientTexture1D / CurveTexture resources consumes texture binding slots and suffers from 8-bit banding. CRShader's gradient and curve directives convert hex/RGBA color stops into Oklab (or linear/sRGB) at compile time and synthesize pure ALU functions (mix + smoothstep / step / linear) with cubic Oklab-to-linear-RGB reconstruction—working identically in .gdshader and .glsl compute shaders!
Side-by-Side Output Comparison
mix and cubic LMS matrix math.- When you do need CPU evaluation or a baked texture,
CrShader::ProceduralLUT.sample_gradient_bytesevaluates the exact same Oklab math on the CPU.
One-Line inspect() Visual Debugger vs --release -O Stripping: Live in-viewport variable heatmaps and NaN/Inf detection during development, stripped to zero GPU cost in production release builds.
Debugging intermediate shader values usually means commenting out final math and writing temporary COLOR = vec4(...) hacks. Wrapping any expression or variable in inspect(:label, expr):
- Captures the intermediate value without altering downstream math.
- Injects a
DebugInspector group withuniform int debug_view : hint_enum("Off", ..., "NaN_Inf_Detector"). - Renders type-aware visualizations: magenta checkerboard on
NaN/Inf, cyan heatmap for negative floats (< 0.0), amber/red heatmap for HDR values (> 1.0), and UV cell grids forvec2. - Strips 100% of probes and the
debug_viewuniform when compiled with--release(-r), while-O(--optimize-names) minifies local variables to_v0,_v1!
Side-by-Side Output Comparison
Godot 48 compositor_effect, compute_kernel & particle_simulation: High-level DSLs for RenderingDevice post-processing passes, scene camera UBOs, and std430 GPU particle simulations.
Authoring raw Vulkan compute shaders for Godot 4.8's CompositorEffect or RenderingDevice normally requires manual descriptor set indices, std140 camera matrix UBO alignment, pixel bounds guards, and packed vec4 SSBO unpacking. CRShader automates all of it:
compositor_effect: Declares workgroup sizes, bindscolor_image(set = 0, binding = 0),depth_texture(binding = 1),normal_roughness_texture(binding = 2), andCrShaderSceneData(binding = 3wheneverINV_PROJECTION_MATRIX,VIEWPORT_SIZE, orTIMEis used).particle_simulation&step_particles: Synthesizes thestd430ParticleBufferSSBO,SimParamspush constant, bounds check,pos/vel/lifeunpacking/repacking, and pulls physics helpers fromstd/particles.
Side-by-Side Output Comparison
INV_PROJECTION_MATRIX and TIME automatically synthesizes the 16-byte-padded CrShaderSceneData std140 uniform buffer at set = 0, binding = 3.positions[idx] (.xyz + life in .w) and velocities[idx], injects attract_point / apply_linear_drag / integrate_euler from std/particles, and writes back updated state.Reusable gdshaderinc Headers & Multi-Target emit_target: Emitting #ifndef-guarded .gdshaderinc libraries and multiple feature-specialized shader files from a single .crshader source.
With emit_target, a single .crshader file can simultaneously generate a reusable .gdshaderinc header (for mixed GDScript/GDShader teams) and multiple specialized .gdshader or .glsl variants whenever you save in the Godot 4.8 Shader Editor tab or run crshader bundle:
.gdshaderincEmitter: Stripsshader_type,render_mode, and processor entry points (vertex/fragment/light), closes trailinggroup_uniforms;, and wraps structs, constants, uniforms, varyings, and helpers in#ifndef <NAME>_GDSHADERINC.- Signature Reader: Consumer
.crshaderfiles that callinclude "res://shared/cel_lighting.gdshaderinc"automatically parse the header's structs, constants, and function return types for type inference!
Side-by-Side Output Comparison
cel.crshader emits shared/cel_lighting.gdshaderinc, cel_standard.gdshader (with rim_energy pruned), and cel_hero.gdshader in one pass.Automatic Lapis @[Tool] Host Node Synthesis (generate_node): Synthesizing complete Crystal Godot 4 nodes (CompositorEffect, MeshInstance3D, CanvasLayer, ComputeParticles) directly from .crshader uniforms.
Adding generate_node inside a .crshader file (or running crshader generate-node scanline.crshader -t compositor) bridges GPU shaders and CPU gameplay code with zero manual glue:
- Harvests uniform types, defaults,
# doc comments,range:sliders,enumhints, andColorPalettearrays into typed Lapis@[Export]properties. - For
:compositor, embeds the compiled#version 450GLSL string directly into the Crystal class, implements_render_callback, bindsRenderSceneBuffersRDlayers across stereo/mono views, and packs scalar/vector properties at exactGLSLLayoutPackerbyte offsets!
Side-by-Side Output Comparison
@intensity (offset 0) and @line_count (offset 4) in apply_parameters match CrShaderParams (std430) byte-for-byte.NodeGeneratorsupports 5 host targets::mesh3d(MeshInstance3D),:canvas2d(CanvasLayer),:compositor(CompositorEffect),:particles(Node3Dcompute dispatcher), and:host(Node).