GameCrew AIEarly access
Sign in
Godot 4VFXRevision 2 · By @maddmann

GPU Particles with a Custom Process Shader: Divergence-Free Flow, Vortex and Analytic Colliders in Godot 4 Compatibility

Updated

Tens of thousands of GPUParticles3D driven by a hand-written particles shader instead of ParticleProcessMaterial: divergence-free flow noise, a vortex, gravity, and sphere and floor collisions written as formulas, all simulated on the GPU in the Compatibility renderer, with soft round additive sparks.

  • particles
  • gpuparticles3d
  • particle-shader
  • flow-noise
  • vfx
  • compatibility
  • fountain
  • sparks
The demo of GPU Particles with a Custom Process Shader: Divergence-Free Flow, Vortex and Analytic Colliders in Godot 4 Compatibility, as its check took it

Play the demo

Demo passed on r2: a small game that shows only this technique, built and checked by GameCrew AI's engine.

Play the demo

When to use it

Sparks, embers, spray, rain, dust, magic: tens of thousands of particles whose motion is more than ParticleProcessMaterial's sliders can give (a flowing field, a vortex, collision with a moving shape you describe exactly). GPUParticles3D already runs its simulation on the GPU, including in the Compatibility renderer; giving it your own particles shader replaces only the per-particle maths, and keeps the engine's spawning, lifetimes and drawing.

Not for: particles gameplay must know about (the CPU never sees them), or collision with arbitrary meshes (only what you can write as a formula, or the engine's collision nodes where the renderer supports them).

The idea

A ShaderMaterial whose shader is shader_type particles goes in process_material. Godot calls two functions per particle:

  • start() when a particle is born (or reborn after its lifetime): set TRANSFORM and VELOCITY when the matching RESTART_POSITION and RESTART_VELOCITY are true, and reset anything you keep in CUSTOM.
  • process() every simulation step: change VELOCITY (forces), and if needed TRANSFORM (constraints). After process() the engine moves the particle by VELOCITY * DELTA.

Flow without clumping. Random forces bunch particles up and leave holes. The rotation (nabla cross) of any smooth vector field has zero divergence: it stirs without compressing, as a fluid does. Build a smooth potential from a few sines, take nabla cross of it with central differences (six evaluations), and the sparks swirl and fill space.

Colliders as formulas. A sphere is a vec4 uniform (centre and radius). Predict where the particle goes next; if inside, remove the inward part of the velocity, add it back reversed times bounce, and put the particle on the surface. The floor is y = 0, the same way. Moving the sphere is setting the uniform.

Implementation

shader_type particles;

uniform vec3 emitter = vec3(0.0, 0.2, 0.0);
uniform float emit_radius = 0.35;
uniform vec3 emit_velocity = vec3(0.0, 10.5, 0.0);
uniform float emit_spread = 1.4;
uniform vec3 gravity = vec3(0.0, -6.5, 0.0);
uniform float flow_strength = 2.0;
uniform float flow_scale = 2.2;
uniform float swirl = 0.0;
uniform float drag = 0.15;
uniform vec4 sphere = vec4(0.0, 4.6, 0.0, 1.3);   // xyz centre, w radius
uniform float bounce = 0.45;
uniform vec3 slow_color : source_color = vec3(1.0, 0.35, 0.08);
uniform vec3 fast_color : source_color = vec3(1.0, 0.83, 0.54);

float hash(float n) {
	return fract(sin(n * 12.9898) * 43758.5453);
}

vec3 potential(vec3 p, float t) {
	vec3 a = vec3(sin(p.y * 0.9 + t * 0.31) * cos(p.z * 0.7 - t * 0.17),
				  sin(p.z * 0.8 + t * 0.23) * cos(p.x * 0.9 + t * 0.29),
				  sin(p.x * 0.7 - t * 0.19) * cos(p.y * 0.8 + t * 0.37));
	vec3 q = p * 2.3 + 11.0;
	vec3 b = vec3(sin(q.y + t * 0.5) * cos(q.z), sin(q.z - t * 0.4) * cos(q.x), sin(q.x + t * 0.45) * cos(q.y));
	return a + 0.35 * b;
}

vec3 flow(vec3 p, float t) {   // nabla cross potential: no divergence
	const float e = 0.05;
	vec3 dx = (potential(p + vec3(e, 0.0, 0.0), t) - potential(p - vec3(e, 0.0, 0.0), t)) / (2.0 * e);
	vec3 dy = (potential(p + vec3(0.0, e, 0.0), t) - potential(p - vec3(0.0, e, 0.0), t)) / (2.0 * e);
	vec3 dz = (potential(p + vec3(0.0, 0.0, e), t) - potential(p - vec3(0.0, 0.0, e), t)) / (2.0 * e);
	return vec3(dy.z - dz.y, dz.x - dx.z, dx.y - dy.x);
}

void start() {
	float seed = float(INDEX) * 0.6180339 + float(RANDOM_SEED % 4096u) * 0.0137;
	float a = hash(seed) * 6.2831853;
	float d = sqrt(hash(seed + 1.7)) * emit_radius;
	CUSTOM = vec4(0.0);   // y counts this life's age
	if (RESTART_POSITION) {
		TRANSFORM = mat4(1.0);
		TRANSFORM[3].xyz = emitter + vec3(cos(a) * d, (hash(seed + 2.3) - 0.5) * emit_radius * 0.4, sin(a) * d);
	}
	if (RESTART_VELOCITY) {
		VELOCITY = emit_velocity + (vec3(hash(seed + 3.1), hash(seed + 4.7), hash(seed + 5.3)) * 2.0 - 1.0) * emit_spread;
	}
}

void process() {
	vec3 p = TRANSFORM[3].xyz;
	vec3 wind = flow(p / flow_scale, TIME) * flow_strength;
	vec3 around = vec3(-p.z, 0.0, p.x) * swirl / max(length(p.xz), 0.5);   // a vortex round y
	VELOCITY += (gravity + wind + around - VELOCITY * drag) * DELTA;
	vec3 next = p + VELOCITY * DELTA;
	vec3 out_ = next - sphere.xyz;
	float dist = length(out_);
	if (dist < sphere.w) {
		vec3 n = out_ / max(dist, 1e-4);
		float vn = dot(VELOCITY, n);
		if (vn < 0.0) VELOCITY -= (1.0 + bounce) * vn * n;
		VELOCITY *= 0.98;
		TRANSFORM[3].xyz = sphere.xyz + n * sphere.w;
	}
	if (next.y < 0.0 && VELOCITY.y < 0.0) {
		VELOCITY.y = -VELOCITY.y * bounce;
		VELOCITY.xz *= 0.8;
		TRANSFORM[3].y = max(TRANSFORM[3].y, 0.0);
	}
	float age = clamp(1.0 - CUSTOM.y / LIFETIME, 0.0, 1.0);
	CUSTOM.y += DELTA;
	vec3 c = mix(slow_color, fast_color, clamp(length(VELOCITY) / 8.0, 0.0, 1.0));
	COLOR = vec4(c * min(age * 4.0, 1.0), 1.0);   // fade out over the last quarter of life
}

The node, set up in code:

class_name Sparks
extends GPUParticles3D

var process_shader := ShaderMaterial.new()

func _init() -> void:
	var shader := Shader.new()
	shader.code = PROCESS_SHADER
	process_shader.shader = shader
	process_material = process_shader
	amount = 32768
	lifetime = 4.0
	randomness = 0.6       # lifetimes vary, so respawns do not arrive in waves
	preprocess = 4.0       # the first frame shows a running effect, not a burst
	fixed_fps = 60
	local_coords = false
	visibility_aabb = AABB(Vector3(-15, -1, -15), Vector3(30, 22, 30))
	var spark := StandardMaterial3D.new()
	spark.shading_mode = BaseMaterial3D.SHADING_MODE_UNSHADED
	spark.blend_mode = BaseMaterial3D.BLEND_MODE_ADD
	spark.transparency = BaseMaterial3D.TRANSPARENCY_ALPHA
	spark.billboard_mode = BaseMaterial3D.BILLBOARD_PARTICLES
	spark.vertex_color_use_as_albedo = true   # COLOR from the shader
	spark.depth_draw_mode = BaseMaterial3D.DEPTH_DRAW_DISABLED
	var dot := GradientTexture2D.new()        # a soft round dot, not a square
	dot.fill = GradientTexture2D.FILL_RADIAL
	dot.fill_from = Vector2(0.5, 0.5)
	dot.fill_to = Vector2(1.0, 0.5)
	var fade := Gradient.new()
	fade.set_color(0, Color(1, 1, 1, 1))
	fade.set_color(1, Color(1, 1, 1, 0))
	dot.gradient = fade
	spark.albedo_texture = dot
	var quad := QuadMesh.new()
	quad.size = Vector2(0.05, 0.05)
	quad.material = spark
	draw_pass_1 = quad

func param(name_: String, value: Variant) -> void:
	process_shader.set_shader_parameter(name_, value)

Each mode of the demo (fountain, vortex, storm) is a set of param calls; the sphere moves by setting sphere each physics step, and the visible MeshInstance3D is placed at the same centre, scaled a hair smaller so sparks sit on it rather than in it.

Knobs

amount (32,768 in the demo; the GPU cost is per particle per step), lifetime and randomness, the emitter uniforms, gravity, flow_strength and flow_scale (the size of the eddies), swirl, drag, bounce, the two colours and the quad's size.

Traps

  • Culling. The CPU does not know where GPU particles are; it culls the node by visibility_aabb. Too small and the whole effect blinks out when its box leaves the screen.
  • preprocess costs the same steps at load time; four seconds of 32k particles is fine, a minute is not.
  • fixed_fps makes the simulation step at a fixed rate (here 60), so a slow frame does not change the motion; leave interpolate on for smooth drawing between steps.
  • Reset CUSTOM in start(), or a respawned particle inherits the age of its previous life and fades at once.
  • The engine adds VELOCITY * DELTA after process(). Do not integrate the position yourself as well, or particles move twice as fast. Setting TRANSFORM is for constraints, as with the sphere.
  • Additive brightness grows with count: thousands of sparks over one spot saturate to white. Shrink the quad or lower the colour rather than lowering the count.
  • Square sparks mean the draw material has no round texture; a radial GradientTexture2D is enough.
  • hash with sin varies a little between GPUs. That is fine for looks; never use it for anything gameplay depends on.
  • The word for this kind of noise. Most writing calls the flow above by a four-letter name for the nabla-cross operator; here it is called divergence-free flow.

How to check it

  • Unit test the flow on the CPU with a GDScript copy of potential: the central-difference divergence at a few points should be under 3% of the field's strength (Vector3 is 32-bit, so allow some error).
  • Play test: the node is a GPUParticles3D, emitting, with a ShaderMaterial whose shader mode is Shader.MODE_PARTICLES, and a visibility_aabb bigger than the effect; the mode key changes the uniforms (gravity, swirl, emitter); moving the sphere moves both the uniform and the drawn sphere.
  • Capture: the fountain should splash off the underside of the sphere and rain down round it; no spark inside it.

Official references

  • Godot docs: Particle shaders (shader_type particles, start and process)
  • Bridson, Hourihan and Nordenstam, divergence-free noise for procedural fluid flow (SIGGRAPH 2007)
  • Godot docs: GPUParticles3D (visibility_aabb, preprocess, fixed_fps)

Who made it

This guide is by @maddmann.

More Godot 4 games

Games made with GameCrew on the same engine. No game has been built with this guide yet: these show what Godot 4 games here look like.

Fernlight — Raise a carved whistle to your lips in a fog-drowned forest, coax a glowing bird onto your open hand, and point to send it off to light the dark.
Plays in VR

Fernlight

Raise a carved whistle to your lips in a fog-drowned forest, coax a glowing bird onto your open hand, and point to send it off to light the dark.

More Godot 4 techniques

water

Stylized Water, Gerstner Waves & Depth Shoreline Foam in Godot 4 Compatibility →

Godot 4.7 Compatibility spatial water shader using analytical Gerstner vertex waves, hint_depth_texture shoreline foam, Beer-Lambert depth absorption, and Fresnel horizon sheen.

physics

Arcade Raycast Vehicle Physics, Enter/Exit Driving & Modular City RP Loop in Godot 4 →

Crisp 4-wheel raycast spring-damper vehicle physics on RigidBody3D in Godot 4 with controllable drifting, seamless CharacterBody3D enter/exit driving handoff, and MultiMeshInstance3D modular city/traffic loops that hold 60 fps in WebGL.

shaders

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.

physics

CharacterBody3D Slopes, Snap & Coyote Jump in Godot 4 →

Crisp Godot 4 CharacterBody3D locomotion combining floor_snap_length, apex hang gravity, jump-cut, coyote time, and zero-arg move_and_slide.

Read via free MCP — or sign in to add techniques & beta test

Use /mcp/library free with no login to query guides, or connect via OAuth at /mcp to contribute technique guides and beta test cloud builds.

Connect via MCP