More fluid simulation settings

This commit is contained in:
Dynamitos committed 2026-10-13 17:24:55 +02:00
1 parent b1004d5c80
commit f2a3f59ab1
5 files changed
+221 -19

No files matched your search

+68
View File
@@ -0,0 +1,68 @@
import FluidGridData;
// Diagnostics-only: sums the interior of several fields so we can watch
// "mass" over time on the CPU. Not part of the simulation.
struct Params
{
// read-only
FluidGridData<float> density;
FluidGridData<float> phi;
FluidGridData<float> velocityX;
FluidGridData<float> velocityY;
FluidGridData<float> velocityZ;
// read-write: [0]=density sum, [1]=phi sum, [2]=|velocity| sum
RWStructuredBuffer<float> out;
};
ParameterBlock<Params> params;
// Reduce the 32x8 thread group via shared memory, then one atomic add per group.
groupshared float laneD[256];
groupshared float laneP[256];
groupshared float laneV[256];
// One thread group per z-slice; each thread covers a 32x8 tile of the x/y plane.
[numthreads(32, 8, 1)]
[shader("compute")]
void massProbe(uint3 dispatchThreadID : SV_DispatchThreadID)
{
FluidGridData<float> density = params.density;
FluidGridData<float> phi = params.phi;
FluidGridData<float> velocityX = params.velocityX;
FluidGridData<float> velocityY = params.velocityY;
FluidGridData<float> velocityZ = params.velocityZ;
RWStructuredBuffer<float> out = params.out;
// Interior only: skip the 1-cell boundary shell (matches the other passes).
int x = dispatchThreadID.x + 1;
int y = dispatchThreadID.y + 1;
int z = dispatchThreadID.z + 1;
if (x >= gridParams.gridSize.x - 1 || y >= gridParams.gridSize.y - 1 || z >= gridParams.gridSize.z - 1)
return;
float dSum = density[x, y, z];
float pSum = phi[x, y, z];
float vSum = sqrt(velocityX[x, y, z] * velocityX[x, y, z] +
velocityY[x, y, z] * velocityY[x, y, z] +
velocityZ[x, y, z] * velocityZ[x, y, z]);
uint lane = dispatchThreadID.x + dispatchThreadID.y * 32; // 0..255
laneD[lane] = dSum;
laneP[lane] = pSum;
laneV[lane] = vSum;
GroupMemoryBarrierWithGroupSync();
// Lane 0 of the group sums all 256 lanes and atomically adds to the global total.
if (lane == 0)
{
float td = 0.0f, tp = 0.0f, tv = 0.0f;
for (uint i = 0; i < 256; ++i)
{
td += laneD[i];
tp += laneP[i];
tv += laneV[i];
}
InterlockedAdd(out[0], td);
InterlockedAdd(out[1], tp);
InterlockedAdd(out[2], tv);
}
}
+8
View File
@@ -76,6 +76,14 @@ void setBound(uint3 dispatchThreadID : SV_DispatchThreadID)
if (numAffecting > 0)
{
// For all quantities (velocity components AND scalars: pressure,
// divergence, density) the boundary cell takes the (factor-scaled)
// interior neighbor value. For scalars the factor is 1 (Neumann / copy),
// which is the correct boundary condition for the pressure Poisson solve
// (zero normal gradient) and for the divergence. Do NOT zero the scalar
// boundary: zeroing the pressure shell breaks the Poisson Neumann
// condition, corrupts the projection, and injects energy into the
// velocity field (observed as |vel|_sum runaway).
grid[uint3(pos)] = valueSum / float(numAffecting);
}
}
@@ -9,6 +9,7 @@
#include "Math/Vector.h"
#include "Scene/FluidScene.h"
#include <algorithm>
#include <iostream>
using namespace Seele;
@@ -21,6 +22,10 @@ constexpr static int pressureSolveIterations = 100;
constexpr static int densityDiffuseIterations = 8;
constexpr static float pressureSORomega = 1.95f;
constexpr static float diffusionSORomega = 1.0f;
// Substep the semi-Lagrangian advection so the backtrace moves <~1 cell per
// step. A single full-dt advect at dt=0.1 moves many cells and smears the
// passive scalar (density) hard, which is the dominant source of mass loss.
constexpr static int advectionSubsteps = 8;
#define SWAP(a, b) \
{ \
@@ -307,6 +312,57 @@ SimulationComputePass::SimulationComputePass(Gfx::PGraphics graphics, PScene sce
.pipelineLayout = applyForces.pipelineLayout,
});
}
{
// Diagnostics-only mass probe: sums interior fields into a 3-float buffer.
massProbe.pipelineLayout = graphics->createPipelineLayout("MassProbePipelineLayout");
massProbe.descriptorLayout = graphics->createDescriptorLayout("params");
massProbe.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
.name = "density",
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
});
massProbe.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
.name = "phi",
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
});
massProbe.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
.name = "velocityX",
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
});
massProbe.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
.name = "velocityY",
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
});
massProbe.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
.name = "velocityZ",
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
});
massProbe.descriptorLayout->addDescriptorBinding(Gfx::DescriptorBinding{
.name = "out",
.descriptorType = Gfx::SE_DESCRIPTOR_TYPE_STORAGE_BUFFER,
});
massProbe.descriptorLayout->create();
massProbe.pipelineLayout->addDescriptorLayout(massProbe.descriptorLayout);
massProbe.pipelineLayout->addDescriptorLayout(gridSizeLayout);
graphics->beginShaderCompilation(ShaderCompilationInfo{
.name = "MassProbe",
.modules = {"MassProbe"},
.entryPoints = {{"massProbe", "MassProbe"}},
.rootSignature = massProbe.pipelineLayout,
});
massProbe.pipelineLayout->create();
massProbe.shader = graphics->createComputeShader({0});
massProbe.pipeline = graphics->createComputePipeline(Gfx::ComputePipelineCreateInfo{
.computeShader = massProbe.shader,
.pipelineLayout = massProbe.pipelineLayout,
});
// 3 floats: [0]=density sum, [1]=phi sum, [2]=|velocity| sum.
probeOutBuffer = graphics->createShaderBuffer(ShaderBufferCreateInfo{
.sourceData = {
.size = 3 * sizeof(float),
},
.name = "MassProbeOut",
});
}
}
SimulationComputePass::~SimulationComputePass() {}
@@ -369,23 +425,33 @@ void SimulationComputePass::render() {
graphics->endDebugRegion();
graphics->beginDebugRegion("Advect");
advectPass(data.velocityXBuffer, data.velocityX0Buffer, data.velocityX0Buffer, data.velocityY0Buffer, data.velocityZ0Buffer, data.dt,
data.gridSize);
advectPass(data.velocityYBuffer, data.velocityY0Buffer, data.velocityX0Buffer, data.velocityY0Buffer, data.velocityZ0Buffer, data.dt,
data.gridSize);
advectPass(data.velocityZBuffer, data.velocityZ0Buffer, data.velocityX0Buffer, data.velocityY0Buffer, data.velocityZ0Buffer, data.dt,
data.gridSize);
// Substep ONLY the advection: each step uses dt/substeps so the
// backtrace displacement stays small, reducing the numerical (bilinear)
// dissipation of the semi-Lagrangian scheme. The pressure re-projection
// is a GLOBAL operation and must run exactly once per frame on the final
// velocity field — running it inside the substep loop over-corrects and
// injects energy into the velocity field (observed as |vel|_sum runaway).
const float subDt = data.dt / advectionSubsteps;
for (int sub = 0; sub < advectionSubsteps; ++sub) {
advectPass(data.velocityXBuffer, data.velocityX0Buffer, data.velocityX0Buffer, data.velocityY0Buffer, data.velocityZ0Buffer, subDt,
data.gridSize);
advectPass(data.velocityYBuffer, data.velocityY0Buffer, data.velocityX0Buffer, data.velocityY0Buffer, data.velocityZ0Buffer, subDt,
data.gridSize);
advectPass(data.velocityZBuffer, data.velocityZ0Buffer, data.velocityX0Buffer, data.velocityY0Buffer, data.velocityZ0Buffer, subDt,
data.gridSize);
if (data.enableGravity) {
applyForcesPass(data.velocityXBuffer, data.velocityYBuffer, data.velocityZBuffer, data.gravity, data.dt, data.gridSize);
if (data.enableGravity) {
applyForcesPass(data.velocityXBuffer, data.velocityYBuffer, data.velocityZBuffer, data.gravity, subDt, data.gridSize);
}
// Set boundary conditions after advection/forces so the divergence sees correct wall values
setBoundsPass(data.velocityXBuffer, 1, data.gridSize, data.planeBuffer, data.numPlanes);
setBoundsPass(data.velocityYBuffer, 2, data.gridSize, data.planeBuffer, data.numPlanes);
setBoundsPass(data.velocityZBuffer, 3, data.gridSize, data.planeBuffer, data.numPlanes);
}
// Set boundary conditions after advection/forces so the divergence sees correct wall values
setBoundsPass(data.velocityXBuffer, 1, data.gridSize, data.planeBuffer, data.numPlanes);
setBoundsPass(data.velocityYBuffer, 2, data.gridSize, data.planeBuffer, data.numPlanes);
setBoundsPass(data.velocityZBuffer, 3, data.gridSize, data.planeBuffer, data.numPlanes);
// Re-project after advection/forces to keep the final velocity field divergence-free.
// Re-project ONCE per frame after all substeps to keep the final velocity
// field divergence-free.
Gfx::PShaderBuffer advectedDivergence = data.velocityXNextBuffer;
Gfx::PShaderBuffer advectedPressure = data.velocityYNextBuffer;
divergencePass(advectedDivergence, advectedPressure, data.velocityXBuffer, data.velocityYBuffer, data.velocityZBuffer, data.gridSize);
@@ -422,14 +488,20 @@ void SimulationComputePass::render() {
}
graphics->endDebugRegion();
graphics->beginDebugRegion("AdvectDensity");
advectPass(data.density0Buffer, densityCurrent, data.velocityX0Buffer, data.velocityY0Buffer, data.velocityZ0Buffer, data.dt,
data.gridSize);
setBoundsPass(data.density0Buffer, 0, data.gridSize, data.planeBuffer, data.numPlanes);
// Substep density advection with the same small subDt as the velocity
// advection so the passive scalar is not smeared by a large backtrace.
for (int sub = 0; sub < advectionSubsteps; ++sub) {
advectPass(data.density0Buffer, densityCurrent, data.velocityX0Buffer, data.velocityY0Buffer, data.velocityZ0Buffer, subDt,
data.gridSize);
setBoundsPass(data.density0Buffer, 0, data.gridSize, data.planeBuffer, data.numPlanes);
}
graphics->endDebugRegion();
graphics->beginDebugRegion("AdvectLevelSet");
advectPass(data.phiBuffer, data.phi0Buffer, data.velocityX0Buffer, data.velocityY0Buffer, data.velocityZ0Buffer, data.dt, data.gridSize);
setBoundsPass(data.phiBuffer, 0, data.gridSize, data.planeBuffer, data.numPlanes);
for (int sub = 0; sub < advectionSubsteps; ++sub) {
advectPass(data.phiBuffer, data.phi0Buffer, data.velocityX0Buffer, data.velocityY0Buffer, data.velocityZ0Buffer, subDt, data.gridSize);
setBoundsPass(data.phiBuffer, 0, data.gridSize, data.planeBuffer, data.numPlanes);
}
// Reinitialize level set every N frames to restore |grad phi| = 1
if (data.frameCounter % reinitInterval == 0) {
@@ -443,6 +515,9 @@ void SimulationComputePass::render() {
data.phi0Buffer->pipelineBarrier(Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT,
Gfx::SE_ACCESS_TRANSFER_READ_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT);
graphics->endDebugRegion();
// Diagnostics: log interior field sums so we can see which quantity is decaying.
massProbePass(data.density0Buffer, data.phiBuffer, data.velocityX0Buffer, data.velocityY0Buffer, data.velocityZ0Buffer, data.gridSize);
}
}
@@ -591,6 +666,43 @@ void SimulationComputePass::applyForcesPass(Gfx::PShaderBuffer velocityX, Gfx::P
Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
}
void SimulationComputePass::massProbePass(Gfx::PShaderBuffer density, Gfx::PShaderBuffer phi, Gfx::PShaderBuffer velocityX, Gfx::PShaderBuffer velocityY,
Gfx::PShaderBuffer velocityZ, UVector gridSize) {
// Zero the 3-float accumulator before dispatching.
float zeros[3] = {0.0f, 0.0f, 0.0f};
probeOutBuffer->updateContents(0, 3 * sizeof(float), zeros);
probeOutBuffer->pipelineBarrier(Gfx::SE_ACCESS_TRANSFER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT, Gfx::SE_ACCESS_SHADER_READ_BIT | Gfx::SE_ACCESS_SHADER_WRITE_BIT,
Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
Gfx::ODescriptorSet probeSet = massProbe.descriptorLayout->allocateDescriptorSet();
probeSet->updateBuffer("density", 0, density);
probeSet->updateBuffer("phi", 0, phi);
probeSet->updateBuffer("velocityX", 0, velocityX);
probeSet->updateBuffer("velocityY", 0, velocityY);
probeSet->updateBuffer("velocityZ", 0, velocityZ);
probeSet->updateBuffer("out", 0, probeOutBuffer);
probeSet->writeChanges();
Gfx::OComputeCommand probeCommand = graphics->createComputeCommand();
probeCommand->bindPipeline(massProbe.pipeline);
probeCommand->bindDescriptor(probeSet);
probeCommand->bindDescriptor(gridSizeSet);
probeCommand->dispatch(getDispatchSize(gridSize, massProbe.threadGroupSize));
graphics->executeCommands(std::move(probeCommand));
// Blocking readback (safe mid-frame: the Vulkan impl waits on a fence internally).
float results[3] = {0.0f, 0.0f, 0.0f};
probeOutBuffer->pipelineBarrier(Gfx::SE_ACCESS_SHADER_WRITE_BIT, Gfx::SE_PIPELINE_STAGE_COMPUTE_SHADER_BIT, Gfx::SE_ACCESS_TRANSFER_READ_BIT,
Gfx::SE_PIPELINE_STAGE_TRANSFER_BIT);
probeOutBuffer->readContents(0, 3 * sizeof(float), results);
std::cout << "[MassProbe] frame=" << probeFrame
<< " density_sum=" << results[0]
<< " phi_sum=" << results[1]
<< " |vel|_sum=" << results[2] << std::endl;
++probeFrame;
}
void SimulationComputePass::reinitializeLevelSetPass(Seele::Gfx::PShaderBuffer phi, Seele::Gfx::PShaderBuffer phi0, Seele::Gfx::PShaderBuffer phiSign, UVector gridSize, Gfx::PShaderBuffer planeBuffer, uint32 numPlanes) {
graphics->beginDebugRegion("ReinitializeLevelSet");
// Snapshot current phi into phiSign for the sign function (preserved across all iterations)
@@ -79,8 +79,21 @@ class SimulationComputePass : public RenderPass {
constexpr static UVector threadGroupSize = {32, 8, 1};
} applyForces;
void applyForcesPass(Gfx::PShaderBuffer velocityX, Gfx::PShaderBuffer velocityY, Gfx::PShaderBuffer velocityZ, Vector gravity, float dt, UVector gridSize);
// Diagnostics: sum interior fields and log to console. Not part of the simulation.
void massProbePass(Gfx::PShaderBuffer density, Gfx::PShaderBuffer phi, Gfx::PShaderBuffer velocityX, Gfx::PShaderBuffer velocityY,
Gfx::PShaderBuffer velocityZ, UVector gridSize);
struct MassProbe {
Gfx::OPipelineLayout pipelineLayout;
Gfx::ODescriptorLayout descriptorLayout;
Gfx::OComputeShader shader;
Gfx::PComputePipeline pipeline;
constexpr static UVector threadGroupSize = {32, 8, 1};
} massProbe;
Gfx::ODescriptorLayout gridSizeLayout;
Gfx::ODescriptorSet gridSizeSet;
// Diagnostics: 3 floats (density sum, phi sum, |velocity| sum), zeroed each frame.
Gfx::OShaderBuffer probeOutBuffer;
uint32 probeFrame = 0;
struct BoundaryPlane {
Vector normal;
float d;
+1
View File
@@ -818,6 +818,7 @@ Array<const char*> Graphics::getRequiredExtensions() {
throw std::runtime_error("Missing required Vulkan instance extension VK_KHR_surface");
}
const bool hasWayland = hasValidatedExtension("VK_KHR_wayland_surface");
const bool hasXlib = hasValidatedExtension("VK_KHR_xlib_surface");
const bool hasXcb = hasValidatedExtension("VK_KHR_xcb_surface");