跪拜 Guibai
← Back to the summary

Faking Fluid: How Lusion's Screen Effect Runs on a Single Velocity Texture, Recreated in Three.js

I thought it was fluid simulation, but it's just a texture: Recreating Lusion's screen fluid effect

cover.png

Preface

This is Siberian Little Fire Dragon.

Long time no see, everyone. Your once-a-year blogger is back! I remember the last update was in April 2025, and now it's been more than a year. Why the long silence? Because my little one was born. From my wife's pregnancy to the baby's arrival, it has consumed most of my energy. On top of that I had to work like a workhorse, so I really didn't have the strength to keep learning and sharing. Sorry, everyone! (Raising a kid is exhausting – I applaud my wife O.o)

Recently I managed to carve out a bit of time. A while ago I found a website (Lusion) with very good effects. I thought I'd pick it up and analyze the effects inside. When I came to one of their mouse-effect pages, I stopped: move the mouse over it and the whole picture seems to be stirred by a finger, follows along, gets pulled and deformed, with a bit of rainbow-colored dispersion at the edges. When you release, the picture doesn't snap back immediately; it slowly settles like a water surface.

Okay, let's get down to business.

First, two screenshots:

fluid-idle.png

fluid-stroke.png

Honestly, my first reaction was that this thing must be using Navier-Stokes – otherwise how could the flow be so natural? Then I opened F12, and sure enough, they even drew the velocity field themselves with an 8-bit texture, never solving any equations at all.

Now that's interesting. This article breaks down the "sleight of hand" and reimplements it from scratch with Three.js.

First, see what it actually looks like

When idle, the screen is a very plain base: a gradient from off-white to cool gray, a blue and a red soft blob, plus a few thin concentric circles.

fluid-detail.png

Looks unremarkable, right? But the fine rings are deliberate. As you'll see, these thin lines are the easiest to "expose" when refracting – displacement and chromatic aberration get amplified, making it look very watery.

Move the mouse quickly and the rings get bent, colors get stretched apart. After releasing, the ink doesn't disappear immediately; it spreads outward and then slowly fades.

Break down the principle

The whole effect is essentially three layers. I drew a diagram:

 Mouse path
   │
   ▼
① ScreenPaint: 1/4-resolution velocity/ink texture
   │  (downsample + blur into 1/8 velocity field)
   ▼
② Render base to baseRT
   │  (base + velocity field)
   ▼
③ ScreenPaintDistortion: 9 offset samples + chromatic aberration
   │
   ▼
 Screen

Keep two points in mind.

The velocity field isn't there to "compute" – it's there to "push". It is itself a texture that each frame gets painted by the mouse, pushed by itself, and decays a little. That's all.

Refraction doesn't change geometry; it takes the already-rendered frame as a texture and samples a few times along the velocity direction. The "deformation" you see is actually a misaligned sampling position.

Once you understand these two points, the rest is just labor.

Libraries used

You might not believe it, but this effect actually uses only one library:

That's right – no fluid library, no GSAP. The post-processing is wired up manually (I'll mention that later). The project shell is Vite + vanilla JS, no framework; the code can be copied anywhere and run.

Okay, that's the toolset. Let's start.

Define the data structure

An RGBA texture, with the four channels holding two kinds of data:

Channel Stores Notes
R velocity x + 0.5 8bit can't store negatives, so it's offset by 0.5
G velocity y + 0.5 same as above
B weight1 brush "ink amount", determines visible intensity
A weight2 extra edge amount, decays faster

Why 8bit? Because we're cheap. At 1/4 resolution, a simulation texture for a 4K screen is only 960×540, so VRAM and bandwidth are basically negligible. The cost is that velocity needs offset encoding and you have to handle quantization dead zones – I'll cover that pitfall later.

When creating the render targets, prepare four: two for the ping-pong simulation, two for blur:

const config = {
  minFilter: THREE.LinearFilter,
  magFilter: THREE.LinearFilter,
  format: THREE.RGBAFormat,
  type: THREE.UnsignedByteType, // 8bit, cheap
  depthBuffer: false,
  stencilBuffer: false,
};

// simulation: current / previous
this._currPaintRT = new THREE.WebGLRenderTarget(1, 1, config);
this._prevPaintRT = new THREE.WebGLRenderTarget(1, 1, config);

// low-res velocity field: original / blur staging
this._lowRT = new THREE.WebGLRenderTarget(1, 1, config);
this._lowBlurRT = new THREE.WebGLRenderTarget(1, 1, config);

The sizes are hardcoded from the original site: simulation at 1/4, velocity field at 1/8.

const paintW = Math.max(1, width >> 2);
const paintH = Math.max(1, height >> 2);
const lowW = Math.max(1, width >> 3);
const lowH = Math.max(1, height >> 3);

One detail: clearing can't be to black. After encoding, velocity 0 becomes 0.5, weight 0 becomes 0, so the clear color must be (0.5, 0.5, 0, 0):

renderer.setClearColor(new THREE.Color(0.5, 0.5, 0), 0);
renderer.clear();

Here I pass linear RGB directly instead of hex. If you write new THREE.Color('#808080'), Three will treat it as sRGB and convert again, biasing the velocity.

Start painting

The per-frame simulation pass does three things: push the previous frame, decay it, and paint the current mouse line segment.

Push: semi-Lagrangian advection

For each pixel, trace backwards along the inverse velocity to sample the previous frame's position:

vec4 lowData = texture2D(u_lowPaintTexture, v_uv);
// 0.5 - encoded value = -velocity, then multiply by a strength
vec2 velInv = (0.5 - lowData.xy) * u_pushStrength;

vec4 data = texture2D(
  u_prevPaintTexture,
  v_uv + velInv * u_paintTexelSize
);
data.xy -= 0.5; // decode

u_pushStrength is 25. The larger this value, the farther the ink gets carried, the longer the trail, and the more it feels like stirring syrup.

Decay: three coefficient settings

// velocity 0.975 / weight1 0.95 / weight2 0.8
vec4 delta = (u_dissipations.xxyz - 1.0) * data;

// current mouse velocity × coverage = newly injected velocity
vec2 newVel = u_vel * d;
delta += vec4(newVel, radiusWeight.yy * d);

data += delta;
data.xy += 0.5;
gl_FragColor = clamp(data, vec4(0.0), vec4(1.0));

Note this is (dissipation - 1.0) * data, not a direct multiply. Because the decay is multiplied onto the old value, writing it in incremental form lets you add the injection amount to it.

Paint: brush is a line segment with radius

The mouse has only one point per frame. If you paint it as a point, it breaks into disjoint segments. So you take the previous frame's endpoint as the current start, connect them into a line segment, and compute the distance from each pixel to the segment:

vec2 sdSegment(vec2 p, vec2 a, vec2 b) {
  vec2 pa = p - a;
  vec2 ba = b - a;
  float h = clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0);
  return vec2(length(pa - ba * h), h);
}

The second returned value is the projection position; use it to interpolate the radius between start and end:

vec2 radiusWeight = mix(u_drawFrom.zw, u_drawTo.zw, res.y);
float d = 1.0 - smoothstep(-0.01, radiusWeight.x, res.x);

The radius isn't fixed; it follows mouse speed:

let radius = fit(speed, 0, 100, this.minRadius, this.maxRadius);
if (!hadMoved) radius = 0;

maxRadius is max(40, viewport width / 20). So a fast swipe leaves a thick, long watery sleeve; a slow drag leaves a thin line. This mapping is the source of the "feel" of the whole effect – tuning it works better than tuning the shader.

Why downsample the velocity field and then blur it

Initially I skipped this step and used the 1/4-resolution raw velocity field for the backtrace. The result was a screen full of grid-like artifacts, and brush edges were as hard as discs.

The reason is straightforward: 8bit has low precision by itself, and when you stack low resolution, the error gets amplified during advection. So after the simulation, the result is copied to 1/8 and blurred horizontally and vertically with a 9-tap blur:

vec4 color = texture2D(u_texture, v_uv) * 0.1633;
vec2 delta = u_delta;

color += texture2D(u_texture, v_uv - delta) * 0.1531;
color += texture2D(u_texture, v_uv + delta) * 0.1531;

delta += u_delta;
color += texture2D(u_texture, v_uv - delta) * 0.12245;
color += texture2D(u_texture, v_uv + delta) * 0.12245;

delta += u_delta;
color += texture2D(u_texture, v_uv - delta) * 0.0918;
color += texture2D(u_texture, v_uv + delta) * 0.0918;

delta += u_delta;
color += texture2D(u_texture, v_uv - delta) * 0.0510;
color += texture2D(u_texture, v_uv + delta) * 0.0510;

The weights sum to exactly 1, so no division is needed. The radius is written as 8 texels, but actually multiplied by 0.25, giving an effective radius of about 2 texels.

This combination makes the velocity field smooth and cheap – it's the key to keeping the whole effect at full frame rate.

Making the picture "sloosh"

Now that the velocity field is ready, here's what your eyes actually see.

The refraction pass doesn't touch any geometry. It only does one thing: take the already-rendered frame as a texture, sample along the velocity direction 9 times, and average them.

vec4 data = texture2D(u_screenPaintTexture, v_uv);
float weight = (data.z + data.w) * 0.5;
vec2 vel = (0.5 - data.xy - 0.001) * 2.0 * weight;

vec2 velocity = vel * u_amount / 4.0 * u_screenPaintTexelSize * u_multiplier;

// start with a bit of noise jitter to break up banding among the 9 samples
vec2 uv = v_uv + bnoise * velocity;
vec4 color = vec4(0.0);
for (int i = 0; i < 9; i++) {
  color += texture2D(u_texture, uv);
  uv += velocity;
}
color /= 9.0;

Parameters:

Parameter Default What it does
amount 3 per-step displacement multiplier, larger = longer smear
multiplier 5 overall refraction amplitude
rgbShift 0.5 chromatic aberration strength
colorMultiplier 10 colored stripe strength
shade 1.25 colored stripe brightness

Then the most striking step – sine stripes with channel-phase offsets:

vec3 rainbow =
  sin(vec3(vel.x + vel.y) * 40.0 + vec3(0.0, 2.0, 4.0) * u_rgbShift)
  * smoothstep(0.4, -0.9, weight)
  * u_shade
  * max(abs(vel.x), abs(vel.y))
  * u_colorMultiplier;

color.rgb += rainbow;

The three RGB channels have phases offset by 0, 2, 4, so the red, green, and blue stripes don't overlap, which looks like dispersion. smoothstep(0.4, -0.9, weight) is a reversed interval that concentrates the stripes at the transition zone where ink amount goes from 0 to 1 – that is, at the brush edge, not the center.

fluid-chroma.png

After you release

There's a problem that's easy to overlook here.

If you only do advection, after the mouse stops, residual velocity remains and the whole ink blob keeps moving in the last direction, looking like it slides due to gravity – very fake.

The original site has its own velocity decay. On top of that I added a pull-force logic: 60ms after you stop the hand, the force starts to retract, and within 140ms it shuts off the external velocity that "pushes the ink".

this._idleTime = hadMoved ? 0 : this._idleTime + dt;
const idle = fit(this._idleTime, 0.06, 0.2, 0, 1);
u.u_active.value = 1 - idle;
u.u_idleDamping.value = 1 - this.idleDampingStrength * idle;

The shader side:

// turn off the overall push
velInv *= u_active;

// spread outward along the ink gradient: ink flows from dense to sparse
vec2 weightGrad = vec2(
  (lowR.z + lowR.w) - (lowL.z + lowL.w),
  (lowU.z + lowU.w) - (lowD.z + lowD.w)
);
vec2 spread = weightGrad * (u_idleSpread * (1.0 - u_active));

// CFL limit: per-frame backtrace should not exceed 0.75 texel, or it diverges numerically
float spreadLen = length(spread);
if (spreadLen > 0.75) spread *= 0.75 / spreadLen;
velInv += spread;

The visual difference after this change is significant: the ink no longer slides as a whole, but spreads outward like ink dropped on paper, then fades out.

fluid-trail.png

The distorted base image also has tricks

Refraction needs a base image with "reference points". A solid color shows no deformation; pure noise shows no direction.

So my base image is procedurally generated, with four pieces:

The ring code is just three lines:

float f = fract(length(p) * 6.5 - u_time * 0.10);
float ring = smoothstep(0.94, 1.0, f);
color = mix(color, vec3(0.06, 0.07, 0.10), ring * 0.16);

Why must they be thin lines? Because thin lines are the most sensitive to displacement and chromatic aberration. The same velocity on a large color block shows nothing, but on a ring you immediately see it "bent". Many fluid demos use grids or checkerboards for the same reason.

Wiring it into post-processing

This thing is essentially a two-stage post-processing effect. If you want the picture to look more cinematic, you can keep appending passes. I wrapped the refraction as a Pass:

class DistortionPass extends Pass {
  constructor(distortion, sourceRT) {
    super();
    this.distortion = distortion;
    this.sourceRT = sourceRT;
  }

  render(renderer, writeBuffer) {
    this.distortion.render(
      this.sourceRT.texture,
      this.renderToScreen ? null : writeBuffer
    );
  }
}

The chain after wiring is:

DistortionPass → Final (vignette/grain) → Smaa → Fsr

Each can be toggled independently, which helps when tuning parameters.

Pitfalls I hit

These are the ones that actually cost me half a day each.

1. 8bit has a quantization dead zone. Thinking in floating point, data *= 0.95 when stored back to 8bit will round values smaller than 1/255 back to 1, so the tail never dissipates and the whole screen eventually turns gray. You must give an explicit minimum decay; I use 0.004 per frame.

delta.zw = sign(delta.zw) * max(vec2(0.004), abs(delta.zw));

2. Ping-pong targets must always be swapped. Reading and writing to the same texture in WebGL is undefined behavior. Each frame, swap prev and curr first, then write into the new curr.

3. Don't mix the two coordinate systems. Drawing uses NDC (origin bottom-left, y up); velocity calculations use CSS pixels (origin top-left, y down). Mixing them places the brush in odd positions or flips the velocity direction entirely.

4. Clamp dt. When switching tabs and coming back, dt can be several seconds. One frame can push the velocity field to divergence. I clamp with Math.min(dt, 0.05).

5. Reset the mouse baseline after resize. When the window size changes, the previous frame's mouse coordinates become invalid, and the first frame computes a huge "jump velocity" that flings the whole screen.

6. Color space. When clearing the RT, use linear values (0.5, 0.5, 0), not hex, to avoid the sRGB conversion.

How to run it

The code is in this repo, a minimal runnable project with only Three.js as a dependency:

GITHUB

The entry points are index.html + main.js. The core files are four:

Also included are Input.js (mouse input), FluidGUI.js (top-right parameter panel), math.js (a few helpers). The three post-processing passes (Final / Smaa / Fsr) are also included; if you don't need them, just delete the corresponding addPass in src/FluidExperience.js.

The original effect belongs to Lusion; this is just a learning re-implementation. Models, textures, and visual design copyrights are theirs.

A few last words

The most interesting part of this effect is that it never solves a fluid equation, yet through "velocity encoding + semi-Lagrangian advection + directional blurred sampling" – these three tricks – it breaks apart the visual features of fluid and puts them back together.

If this article helped you, give it a thumbs up. When I have time,I'll look at other effects.

Comments

Top 2 from juejin.cn, machine-translated. The original thread is authoritative.

组合搭配函数

Best of all is the line that the velocity field isn't computed — it's pushed. Take the whole trick apart and it's an 8-bit texture plus semi-Lagrangian advection, no wonder it runs at full framerate. The quantization dead-zone pitfall is described very concretely: after multiplying data by 0.95, a value smaller than 1/255 gets rounded back up to 1, turning the whole screen gray. You'd never anticipate that kind of problem without actually running it once. One question: the idle logic that starts easing off 60ms after release — on a touchscreen, could the instant the finger lifts be misjudged as stopping? Is there separate handling for touch?

用户381861856096

💪💪💪