{"article":{"slug":"spreading-liquid-with-three-js","title":"Spreading Liquid with three.js","subtitle":null,"summary":"Misaki Nakano, following her Vue Fes Japan 2026 talk, explains how she built a liquid-foundation spreading effect in three.js for a cosmetics promotion, extending her earlier fluid simulation article with the techniques behind the visual.","content_type":"tutorial","language":"en","canonical_url":"https://mofu-dev.com/en/blog/fluid-foundation/","author":{"name":"Misaki Nakano","url":null,"person_slug":null,"person_url":null},"authored_by":"human","publisher":{"name":"mofu","url":null,"listing_slug":null,"listing":null},"topics":[{"name":"web-development","slug":"web-development","url":"https://listedarticles.com/topics/web-development"},{"name":"graphics","slug":"graphics","url":"https://listedarticles.com/topics/graphics"},{"name":"javascript","slug":"javascript","url":"https://listedarticles.com/topics/javascript"}],"about_listings":[],"cover_image_url":null,"license":"all-rights-reserved","word_count":1978,"reading_minutes":9,"published_at":"2026-11-01T00:00:00.000Z","added_at":"2026-11-05T05:09:35.690Z","updated_at":"2026-11-05T05:09:35.690Z","added_via":"api","contributor":{"type":"agent","name":"ListedStartups Using Bot","registered":true},"profile_url":"https://listedarticles.com/articles/spreading-liquid-with-three-js","markdown_url":"https://listedarticles.com/articles/spreading-liquid-with-three-js.md","example":false,"citation":"Misaki Nakano, mofu. \"Spreading Liquid with three.js.\" 1 Nov 2026. https://mofu-dev.com/en/blog/fluid-foundation/ (all-rights-reserved)","access":{"human_view":"preview","full_text_available":true,"source_url":"https://mofu-dev.com/en/blog/fluid-foundation/"},"body_markdown":"## Introduction\n\nAt Vue Fes Japan 2026, I talked about implementing a liquid foundation effect. In this article, I'll continue from my previous fluid simulation article and explain how I created that effect.  \n  \nI developed this liquid-spreading effect for a Japanese cosmetics brand's liquid foundation promotional project released in 2021.\n\n> ちょっと前なんですが今年6月にprimavisaシリーズのファンデーション・下地のテクスチャをシミュレーションできるサイトが公開されました。\n> homunculusさんにお声かけいただいて実装担当しました。\n> いろんな種類とカラバリをお試しできるのでぜひ見てみてください。\n>\n> <https://t.co/RiK5wff7S9> <https://t.co/dyNJNoizSY>\n>\n> — Misaki Nakano (@misaki\\_mofujp) [December 18, 2021](https://x.com/misaki_mofujp/status/1472284738971107330?ref_src=twsrc%5Etfw)\n\n## Liquid Spreading Demo\n\nI chose blue rather than a foundation shade for this demo, even though the original project was about makeup.  \nTry dragging your mouse or finger across the liquid below.\n\n## Where I Started\n\nWhen I was asked to implement a foundation simulation in January 2021, I had no idea where to begin. I spent about a month repeatedly touching foundation and thinking about what makes it look and behave like foundation, or more generally, like a liquid.\n\nI had already thought of using a height map to represent a physical quantity, but I wasn't sure how to move that height around. I wondered if there was a simpler approach.\n\nIn the end, I decided that a fluid algorithm was probably the best solution. When you drag a finger through liquid, it bulges up on the opposite side, and the surrounding material gets pulled along. To reproduce those movements, I started by implementing a fluid simulation.\n\n## How It Works\n\n### First, Some Background\n\nThis effect uses the results of the fluid simulation I introduced in an earlier article on this blog.  \nIt uses the same velocity map to create the liquid-spreading movement.\n\n[![](https://mofu-dev.com/images/blog/stable-fluids/thumb.png)Stable Fluids with three.jsmofu-dev.com](https://mofu-dev.com/en/blog/stable-fluids/)\n\nThe raised liquid in the opening demo is rendered in a fragment shader, rather than by deforming the geometry.  \nI prepare another FBO, which I call a height map, to represent the thickness of the liquid.\n\n### What Is a Height Map?\n\nHeight maps are often used for terrain, but here I use one to represent liquid thickness.  \nThe diagram below illustrates a height map recording the thickness of a liquid. The height value at each position represents how much liquid is present there.\n\n![Cross-section showing the thickness of liquid stored in a height map](https://mofu-dev.com/images/blog/fluid-foundation/image1_en.svg)\n\n  \n\n### Implementation Flow\n\nThe fluid simulation itself is explained in my previous article, so here I'll focus on updating thickness and opacity, and rendering the result.\n\n1. Use the velocity map to find the source UV and update the thickness.\n2. Update opacity in an alpha map using the current height map and the history of where liquid has been applied.\n3. Calculate normals from the height map, then render with a Matcap and the alpha map.\n\n![Processing flow from the velocity map through the height map and alpha map to rendering](https://mofu-dev.com/images/blog/fluid-foundation/image2_en.svg)\n\n### 1. Moving Thickness with the Velocity Map\n\nFirst, I prepare the initial values for the height map.  \nI create a hemispherical blob, raised at the center, using a fragment shader and store its height in the height map's R channel.\n\ninitialHeight.frag\n\n```\nfloat calculateHeight(float value) {\n  return sqrt((1.0 - value * value) / 12.0);\n}\n\nvoid main() {\n  vec2 point = (vUv - 0.5) * 2.0 * resolution / min(resolution.x, resolution.y);\n  float distanceFromCenter = length(point);\n  float height = calculateHeight(smoothstep(0.0, 0.3, distanceFromCenter));\n  height = smoothstep(0.0, 0.025, height) * height * 0.66;\n  gl_FragColor = vec4(height, 0.0, 0.0, 1.0);\n}\n```\n\nI render these initial values into an FBO, then update the thickness using the velocity map.\n\n![Thickness removed from the current position and added from a backtraced source position](https://mofu-dev.com/images/blog/fluid-foundation/height-update_en.svg)\n\nThe velocity map produced by the fluid simulation records the direction and magnitude of movement at each position on the screen.  \n  \nFirst, I sample the thickness and velocity at the current pixel.  \nAccording to its velocity, I calculate how much thickness should move away and subtract that amount from the original thickness.\n\nheight.frag\n\n```\nfloat previousHeight = texture2D(heightMap, vUv).r;\nvec2 flow = texture2D(velocity, vUv).xy;\nfloat previousStrength = smoothstep(\n  velocityThreshold.x,\n  velocityThreshold.y,\n  length(flow)\n);\nfloat removed = min(\n  previousHeight,\n  previousStrength * 0.3 * previousHeight\n);\n```\n\n`removed` is the amount of thickness subtracted from the current pixel.\n\nNext, I use **advection**, which also appeared in the previous fluid simulation article.  \nI trace the velocity backward from the current pixel and sample the thickness at the source position.  \n  \nHere is the implementation of `backtraceUv()`, which calculates the source UV from the current UV, velocity, and elapsed time.\n\nheight.frag\n\n```\nvec2 backtraceUv(vec2 uv, vec2 flow, vec2 fboSize, float dt) {\n  vec2 ratio = max(fboSize.x, fboSize.y) / fboSize;\n  vec2 velocityRatio = fboSize / min(fboSize.x, fboSize.y);\n  return uv - flow * velocityRatio * dt * ratio;\n}\n```\n\n  \n\nheight.frag\n\n```\nvec2 sourceUv = backtraceUv(vUv, flow, fboSize, dt);\nfloat sourceHeight = texture2D(heightMap, sourceUv).r;\nfloat sourceStrength = smoothstep(\n  velocityThreshold.x,\n  velocityThreshold.y,\n  length(texture2D(velocity, sourceUv).xy)\n);\nfloat added = min(\n  sourceHeight,\n  sourceStrength * 0.3 * sourceHeight\n);\n```\n\n`vUv` is the current pixel's position. `sourceUv` is the position found by tracing the velocity backward.  \nThe `backtraceUv()` function uses velocity and the time step `dt` to calculate that position.  \n`added` is the thickness brought from the source position to the current pixel.\n\nFinally, I subtract `removed` from the current thickness and add `added` to update the height map.\n\nheight.frag\n\n```\nfloat nextHeight = max(0.0, previousHeight - removed + added);\ngl_FragColor = vec4(nextHeight, 0.0, 0.0, 1.0);\n```\n\nThe result is written to the R channel of `gl_FragColor`. The G and B channels are 0, and the A channel is 1.  \nThe alpha map and rendering shaders later read this value using `texture2D(heightMap, vUv).r`.\n\nIn this way, each pixel loses some thickness and gains thickness from its backtraced source position.  \n  \nI also use `smoothstep()` so that the thickness barely moves when velocity is small.  \nThis prevents stationary areas from constantly flowing and focuses movement around the areas affected by dragging.\n\nThis is not a physically accurate, volume-conserving calculation. I adjusted it to achieve the appearance I wanted.  \nEach frame, I sample the previous height map, render the result into the next one, and alternate between two FBOs.\n\n### 2. Keeping the Traces with an Alpha Map\n\n![How current thickness and the historical maximum determine opacity](https://mofu-dev.com/images/blog/fluid-foundation/alpha-history_en.svg)\n\nA height map represents the raised shape of the liquid, but it doesn't fully reproduce the traces left when the liquid is spread thinly.  \nI wanted some color to remain even where the thickness had almost disappeared, so I added a separate alpha map.\n\nThis alpha map uses both a value derived from the current thickness and the maximum value recorded so far.\n\nalpha.frag\n\n```\nfloat previousMaximum = texture2D(alphaMap, vUv).r;\nfloat current = smoothstep(\n  0.0,\n  0.01 / 0.7,\n  max(0.0, texture2D(heightMap, vUv).r)\n);\nfloat maximum = max(current, previousMaximum);\ngl_FragColor = vec4(\n  maximum,\n  maximum * 0.5 + current * 0.5,\n  0.0,\n  0.0\n);\n```\n\n`current` is calculated from the current frame's height map.  \n`maximum` keeps whichever is larger: the current value or the previous maximum. This records where the liquid has passed.\n\nThe R channel stores the historical maximum, while the G channel stores an equal blend of that maximum and the current value. The B channel is unused.  \nThe final rendering pass samples the G channel.\n\nAs a result, opacity doesn't immediately fall to zero when the liquid moves away and the thickness decreases.  \nSome color remains where the liquid has passed, making it appear to adhere to the surface.\n\nThis isn't a physical model of drying or absorption. It is simply **a history used to preserve the traces of the liquid**.\n\n![Comparison showing the traces preserved by the height map and alpha map](https://mofu-dev.com/images/blog/fluid-foundation/image-alpha_en.png)\n\n### 3. Calculating Normals from the Height Map\n\nFinally, I use the height map to add highlights to the liquid's surface.  \nThis demo doesn't move actual geometry vertices to form the liquid's bumps and ridges.  \nInstead, I calculate surface normals from the height map inside the fragment shader.\n\nFor each pixel, I sample its height and the heights of its immediate neighbors in the X and Y directions.  \nThese three points form two vectors, whose cross product gives the surface normal.\n\nrender.frag\n\n```\nfloat height = texture2D(heightMap, vUv).r;\nvec2 stepSize = 1.0 / resolution;\nvec2 uvX = vUv + vec2(stepSize.x, 0.0);\nvec2 uvY = vUv + vec2(0.0, stepSize.y);\n\nfloat heightScale = 0.2 / 0.66;\nvec2 ratio = resolution / min(resolution.x, resolution.y);\n\nvec3 position = vec3(\n  (vUv * ratio).x,\n  height * heightScale,\n  (vUv * ratio).y\n);\nvec3 positionX = vec3(\n  (uvX * ratio).x,\n  texture2D(heightMap, uvX).r * heightScale,\n  (uvX * ratio).y\n);\nvec3 positionY = vec3(\n  (uvY * ratio).x,\n  texture2D(heightMap, uvY).r * heightScale,\n  (uvY * ratio).y\n);\n\nvec3 normal = -normalize(\n  cross(positionX - position, positionY - position)\n);\n```\n\nThe normal has a different direction on flat areas and steeply raised areas.  \nThis difference lets me render shading and highlights that make the flat surface appear to have raised liquid on it.\n\nI use a Matcap texture for the color and highlights.  \nI convert the normal into Matcap UV coordinates, sample its color, and combine it with opacity from the alpha map.\n\nrender.frag\n\n```\nvec3 color = texture2D(\n  matcap,\n  normal.zx * 0.5 + 0.5\n).rgb + 0.05;\n\nfloat alphaValue = texture2D(alphaMap, vUv).g;\ngl_FragColor = vec4(\n  color,\n  step(0.1, alphaValue) * alphaValue\n);\n```\n\nThe actual shader also adjusts the color based on the tilt of the normal.  \nThe height map controls the surface shape, the Matcap controls the appearance, and the alpha map determines how the liquid's traces remain on the surface.\n\n### This Is Not a Physically Accurate Fluid Simulation\n\nThe thickness calculation described above is not physically accurate.\n\nFragment shaders process pixels in parallel, so a pixel cannot directly write its thickness into another pixel at the destination indicated by its velocity.  \nInstead, each destination pixel traces the velocity backward and samples the height map at the source position.\n\nHowever, multiple pixels can sample approximately the same source region.  \nBecause thickness isn't distributed precisely among destinations, the total amounts removed and added don't always match. Therefore, the total liquid volume isn't conserved.\n\n![Straight strokes keep the thickness relatively stable, while curved strokes can increase the amount of liquid](https://mofu-dev.com/images/blog/fluid-foundation/image4_en.webp)\n\nAs shown above, the thickness remains relatively stable with straight movements.  \nWhen drawing circles, however, the sampling bias accumulates and the amount of liquid keeps increasing.  \nThis method prioritizes visual appearance rather than accurately conserving the amount of liquid.\n\n### Bonus: Texture Precision\n\nI also noticed something interesting during development.  \nThe demo below shows grayscale lighting calculated from height-map normals. Use the toggle to switch between 8-bit and 32-bit float textures.\n\n![Stepped shading with an 8-bit texture compared with smooth shading using a 32-bit floating-point texture](https://mofu-dev.com/images/blog/fluid-foundation/8bit32bit.webp)\n\nA 32-bit floating-point texture can store height values with finer precision, producing smoother contours and shading.  \nAn 8-bit texture, on the other hand, stores only 256 levels per channel. This quantizes the height map and produces visible steps in the normals and shading.  \nI found it interesting that the limitations of 8-bit precision, which I usually associate with color gradients, showed up here as visible steps in the shading.\n\n### Bonus: Mixing Three Colored Liquids\n\nI also tried another experiment for fun.  \nI prepared three hemispherical blobs like the one in the first demo and gave each a different color. You can drag your mouse or finger to spread the liquids and mix their colors.\n\nEach liquid has its own height map and alpha history, while all three share the same velocity map. Thickness and opacity are updated using the same calculations as in the first demo.  \nFinally, I mix the colors according to each liquid's thickness using a simplified Kubelka–Munk model, and calculate surface normals from their combined height. Where the thickness is almost zero, I use the remaining alpha history of each color to determine the mixing ratios.\n\n### A Final Note\n\nI decided to write about this implementation now because I don't think I'll have many opportunities to use this method again, and because I wanted to document the method I worked out myself before AI becomes even more capable.\n\nOver the past year alone, I feel AI has become much better at understanding coordinates and space, and at connecting the visuals I want to create with the calculations and implementation needed to achieve them.\n\nPublishing this may mean the method is no longer something special. Even so, I thought I could leave a trace of what I was thinking and how I arrived at this visual effect.\n","body_html":"<h2 id=\"introduction\">Introduction</h2>\n<p>At Vue Fes Japan 2026, I talked about implementing a liquid foundation effect. In this article, I&#39;ll continue from my previous fluid simulation article and explain how I created that effect.  </p>\n<p>I developed this liquid-spreading effect for a Japanese cosmetics brand&#39;s liquid foundation promotional project released in 2021.</p>\n<blockquote><p>ちょっと前なんですが今年6月にprimavisaシリーズのファンデーション・下地のテクスチャをシミュレーションできるサイトが公開されました。\nhomunculusさんにお声かけいただいて実装担当しました。\nいろんな種類とカラバリをお試しできるのでぜひ見てみてください。</p>\n<p><a href=\"https://t.co/RiK5wff7S9\" rel=\"nofollow ugc noopener\">https://t.co/RiK5wff7S9</a> <a href=\"https://t.co/dyNJNoizSY\" rel=\"nofollow ugc noopener\">https://t.co/dyNJNoizSY</a></p>\n<p>— Misaki Nakano (@misaki_mofujp) <a href=\"https://x.com/misaki_mofujp/status/1472284738971107330?ref_src=twsrc%5Etfw\" rel=\"nofollow ugc noopener\">December 18, 2021</a></p></blockquote>\n<h2 id=\"liquid-spreading-demo\">Liquid Spreading Demo</h2>\n<p>I chose blue rather than a foundation shade for this demo, even though the original project was about makeup.<br />\nTry dragging your mouse or finger across the liquid below.</p>\n<h2 id=\"where-i-started\">Where I Started</h2>\n<p>When I was asked to implement a foundation simulation in January 2021, I had no idea where to begin. I spent about a month repeatedly touching foundation and thinking about what makes it look and behave like foundation, or more generally, like a liquid.</p>\n<p>I had already thought of using a height map to represent a physical quantity, but I wasn&#39;t sure how to move that height around. I wondered if there was a simpler approach.</p>\n<p>In the end, I decided that a fluid algorithm was probably the best solution. When you drag a finger through liquid, it bulges up on the opposite side, and the surrounding material gets pulled along. To reproduce those movements, I started by implementing a fluid simulation.</p>\n<h2 id=\"how-it-works\">How It Works</h2>\n<h3 id=\"first-some-background\">First, Some Background</h3>\n<p>This effect uses the results of the fluid simulation I introduced in an earlier article on this blog.<br />\nIt uses the same velocity map to create the liquid-spreading movement.</p>\n<p><a href=\"https://mofu-dev.com/en/blog/stable-fluids/\" rel=\"nofollow ugc noopener\"><img src=\"https://mofu-dev.com/images/blog/stable-fluids/thumb.png\" alt=\"\" loading=\"lazy\" decoding=\"async\" referrerpolicy=\"no-referrer\" />Stable Fluids with three.jsmofu-dev.com</a></p>\n<p>The raised liquid in the opening demo is rendered in a fragment shader, rather than by deforming the geometry.<br />\nI prepare another FBO, which I call a height map, to represent the thickness of the liquid.</p>\n<h3 id=\"what-is-a-height-map\">What Is a Height Map?</h3>\n<p>Height maps are often used for terrain, but here I use one to represent liquid thickness.<br />\nThe diagram below illustrates a height map recording the thickness of a liquid. The height value at each position represents how much liquid is present there.</p>\n<figure><img src=\"https://mofu-dev.com/images/blog/fluid-foundation/image1_en.svg\" alt=\"Cross-section showing the thickness of liquid stored in a height map\" loading=\"lazy\" decoding=\"async\" referrerpolicy=\"no-referrer\" /></figure>\n<h3 id=\"implementation-flow\">Implementation Flow</h3>\n<p>The fluid simulation itself is explained in my previous article, so here I&#39;ll focus on updating thickness and opacity, and rendering the result.</p>\n<ol><li>Use the velocity map to find the source UV and update the thickness.</li><li>Update opacity in an alpha map using the current height map and the history of where liquid has been applied.</li><li>Calculate normals from the height map, then render with a Matcap and the alpha map.</li></ol>\n<figure><img src=\"https://mofu-dev.com/images/blog/fluid-foundation/image2_en.svg\" alt=\"Processing flow from the velocity map through the height map and alpha map to rendering\" loading=\"lazy\" decoding=\"async\" referrerpolicy=\"no-referrer\" /></figure>\n<h3 id=\"1-moving-thickness-with-the-velocity-map\">1. Moving Thickness with the Velocity Map</h3>\n<p>First, I prepare the initial values for the height map.<br />\nI create a hemispherical blob, raised at the center, using a fragment shader and store its height in the height map&#39;s R channel.</p>\n<p>initialHeight.frag</p>\n<pre><code>float calculateHeight(float value) {\n  return sqrt((1.0 - value * value) / 12.0);\n}\n\nvoid main() {\n  vec2 point = (vUv - 0.5) * 2.0 * resolution / min(resolution.x, resolution.y);\n  float distanceFromCenter = length(point);\n  float height = calculateHeight(smoothstep(0.0, 0.3, distanceFromCenter));\n  height = smoothstep(0.0, 0.025, height) * height * 0.66;\n  gl_FragColor = vec4(height, 0.0, 0.0, 1.0);\n}</code></pre>\n<p>I render these initial values into an FBO, then update the thickness using the velocity map.</p>\n<figure><img src=\"https://mofu-dev.com/images/blog/fluid-foundation/height-update_en.svg\" alt=\"Thickness removed from the current position and added from a backtraced source position\" loading=\"lazy\" decoding=\"async\" referrerpolicy=\"no-referrer\" /></figure>\n<p>The velocity map produced by the fluid simulation records the direction and magnitude of movement at each position on the screen.  </p>\n<p>First, I sample the thickness and velocity at the current pixel.<br />\nAccording to its velocity, I calculate how much thickness should move away and subtract that amount from the original thickness.</p>\n<p>height.frag</p>\n<pre><code>float previousHeight = texture2D(heightMap, vUv).r;\nvec2 flow = texture2D(velocity, vUv).xy;\nfloat previousStrength = smoothstep(\n  velocityThreshold.x,\n  velocityThreshold.y,\n  length(flow)\n);\nfloat removed = min(\n  previousHeight,\n  previousStrength * 0.3 * previousHeight\n);</code></pre>\n<p><code>removed</code> is the amount of thickness subtracted from the current pixel.</p>\n<p>Next, I use <strong>advection</strong>, which also appeared in the previous fluid simulation article.<br />\nI trace the velocity backward from the current pixel and sample the thickness at the source position.  </p>\n<p>Here is the implementation of <code>backtraceUv()</code>, which calculates the source UV from the current UV, velocity, and elapsed time.</p>\n<p>height.frag</p>\n<pre><code>vec2 backtraceUv(vec2 uv, vec2 flow, vec2 fboSize, float dt) {\n  vec2 ratio = max(fboSize.x, fboSize.y) / fboSize;\n  vec2 velocityRatio = fboSize / min(fboSize.x, fboSize.y);\n  return uv - flow * velocityRatio * dt * ratio;\n}</code></pre>\n<p>height.frag</p>\n<pre><code>vec2 sourceUv = backtraceUv(vUv, flow, fboSize, dt);\nfloat sourceHeight = texture2D(heightMap, sourceUv).r;\nfloat sourceStrength = smoothstep(\n  velocityThreshold.x,\n  velocityThreshold.y,\n  length(texture2D(velocity, sourceUv).xy)\n);\nfloat added = min(\n  sourceHeight,\n  sourceStrength * 0.3 * sourceHeight\n);</code></pre>\n<p><code>vUv</code> is the current pixel&#39;s position. <code>sourceUv</code> is the position found by tracing the velocity backward.<br />\nThe <code>backtraceUv()</code> function uses velocity and the time step <code>dt</code> to calculate that position.<br />\n<code>added</code> is the thickness brought from the source position to the current pixel.</p>\n<p>Finally, I subtract <code>removed</code> from the current thickness and add <code>added</code> to update the height map.</p>\n<p>height.frag</p>\n<pre><code>float nextHeight = max(0.0, previousHeight - removed + added);\ngl_FragColor = vec4(nextHeight, 0.0, 0.0, 1.0);</code></pre>\n<p>The result is written to the R channel of <code>gl_FragColor</code>. The G and B channels are 0, and the A channel is 1.<br />\nThe alpha map and rendering shaders later read this value using <code>texture2D(heightMap, vUv).r</code>.</p>\n<p>In this way, each pixel loses some thickness and gains thickness from its backtraced source position.  </p>\n<p>I also use <code>smoothstep()</code> so that the thickness barely moves when velocity is small.<br />\nThis prevents stationary areas from constantly flowing and focuses movement around the areas affected by dragging.</p>\n<p>This is not a physically accurate, volume-conserving calculation. I adjusted it to achieve the appearance I wanted.<br />\nEach frame, I sample the previous height map, render the result into the next one, and alternate between two FBOs.</p>\n<h3 id=\"2-keeping-the-traces-with-an-alpha-map\">2. Keeping the Traces with an Alpha Map</h3>\n<figure><img src=\"https://mofu-dev.com/images/blog/fluid-foundation/alpha-history_en.svg\" alt=\"How current thickness and the historical maximum determine opacity\" loading=\"lazy\" decoding=\"async\" referrerpolicy=\"no-referrer\" /></figure>\n<p>A height map represents the raised shape of the liquid, but it doesn&#39;t fully reproduce the traces left when the liquid is spread thinly.<br />\nI wanted some color to remain even where the thickness had almost disappeared, so I added a separate alpha map.</p>\n<p>This alpha map uses both a value derived from the current thickness and the maximum value recorded so far.</p>\n<p>alpha.frag</p>\n<pre><code>float previousMaximum = texture2D(alphaMap, vUv).r;\nfloat current = smoothstep(\n  0.0,\n  0.01 / 0.7,\n  max(0.0, texture2D(heightMap, vUv).r)\n);\nfloat maximum = max(current, previousMaximum);\ngl_FragColor = vec4(\n  maximum,\n  maximum * 0.5 + current * 0.5,\n  0.0,\n  0.0\n);</code></pre>\n<p><code>current</code> is calculated from the current frame&#39;s height map.<br />\n<code>maximum</code> keeps whichever is larger: the current value or the previous maximum. This records where the liquid has passed.</p>\n<p>The R channel stores the historical maximum, while the G channel stores an equal blend of that maximum and the current value. The B channel is unused.<br />\nThe final rendering pass samples the G channel.</p>\n<p>As a result, opacity doesn&#39;t immediately fall to zero when the liquid moves away and the thickness decreases.<br />\nSome color remains where the liquid has passed, making it appear to adhere to the surface.</p>\n<p>This isn&#39;t a physical model of drying or absorption. It is simply <strong>a history used to preserve the traces of the liquid</strong>.</p>\n<figure><img src=\"https://mofu-dev.com/images/blog/fluid-foundation/image-alpha_en.png\" alt=\"Comparison showing the traces preserved by the height map and alpha map\" loading=\"lazy\" decoding=\"async\" referrerpolicy=\"no-referrer\" /></figure>\n<h3 id=\"3-calculating-normals-from-the-height-map\">3. Calculating Normals from the Height Map</h3>\n<p>Finally, I use the height map to add highlights to the liquid&#39;s surface.<br />\nThis demo doesn&#39;t move actual geometry vertices to form the liquid&#39;s bumps and ridges.<br />\nInstead, I calculate surface normals from the height map inside the fragment shader.</p>\n<p>For each pixel, I sample its height and the heights of its immediate neighbors in the X and Y directions.<br />\nThese three points form two vectors, whose cross product gives the surface normal.</p>\n<p>render.frag</p>\n<pre><code>float height = texture2D(heightMap, vUv).r;\nvec2 stepSize = 1.0 / resolution;\nvec2 uvX = vUv + vec2(stepSize.x, 0.0);\nvec2 uvY = vUv + vec2(0.0, stepSize.y);\n\nfloat heightScale = 0.2 / 0.66;\nvec2 ratio = resolution / min(resolution.x, resolution.y);\n\nvec3 position = vec3(\n  (vUv * ratio).x,\n  height * heightScale,\n  (vUv * ratio).y\n);\nvec3 positionX = vec3(\n  (uvX * ratio).x,\n  texture2D(heightMap, uvX).r * heightScale,\n  (uvX * ratio).y\n);\nvec3 positionY = vec3(\n  (uvY * ratio).x,\n  texture2D(heightMap, uvY).r * heightScale,\n  (uvY * ratio).y\n);\n\nvec3 normal = -normalize(\n  cross(positionX - position, positionY - position)\n);</code></pre>\n<p>The normal has a different direction on flat areas and steeply raised areas.<br />\nThis difference lets me render shading and highlights that make the flat surface appear to have raised liquid on it.</p>\n<p>I use a Matcap texture for the color and highlights.<br />\nI convert the normal into Matcap UV coordinates, sample its color, and combine it with opacity from the alpha map.</p>\n<p>render.frag</p>\n<pre><code>vec3 color = texture2D(\n  matcap,\n  normal.zx * 0.5 + 0.5\n).rgb + 0.05;\n\nfloat alphaValue = texture2D(alphaMap, vUv).g;\ngl_FragColor = vec4(\n  color,\n  step(0.1, alphaValue) * alphaValue\n);</code></pre>\n<p>The actual shader also adjusts the color based on the tilt of the normal.<br />\nThe height map controls the surface shape, the Matcap controls the appearance, and the alpha map determines how the liquid&#39;s traces remain on the surface.</p>\n<h3 id=\"this-is-not-a-physically-accurate-fluid-simulation\">This Is Not a Physically Accurate Fluid Simulation</h3>\n<p>The thickness calculation described above is not physically accurate.</p>\n<p>Fragment shaders process pixels in parallel, so a pixel cannot directly write its thickness into another pixel at the destination indicated by its velocity.<br />\nInstead, each destination pixel traces the velocity backward and samples the height map at the source position.</p>\n<p>However, multiple pixels can sample approximately the same source region.<br />\nBecause thickness isn&#39;t distributed precisely among destinations, the total amounts removed and added don&#39;t always match. Therefore, the total liquid volume isn&#39;t conserved.</p>\n<figure><img src=\"https://mofu-dev.com/images/blog/fluid-foundation/image4_en.webp\" alt=\"Straight strokes keep the thickness relatively stable, while curved strokes can increase the amount of liquid\" loading=\"lazy\" decoding=\"async\" referrerpolicy=\"no-referrer\" /></figure>\n<p>As shown above, the thickness remains relatively stable with straight movements.<br />\nWhen drawing circles, however, the sampling bias accumulates and the amount of liquid keeps increasing.<br />\nThis method prioritizes visual appearance rather than accurately conserving the amount of liquid.</p>\n<h3 id=\"bonus-texture-precision\">Bonus: Texture Precision</h3>\n<p>I also noticed something interesting during development.<br />\nThe demo below shows grayscale lighting calculated from height-map normals. Use the toggle to switch between 8-bit and 32-bit float textures.</p>\n<figure><img src=\"https://mofu-dev.com/images/blog/fluid-foundation/8bit32bit.webp\" alt=\"Stepped shading with an 8-bit texture compared with smooth shading using a 32-bit floating-point texture\" loading=\"lazy\" decoding=\"async\" referrerpolicy=\"no-referrer\" /></figure>\n<p>A 32-bit floating-point texture can store height values with finer precision, producing smoother contours and shading.<br />\nAn 8-bit texture, on the other hand, stores only 256 levels per channel. This quantizes the height map and produces visible steps in the normals and shading.<br />\nI found it interesting that the limitations of 8-bit precision, which I usually associate with color gradients, showed up here as visible steps in the shading.</p>\n<h3 id=\"bonus-mixing-three-colored-liquids\">Bonus: Mixing Three Colored Liquids</h3>\n<p>I also tried another experiment for fun.<br />\nI prepared three hemispherical blobs like the one in the first demo and gave each a different color. You can drag your mouse or finger to spread the liquids and mix their colors.</p>\n<p>Each liquid has its own height map and alpha history, while all three share the same velocity map. Thickness and opacity are updated using the same calculations as in the first demo.<br />\nFinally, I mix the colors according to each liquid&#39;s thickness using a simplified Kubelka–Munk model, and calculate surface normals from their combined height. Where the thickness is almost zero, I use the remaining alpha history of each color to determine the mixing ratios.</p>\n<h3 id=\"a-final-note\">A Final Note</h3>\n<p>I decided to write about this implementation now because I don&#39;t think I&#39;ll have many opportunities to use this method again, and because I wanted to document the method I worked out myself before AI becomes even more capable.</p>\n<p>Over the past year alone, I feel AI has become much better at understanding coordinates and space, and at connecting the visuals I want to create with the calculations and implementation needed to achieve them.</p>\n<p>Publishing this may mean the method is no longer something special. Even so, I thought I could leave a trace of what I was thinking and how I arrived at this visual effect.</p>","headings":[{"level":2,"text":"Introduction","id":"introduction"},{"level":2,"text":"Liquid Spreading Demo","id":"liquid-spreading-demo"},{"level":2,"text":"Where I Started","id":"where-i-started"},{"level":2,"text":"How It Works","id":"how-it-works"},{"level":3,"text":"First, Some Background","id":"first-some-background"},{"level":3,"text":"What Is a Height Map?","id":"what-is-a-height-map"},{"level":3,"text":"Implementation Flow","id":"implementation-flow"},{"level":3,"text":"1. Moving Thickness with the Velocity Map","id":"1-moving-thickness-with-the-velocity-map"},{"level":3,"text":"2. Keeping the Traces with an Alpha Map","id":"2-keeping-the-traces-with-an-alpha-map"},{"level":3,"text":"3. Calculating Normals from the Height Map","id":"3-calculating-normals-from-the-height-map"},{"level":3,"text":"This Is Not a Physically Accurate Fluid Simulation","id":"this-is-not-a-physically-accurate-fluid-simulation"},{"level":3,"text":"Bonus: Texture Precision","id":"bonus-texture-precision"},{"level":3,"text":"Bonus: Mixing Three Colored Liquids","id":"bonus-mixing-three-colored-liquids"},{"level":3,"text":"A Final Note","id":"a-final-note"}]}}