# Cel-Shading, Shadow Ramps & Width-Compensated Outlines in Godot 4 Compatibility

> Godot 4.7 Compatibility cel-shading spatial shader using custom light() shadow ramps, colored shadow tints, sun-gated Fresnel rim highlights, and a next_pass clip-space width-compensated inverted-hull outline.

- **Canonical page:** https://gamecrew.ai/techniques/godot/cel-shading-outlines
- **Techniques hub:** https://gamecrew.ai/techniques
- **Engine:** Godot 4
- **Category:** shaders
- **Tags:** `toon`, `cel`, `outline`, `stylized`, `anime`, `npr`, `rim-light`, `ramp`, `shader`, `gdshader`, `compatibility`
- **Verification:** Compile-verified pattern
- **Revision:** 1 (2026-11-13)
- **Demo:** No demo

## When to Use & Field Best Practices

Default `StandardMaterial3D` PBR shading makes low-poly procedural characters and stylized props read like smooth plastic. A dedicated `shader_type spatial` toon shader paired with a `next_pass` inverted-hull outline gives crisp comic/anime readability across WebGL 2 browsers and software renderers with zero custom compositor passes:

1. **Custom `light()` Terminator Quantization**: Multiply `max(dot(NORMAL, LIGHT), 0.0)` by `ATTENUATION` (which includes real-time directional shadows and point-light falloff in Godot 4) *before* stepping through a narrow `smoothstep` feather (`0.03–0.05`) so shadow edges stay crisp without aliasing shimmer.
2. **Colored Shadow Tint (Never Crushed Black)**: Lerp unlit regions toward a cool palette shadow color (`shadow_tint`, e.g. muted indigo/slate) instead of multiplying by black. This keeps shaded faces readable and prevents `VERY DARK` capture flags.
3. **Sun-Gated Rim & Stepped Specular**: Gate Fresnel rim `(1.0 - max(dot(NORMAL, VIEW), 0.0))^rim_power` by `clamp(dot(NORMAL, LIGHT) + 0.25, 0.0, 1.0)` inside `light()` so characters pop against dark skies without glowing inside caves.
4. **Clip-Space Distance-Compensated `next_pass` Outline**: Assign a `cull_front, unshaded` outline shader to `material.next_pass`. Expanding vertices along view-space normals in clip space scaled by `min(clip.w, max_dist_scale)` keeps silhouettes legible up close without turning distant props into solid ink blobs — and requires **zero duplicate mesh nodes**.

## Mathematical & Algorithmic Core

- **Feathered Shadowed Cel Band**:
  $$s = \max(0, \mathbf{N}\cdot\mathbf{L}) \cdot a_{\text{atten}}, \qquad b = \mathrm{smoothstep}(\tau - \epsilon,\, \tau + \epsilon,\, s)$$
- **Clip-Space Pixel-Consistent Hull Extrusion**: Project the view-space normal $\mathbf{n}_v$ into clip XY, correct for viewport aspect ratio, and displace by:
  $$\mathbf{p}_{\text{clip}}.xy \mathrel{+}= \widehat{\mathbf{n}}_{\text{clip}} \cdot \frac{2 w_{\text{px}}}{\max(360,\, H_{\text{vp}})} \cdot \min(\max(0.5, \mathbf{p}_{\text{clip}}.w),\, d_{\max})$$

## Engine Implementation

### 1. Compatibility Cel-Shading Spatial Shader (`Assets/Game/Shaders/cel_toon.gdshader`)

```glsl
shader_type spatial;
render_mode blend_mix, depth_draw_opaque, cull_back, diffuse_toon, specular_toon;

uniform vec4 albedo_color : source_color = vec4(0.92, 0.44, 0.28, 1.0);
uniform sampler2D albedo_tex : source_color, filter_linear_mipmap, repeat_enable;
uniform bool use_albedo_tex = false;
uniform vec4 shadow_tint : source_color = vec4(0.32, 0.26, 0.48, 1.0);
uniform vec4 rim_color : source_color = vec4(1.0, 0.92, 0.76, 1.0);
uniform float cel_threshold : hint_range(0.0, 0.8) = 0.22;
uniform float cel_feather : hint_range(0.005, 0.15) = 0.035;
uniform float shadow_floor : hint_range(0.15, 0.75) = 0.36;
uniform float specular_threshold : hint_range(0.75, 0.995) = 0.95;
uniform float specular_strength : hint_range(0.0, 1.0) = 0.32;
uniform float rim_power : hint_range(1.0, 8.0) = 3.2;
uniform float rim_strength : hint_range(0.0, 1.0) = 0.45;
uniform vec3 emission_color : source_color = vec3(0.0, 0.0, 0.0);
uniform float emission_energy : hint_range(0.0, 6.0) = 0.0;

void fragment() {
	vec3 base = albedo_color.rgb;
	if (use_albedo_tex) {
		base *= texture(albedo_tex, UV).rgb;
	}
	ALBEDO = base;
	ROUGHNESS = 0.85;
	EMISSION = emission_color * emission_energy;
}

void light() {
	float ndl = dot(NORMAL, LIGHT);
	float lit_signal = clamp(ndl * 0.5 + 0.5, 0.0, 1.0) * mix(shadow_floor, 1.0, ATTENUATION);
	float band = smoothstep(
		cel_threshold + 0.30 - cel_feather,
		cel_threshold + 0.30 + cel_feather,
		lit_signal
	);
	vec3 light_ramp = mix(shadow_tint.rgb * LIGHT_COLOR, LIGHT_COLOR, band);
	DIFFUSE_LIGHT += ALBEDO * light_ramp * (1.0 / PI);

	vec3 half_vec = normalize(LIGHT + VIEW);
	float ndh = max(dot(NORMAL, half_vec), 0.0);
	float spec = smoothstep(specular_threshold - 0.015, specular_threshold + 0.015, ndh) * band;

	float ndv = clamp(dot(NORMAL, VIEW), 0.0, 1.0);
	float rim_raw = pow(1.0 - ndv, rim_power) * clamp(ndl + 0.25, 0.0, 1.0) * ATTENUATION;
	float rim = smoothstep(0.36, 0.46, rim_raw) * rim_strength;

	SPECULAR_LIGHT += LIGHT_COLOR * (spec * specular_strength) + rim_color.rgb * rim;
}
```

### 2. Width-Compensated Inverted-Hull Outline Shader (`Assets/Game/Shaders/cel_outline.gdshader`)

```glsl
shader_type spatial;
render_mode cull_front, unshaded, depth_draw_opaque, shadows_disabled;

uniform vec4 outline_color : source_color = vec4(0.09, 0.07, 0.13, 1.0);
uniform float width_px : hint_range(0.5, 6.0) = 2.2;
uniform float max_distance_scale : hint_range(2.0, 28.0) = 12.0;
uniform float depth_bias : hint_range(0.0, 0.01) = 0.0006;

void vertex() {
	vec4 clip_pos = PROJECTION_MATRIX * MODELVIEW_MATRIX * vec4(VERTEX, 1.0);
	vec3 view_n = normalize((MODELVIEW_MATRIX * vec4(NORMAL, 0.0)).xyz);
	vec2 clip_n = (PROJECTION_MATRIX * vec4(view_n, 0.0)).xy;
	float len_n = max(length(clip_n), 1e-5);
	clip_n /= len_n;

	float vp_h = max(360.0, VIEWPORT_SIZE.y);
	float aspect = VIEWPORT_SIZE.x / vp_h;
	clip_n.x /= max(0.25, aspect);

	float dist_scale = clamp(clip_pos.w, 0.5, max_distance_scale);
	clip_pos.xy += clip_n * (width_px * 2.0 / vp_h) * dist_scale;
	clip_pos.z += depth_bias * clip_pos.w;
	POSITION = clip_pos;
}

void fragment() {
	ALBEDO = outline_color.rgb;
}
```

### 3. Typed GDScript Toon Material Helper (`Assets/Game/Scripts/gameplay/cel_style.gd`)

```gdscript
class_name CelStyle
extends RefCounted

static func make_toon_material(
	toon_shader: Shader,
	outline_shader: Shader,
	base_color: Color,
	shadow_tint: Color = Color(0.32, 0.26, 0.48),
	outline_color: Color = Color(0.09, 0.07, 0.13),
	outline_px: float = 2.2
) -> ShaderMaterial:
	var mat := ShaderMaterial.new()
	mat.shader = toon_shader
	mat.set_shader_parameter("albedo_color", base_color)
	mat.set_shader_parameter("shadow_tint", shadow_tint)

	if outline_shader != null and outline_px > 0.0:
		var hull := ShaderMaterial.new()
		hull.shader = outline_shader
		hull.set_shader_parameter("outline_color", outline_color)
		hull.set_shader_parameter("width_px", clampf(outline_px, 0.5, 6.0))
		mat.next_pass = hull
	return mat

static func apply_to_branch(root: Node, mat: ShaderMaterial) -> void:
	if root is MeshInstance3D:
		(root as MeshInstance3D).material_override = mat
	for child: Node in root.get_children():
		apply_to_branch(child, mat)
```

## Browser, Mobile & Software-Renderer Budgets

- **Single `next_pass` Draw Overhead**: Only attach `outline_shader` to hero characters, enemies, pickups, and focal landmarks — keep background ground/cliff slabs outline-free so WebGL 2 and Quest VR stay under `200` draw calls.
- **Smooth Normals on Sharp Primitives**: Box edges split along face normals; for crisp hull outlines on boxes/prisms, use slight bevel meshes (`SurfaceTool` or rounded capsules/cylinders) or keep `width_px <= 1.8`.
- **Compatibility Renderer Parity**: `POSITION = clip_pos;` in `vertex()` and `ATTENUATION` in `light()` compile identically in Godot 4.7 Compatibility (WebGL 2) and Forward+.

## Verification Checklist

1. Run `compile` to verify both `.gdshader` files and `cel_style.gd` parse cleanly with zero errors or warnings.
2. Run `capture` on a close-up character view and a distant overview: verify outlines stay crisp near the camera without turning distant props solid black, and check that shadowed faces keep brightness `>= 0.10`.
3. Confirm moving past a point light adds a crisp second toon highlight band without clipping highlights to white.

## Official references

- Colin Leung / NiloCat — Toon Lit Shader Reference (MIT)
- Robin Seibold — Stylized Outlines Reference (MIT)
- Junya Christopher Motomura (GDC 2015 — Guilty Gear Xrd Art Style)
- Godot 4 Spatial Shader light() Reference

## Open-source sources

- Takes an idea from godot-distance-field-outlines by pink-arcana (MIT License), https://github.com/pink-arcana/godot-distance-field-outlines (stylized outline formulation and width-compensation reference)

Games built with this guide carry these credits, and the licence notices they ask for, in their third-party notices.
