godot-shaders-basics

$npx mdskill add thedivergentai/GD-Agentic-Skills/godot-shaders-basics

Provides expert Godot shader patterns for batching, postFX, and depth.

  • Prevents draw-call batching breaks and foliage shadow issues.
  • Uses instance uniforms, ALPHA_SCISSOR, and screen textures.
  • Recommends patterns based on Godot 4.7+ and performance pitfalls.
  • Delivers ready-to-use shader code and migration notes.

SKILL.md

.github/skills/godot-shaders-basicsView on GitHub ↗
---
name: godot-shaders-basics
description: "Expert Godot shader patterns for batch-safe hitflash, alpha-scissor foliage/dissolve, screenspace postFX, depth reconstruction, triplanar, and instance uniforms — not first-shader tutorials. Trigger on draw-call batching breaks, discard vs depth-prepass, foliage shadows, post-process quads, or world-position FX. Keywords: instance uniform, ALPHA_SCISSOR, hint_screen_texture, hint_depth_texture, global uniform, sampler2DArray, canvas_item, spatial, post-processing."
---
## Godot 4.7 Baseline

- Expert patterns target **Godot 4.7+** (stable, 2026-06-18).
- Consult the [Godot 4.7 migration guide](https://docs.godotengine.org/en/4.7/tutorials/migrating/upgrading_to_godot_4.7.html) when upgrading from 4.6.
- `LinearToSRGB` visual-shader node no longer clamps to `[0,1]` on Mobile/Forward+.
- Drawable Texture API for custom render targets; `get_format()` lives on **Texture2D** base for `ImageTexture` / `PortableCompressedTexture2D`.
- **NEVER** assume 4.6 defaults without checking 4.7 migration notes.

# Shader Expert Patterns

Batching-safe materials, scissor/dissolve, screenspace FX, and depth reconstruction — Official Docs cover first shaders and built-in glossaries.

## NEVER Do in Shaders

- **NEVER use `discard` unconditionally for optimization** — It prevents the depth prepass from working effectively. A discarded pixel still costs vertex processing; sometimes not rendering the object is better [1].
- **NEVER use `if/else` for dynamic states in high-performance shaders** — GPUs hate branching. Use `mix()`, `step()`, and `smoothstep()` for mathematical, hardware-optimized selection [5, 21].
- **NEVER compare floats exactly** — Hardware precision varies; `if (v == 0.5)` is unreliable. Use `abs(a - b) < epsilon` or `step()`.
- **NEVER use standard Alpha Blending for massive foliage** — It prevents shadows and SSR. Use Alpha Scissor or Alpha Hash (dithering) to enable depth prepass and shadow casting [7].
- **NEVER hardcode `POSITION` to `vec4(VERTEX, 1.0)` for full-screen quads in 4.3+** — Godot 4.3 uses Reversed-Z depth; this will cause clipping. Use `POSITION = vec4(VERTEX.xy, 1.0, 1.0)` [8, 9].
- **NEVER duplicate materials to change one color/value on many enemies** — Use `instance uniform`. This allows unique values for thousands of nodes while maintaining a single draw call (batching) [10].
- **NEVER use `TIME` without a speed multiplier** — Fragment speed should be controllable via uniforms to ensure consistency across different gameplay states.
- **NEVER forget `hint_source_color` for color uniforms** — Without it, the engine treats colors as linear math, leading to incorrect gamma and washed-out visuals in the inspector.
- **NEVER calculate complex math in `fragment()` that could be in `vertex()`** — `vertex()` runs once per point; `fragment()` runs millions of times per frame. Interpolate values via `varying` instead.
- **NEVER use `#define` macros for dynamic runtime toggles** — These create new shader permutations, causing massive compilation stutters when first encountered in-game. Use uniforms instead.
- **NEVER forget to normalize vectors** — Using `reflect(dir, normal)` on unnormalized vectors causes severe rendering artifacts and incorrect lighting math.
- **NEVER modify UV without bounds checking or `fract()`** — Shifting UVs beyond 0.0-1.0 without `repeat` wrapping or clamping will sample edge pixels or return black, breaking texture consistency.


## Scenario → Script Triggers

> **MANDATORY** for the matching effect. **Do NOT Load** beginner canvas_item tint recipes or built-in variable glossaries here.

| Goal | Script |
|------|--------|
| Per-enemy hitflash without breaking batches | **MANDATORY** [instance_uniform_hitflash.gdshader](scripts/instance_uniform_hitflash.gdshader) |
| Foliage wind + shadows | **MANDATORY** [foliage_wind_sway_expert.gdshader](scripts/foliage_wind_sway_expert.gdshader) (alpha scissor/hash — not unconditional `discard`) |
| Dissolve that keeps depth-prepass | **MANDATORY** [dissolve_scissor_expert.gdshader](scripts/dissolve_scissor_expert.gdshader) |
| PostFX pixelate / stylize | **MANDATORY** [screenspace_hex_pixelate.gdshader](scripts/screenspace_hex_pixelate.gdshader) |
| Full-screen quad (Reversed-Z) | **MANDATORY** [screenspace_full_quad.gdshader](scripts/screenspace_full_quad.gdshader) |
| Depth → world for water/fog | **MANDATORY** [depth_world_reconstruction.gdshader](scripts/depth_world_reconstruction.gdshader) |
| Grass flatten from player | [global_grass_flatten.gdshader](scripts/global_grass_flatten.gdshader) |
| UV-less cliffs/rocks | [triplanar_world_mapping.gdshader](scripts/triplanar_world_mapping.gdshader) |
| Unique textures on instanced meshes | [instance_texture_array.gdshader](scripts/instance_texture_array.gdshader) |
| Vertex displacement terrain | [noise_terrain_displacement.gdshader](scripts/noise_terrain_displacement.gdshader) |
| Animate uniforms at runtime | [shader_parameter_animator.gd](scripts/shader_parameter_animator.gd) |
| VFX port template | [vfx_port_shader.gdshader](scripts/vfx_port_shader.gdshader) |

**Golden path for cutouts/dissolve:** `ALPHA_SCISSOR` / alpha hash (see dissolve + foliage scripts) — not `discard` for optimization. NEVER list explains why.

## Available Scripts

### [instance_uniform_hitflash.gdshader](scripts/instance_uniform_hitflash.gdshader)
Instance-uniform flashes; one material, many unique intensities.

### [dissolve_scissor_expert.gdshader](scripts/dissolve_scissor_expert.gdshader)
Mask dissolve with `ALPHA_SCISSOR` for depth-prepass + shadows.

### [foliage_wind_sway_expert.gdshader](scripts/foliage_wind_sway_expert.gdshader)
World-space wind sway for foliage batches.

### [global_grass_flatten.gdshader](scripts/global_grass_flatten.gdshader)
`global uniform` player interaction flattening grass.

### [screenspace_hex_pixelate.gdshader](scripts/screenspace_hex_pixelate.gdshader)
`hint_screen_texture` stylized postFX.

### [screenspace_full_quad.gdshader](scripts/screenspace_full_quad.gdshader)
Reversed-Z-safe full-rect post pass.

### [depth_world_reconstruction.gdshader](scripts/depth_world_reconstruction.gdshader)
`hint_depth_texture` → world position.

### [triplanar_world_mapping.gdshader](scripts/triplanar_world_mapping.gdshader)
World-axis projection without UVs.

### [instance_texture_array.gdshader](scripts/instance_texture_array.gdshader)
`sampler2DArray` + instance uniform for unique batched textures.

### [noise_terrain_displacement.gdshader](scripts/noise_terrain_displacement.gdshader)
Vertex noise displacement.

### [vfx_port_shader.gdshader](scripts/vfx_port_shader.gdshader)
Validated VFX shader template.

### [shader_parameter_animator.gd](scripts/shader_parameter_animator.gd)
Tween/runtime uniform animation without AnimationPlayer.

### [shader_warmup_loader.gd](scripts/shader_warmup_loader.gd)
Pre-warm shader pipelines during loading screens to avoid first-frame stutter.

## Expert Pointers

- Move invariant math to `vertex()`; pass via `varying`.
- Color uniforms need `hint_source_color`.
- Prefer Official Docs for shading-language builtins; this skill owns batching, scissor, screenspace, and depth routing.


## Deep recipes (on demand)

> LLM-ignorance rule: if a general agent would not know it before reading, it lives here or in `scripts/` — never delete, only move.

| Topic | Reference |
|-------|-----------|
| 2D dissolve/wave/outline | [2d-effect-recipes.md](references/2d-effect-recipes.md) |
| 3D toon + vignette | [3d-and-postfx-recipes.md](references/3d-and-postfx-recipes.md) |
| Uniforms / built-ins | [uniforms-and-builtins.md](references/uniforms-and-builtins.md) |
| Fog, compute, warmup | [expert-advanced-patterns.md](references/expert-advanced-patterns.md) |

## Reference

> Progressive disclosure: open Official Documentation links only when researching a specific API;
> load Related Skills when routing work to a peer domain — do not preload the whole lattice.

### Official Documentation
- [Introduction to shaders](https://docs.godotengine.org/en/stable/tutorials/shaders/introduction_to_shaders.html) — Entry map of shader types, render modes, and when to use ShaderMaterial vs StandardMaterial3D.
- [Shading language](https://docs.godotengine.org/en/stable/tutorials/shaders/shader_reference/shading_language.html) — Core GLSL-like syntax: uniforms, hints, varyings, built-ins, and preprocessor rules used throughout this skill.
- [CanvasItem shaders](https://docs.godotengine.org/en/stable/tutorials/shaders/shader_reference/canvas_item_shader.html) — 2D `canvas_item` built-ins (`UV`, `COLOR`, `TEXTURE`, `SCREEN_UV`) for sprites, UI, and 2D post FX.
- [Spatial shaders](https://docs.godotengine.org/en/stable/tutorials/shaders/shader_reference/spatial_shader.html) — 3D `spatial` built-ins (`ALBEDO`, `NORMAL`, `instance uniform`, depth/screen textures) for materials and full-screen quads.
- [Your first 2D shader](https://docs.godotengine.org/en/stable/tutorials/shaders/your_first_shader/your_first_2d_shader.html) — Minimal canvas_item workflow from ShaderMaterial attach through fragment tinting.
- [Your first 3D shader](https://docs.godotengine.org/en/stable/tutorials/shaders/your_first_shader/your_first_3d_shader.html) — Minimal spatial workflow and conversion path from StandardMaterial3D into writable shaders.
- [ShaderMaterial](https://docs.godotengine.org/en/stable/classes/class_shadermaterial.html) — Runtime `set_shader_parameter` / instance parameter API used by animators and hit-flash batching.
- [Custom post-processing](https://docs.godotengine.org/en/stable/tutorials/shaders/custom_postprocessing.html) — Screen-reading shaders, `hint_screen_texture`, and compositing patterns for pixelate/vignette-style FX.
- [Advanced post-processing](https://docs.godotengine.org/en/stable/tutorials/shaders/advanced_postprocessing.html) — Depth buffer, reversed-Z, and world reconstruction needed for water/fog/debug visualizers.
- [Compute shaders](https://docs.godotengine.org/en/stable/tutorials/shaders/compute_shaders.html) — RenderingDevice GPGPU path for particle sims and other non-fragment workloads.
- [Using VisualShaders](https://docs.godotengine.org/en/stable/tutorials/shaders/visual_shaders.html) — Graph editor + `VisualShaderNodeCustom` extensibility covered in the expert patterns.
- [GPU optimization](https://docs.godotengine.org/en/stable/tutorials/performance/gpu_optimization.html) — Overdraw, transparency, and batching guidance that motivates alpha scissor, instance uniforms, and vertex-vs-fragment cost.

### Related Skills

#### Prerequisites
- [godot-project-foundations](https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-project-foundations/SKILL.md) — Nodes, Resources, and project layout required before attaching ShaderMaterials and shipping `.gdshader` assets.
- [godot-resource-data-patterns](https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-resource-data-patterns/SKILL.md) — Sharing vs duplicating ShaderMaterial/Shader Resources so uniforms and instance parameters stay batch-friendly.

#### Complements
- [godot-3d-materials](https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-3d-materials/SKILL.md) — StandardMaterial3D/ORM first; graduate to spatial shaders for triplanar, dissolve, and instance-uniform effects.
- [godot-3d-lighting](https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-3d-lighting/SKILL.md) — How custom `ALBEDO`/`EMISSION`/`light()` output interacts with Forward+, GI, and fog volumes.
- [godot-particles](https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-particles/SKILL.md) — Particle process/draw materials and alpha pipelines that must match scissor/hash vs blend choices from this skill.
- [godot-2d-animation](https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-2d-animation/SKILL.md) — CanvasItem shader hooks for stylized 2D motion, outline, and dissolve on animated sprites.
- [godot-camera-systems](https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-camera-systems/SKILL.md) — Camera near/far and view/projection matrices that screen-space and depth-reconstruction shaders depend on.
- [godot-performance-optimization](https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-performance-optimization/SKILL.md) — Draw-call batching, MultiMesh, and GPU budgets that justify `instance uniform` and avoiding unique materials.
- [godot-debugging-profiling](https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-debugging-profiling/SKILL.md) — GPU/overdraw profilers and debug views to validate shader cost and depth/normal visualizers.

#### Downstream / consumers
- [godot-procedural-generation](https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-procedural-generation/SKILL.md) — Procedural meshes/terrain consume noise displacement, triplanar, and UV-less spatial patterns from this skill.
- [godot-3d-world-building](https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-3d-world-building/SKILL.md) — Large environment props apply foliage wind, grass flatten, and world-projection shaders at level scale.
- [godot-genre-open-world](https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-genre-open-world/SKILL.md) — Open-world foliage interaction, distance FX, and shared-material batching consume these shader templates.

#### Master
- [godot-master](https://github.com/thedivergentai/gd-agentic-skills/blob/main/skills/godot-master/SKILL.md) — Library router and mirrored module entry for cross-skill discovery.

More from thedivergentai/GD-Agentic-Skills

SkillDescription
godot-2d-animationExpert patterns for 2D animation in Godot using AnimatedSprite2D and skeletal cutout rigs. Use when implementing sprite frame animations, procedural animation (squash/stretch), cutout bone hierarchies, or frame-perfect timing systems. Trigger keywords: AnimatedSprite2D, SpriteFrames, animation_finished, animation_looped, frame_changed, frame_progress, set_frame_and_progress, cutout animation, skeletal 2D, Bone2D, procedural animation, animation state machine, advance(0).
godot-2d-physicsExpert patterns for Godot 2D physics including collision layers/masks, Area2D triggers, raycasting, and PhysicsDirectSpaceState2D queries. Use when implementing collision detection, trigger zones, line-of-sight systems, or manual physics queries. Trigger keywords: CollisionShape2D, CollisionPolygon2D, collision_layer, collision_mask, set_collision_layer_value, set_collision_mask_value, Area2D, body_entered, body_exited, RayCast2D, force_raycast_update, PhysicsPointQueryParameters2D, PhysicsShapeQueryParameters2D, direct_space_state, move_and_collide, move_and_slide.
godot-3d-lightingExpert patterns for Godot 3D lighting including DirectionalLight3D shadow cascades, OmniLight3D attenuation, SpotLight3D projectors, VoxelGI vs SDFGI, and LightmapGI baking. Use when implementing realistic 3D lighting, shadow optimization, global illumination, or light probes. Trigger keywords: DirectionalLight3D, OmniLight3D, SpotLight3D, shadow_enabled, directional_shadow_mode, directional_shadow_split, omni_range, omni_attenuation, spot_range, spot_angle, VoxelGI, SDFGI, LightmapGI, ReflectionProbe, Environment, WorldEnvironment.
godot-3d-materialsExpert patterns for Godot 3D PBR materials using StandardMaterial3D including albedo, metallic/roughness workflows, normal maps, ORM texture packing, transparency modes, and shader conversion. Use when creating realistic 3D surfaces, PBR workflows, or material optimization. Trigger keywords: StandardMaterial3D, BaseMaterial3D, albedo_texture, metallic, metallic_texture, roughness, roughness_texture, normal_texture, normal_enabled, orm_texture, transparency, alpha_scissor, alpha_hash, cull_mode, ShaderMaterial, shader parameters.
godot-3d-world-buildingExpert patterns for 3D level design using GridMap with MeshLibrary, CSG constructive solid geometry, occlusion, and runtime GridMap builders. Use when building 3D levels, modular tilesets, or BSP-style geometry. For sky/fog/Environment recipes, route to godot-3d-lighting. Trigger keywords: GridMap, MeshLibrary, set_cell_item, get_cell_item, map_to_local, local_to_map, CSGCombiner3D, CSGBox3D, CSGSphere3D, CSGPolygon3D, OccluderInstance3D, bake CSG.
godot-ability-systemExpert patterns for RPG/action ability systems including cooldown strategies, combo systems, ability chaining, skill trees with prerequisites, upgrade paths, and resource management. Use when implementing unlockable abilities, character progression, or complex skill systems. Trigger keywords: PlayerAbility, AbilityManager, cooldown, SkillTree, SkillNode, prerequisites, can_use, execute, ComboSystem, ability_chain, global_cooldown, charge_system, upgrade_path.
godot-adapt-2d-to-3dExpert patterns for migrating 2D games to 3D including node type conversions, camera systems (third-person, first-person, orbit), physics layer migration, sprite-to-model art pipeline, and control scheme adaptations. Use when porting 2D projects to 3D or adding 3D elements. Trigger keywords: CharacterBody2D to CharacterBody3D, Area2D to Area3D, Camera2D to Camera3D, Vector2 to Vector3, collision_layer migration, sprite to MeshInstance3D, 2D to 3D conversion.
godot-adapt-3d-to-2dExpert patterns for simplifying 3D games to 2D including dimension reduction strategies, 2.5D fake-depth, isometric ports, camera flattening, physics conversion, 3D-to-sprite art pipeline, and control simplification. Use when porting 3D to 2D, building 2.5D / isometric / fake-depth gameplay, creating 2D versions for mobile, or prototyping. Trigger keywords: CharacterBody3D to CharacterBody2D, Camera3D to Camera2D, Vector3 to Vector2, flatten Z-axis, 2.5D, isometric, fake depth, Y-sort, simulated Z, orthogonal projection, 3D to sprite conversion, performance optimization.
godot-adapt-desktop-to-mobileExpert patterns for porting desktop games to mobile including touch control schemes (virtual joystick, gesture detection), UI scaling for small screens, performance optimization for mobile GPUs, battery life management, and platform-specific features. Use when creating mobile ports or cross-platform mobile builds. Trigger keywords: TouchScreenButton, virtual_joystick, gesture_detector, InputEventScreenTouch, InputEventScreenDrag, mobile_optimization, battery_saving, adaptive_performance, MOBILE_ENABLED.
godot-adapt-mobile-to-desktopExpert patterns for scaling mobile games to desktop including mouse/keyboard controls, increased resolution and graphical fidelity, expanded UI layouts, settings menus, window management, and platform-specific features. Use when creating desktop ports or cross-platform releases. Trigger keywords: mouse_controls, keyboard_shortcuts, resolution_scaling, graphics_settings, fullscreen_toggle, window_modes, Steam_integration, desktop_optimization.