Files
2026-04-30 13:50:11 +09:00

259 lines
8.8 KiB
JavaScript

// Stable fluids simulation on GPU (WebGL)
// Inspired by: Jos Stam's "Stable Fluids" and GPU Gems
(function() {
const canvas = document.querySelector('canvas');
if (!canvas) return;
const gl = canvas.getContext('webgl2', { alpha: false });
if (!gl) return console.error('WebGL2 required');
// Config
const SIM_RESOLUTION = 128;
const DYE_RESOLUTION = 512;
const VELOCITY_DISSIPATION = 0.98;
const DENSITY_DISSIPATION = 0.9;
const PRESSURE_ITERATIONS = 25;
let time = 0;
// Resize canvas
function resize() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
gl.viewport(0, 0, canvas.width, canvas.height);
}
resize();
window.addEventListener('resize', resize);
// Shader compilation
function compileShader(src, type) {
const shader = gl.createShader(type);
gl.shaderSource(shader, src);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
console.error(gl.getShaderInfoLog(shader));
return null;
}
return shader;
}
function createProgram(vertSrc, fragSrc) {
const vert = compileShader(vertSrc, gl.VERTEX_SHADER);
const frag = compileShader(fragSrc, gl.FRAGMENT_SHADER);
if (!vert || !frag) return null;
const prog = gl.createProgram();
gl.attachShader(prog, vert);
gl.attachShader(prog, frag);
gl.linkProgram(prog);
if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) {
console.error(gl.getProgramInfoLog(prog));
return null;
}
gl.deleteShader(vert);
gl.deleteShader(frag);
return prog;
}
const quadVertShader = `#version 300 es
precision highp float;
out vec2 uv;
void main() {
uv = vec2((gl_VertexID >> 1) & 1, gl_VertexID & 1) * 2.0;
gl_Position = vec4(uv * 2.0 - 1.0, 0.0, 1.0);
}
`;
const clearShader = createProgram(quadVertShader, `#version 300 es
precision highp float;
uniform sampler2D field;
uniform float value;
in vec2 uv;
out vec4 outColor;
void main() {
outColor = texture(field, uv) * value;
}
`);
const advectShader = createProgram(quadVertShader, `#version 300 es
precision highp float;
uniform sampler2D field;
uniform sampler2D velocity;
uniform float dt;
uniform float dissipation;
in vec2 uv;
out vec4 outColor;
void main() {
vec2 coord = uv - dt * texture(velocity, uv).xy;
outColor = dissipation * texture(field, fract(coord + 0.5) - 0.5);
}
`);
const divergenceShader = createProgram(quadVertShader, `#version 300 es
precision highp float;
uniform sampler2D velocity;
uniform float texelSize;
in vec2 uv;
out vec4 outColor;
void main() {
float left = texture(velocity, uv - vec2(texelSize, 0)).x;
float right = texture(velocity, uv + vec2(texelSize, 0)).x;
float bottom = texture(velocity, uv - vec2(0, texelSize)).y;
float top = texture(velocity, uv + vec2(0, texelSize)).y;
float div = 0.5 * (right - left + top - bottom);
outColor = vec4(div, 0, 0, 1);
}
`);
const pressureShader = createProgram(quadVertShader, `#version 300 es
precision highp float;
uniform sampler2D pressure;
uniform sampler2D divergence;
uniform float texelSize;
in vec2 uv;
out vec4 outColor;
void main() {
float left = texture(pressure, uv - vec2(texelSize, 0)).x;
float right = texture(pressure, uv + vec2(texelSize, 0)).x;
float bottom = texture(pressure, uv - vec2(0, texelSize)).x;
float top = texture(pressure, uv + vec2(0, texelSize)).x;
float div = texture(divergence, uv).x;
float p = (left + right + bottom + top - div) * 0.25;
outColor = vec4(p, 0, 0, 1);
}
`);
const subtractGradientShader = createProgram(quadVertShader, `#version 300 es
precision highp float;
uniform sampler2D velocity;
uniform sampler2D pressure;
uniform float texelSize;
in vec2 uv;
out vec4 outColor;
void main() {
float left = texture(pressure, uv - vec2(texelSize, 0)).x;
float right = texture(pressure, uv + vec2(texelSize, 0)).x;
float bottom = texture(pressure, uv - vec2(0, texelSize)).x;
float top = texture(pressure, uv + vec2(0, texelSize)).x;
vec2 vel = texture(velocity, uv).xy;
vel -= vec2(right - left, top - bottom) * 0.5;
outColor = vec4(vel, 0, 1);
}
`);
const displayShader = createProgram(quadVertShader, `#version 300 es
precision highp float;
uniform sampler2D density;
in vec2 uv;
out vec4 outColor;
void main() {
float d = texture(density, uv).x;
outColor = vec4(mix(vec3(0), vec3(1, 0.5, 0.2), d * 3.0), 1);
}
`);
// Texture utilities
function createTexture(w, h, format, type, data) {
const tex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.texImage2D(gl.TEXTURE_2D, 0, format, w, h, 0, format, type, data);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
return tex;
}
// Create ping-pong textures
const velocity = [
createTexture(SIM_RESOLUTION, SIM_RESOLUTION, gl.RG16F, gl.HALF_FLOAT),
createTexture(SIM_RESOLUTION, SIM_RESOLUTION, gl.RG16F, gl.HALF_FLOAT)
];
const density = [
createTexture(DYE_RESOLUTION, DYE_RESOLUTION, gl.R16F, gl.HALF_FLOAT),
createTexture(DYE_RESOLUTION, DYE_RESOLUTION, gl.R16F, gl.HALF_FLOAT)
];
const pressure = [
createTexture(SIM_RESOLUTION, SIM_RESOLUTION, gl.R16F, gl.HALF_FLOAT),
createTexture(SIM_RESOLUTION, SIM_RESOLUTION, gl.R16F, gl.HALF_FLOAT)
];
const divergence = createTexture(SIM_RESOLUTION, SIM_RESOLUTION, gl.R16F, gl.HALF_FLOAT);
// Framebuffer
const fbo = gl.createFramebuffer();
function renderToTexture(target) {
gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, target, 0);
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
}
function renderProgram(program, target, w, h) {
renderToTexture(target);
gl.viewport(0, 0, w, h);
gl.useProgram(program);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
}
// Inject dye and velocity
let velocityIdx = 0, densityIdx = 0, pressureIdx = 0;
function step() {
time += 0.016;
// Add dye at center
gl.bindTexture(gl.TEXTURE_2D, density[densityIdx]);
const cx = 0.5, cy = 0.5 + 0.1 * Math.sin(time);
const amount = 0.1;
// Simple dye injection via texture update (not efficient but works)
gl.texSubImage2D(gl.TEXTURE_2D, 0, Math.floor(cx * DYE_RESOLUTION), Math.floor(cy * DYE_RESOLUTION), 1, 1, gl.RED, gl.HALF_FLOAT, new Uint16Array([65504]));
// Add velocity
const angle = time * 2;
const vx = Math.cos(angle) * 0.3;
const vy = Math.sin(angle) * 0.3;
gl.bindTexture(gl.TEXTURE_2D, velocity[velocityIdx]);
gl.texSubImage2D(gl.TEXTURE_2D, 0, Math.floor(cx * SIM_RESOLUTION), Math.floor(cy * SIM_RESOLUTION), 1, 1, gl.RG, gl.HALF_FLOAT, new Uint16Array([convertToHalf(vx), convertToHalf(vy)]));
// Advect velocity
gl.useProgram(advectShader);
gl.uniform1i(gl.getUniformLocation(advectShader, 'field'), 0);
gl.uniform1i(gl.getUniformLocation(advectShader, 'velocity'), 1);
gl.uniform1f(gl.getUniformLocation(advectShader, 'dt'), 0.016);
gl.uniform1f(gl.getUniformLocation(advectShader, 'dissipation'), VELOCITY_DISSIPATION);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, velocity[velocityIdx]);
gl.activeTexture(gl.TEXTURE1);
gl.bindTexture(gl.TEXTURE_2D, velocity[velocityIdx]);
velocityIdx = 1 - velocityIdx;
renderProgram(advectShader, velocity[velocityIdx], SIM_RESOLUTION, SIM_RESOLUTION);
// Advect density
gl.useProgram(advectShader);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, density[densityIdx]);
gl.activeTexture(gl.TEXTURE1);
gl.bindTexture(gl.TEXTURE_2D, velocity[velocityIdx]);
gl.uniform1f(gl.getUniformLocation(advectShader, 'dissipation'), DENSITY_DISSIPATION);
densityIdx = 1 - densityIdx;
renderProgram(advectShader, density[densityIdx], DYE_RESOLUTION, DYE_RESOLUTION);
// Display
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.viewport(0, 0, canvas.width, canvas.height);
gl.useProgram(displayShader);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, density[densityIdx]);
gl.uniform1i(gl.getUniformLocation(displayShader, 'density'), 0);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
requestAnimationFrame(step);
}
function convertToHalf(f) {
// Simplified float-to-half conversion
return Math.floor(f * 32768) & 0xFFFF;
}
step();
})();