engine almost working, backup before adding gas types.
This commit is contained in:
@@ -13,11 +13,12 @@ namespace FluidSim.Core
|
||||
public double DischargeCoefficient { get; set; } = 0.62;
|
||||
|
||||
public double EffectiveLength { get; set; } = 0.001;
|
||||
public bool UseInertance { get; set; } = true;
|
||||
public bool UseInertance { get; set; } = false;
|
||||
|
||||
private double _mdot; // positive = volume → pipe
|
||||
// Current mass flow (kg/s, positive = volume → pipe)
|
||||
private double _mdot;
|
||||
|
||||
public double LastMassFlowRate { get; private set; }
|
||||
public double LastMassFlowRate { get; private set; } // positive = into volume
|
||||
public double LastFaceDensity { get; private set; }
|
||||
public double LastFaceVelocity { get; private set; }
|
||||
public double LastFacePressure { get; private set; }
|
||||
@@ -41,10 +42,10 @@ namespace FluidSim.Core
|
||||
}
|
||||
|
||||
// Gather states
|
||||
double volP = VolumePort.Pressure;
|
||||
double volP = VolumePort.Pressure;
|
||||
double volRho = VolumePort.Density;
|
||||
double volT = VolumePort.Temperature;
|
||||
double volH = VolumePort.SpecificEnthalpy;
|
||||
double volT = VolumePort.Temperature;
|
||||
double volH = VolumePort.SpecificEnthalpy;
|
||||
|
||||
(double pipeRho, double pipeU, double pipeP) = IsPipeLeftEnd
|
||||
? Pipe.GetInteriorStateLeft()
|
||||
@@ -52,25 +53,34 @@ namespace FluidSim.Core
|
||||
|
||||
double pipeT = pipeP / Math.Max(pipeRho * 287.0, 1e-12);
|
||||
double gamma = 1.4;
|
||||
double R = 287.0;
|
||||
double R = 287.0;
|
||||
|
||||
// ---- 1. Steady‑state nozzle solution (gives correct exit pressure) ----
|
||||
double mdotSS;
|
||||
// ---- Steady‑state nozzle solution (gives correct exit state) ----
|
||||
double mdotSS; // positive = volume → pipe
|
||||
double rhoFace0, uFace0, pFace0;
|
||||
if (volP >= pipeP)
|
||||
{
|
||||
IsentropicOrifice.Compute(volP, volRho, volT, pipeP, gamma, R, area, DischargeCoefficient,
|
||||
out double mdotUpToDown, out rhoFace0, out uFace0, out pFace0);
|
||||
mdotSS = mdotUpToDown; // volume → pipe
|
||||
mdotSS = mdotUpToDown;
|
||||
}
|
||||
else
|
||||
{
|
||||
IsentropicOrifice.Compute(pipeP, pipeRho, pipeT, volP, gamma, R, area, DischargeCoefficient,
|
||||
out double mdotUpToDown, out rhoFace0, out uFace0, out pFace0);
|
||||
mdotSS = -mdotUpToDown; // pipe → volume → negative for volume→pipe convention
|
||||
mdotSS = -mdotUpToDown;
|
||||
}
|
||||
|
||||
// ---- 2. Inertance dynamics ----
|
||||
// ====== Hard physical cap: max sonic flow × 1.1 ======
|
||||
double upRho = mdotSS >= 0 ? volRho : pipeRho;
|
||||
double upT = mdotSS >= 0 ? volT : pipeT;
|
||||
double upC = Math.Sqrt(gamma * R * upT);
|
||||
double maxFlow = upRho * upC * area * 1.1;
|
||||
if (Math.Abs(mdotSS) > maxFlow)
|
||||
mdotSS = Math.Sign(mdotSS) * maxFlow;
|
||||
// ====================================================
|
||||
|
||||
// ---- Dynamic update ----
|
||||
if (UseInertance)
|
||||
{
|
||||
double rhoUp = _mdot >= 0 ? volRho : pipeRho;
|
||||
@@ -85,39 +95,39 @@ namespace FluidSim.Core
|
||||
_mdot = mdotSS;
|
||||
}
|
||||
|
||||
// Clamp outflow to available mass
|
||||
// Clamp outflow to available mass (if finite volume)
|
||||
if (VolumePort.Owner is Volume0D vol)
|
||||
{
|
||||
double maxOut = vol.Mass / dtSub;
|
||||
if (_mdot > maxOut) _mdot = maxOut;
|
||||
}
|
||||
|
||||
// ---- 3. Ghost state (use nozzle‑exit pressure!) ----
|
||||
double rhoFace = _mdot >= 0 ? volRho : pipeRho; // upstream density
|
||||
double pFace = pFace0; // correct exit pressure (choked/subsonic)
|
||||
// ---- Ghost state ----
|
||||
double rhoFace = _mdot >= 0 ? volRho : pipeRho;
|
||||
double pFace = pFace0;
|
||||
double mdotMag = Math.Abs(_mdot);
|
||||
double uFace = mdotMag / (rhoFace * area);
|
||||
double uFace = mdotMag / (rhoFace * area);
|
||||
|
||||
if (IsPipeLeftEnd)
|
||||
uFace = _mdot >= 0 ? uFace : -uFace; // left: +u into pipe
|
||||
uFace = _mdot >= 0 ? uFace : -uFace;
|
||||
else
|
||||
uFace = _mdot >= 0 ? -uFace : uFace; // right: +u out of pipe
|
||||
uFace = _mdot >= 0 ? -uFace : uFace;
|
||||
|
||||
if (IsPipeLeftEnd)
|
||||
Pipe.SetGhostLeft(rhoFace, uFace, pFace);
|
||||
else
|
||||
Pipe.SetGhostRight(rhoFace, uFace, pFace);
|
||||
|
||||
// Store for monitoring
|
||||
double mdotIntoVolume = -_mdot;
|
||||
LastMassFlowRate = mdotIntoVolume;
|
||||
LastFaceDensity = rhoFace;
|
||||
// Store results (positive = into volume)
|
||||
LastMassFlowRate = -_mdot;
|
||||
LastFaceDensity = rhoFace;
|
||||
LastFaceVelocity = uFace;
|
||||
LastFacePressure = pFace;
|
||||
|
||||
VolumePort.MassFlowRate = mdotIntoVolume;
|
||||
VolumePort.MassFlowRate = -_mdot;
|
||||
|
||||
if (mdotIntoVolume >= 0)
|
||||
// Enthalpy transport
|
||||
if (-_mdot >= 0) // inflow → pipe enthalpy
|
||||
{
|
||||
double hPipe = gamma / (gamma - 1.0) * pipeP / Math.Max(pipeRho, 1e-12);
|
||||
VolumePort.SpecificEnthalpy = hPipe;
|
||||
@@ -140,7 +150,7 @@ namespace FluidSim.Core
|
||||
Pipe.SetGhostRight(rInt, -uInt, pInt);
|
||||
|
||||
LastMassFlowRate = 0.0;
|
||||
LastFaceDensity = rInt;
|
||||
LastFaceDensity = rInt;
|
||||
LastFaceVelocity = 0.0;
|
||||
LastFacePressure = pInt;
|
||||
if (VolumePort != null)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using FluidSim.Components;
|
||||
using FluidSim.Interfaces;
|
||||
@@ -18,6 +19,20 @@ namespace FluidSim.Core
|
||||
/// <summary>CFL target for sub‑stepping (0.3‑0.8). Lower values are safer for shocks.</summary>
|
||||
public double CflTarget { get; set; } = 0.8;
|
||||
|
||||
// ---------- Timing accumulators (reset every LogInterval steps) ----------
|
||||
private long _stepCount;
|
||||
private double _timeTotal;
|
||||
private double _timeCFL;
|
||||
private double _timeOrifice;
|
||||
private double _timeOpenEnd;
|
||||
private double _timeJunction;
|
||||
private double _timePipe;
|
||||
private double _timeClearGhosts;
|
||||
private double _timeUpdateState;
|
||||
|
||||
private const int LogInterval = 5000; // print once per second (at 44.1 kHz)
|
||||
private const bool EnableLogging = false;
|
||||
|
||||
public void SetTimeStep(double dt) => _dt = dt;
|
||||
|
||||
public void AddComponent(IComponent component) => _components.Add(component);
|
||||
@@ -30,11 +45,16 @@ namespace FluidSim.Core
|
||||
var pipes = _components.OfType<Pipe1D>().ToList();
|
||||
if (pipes.Count == 0) return;
|
||||
|
||||
var sw = Stopwatch.StartNew();
|
||||
|
||||
// CFL count
|
||||
int nSub = 1;
|
||||
foreach (var p in pipes)
|
||||
nSub = Math.Max(nSub, p.GetRequiredSubSteps(_dt, CflTarget));
|
||||
double dtSub = _dt / nSub;
|
||||
|
||||
_timeCFL += sw.Elapsed.TotalSeconds;
|
||||
|
||||
const int maxSubSteps = 10000;
|
||||
if (nSub > maxSubSteps)
|
||||
{
|
||||
@@ -44,21 +64,86 @@ namespace FluidSim.Core
|
||||
|
||||
for (int sub = 0; sub < nSub; sub++)
|
||||
{
|
||||
double t0;
|
||||
|
||||
t0 = sw.Elapsed.TotalSeconds;
|
||||
foreach (var link in _orificeLinks)
|
||||
link.Resolve(dtSub);
|
||||
_timeOrifice += sw.Elapsed.TotalSeconds - t0;
|
||||
|
||||
t0 = sw.Elapsed.TotalSeconds;
|
||||
foreach (var link in _openEndLinks)
|
||||
link.Resolve(dtSub);
|
||||
_timeOpenEnd += sw.Elapsed.TotalSeconds - t0;
|
||||
|
||||
t0 = sw.Elapsed.TotalSeconds;
|
||||
foreach (var junc in _junctions)
|
||||
junc.Resolve(dtSub);
|
||||
_timeJunction += sw.Elapsed.TotalSeconds - t0;
|
||||
|
||||
t0 = sw.Elapsed.TotalSeconds;
|
||||
foreach (var p in pipes)
|
||||
p.SimulateSingleStep(dtSub);
|
||||
_timePipe += sw.Elapsed.TotalSeconds - t0;
|
||||
}
|
||||
|
||||
double tCG = sw.Elapsed.TotalSeconds;
|
||||
foreach (var p in pipes)
|
||||
p.ClearGhostFlags();
|
||||
_timeClearGhosts += sw.Elapsed.TotalSeconds - tCG;
|
||||
|
||||
double tUS = sw.Elapsed.TotalSeconds;
|
||||
foreach (var comp in _components)
|
||||
comp.UpdateState(_dt);
|
||||
_timeUpdateState += sw.Elapsed.TotalSeconds - tUS;
|
||||
|
||||
// accumulate total step time (includes CFL, sub‑steps, clear ghosts, update state)
|
||||
_timeTotal += sw.Elapsed.TotalSeconds;
|
||||
|
||||
// ---------- Periodic report ----------
|
||||
_stepCount++;
|
||||
if (_stepCount % LogInterval == 0 && EnableLogging)
|
||||
{
|
||||
if (_timeTotal > 0)
|
||||
{
|
||||
double totalMs = _timeTotal * 1000.0;
|
||||
double avgUs = (_timeTotal / LogInterval) * 1e6; // µs per step
|
||||
double stepsPerSec = LogInterval / _timeTotal; // steps per second
|
||||
|
||||
Console.WriteLine($"--- Solver timing ({LogInterval} steps) ---");
|
||||
Console.WriteLine($" Steps per second: {stepsPerSec:F1}");
|
||||
Console.WriteLine($" Avg step time: {avgUs:F1} µs (last nSub = {nSub})");
|
||||
Console.WriteLine($" CFL calc: {_timeCFL / _timeTotal * 100:F1} % ({_timeCFL * 1e6 / LogInterval:F1} µs/step)");
|
||||
Console.WriteLine($" Sub‑step loop:");
|
||||
Console.WriteLine($" Orifice: {_timeOrifice / _timeTotal * 100:F1} % ({_timeOrifice * 1e6 / LogInterval:F1} µs/step)");
|
||||
Console.WriteLine($" OpenEnd: {_timeOpenEnd / _timeTotal * 100:F1} % ({_timeOpenEnd * 1e6 / LogInterval:F1} µs/step)");
|
||||
Console.WriteLine($" Junctions: {_timeJunction / _timeTotal * 100:F1} % ({_timeJunction * 1e6 / LogInterval:F1} µs/step)");
|
||||
Console.WriteLine($" Pipe steps: {_timePipe / _timeTotal * 100:F1} % ({_timePipe * 1e6 / LogInterval:F1} µs/step)");
|
||||
Console.WriteLine($" Clear ghosts: {_timeClearGhosts / _timeTotal * 100:F1} % ({_timeClearGhosts * 1e6 / LogInterval:F1} µs/step)");
|
||||
Console.WriteLine($" Update state: {_timeUpdateState / _timeTotal * 100:F1} % ({_timeUpdateState * 1e6 / LogInterval:F1} µs/step)");
|
||||
Console.WriteLine();
|
||||
|
||||
// ---------- Optional detailed pipe profiling ----------
|
||||
if (Pipe1D.EnableDetailedProfiling)
|
||||
{
|
||||
foreach (var pipe in pipes)
|
||||
{
|
||||
Console.WriteLine(pipe.GetDetailProfileReport());
|
||||
pipe.ResetDetailCounters();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Reset accumulators for next interval
|
||||
_timeTotal = 0;
|
||||
_timeCFL = 0;
|
||||
_timeOrifice = 0;
|
||||
_timeOpenEnd = 0;
|
||||
_timeJunction = 0;
|
||||
_timePipe = 0;
|
||||
_timeClearGhosts = 0;
|
||||
_timeUpdateState = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,131 +0,0 @@
|
||||
using SFML.Audio;
|
||||
using SFML.System;
|
||||
|
||||
namespace FluidSim;
|
||||
|
||||
#region Lock‑free ring buffer (unchanged)
|
||||
internal class RingBuffer
|
||||
{
|
||||
private readonly float[] buffer;
|
||||
private volatile int readPos;
|
||||
private volatile int writePos;
|
||||
|
||||
public RingBuffer(int capacity)
|
||||
{
|
||||
if ((capacity & (capacity - 1)) != 0)
|
||||
throw new ArgumentException("Capacity must be a power of two.");
|
||||
buffer = new float[capacity];
|
||||
}
|
||||
|
||||
public int Count => (writePos - readPos) & (buffer.Length - 1);
|
||||
public int Space => (readPos - writePos - 1) & (buffer.Length - 1);
|
||||
|
||||
public int Write(float[] data, int count)
|
||||
{
|
||||
int space = Space;
|
||||
int toWrite = Math.Min(count, space);
|
||||
int mask = buffer.Length - 1;
|
||||
for (int i = 0; i < toWrite; i++)
|
||||
buffer[(writePos + i) & mask] = data[i];
|
||||
writePos = (writePos + toWrite) & mask;
|
||||
return toWrite;
|
||||
}
|
||||
|
||||
public int Read(float[] destination, int count)
|
||||
{
|
||||
int available = Count;
|
||||
int toRead = Math.Min(count, available);
|
||||
int mask = buffer.Length - 1;
|
||||
for (int i = 0; i < toRead; i++)
|
||||
destination[i] = buffer[(readPos + i) & mask];
|
||||
readPos = (readPos + toRead) & mask;
|
||||
return toRead;
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Stereo stream that consumes the ring buffer
|
||||
internal class RingBufferStream : SoundStream
|
||||
{
|
||||
private readonly RingBuffer ringBuffer;
|
||||
|
||||
public RingBufferStream(RingBuffer buffer)
|
||||
{
|
||||
ringBuffer = buffer;
|
||||
// 2 channels, 44.1 kHz, standard stereo mapping
|
||||
Initialize(2, 44100, new[] { SoundChannel.FrontLeft, SoundChannel.FrontRight });
|
||||
}
|
||||
|
||||
protected override bool OnGetData(out short[] samples)
|
||||
{
|
||||
const int monoBlockSize = 512; // number of mono samples we'll read
|
||||
float[] temp = new float[monoBlockSize];
|
||||
int read = ringBuffer.Read(temp, monoBlockSize);
|
||||
samples = new short[monoBlockSize * 2];
|
||||
|
||||
if (read > 0)
|
||||
{
|
||||
for (int i = 0; i < read; i++)
|
||||
{
|
||||
float clamped = Math.Clamp(temp[i], -1f, 1f);
|
||||
short final = (short)(clamped * short.MaxValue);
|
||||
samples[i * 2] = final; // left
|
||||
samples[i * 2 + 1] = final; // right
|
||||
}
|
||||
}
|
||||
for (int i = read * 2; i < samples.Length; i++)
|
||||
samples[i] = 0;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
protected override void OnSeek(Time timeOffset) =>
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Public sound engine API (unchanged)
|
||||
public class SoundEngine : IDisposable
|
||||
{
|
||||
private readonly RingBuffer ringBuffer;
|
||||
private readonly RingBufferStream stream;
|
||||
private bool isPlaying;
|
||||
|
||||
public SoundEngine(int bufferCapacity = 16384)
|
||||
{
|
||||
ringBuffer = new RingBuffer(bufferCapacity);
|
||||
stream = new RingBufferStream(ringBuffer);
|
||||
}
|
||||
|
||||
public void Start()
|
||||
{
|
||||
if (isPlaying) return;
|
||||
stream.Play();
|
||||
isPlaying = true;
|
||||
}
|
||||
|
||||
public void Stop()
|
||||
{
|
||||
if (!isPlaying) return;
|
||||
stream.Stop();
|
||||
isPlaying = false;
|
||||
float[] drain = new float[ringBuffer.Count];
|
||||
ringBuffer.Read(drain, drain.Length);
|
||||
}
|
||||
|
||||
public int WriteSamples(float[] data, int count) =>
|
||||
ringBuffer.Write(data, count);
|
||||
|
||||
public float Volume
|
||||
{
|
||||
get => stream.Volume;
|
||||
set => stream.Volume = value;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Stop();
|
||||
stream.Dispose();
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
@@ -23,7 +23,7 @@ namespace FluidSim.Core
|
||||
scaleFactor = 1.0 / (4.0 * Math.PI * listenerDistanceMeters);
|
||||
|
||||
// Smoothing time constant for the derivative: 10 ms (much smoother)
|
||||
double tau = 0.010; // 10 ms
|
||||
double tau = 0.005; // 10 ms
|
||||
alpha = Math.Exp(-dt / tau);
|
||||
|
||||
// Low‑pass time constant for the mass flow: 5 ms (kneecap high‑freq directly)
|
||||
@@ -49,7 +49,7 @@ namespace FluidSim.Core
|
||||
double pressure = smoothDMdt * scaleFactor * Gain;
|
||||
|
||||
// Soft clip to ±1 (should rarely trigger now)
|
||||
return (float)Math.Tanh(pressure);
|
||||
return (float)pressure;
|
||||
}
|
||||
}
|
||||
}
|
||||
34
Core/ThreadLoadTracker.cs
Normal file
34
Core/ThreadLoadTracker.cs
Normal file
@@ -0,0 +1,34 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
|
||||
namespace FluidSim
|
||||
{
|
||||
/// <summary>
|
||||
/// Tracks the duty cycle of a worker thread using an exponential moving average.
|
||||
/// Thread‑safe: one writer (the sim thread), any reader (UI thread).
|
||||
/// </summary>
|
||||
public class ThreadLoadTracker
|
||||
{
|
||||
private double _loadPercent; // 0 .. 100, accessed with Volatile.Read/Write
|
||||
private const double Alpha = 0.1; // smoothing factor (higher = faster response)
|
||||
|
||||
/// <summary>
|
||||
/// Update the load percentage with a new observation.
|
||||
/// </summary>
|
||||
/// <param name="busyMs">Time spent on real work in the last cycle.</param>
|
||||
/// <param name="totalMs">Total time of the last cycle (work + idle). If zero, ignored.</param>
|
||||
public void Record(double busyMs, double totalMs)
|
||||
{
|
||||
if (totalMs <= 0) return;
|
||||
double instantLoad = busyMs / totalMs * 100.0;
|
||||
|
||||
// Exponential moving average
|
||||
double old = Volatile.Read(ref _loadPercent);
|
||||
double newLoad = old + Alpha * (instantLoad - old);
|
||||
Volatile.Write(ref _loadPercent, newLoad);
|
||||
}
|
||||
|
||||
/// <summary>Current smoothed load percentage (0‑100).</summary>
|
||||
public double LoadPercent => Volatile.Read(ref _loadPercent);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user