This commit is contained in:
2026-05-05 19:39:11 +02:00
parent 608dabff12
commit d6b1d214f5
11 changed files with 493 additions and 277 deletions

11
Core/Constants.cs Normal file
View File

@@ -0,0 +1,11 @@
namespace FluidSim.Core
{
public static class Constants
{
public const double Gamma = 1.4;
public const double R_gas = 287.0; // J/(kg·K)
public const double P_amb = 101325.0; // Pa
public const double T_amb = 300.0; // K
public static readonly double Rho_amb = P_amb / (R_gas * T_amb); // ≈ 1.177 kg/m³
}
}

View File

@@ -9,7 +9,6 @@ namespace FluidSim.Core
out double massFlow, out double rhoFace, out double uFace, out double pFace,
double gamma = 1.4)
{
// Default fallback (no flow)
massFlow = 0.0;
rhoFace = 0.0;
uFace = 0.0;
@@ -29,16 +28,43 @@ namespace FluidSim.Core
double pr = downstreamPressure / p0;
double choked = Math.Pow(2.0 / (gamma + 1.0), gamma / (gamma - 1.0));
if (pr < choked) pr = choked;
double M = Math.Sqrt((2.0 / (gamma - 1.0)) * (Math.Pow(pr, -(gamma - 1.0) / gamma) - 1.0));
if (double.IsNaN(M)) return;
// If pr > 1, flow is INTO the cylinder (reverse), so we swap the roles.
bool reverse = (pr > 1.0);
if (reverse)
{
// Treat the cylinder as the downstream, the pipe as the upstream.
double p_up = downstreamPressure;
double T_up = 300.0; // pipe temperature (ambient)
double rho_up = downstreamPressure / (R * T_up);
uFace = M * Math.Sqrt(gamma * R * T0);
rhoFace = rho0 * Math.Pow(pr, 1.0 / gamma);
pFace = p0 * pr;
double pr_rev = p0 / p_up; // now cylinder / pipe
if (pr_rev < choked) pr_rev = choked;
double M = Math.Sqrt((2.0 / (gamma - 1.0)) * (Math.Pow(pr_rev, -(gamma - 1.0) / gamma) - 1.0));
if (double.IsNaN(M)) return;
// Flow from pipe INTO cylinder (positive mass flow into volume)
uFace = M * Math.Sqrt(gamma * R * T_up);
rhoFace = rho_up * Math.Pow(pr_rev, 1.0 / gamma);
pFace = p_up * pr_rev;
massFlow = rhoFace * uFace * area;
// massFlow is positive = into cylinder
}
else
{
// Normal flow out of cylinder
if (pr < choked) pr = choked;
double M = Math.Sqrt((2.0 / (gamma - 1.0)) * (Math.Pow(pr, -(gamma - 1.0) / gamma) - 1.0));
if (double.IsNaN(M)) return;
uFace = M * Math.Sqrt(gamma * R * T0);
rhoFace = rho0 * Math.Pow(pr, 1.0 / gamma);
pFace = p0 * pr;
massFlow = -rhoFace * uFace * area; // negative = out of cylinder
}
massFlow = rhoFace * uFace * area;
if (double.IsNaN(massFlow) || double.IsInfinity(massFlow))
massFlow = 0.0;
}

View File

@@ -4,95 +4,124 @@ namespace FluidSim.Core
{
public class OutdoorExhaustReverb
{
// ---- Geometry ----
private const float GroundReflDelay = 0.008f; // 8 ms (≈1.3 m)
private const float WallRefl1Delay = 0.045f; // ≈15 m
private const float WallRefl2Delay = 0.080f; // ≈27 m
// ========== Early reflection delays (stereo: left/right) ==========
private readonly DelayLine groundL, groundR;
private readonly DelayLine wall1L, wall1R;
private readonly DelayLine wall2L, wall2R;
private DelayLine groundRefl;
private DelayLine wallRefl1;
private DelayLine wallRefl2;
// ---- FDN for late diffuse tail ----
private const int FDN_CHANNELS = 8; // dense, realistic
private DelayLine[] fdnDelays;
private float[] fdnState;
private OrthonormalMixer mixer; // energypreserving mixing
private LowPassFilter[] channelFilters; // perchannel air absorption
// ========== Diffuse tail FDNs (left/right each with 8 channels) ==========
private const int FDN_CHANNELS = 8;
private readonly DelayLine[] fdnL, fdnR;
private readonly float[] stateL, stateR;
private readonly OrthonormalMixer mixerL, mixerR;
private readonly LowPassFilter[] filterL, filterR;
public float DryMix { get; set; } = 1.0f;
public float EarlyMix { get; set; } = 0.5f;
public float TailMix { get; set; } = 0.9f;
public float Feedback { get; set; } = 0.75f; // safe range 0.70.9
public float DampingFreq { get; set; } = 6000f; // Hz, above which air absorbs strongly
public float MatrixCoeff { get; set; } = 0.5f; // (kept for compatibility, not used)
public float Feedback { get; set; } = 0.75f; // safe range 0.70.9
public float DampingFreq { get; set; } = 6000f; // Hz
public OutdoorExhaustReverb(int sampleRate)
{
// Early reflection lines
groundRefl = new DelayLine((int)(sampleRate * GroundReflDelay));
wallRefl1 = new DelayLine((int)(sampleRate * WallRefl1Delay));
wallRefl2 = new DelayLine((int)(sampleRate * WallRefl2Delay));
// Early reflections left/right offset by ~12 ms for stereo width
groundL = new DelayLine((int)(sampleRate * 0.008)); // 8 ms
groundR = new DelayLine((int)(sampleRate * 0.010)); // 10 ms
wall1L = new DelayLine((int)(sampleRate * 0.045));
wall1R = new DelayLine((int)(sampleRate * 0.047));
wall2L = new DelayLine((int)(sampleRate * 0.080));
wall2R = new DelayLine((int)(sampleRate * 0.082));
// FDN delays: prime numbers for dense modal density (70150 ms)
int[] baseLengths = { 3203, 4027, 5521, 7027, 8521, 10007, 11503, 13009 };
fdnDelays = new DelayLine[FDN_CHANNELS];
// FDN delay lengths prime numbers, offset between L/R
int[] lengthsL = { 3203, 4027, 5521, 7027, 8521, 10007, 11503, 13009 };
int[] lengthsR = { 3217, 4049, 5531, 7043, 8537, 10037, 11519, 13033 };
fdnL = new DelayLine[FDN_CHANNELS];
fdnR = new DelayLine[FDN_CHANNELS];
for (int i = 0; i < FDN_CHANNELS; i++)
{
int len = Math.Min(baseLengths[i], (int)(sampleRate * 0.25)); // max 250 ms
fdnDelays[i] = new DelayLine(len);
int lenL = Math.Min(lengthsL[i], (int)(sampleRate * 0.25));
int lenR = Math.Min(lengthsR[i], (int)(sampleRate * 0.25));
fdnL[i] = new DelayLine(lenL);
fdnR[i] = new DelayLine(lenR);
}
fdnState = new float[FDN_CHANNELS];
mixer = new OrthonormalMixer(FDN_CHANNELS);
stateL = new float[FDN_CHANNELS];
stateR = new float[FDN_CHANNELS];
mixerL = new OrthonormalMixer(FDN_CHANNELS);
mixerR = new OrthonormalMixer(FDN_CHANNELS);
// Air absorption: a gentle firstorder lowpass per channel
channelFilters = new LowPassFilter[FDN_CHANNELS];
float initialCutoff = DampingFreq;
filterL = new LowPassFilter[FDN_CHANNELS];
filterR = new LowPassFilter[FDN_CHANNELS];
for (int i = 0; i < FDN_CHANNELS; i++)
channelFilters[i] = new LowPassFilter(sampleRate, initialCutoff);
{
filterL[i] = new LowPassFilter(sampleRate, DampingFreq);
filterR[i] = new LowPassFilter(sampleRate, DampingFreq);
}
}
public float Process(float drySample)
/// <summary>Stereo reverb returns (left, right) sample pair.</summary>
public (float left, float right) ProcessStereo(float drySample)
{
// ---- Early reflections ----
float g = groundRefl.ReadWrite(drySample * 0.8f);
float w1 = wallRefl1.ReadWrite(drySample * 0.5f);
float w2 = wallRefl2.ReadWrite(drySample * 0.4f);
float early = (g + w1 + w2) * EarlyMix;
float gL = groundL.ReadWrite(drySample * 0.8f);
float gR = groundR.ReadWrite(drySample * 0.8f);
float w1L = wall1L.ReadWrite(drySample * 0.5f);
float w1R = wall1R.ReadWrite(drySample * 0.5f);
float w2L = wall2L.ReadWrite(drySample * 0.4f);
float w2R = wall2R.ReadWrite(drySample * 0.4f);
// ---- FDN diffuse tail ----
// Read the delayed outputs (which were stored last iteration)
float[] delOut = new float[FDN_CHANNELS];
float earlyL = (gL + w1L + w2L) * EarlyMix;
float earlyR = (gR + w1R + w2R) * EarlyMix;
// ---- Read diffuse tail ----
float[] delOutL = new float[FDN_CHANNELS];
float[] delOutR = new float[FDN_CHANNELS];
for (int i = 0; i < FDN_CHANNELS; i++)
delOut[i] = fdnDelays[i].Read();
{
delOutL[i] = fdnL[i].Read();
delOutR[i] = fdnR[i].Read();
}
// Mix the delayed outputs with the orthonormal matrix -> scattered signals
mixer.Process(delOut, fdnState); // result written into fdnState
// Mix via orthonormal matrix
float[] mixL = new float[FDN_CHANNELS];
float[] mixR = new float[FDN_CHANNELS];
mixerL.Process(delOutL, mixL);
mixerR.Process(delOutR, mixR);
// Add fresh input to all channels
// Feedback + air absorption
for (int i = 0; i < FDN_CHANNELS; i++)
fdnState[i] = drySample * 0.15f + Feedback * fdnState[i];
{
stateL[i] = drySample * 0.15f + Feedback * mixL[i];
stateL[i] = filterL[i].Process(stateL[i]);
fdnL[i].Write(stateL[i]);
// Air absorption: perchannel onepole lowpass
stateR[i] = drySample * 0.15f + Feedback * mixR[i];
stateR[i] = filterR[i].Process(stateR[i]);
fdnR[i].Write(stateR[i]);
}
float tailL = 0.0f, tailR = 0.0f;
for (int i = 0; i < FDN_CHANNELS; i++)
fdnState[i] = channelFilters[i].Process(fdnState[i]);
{
tailL += delOutL[i];
tailR += delOutR[i];
}
tailL *= TailMix;
tailR *= TailMix;
// Write the new states into the delay lines
for (int i = 0; i < FDN_CHANNELS; i++)
fdnDelays[i].Write(fdnState[i]);
// The tail output is the sum of the delayed outputs *before* the loop
float tailSum = 0f;
for (int i = 0; i < FDN_CHANNELS; i++)
tailSum += delOut[i];
float tail = tailSum * TailMix;
// Final mix
return drySample * DryMix + early + tail;
float left = drySample * DryMix + earlyL + tailL;
float right = drySample * DryMix + earlyR + tailR;
return (left, right);
}
// ---------- Helper classes (same as before but with separate Read/Write) ----------
/// <summary>Mono fallback sums left+right / 2.</summary>
public float Process(float drySample)
{
var (l, r) = ProcessStereo(drySample);
return (l + r) * 0.5f;
}
// ========== Helper classes ==========
private class DelayLine
{
private float[] buffer;
@@ -100,19 +129,13 @@ namespace FluidSim.Core
public DelayLine(int length)
{
buffer = new float[Math.Max(length, 1)];
writePos = 0;
}
// Separated Read/Write to avoid ringing with immediate feedback
public float Read()
{
return buffer[writePos];
}
public float Read() => buffer[writePos];
public void Write(float value)
{
buffer[writePos] = value;
writePos = (writePos + 1) % buffer.Length;
}
// Old combined method (not used in FDN, only for early reflections)
public float ReadWrite(float value)
{
float outVal = buffer[writePos];
@@ -124,8 +147,7 @@ namespace FluidSim.Core
private class LowPassFilter
{
private float b0, a1;
private float y1;
private float b0, a1, y1;
private float sampleRate;
public LowPassFilter(int sampleRate, float cutoff)
{
@@ -137,7 +159,7 @@ namespace FluidSim.Core
float w = 2 * (float)Math.PI * cutoff / sampleRate;
float a0 = 1 + w;
b0 = w / a0;
a1 = (1 - w) / a0; // firstorder lowpass
a1 = (1 - w) / a0;
}
public float Process(float x)
{
@@ -147,18 +169,13 @@ namespace FluidSim.Core
}
}
/// <summary>
/// Computes a fast orthonormal mixing matrix (like Hadamard, but energypreserving).
/// </summary>
private class OrthonormalMixer
{
private int size;
public OrthonormalMixer(int size) { this.size = size; }
public OrthonormalMixer(int size) => this.size = size;
public void Process(float[] input, float[] output)
{
// Simple energyconserving “allpass” mixing:
// Use a Householder reflection: y = (2/n) * sum(x) * ones - x
float sum = 0;
for (int i = 0; i < size; i++) sum += input[i];
float factor = 2.0f / size;

View File

@@ -9,6 +9,8 @@ namespace FluidSim.Core
public bool IsPipeLeftEnd { get; }
public double OrificeArea { get; set; }
public double LastMassFlowIntoVolume { get; set; }
public PipeVolumeConnection(Volume0D vol, Pipe1D pipe, bool isPipeLeftEnd, double orificeArea)
{
Volume = vol;

View File

@@ -35,52 +35,85 @@ namespace FluidSim.Core
public float Step()
{
// 1. Compute nozzle flows and update volumes (once per audio sample)
// 1. For each connection, handle flow or closed wall
foreach (var conn in _connections)
{
double area = conn.OrificeArea;
if (area < 1e-12) // valve closed → treat as solid wall
{
conn.Volume.MassFlowRateIn = 0.0;
conn.Volume.SpecificEnthalpyIn = conn.Volume.SpecificEnthalpy; // not used
// Set ghost to a reflective wall (u = -u_pipe, same p, ρ)
int cellIdx = conn.IsPipeLeftEnd ? 0 : conn.Pipe.GetCellCount() - 1;
double rho = Math.Max(conn.Pipe.GetCellDensity(cellIdx), 1e-6);
double p = Math.Max(conn.Pipe.GetCellPressure(cellIdx), 100.0);
double u = conn.Pipe.GetCellVelocity(cellIdx);
if (conn.IsPipeLeftEnd)
conn.Pipe.SetGhostLeft(rho, -u, p);
else
conn.Pipe.SetGhostRight(rho, -u, p);
continue;
}
// Valve open → use the nozzle model
double downstreamPressure = conn.IsPipeLeftEnd
? conn.Pipe.GetCellPressure(0)
: conn.Pipe.GetCellPressure(conn.Pipe.GetCellCount() - 1);
NozzleFlow.Compute(conn.Volume, conn.OrificeArea, downstreamPressure,
NozzleFlow.Compute(conn.Volume, area, downstreamPressure,
out double mdot, out double rhoFace, out double uFace, out double pFace,
gamma: conn.Volume.Gamma);
// Limit mass flow to available mass
// Clamp mdot to available mass
double maxMdot = conn.Volume.Mass / _dt;
conn.LastMassFlowIntoVolume = mdot;
if (mdot > maxMdot) mdot = maxMdot;
if (mdot < -maxMdot) mdot = -maxMdot;
conn.Volume.MassFlowRateIn = -mdot;
conn.Volume.SpecificEnthalpyIn = (conn.Volume.Gamma / (conn.Volume.Gamma - 1.0)) *
(conn.Volume.Pressure / Math.Max(conn.Volume.Density, 1e-12));
conn.Volume.MassFlowRateIn = mdot;
// enthalpy: if inflow, use pipe enthalpy; if outflow, use cylinder enthalpy
if (mdot >= 0)
{
int cellIdx = conn.IsPipeLeftEnd ? 0 : conn.Pipe.GetCellCount() - 1;
double pPipe = Math.Max(conn.Pipe.GetCellPressure(cellIdx), 100.0);
double rhoPipe = Math.Max(conn.Pipe.GetCellDensity(cellIdx), 1e-6);
conn.Volume.SpecificEnthalpyIn = (conn.Volume.Gamma / (conn.Volume.Gamma - 1.0)) * pPipe / rhoPipe;
}
else
{
conn.Volume.SpecificEnthalpyIn = conn.Volume.SpecificEnthalpy;
}
// Integrate the volume
conn.Volume.Integrate(_dt);
// Set ghost from nozzle face state (but don't allow zero density)
if (rhoFace < 1e-6) rhoFace = Constants.Rho_amb;
if (pFace < 100.0) pFace = Constants.P_amb;
if (conn.IsPipeLeftEnd)
conn.Pipe.SetGhostLeft(rhoFace, uFace, pFace);
else
conn.Pipe.SetGhostRight(rhoFace, uFace, pFace);
}
// 2. Determine required substeps
// 2. Substep pipes
int nSub = 1;
foreach (var p in _pipes)
nSub = Math.Max(nSub, p.GetRequiredSubSteps(_dt));
double dtSub = _dt / nSub;
// 3. Substep loop for pipes
for (int sub = 0; sub < nSub; sub++)
foreach (var p in _pipes)
p.SimulateSingleStep(dtSub);
// 4. Clear ghost flags
// 3. Clear ghost flags
foreach (var p in _pipes)
p.ClearGhostFlag();
// 5. Return raw mass flow from the first pipes open end (assumed exhaust tailpipe)
// 4. Return exhaust tailpipe mass flow
if (_pipes.Count > 0)
return (float)_pipes[0].GetOpenEndMassFlow();
return 0f;
}
}