added two stroke scenario with vehicle
This commit is contained in:
@@ -4,33 +4,30 @@ namespace FluidSim.Components
|
||||
{
|
||||
public class Crankshaft
|
||||
{
|
||||
public float AngularVelocity; // rad/s
|
||||
public float CrankAngle; // rad, 0 … 4π
|
||||
public float AngularVelocity;
|
||||
public float CrankAngle;
|
||||
public float PreviousAngle;
|
||||
|
||||
public float Inertia = 0.2f; // kg·m²
|
||||
public float FrictionConstant; // N·m
|
||||
public float FrictionViscous; // N·m per rad/s
|
||||
|
||||
public float Inertia = 0.2f;
|
||||
public float FrictionConstant;
|
||||
public float FrictionViscous;
|
||||
public float LastNetTorque { get; private set; }
|
||||
public float AveragePower { get; private set; } // smoothed, watts
|
||||
public float AverageTorque { get; private set; } // smoothed, Nm
|
||||
public float AveragePower { get; private set; }
|
||||
public float AverageTorque { get; private set; }
|
||||
|
||||
private float externalTorque;
|
||||
private float _loadTorque; // external brake torque (Nm)
|
||||
private float _loadTorque;
|
||||
|
||||
// Power averaging buffer
|
||||
private readonly float[] _powerBuffer;
|
||||
private int _powerBufIdx;
|
||||
private int _powerBufCount;
|
||||
private int _powerBufIdx, _powerBufCount;
|
||||
private float _powerBufSum;
|
||||
|
||||
// Torque averaging buffer (same size as power buffer)
|
||||
private readonly float[] _torqueBuffer;
|
||||
private int _torqueBufIdx;
|
||||
private int _torqueBufCount;
|
||||
private int _torqueBufIdx, _torqueBufCount;
|
||||
private float _torqueBufSum;
|
||||
|
||||
/// <summary>Engine cycle length in radians. 4π = four‑stroke, 2π = two‑stroke.</summary>
|
||||
public float CycleLength { get; set; } = 4f * MathF.PI;
|
||||
|
||||
public Crankshaft(float initialRPM = 400f)
|
||||
{
|
||||
AngularVelocity = initialRPM * 2f * MathF.PI / 60f;
|
||||
@@ -43,9 +40,13 @@ namespace FluidSim.Components
|
||||
|
||||
public void AddTorque(float torque) => externalTorque += torque;
|
||||
|
||||
public void SetLoadTorque(float torque)
|
||||
public void SetLoadTorque(float torque) => _loadTorque = Math.Max(torque, 0f);
|
||||
|
||||
private float _effectiveInertia; // if >0, overrides Inertia
|
||||
|
||||
public void SetEffectiveInertia(float inertia)
|
||||
{
|
||||
_loadTorque = Math.Max(torque, 0f);
|
||||
_effectiveInertia = inertia;
|
||||
}
|
||||
|
||||
public void Step(float dt)
|
||||
@@ -57,51 +58,40 @@ namespace FluidSim.Components
|
||||
|
||||
PreviousAngle = CrankAngle;
|
||||
|
||||
// Internal friction torque
|
||||
float friction = FrictionConstant * MathF.Sign(AngularVelocity)
|
||||
+ FrictionViscous * AngularVelocity;
|
||||
|
||||
// Net torque from gas pressure minus friction (used for power/torque display)
|
||||
float netTorque = externalTorque - friction;
|
||||
LastNetTorque = netTorque;
|
||||
|
||||
// Total torque after subtracting external load (brake)
|
||||
float totalNetTorque = netTorque - _loadTorque;
|
||||
float alpha = totalNetTorque / Inertia;
|
||||
float currentInertia = _effectiveInertia > 0f ? _effectiveInertia : Inertia;
|
||||
float alpha = totalNetTorque / currentInertia;
|
||||
AngularVelocity += alpha * dt;
|
||||
|
||||
if (AngularVelocity < 0f) AngularVelocity = 0f;
|
||||
|
||||
CrankAngle += AngularVelocity * dt;
|
||||
if (CrankAngle >= 4f * MathF.PI)
|
||||
CrankAngle -= 4f * MathF.PI;
|
||||
if (CrankAngle >= CycleLength)
|
||||
CrankAngle -= CycleLength;
|
||||
else if (CrankAngle < 0f)
|
||||
CrankAngle += 4f * MathF.PI;
|
||||
CrankAngle += CycleLength;
|
||||
|
||||
// ---- Power averaging ----
|
||||
// Power averaging
|
||||
float instantPower = netTorque * AngularVelocity;
|
||||
if (_powerBufCount == _powerBuffer.Length)
|
||||
{
|
||||
_powerBufSum -= _powerBuffer[_powerBufIdx];
|
||||
}
|
||||
else
|
||||
{
|
||||
_powerBufCount++;
|
||||
}
|
||||
_powerBuffer[_powerBufIdx] = instantPower;
|
||||
_powerBufSum += instantPower;
|
||||
_powerBufIdx = (_powerBufIdx + 1) % _powerBuffer.Length;
|
||||
AveragePower = _powerBufSum / _powerBufCount;
|
||||
|
||||
// ---- Torque averaging ----
|
||||
// Torque averaging
|
||||
if (_torqueBufCount == _torqueBuffer.Length)
|
||||
{
|
||||
_torqueBufSum -= _torqueBuffer[_torqueBufIdx];
|
||||
}
|
||||
else
|
||||
{
|
||||
_torqueBufCount++;
|
||||
}
|
||||
_torqueBuffer[_torqueBufIdx] = netTorque;
|
||||
_torqueBufSum += netTorque;
|
||||
_torqueBufIdx = (_torqueBufIdx + 1) % _torqueBuffer.Length;
|
||||
|
||||
@@ -1,99 +1,25 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using FluidSim.Interfaces;
|
||||
using FluidSim.Components; // if needed
|
||||
|
||||
namespace FluidSim.Components
|
||||
{
|
||||
public class Cylinder : IComponent
|
||||
public class Cylinder : EngineCylinder
|
||||
{
|
||||
public Port IntakePort { get; }
|
||||
public Port ExhaustPort { get; }
|
||||
public Crankshaft Crankshaft { get; }
|
||||
public float IVO, IVC, EVO, EVC; // degrees in a 720° cycle
|
||||
|
||||
private readonly Port[] _ports;
|
||||
IReadOnlyList<Port> IComponent.Ports => _ports;
|
||||
protected override float CycleLengthRad => 4f * MathF.PI;
|
||||
protected override float MaxCycleDeg => 720f;
|
||||
|
||||
public float Bore { get; }
|
||||
public float Stroke { get; }
|
||||
public float ConRodLength { get; }
|
||||
public float CompressionRatio { get; }
|
||||
|
||||
public float IVO, IVC, EVO, EVC; // degrees
|
||||
public float IntakeValveDiameter = 0.03f;
|
||||
public float ExhaustValveDiameter = 0.028f;
|
||||
public float IntakeValveLift = 0.005f;
|
||||
public float ExhaustValveLift = 0.005f;
|
||||
|
||||
public float IntakeValveMaxArea => MathF.PI * IntakeValveDiameter * IntakeValveLift;
|
||||
public float ExhaustValveMaxArea => MathF.PI * ExhaustValveDiameter * ExhaustValveLift;
|
||||
|
||||
public float SparkAdvance = 20f;
|
||||
public float WiebeA = 5f, WiebeM = 2f, WiebeDuration = 60f, WiebeStart = 5f;
|
||||
public float StoichiometricAFR = 14.7f;
|
||||
public float FuelLowerHeatingValue = 44e6f;
|
||||
public float EnergyVariationFraction = 0.05f;
|
||||
public float MisfireProbability = 0.0f;
|
||||
public float CylinderWallArea = 0.02f;
|
||||
public float HeatTransferCoefficient = 100f;
|
||||
public float AmbientTemperature = 300f;
|
||||
|
||||
public float PhaseOffset; // rad
|
||||
|
||||
public float Volume => cylinderVolume;
|
||||
public float Pressure => (Gamma - 1f) * cylinderEnergy / MathF.Max(cylinderVolume, 1e-12f);
|
||||
public float Temperature => Pressure / MathF.Max(Density * GasConstant, 1e-12f);
|
||||
public float Density => Mass / MathF.Max(cylinderVolume, 1e-12f);
|
||||
public float Mass => _airMass + _exhaustMass;
|
||||
public float AirFraction => _airMass / MathF.Max(Mass, 1e-12f);
|
||||
public float PistonFraction => (cylinderVolume - clearanceVolume) / SweptVolume;
|
||||
|
||||
private float cylinderVolume, cylinderEnergy;
|
||||
private float _airMass, _exhaustMass;
|
||||
private float trappedAirMass, fuelMass, burnFraction;
|
||||
private bool combustionActive, fuelInjected;
|
||||
private float _energyFactor = 1f;
|
||||
private readonly Random _random = new Random();
|
||||
|
||||
private const float Gamma = 1.4f;
|
||||
private const float GasConstant = 287f;
|
||||
private const float MaxPressurePa = 200e5f;
|
||||
private const float MaxTemperatureK = 3500f;
|
||||
public override float IntakeValveArea =>
|
||||
MathF.PI * IntakeValveDiameter * ValveLift(CrankDeg, IVO, IVC, IntakeValveLift);
|
||||
public override float ExhaustValveArea =>
|
||||
MathF.PI * ExhaustValveDiameter * ValveLift(CrankDeg, EVO, EVC, ExhaustValveLift);
|
||||
|
||||
public Cylinder(float bore, float stroke, float conRodLength, float compressionRatio,
|
||||
float ivo, float ivc, float evo, float evc, Crankshaft crankshaft)
|
||||
: base(bore, stroke, conRodLength, compressionRatio, crankshaft)
|
||||
{
|
||||
Bore = bore; Stroke = stroke; ConRodLength = conRodLength;
|
||||
CompressionRatio = compressionRatio;
|
||||
IVO = ivo; IVC = ivc; EVO = evo; EVC = evc;
|
||||
Crankshaft = crankshaft ?? throw new ArgumentNullException(nameof(crankshaft));
|
||||
|
||||
cylinderVolume = clearanceVolume;
|
||||
float initRho = 1.225f;
|
||||
_airMass = initRho * clearanceVolume;
|
||||
_exhaustMass = 0f;
|
||||
cylinderEnergy = 101325f * clearanceVolume / (Gamma - 1f);
|
||||
|
||||
IntakePort = new Port { Owner = this };
|
||||
ExhaustPort = new Port { Owner = this };
|
||||
_ports = new[] { IntakePort, ExhaustPort };
|
||||
}
|
||||
|
||||
private float SweptVolume => MathF.PI * 0.25f * Bore * Bore * Stroke;
|
||||
private float clearanceVolume => SweptVolume / (CompressionRatio - 1f);
|
||||
private float CrankRadius => Stroke * 0.5f;
|
||||
private float Obliquity => CrankRadius / ConRodLength;
|
||||
|
||||
private float CrankDeg =>
|
||||
((Crankshaft.CrankAngle + PhaseOffset) % (4f * MathF.PI)) * 180f / MathF.PI % 720f;
|
||||
|
||||
public float ComputeVolume(float thetaRad)
|
||||
{
|
||||
float r = CrankRadius, l = ConRodLength;
|
||||
float cosTh = MathF.Cos(thetaRad), sinTh = MathF.Sin(thetaRad);
|
||||
float term = MathF.Sqrt(1f - Obliquity * Obliquity * sinTh * sinTh);
|
||||
float x = r * (1f - cosTh) + l * (1f - term);
|
||||
float area = MathF.PI * 0.25f * Bore * Bore;
|
||||
return clearanceVolume + area * x;
|
||||
}
|
||||
|
||||
private float ValveLift(float thetaDeg, float opens, float closes, float peakLift)
|
||||
@@ -101,15 +27,10 @@ namespace FluidSim.Components
|
||||
float deg = thetaDeg % 720f;
|
||||
if (deg < 0f) deg += 720f;
|
||||
|
||||
float duration;
|
||||
float effectiveOpen = opens;
|
||||
float effectiveClose = closes;
|
||||
|
||||
if (closes < opens)
|
||||
{
|
||||
effectiveClose += 720f;
|
||||
}
|
||||
duration = effectiveClose - effectiveOpen;
|
||||
if (closes < opens) effectiveClose += 720f;
|
||||
float duration = effectiveClose - effectiveOpen;
|
||||
if (duration <= 0f) return 0f;
|
||||
|
||||
float mapped = deg;
|
||||
@@ -136,43 +57,9 @@ namespace FluidSim.Components
|
||||
return 0f;
|
||||
}
|
||||
|
||||
public float IntakeValveArea =>
|
||||
MathF.PI * IntakeValveDiameter * ValveLift(CrankDeg, IVO, IVC, IntakeValveLift);
|
||||
public float ExhaustValveArea =>
|
||||
MathF.PI * ExhaustValveDiameter * ValveLift(CrankDeg, EVO, EVC, ExhaustValveLift);
|
||||
|
||||
private float Wiebe(float angleSinceSpark)
|
||||
protected override void HandleCycleEvents(float prevDeg, float currDeg, float dt)
|
||||
{
|
||||
if (angleSinceSpark < WiebeStart) return 0f;
|
||||
float phi = (angleSinceSpark - WiebeStart) / WiebeDuration;
|
||||
if (phi <= 0f) return 0f;
|
||||
return 1f - MathF.Exp(-WiebeA * MathF.Pow(phi, WiebeM + 1f));
|
||||
}
|
||||
|
||||
public void PreStep(float dt)
|
||||
{
|
||||
// Speed‑dependent spark advance (simple linear)
|
||||
float rpm = Crankshaft.AngularVelocity * 60f / (2f * MathF.PI);
|
||||
SparkAdvance = Math.Clamp(10f + rpm * 0.002f, 5f, 40f); // 10° at idle, ~30° at 10k rpm
|
||||
|
||||
float prevVolume = cylinderVolume;
|
||||
float crankAngleRad = Crankshaft.CrankAngle + PhaseOffset;
|
||||
cylinderVolume = ComputeVolume(crankAngleRad);
|
||||
|
||||
float dV = cylinderVolume - prevVolume;
|
||||
float pRel = Pressure - 101325f;
|
||||
float sinTh = MathF.Sin(crankAngleRad), cosTh = MathF.Cos(crankAngleRad);
|
||||
float term = MathF.Sqrt(1f - Obliquity * Obliquity * sinTh * sinTh);
|
||||
float dxdtheta = CrankRadius * sinTh * (1f + Obliquity * cosTh / term);
|
||||
float pistonArea = MathF.PI * 0.25f * Bore * Bore;
|
||||
Crankshaft.AddTorque(pRel * pistonArea * dxdtheta);
|
||||
|
||||
cylinderEnergy -= Pressure * dV;
|
||||
|
||||
float prevDeg = (Crankshaft.PreviousAngle + PhaseOffset) * 180f / MathF.PI % 720f;
|
||||
float currDeg = crankAngleRad * 180f / MathF.PI % 720f;
|
||||
|
||||
// Intake closing – triggers fuel injection
|
||||
// Intake closing → fuel injection
|
||||
if (prevDeg >= IVO && prevDeg < IVC && currDeg >= IVC)
|
||||
{
|
||||
trappedAirMass = _airMass;
|
||||
@@ -180,11 +67,14 @@ namespace FluidSim.Components
|
||||
fuelInjected = true;
|
||||
}
|
||||
|
||||
// Spark
|
||||
float sparkAngle = 0f - SparkAdvance;
|
||||
if (sparkAngle < 0f) sparkAngle += 720f;
|
||||
bool crossedSpark = (prevDeg < sparkAngle && currDeg >= sparkAngle) ||
|
||||
(prevDeg > sparkAngle + 360f && currDeg < sparkAngle);
|
||||
// Spark – occurs at TDC (0°) minus advance, every 720°
|
||||
float sparkAngle = (0f - SparkAdvance + 720f) % 720f;
|
||||
bool crossedSpark = false;
|
||||
if (prevDeg < sparkAngle && currDeg >= sparkAngle)
|
||||
crossedSpark = true;
|
||||
else if (prevDeg > sparkAngle && currDeg < sparkAngle)
|
||||
crossedSpark = true;
|
||||
|
||||
if (crossedSpark && !combustionActive && fuelInjected)
|
||||
{
|
||||
if (_random.NextDouble() < MisfireProbability)
|
||||
@@ -199,7 +89,7 @@ namespace FluidSim.Components
|
||||
}
|
||||
}
|
||||
|
||||
// Combustion
|
||||
// Combustion progression
|
||||
if (combustionActive)
|
||||
{
|
||||
float angleSinceSpark = currDeg - sparkAngle;
|
||||
@@ -222,62 +112,6 @@ namespace FluidSim.Components
|
||||
burnFraction = newFraction;
|
||||
}
|
||||
}
|
||||
|
||||
// Heat loss
|
||||
float dQ_loss = HeatTransferCoefficient * CylinderWallArea *
|
||||
(Temperature - AmbientTemperature) * dt;
|
||||
cylinderEnergy -= dQ_loss;
|
||||
|
||||
// Update port states
|
||||
float p = Pressure, rho = Density, T = Temperature;
|
||||
float h = Gamma / (Gamma - 1f) * p / MathF.Max(rho, 1e-12f);
|
||||
float af = AirFraction;
|
||||
IntakePort.Pressure = p; IntakePort.Density = rho;
|
||||
IntakePort.Temperature = T; IntakePort.SpecificEnthalpy = h; IntakePort.AirFraction = af;
|
||||
ExhaustPort.Pressure = p; ExhaustPort.Density = rho;
|
||||
ExhaustPort.Temperature = T; ExhaustPort.SpecificEnthalpy = h; ExhaustPort.AirFraction = af;
|
||||
}
|
||||
|
||||
public void UpdateState(float dt)
|
||||
{
|
||||
float dmAir = 0f, dmExhaust = 0f, dE = 0f;
|
||||
foreach (var port in _ports)
|
||||
{
|
||||
float mdot = port.MassFlowRate;
|
||||
float af = mdot >= 0f ? port.AirFraction : AirFraction;
|
||||
dmAir += mdot * af * dt;
|
||||
dmExhaust += mdot * (1f - af) * dt;
|
||||
dE += mdot * port.SpecificEnthalpy * dt;
|
||||
}
|
||||
|
||||
_airMass += dmAir; _exhaustMass += dmExhaust;
|
||||
cylinderEnergy += dE;
|
||||
|
||||
float V = MathF.Max(cylinderVolume, 1e-12f);
|
||||
float currentP = (Gamma - 1f) * cylinderEnergy / V;
|
||||
if (currentP > MaxPressurePa) cylinderEnergy = MaxPressurePa * V / (Gamma - 1f);
|
||||
|
||||
float currentRho = (_airMass + _exhaustMass) / V;
|
||||
float currentT = currentP / MathF.Max(currentRho * GasConstant, 1e-12f);
|
||||
if (currentT > MaxTemperatureK)
|
||||
{
|
||||
float pAtTlimit = currentRho * GasConstant * MaxTemperatureK;
|
||||
cylinderEnergy = pAtTlimit * V / (Gamma - 1f);
|
||||
}
|
||||
|
||||
float totalMass = _airMass + _exhaustMass;
|
||||
if (totalMass < 1e-9f)
|
||||
{
|
||||
_airMass = 1e-9f; _exhaustMass = 0f;
|
||||
cylinderEnergy = 101325f * V / (Gamma - 1f);
|
||||
}
|
||||
else if (cylinderEnergy < 0f)
|
||||
{
|
||||
cylinderEnergy = 101325f * V / (Gamma - 1f);
|
||||
}
|
||||
|
||||
if (_airMass < 0f) _airMass = 0f;
|
||||
if (_exhaustMass < 0f) _exhaustMass = 0f;
|
||||
}
|
||||
}
|
||||
}
|
||||
203
Components/EngineCylinder.cs
Normal file
203
Components/EngineCylinder.cs
Normal file
@@ -0,0 +1,203 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using FluidSim.Interfaces;
|
||||
|
||||
namespace FluidSim.Components
|
||||
{
|
||||
/// <summary>Common base for all reciprocating engine cylinders.</summary>
|
||||
public abstract class EngineCylinder : IComponent
|
||||
{
|
||||
public Port IntakePort { get; }
|
||||
public Port ExhaustPort { get; }
|
||||
public Crankshaft Crankshaft { get; }
|
||||
|
||||
private readonly Port[] _ports;
|
||||
IReadOnlyList<Port> IComponent.Ports => _ports;
|
||||
|
||||
// ----- Geometry -----
|
||||
public float Bore { get; }
|
||||
public float Stroke { get; }
|
||||
public float ConRodLength { get; }
|
||||
public float CompressionRatio { get; }
|
||||
|
||||
// ----- Valve / port sizes (used for curtain area) -----
|
||||
public float IntakeValveDiameter = 0.03f;
|
||||
public float ExhaustValveDiameter = 0.028f;
|
||||
public float IntakeValveLift = 0.005f;
|
||||
public float ExhaustValveLift = 0.005f;
|
||||
|
||||
// ----- Combustion -----
|
||||
public float SparkAdvance = 20f;
|
||||
public float WiebeA = 5f, WiebeM = 2f, WiebeDuration = 60f, WiebeStart = 5f;
|
||||
public float StoichiometricAFR = 14.7f;
|
||||
public float FuelLowerHeatingValue = 44e6f;
|
||||
public float EnergyVariationFraction = 0.05f;
|
||||
public float MisfireProbability = 0f;
|
||||
public float CylinderWallArea = 0.02f;
|
||||
public float HeatTransferCoefficient = 100f;
|
||||
public float AmbientTemperature = 300f;
|
||||
|
||||
public float PhaseOffset; // radians
|
||||
|
||||
// ----- State (public, used by drawing) -----
|
||||
public float Volume => cylinderVolume;
|
||||
public float Pressure => (Gamma - 1f) * cylinderEnergy / MathF.Max(cylinderVolume, 1e-12f);
|
||||
public float Temperature => Pressure / MathF.Max(Density * GasConstant, 1e-12f);
|
||||
public float Density => Mass / MathF.Max(cylinderVolume, 1e-12f);
|
||||
public float Mass => _airMass + _exhaustMass;
|
||||
public float AirFraction => _airMass / MathF.Max(Mass, 1e-12f);
|
||||
public float PistonFraction => (cylinderVolume - clearanceVolume) / SweptVolume;
|
||||
|
||||
protected float cylinderVolume, cylinderEnergy;
|
||||
protected float _airMass, _exhaustMass;
|
||||
protected float trappedAirMass, fuelMass, burnFraction;
|
||||
protected bool combustionActive, fuelInjected;
|
||||
protected float _energyFactor = 1f;
|
||||
protected readonly Random _random = new Random();
|
||||
|
||||
protected const float Gamma = 1.4f;
|
||||
protected const float GasConstant = 287f;
|
||||
protected const float MaxPressurePa = 200e5f;
|
||||
protected const float MaxTemperatureK = 3500f;
|
||||
|
||||
// ----- Derived geometry (cycle‑independent) -----
|
||||
protected float SweptVolume => MathF.PI * 0.25f * Bore * Bore * Stroke;
|
||||
protected float clearanceVolume => SweptVolume / (CompressionRatio - 1f);
|
||||
protected float CrankRadius => Stroke * 0.5f;
|
||||
protected float Obliquity => CrankRadius / ConRodLength;
|
||||
|
||||
// ----- Abstract members (cycle‑specific) -----
|
||||
protected abstract float CycleLengthRad { get; } // 4π or 2π
|
||||
protected abstract float MaxCycleDeg { get; } // 720 or 360
|
||||
public abstract float IntakeValveArea { get; }
|
||||
public abstract float ExhaustValveArea { get; }
|
||||
protected abstract void HandleCycleEvents(float prevDeg, float currDeg, float dt);
|
||||
|
||||
protected EngineCylinder(float bore, float stroke, float conRodLength,
|
||||
float compressionRatio, Crankshaft crankshaft)
|
||||
{
|
||||
Bore = bore; Stroke = stroke; ConRodLength = conRodLength;
|
||||
CompressionRatio = compressionRatio;
|
||||
Crankshaft = crankshaft ?? throw new ArgumentNullException(nameof(crankshaft));
|
||||
|
||||
cylinderVolume = clearanceVolume;
|
||||
float initRho = 1.225f;
|
||||
_airMass = initRho * clearanceVolume;
|
||||
_exhaustMass = 0f;
|
||||
cylinderEnergy = 101325f * clearanceVolume / (Gamma - 1f);
|
||||
|
||||
IntakePort = new Port { Owner = this };
|
||||
ExhaustPort = new Port { Owner = this };
|
||||
_ports = new[] { IntakePort, ExhaustPort };
|
||||
|
||||
// Set crankshaft cycle length
|
||||
crankshaft.CycleLength = CycleLengthRad;
|
||||
}
|
||||
|
||||
public float ComputeVolume(float thetaRad)
|
||||
{
|
||||
float r = CrankRadius, l = ConRodLength;
|
||||
float cosTh = MathF.Cos(thetaRad), sinTh = MathF.Sin(thetaRad);
|
||||
float term = MathF.Sqrt(1f - Obliquity * Obliquity * sinTh * sinTh);
|
||||
float x = r * (1f - cosTh) + l * (1f - term);
|
||||
float area = MathF.PI * 0.25f * Bore * Bore;
|
||||
return clearanceVolume + area * x;
|
||||
}
|
||||
|
||||
protected float CrankDeg =>
|
||||
((Crankshaft.CrankAngle + PhaseOffset) % CycleLengthRad) * 180f / MathF.PI;
|
||||
|
||||
protected float Wiebe(float angleSinceSpark)
|
||||
{
|
||||
if (angleSinceSpark < WiebeStart) return 0f;
|
||||
float phi = (angleSinceSpark - WiebeStart) / WiebeDuration;
|
||||
return 1f - MathF.Exp(-WiebeA * MathF.Pow(phi, WiebeM + 1f));
|
||||
}
|
||||
|
||||
// ----- Main update called before flow solver -----
|
||||
public void PreStep(float dt)
|
||||
{
|
||||
// Speed‑dependent spark advance
|
||||
float rpm = Crankshaft.AngularVelocity * 60f / (2f * MathF.PI);
|
||||
SparkAdvance = Math.Clamp(10f + rpm * 0.002f, 5f, 40f);
|
||||
|
||||
float prevVolume = cylinderVolume;
|
||||
float crankAngleRad = Crankshaft.CrankAngle + PhaseOffset;
|
||||
cylinderVolume = ComputeVolume(crankAngleRad);
|
||||
|
||||
// Piston work
|
||||
float dV = cylinderVolume - prevVolume;
|
||||
float pRel = Pressure - 101325f;
|
||||
float sinTh = MathF.Sin(crankAngleRad), cosTh = MathF.Cos(crankAngleRad);
|
||||
float term = MathF.Sqrt(1f - Obliquity * Obliquity * sinTh * sinTh);
|
||||
float dxdtheta = CrankRadius * sinTh * (1f + Obliquity * cosTh / term);
|
||||
float pistonArea = MathF.PI * 0.25f * Bore * Bore;
|
||||
Crankshaft.AddTorque(pRel * pistonArea * dxdtheta);
|
||||
|
||||
cylinderEnergy -= Pressure * dV;
|
||||
|
||||
float prevDeg = (Crankshaft.PreviousAngle + PhaseOffset) * 180f / MathF.PI % MaxCycleDeg;
|
||||
float currDeg = crankAngleRad * 180f / MathF.PI % MaxCycleDeg;
|
||||
|
||||
// Let derived class handle valve events, spark, fuel
|
||||
HandleCycleEvents(prevDeg, currDeg, dt);
|
||||
|
||||
// Heat loss
|
||||
float dQ_loss = HeatTransferCoefficient * CylinderWallArea *
|
||||
(Temperature - AmbientTemperature) * dt;
|
||||
cylinderEnergy -= dQ_loss;
|
||||
|
||||
// Update port states
|
||||
float p = Pressure, rho = Density, T = Temperature;
|
||||
float h = Gamma / (Gamma - 1f) * p / MathF.Max(rho, 1e-12f);
|
||||
float af = AirFraction;
|
||||
IntakePort.Pressure = p; IntakePort.Density = rho;
|
||||
IntakePort.Temperature = T; IntakePort.SpecificEnthalpy = h; IntakePort.AirFraction = af;
|
||||
ExhaustPort.Pressure = p; ExhaustPort.Density = rho;
|
||||
ExhaustPort.Temperature = T; ExhaustPort.SpecificEnthalpy = h; ExhaustPort.AirFraction = af;
|
||||
}
|
||||
|
||||
// ----- State update (mass/energy balance) -----
|
||||
public void UpdateState(float dt)
|
||||
{
|
||||
float dmAir = 0f, dmExhaust = 0f, dE = 0f;
|
||||
foreach (var port in _ports)
|
||||
{
|
||||
float mdot = port.MassFlowRate;
|
||||
float af = mdot >= 0f ? port.AirFraction : AirFraction;
|
||||
dmAir += mdot * af * dt;
|
||||
dmExhaust += mdot * (1f - af) * dt;
|
||||
dE += mdot * port.SpecificEnthalpy * dt;
|
||||
}
|
||||
|
||||
_airMass += dmAir; _exhaustMass += dmExhaust;
|
||||
cylinderEnergy += dE;
|
||||
|
||||
float V = MathF.Max(cylinderVolume, 1e-12f);
|
||||
float currentP = (Gamma - 1f) * cylinderEnergy / V;
|
||||
if (currentP > MaxPressurePa) cylinderEnergy = MaxPressurePa * V / (Gamma - 1f);
|
||||
|
||||
float currentRho = (_airMass + _exhaustMass) / V;
|
||||
float currentT = currentP / MathF.Max(currentRho * GasConstant, 1e-12f);
|
||||
if (currentT > MaxTemperatureK)
|
||||
{
|
||||
float pAtTlimit = currentRho * GasConstant * MaxTemperatureK;
|
||||
cylinderEnergy = pAtTlimit * V / (Gamma - 1f);
|
||||
}
|
||||
|
||||
float totalMass = _airMass + _exhaustMass;
|
||||
if (totalMass < 1e-9f)
|
||||
{
|
||||
_airMass = 1e-9f; _exhaustMass = 0f;
|
||||
cylinderEnergy = 101325f * V / (Gamma - 1f);
|
||||
}
|
||||
else if (cylinderEnergy < 0f)
|
||||
{
|
||||
cylinderEnergy = 101325f * V / (Gamma - 1f);
|
||||
}
|
||||
|
||||
if (_airMass < 0f) _airMass = 0f;
|
||||
if (_exhaustMass < 0f) _exhaustMass = 0f;
|
||||
}
|
||||
}
|
||||
}
|
||||
140
Components/TwoStrokeCylinder.cs
Normal file
140
Components/TwoStrokeCylinder.cs
Normal file
@@ -0,0 +1,140 @@
|
||||
using System;
|
||||
|
||||
namespace FluidSim.Components
|
||||
{
|
||||
/// <summary>
|
||||
/// Two‑stroke cylinder with forced symmetrical port timings around BDC (180°).
|
||||
/// All angles are in degrees within a 360° cycle.
|
||||
/// </summary>
|
||||
public class TwoStrokeCylinder : EngineCylinder
|
||||
{
|
||||
// --- Public read‑only properties for drawing ---
|
||||
public float IVO => 180f - transferDuration / 2f;
|
||||
public float IVC => 180f + transferDuration / 2f;
|
||||
public float EVO => 180f - exhaustDuration / 2f;
|
||||
public float EVC => 180f + exhaustDuration / 2f;
|
||||
|
||||
// --- Configurable durations (set in constructor) ---
|
||||
private readonly float transferDuration; // e.g. 120°
|
||||
private readonly float exhaustDuration; // e.g. 180°
|
||||
|
||||
protected override float CycleLengthRad => 2f * MathF.PI;
|
||||
protected override float MaxCycleDeg => 360f;
|
||||
|
||||
public override float IntakeValveArea =>
|
||||
MathF.PI * IntakeValveDiameter * ValveLift(CrankDeg, IVO, IVC, IntakeValveLift);
|
||||
public override float ExhaustValveArea =>
|
||||
MathF.PI * ExhaustValveDiameter * ValveLift(CrankDeg, EVO, EVC, ExhaustValveLift);
|
||||
|
||||
/// <summary>
|
||||
/// Create a two‑stroke cylinder with forced symmetrical port timing.
|
||||
/// </summary>
|
||||
/// <param name="transferDuration">Total transfer port open duration in degrees (e.g. 120°).</param>
|
||||
/// <param name="exhaustDuration">Total exhaust port open duration in degrees (e.g. 180°).</param>
|
||||
public TwoStrokeCylinder(float bore, float stroke, float conRodLength,
|
||||
float compressionRatio,
|
||||
float transferDuration, float exhaustDuration,
|
||||
Crankshaft crankshaft)
|
||||
: base(bore, stroke, conRodLength, compressionRatio, crankshaft)
|
||||
{
|
||||
this.transferDuration = transferDuration;
|
||||
this.exhaustDuration = exhaustDuration;
|
||||
|
||||
// Safety check: exhaust must open before transfer
|
||||
if (EVO >= IVO)
|
||||
throw new ArgumentException("Exhaust must open before transfer port (exhaust duration > transfer duration).");
|
||||
}
|
||||
|
||||
// ----- Valve lift – same implementation, now uses the computed IVO/IVC/EVO/EVC -----
|
||||
private float ValveLift(float thetaDeg, float opens, float closes, float peakLift)
|
||||
{
|
||||
float deg = thetaDeg % 360f;
|
||||
if (deg < 0f) deg += 360f;
|
||||
|
||||
float effectiveOpen = opens;
|
||||
float effectiveClose = closes;
|
||||
if (closes < opens) effectiveClose += 360f;
|
||||
float duration = effectiveClose - effectiveOpen;
|
||||
if (duration <= 0f) return 0f;
|
||||
|
||||
float mapped = deg;
|
||||
if (mapped < opens) mapped += 360f;
|
||||
if (mapped < opens || mapped > effectiveClose) return 0f;
|
||||
|
||||
float rampDur = duration * 0.25f;
|
||||
float holdDur = duration - 2f * rampDur;
|
||||
|
||||
if (mapped >= opens && mapped < opens + rampDur)
|
||||
{
|
||||
float t = (mapped - opens) / rampDur;
|
||||
return peakLift * t * t * (3f - 2f * t);
|
||||
}
|
||||
else if (mapped >= opens + rampDur && mapped < opens + rampDur + holdDur)
|
||||
{
|
||||
return peakLift;
|
||||
}
|
||||
else if (mapped >= opens + rampDur + holdDur && mapped <= effectiveClose)
|
||||
{
|
||||
float t = (mapped - (opens + rampDur + holdDur)) / rampDur;
|
||||
return peakLift * (1f - t) * (1f - t) * (1f + 2f * t);
|
||||
}
|
||||
return 0f;
|
||||
}
|
||||
|
||||
protected override void HandleCycleEvents(float prevDeg, float currDeg, float dt)
|
||||
{
|
||||
// Transfer port closing → fuel injection
|
||||
if (prevDeg >= IVO && prevDeg < IVC && currDeg >= IVC)
|
||||
{
|
||||
trappedAirMass = _airMass;
|
||||
fuelMass = trappedAirMass / StoichiometricAFR;
|
||||
fuelInjected = true;
|
||||
}
|
||||
|
||||
// Spark every 360° at TDC (0°) minus advance
|
||||
float sparkAngle = (0f - SparkAdvance + 360f) % 360f;
|
||||
bool crossedSpark = false;
|
||||
if (prevDeg < sparkAngle && currDeg >= sparkAngle)
|
||||
crossedSpark = true;
|
||||
else if (prevDeg > sparkAngle && currDeg < sparkAngle)
|
||||
crossedSpark = true;
|
||||
|
||||
if (crossedSpark && !combustionActive && fuelInjected)
|
||||
{
|
||||
if (_random.NextDouble() < MisfireProbability)
|
||||
{
|
||||
combustionActive = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
combustionActive = true; burnFraction = 0f;
|
||||
float range = EnergyVariationFraction;
|
||||
_energyFactor = 1f + range * (2f * (float)_random.NextDouble() - 1f);
|
||||
}
|
||||
}
|
||||
|
||||
if (combustionActive)
|
||||
{
|
||||
float angleSinceSpark = currDeg - sparkAngle;
|
||||
if (angleSinceSpark < 0f) angleSinceSpark += 360f;
|
||||
float newFraction = Wiebe(angleSinceSpark);
|
||||
if (newFraction >= 1f || angleSinceSpark > (WiebeDuration + WiebeStart + SparkAdvance))
|
||||
{
|
||||
newFraction = 1f; combustionActive = false;
|
||||
float totalMass = _airMass + _exhaustMass;
|
||||
_airMass = 0f; _exhaustMass = totalMass;
|
||||
}
|
||||
fuelInjected = false;
|
||||
|
||||
float dFraction = newFraction - burnFraction;
|
||||
if (dFraction > 0f)
|
||||
{
|
||||
float dQ = fuelMass * FuelLowerHeatingValue * _energyFactor * dFraction;
|
||||
cylinderEnergy += dQ;
|
||||
_exhaustMass += fuelMass * dFraction;
|
||||
burnFraction = newFraction;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
166
Components/Vehicle.cs
Normal file
166
Components/Vehicle.cs
Normal file
@@ -0,0 +1,166 @@
|
||||
using System;
|
||||
|
||||
namespace FluidSim.Components
|
||||
{
|
||||
public class Vehicle
|
||||
{
|
||||
// ---- Gearbox ----
|
||||
public int CurrentGear { get; private set; } = 0;
|
||||
public readonly float[] GearRatios = { 2.5f, 1.8f, 1.4f, 1.1f, 0.9f, 0.75f };
|
||||
public float FinalDriveRatio = 3.0f;
|
||||
public float PrimaryReduction = 2.5f;
|
||||
|
||||
// ---- Clutch ----
|
||||
public float ClutchInput { get; set; }
|
||||
public float ClutchDisengageTime = 0.15f;
|
||||
private float _clutchTimer;
|
||||
private float _currentEngagement = 0f;
|
||||
|
||||
/// <summary>Time constant for clutch engagement smoothing (seconds).</summary>
|
||||
public float EngagementSmoothTime = 0.5f; // longer, gentler bite
|
||||
|
||||
private float TargetEngagement
|
||||
{
|
||||
get
|
||||
{
|
||||
if (ClutchInput > 0.01f) return 1f - ClutchInput;
|
||||
if (CurrentGear == 0 || _clutchTimer > 0f) return 0f;
|
||||
return 1f;
|
||||
}
|
||||
}
|
||||
|
||||
public float Engagement => _currentEngagement;
|
||||
|
||||
// ---- Clutch torque model ----
|
||||
/// <summary>Peak clutch friction torque (Nm) when fully engaged at high RPM.</summary>
|
||||
public float BaseMaxTorque = 80f; // much lower than before
|
||||
|
||||
/// <summary>Stiffness when slipping (Nm per rad/s). Lower = softer engagement.</summary>
|
||||
public float ClutchStiffness = 50f; // very soft
|
||||
|
||||
/// <summary>Below this engine RPM, the clutch torque is progressively reduced to prevent stalling.</summary>
|
||||
public float IdleRpm = 1200f;
|
||||
public float StallPreventionRamp = 300f; // RPM band above idle where torque ramps up
|
||||
|
||||
// ---- Physical constants ----
|
||||
public float Mass = 160f;
|
||||
public float WheelRadius = 0.32f;
|
||||
public float DragCoefficient = 0.35f;
|
||||
public float FrontalArea = 0.8f;
|
||||
public float AirDensity = 1.225f;
|
||||
public float RollingFrictionCoeff = 0.01f;
|
||||
public float Gravity = 9.81f;
|
||||
|
||||
// ---- State ----
|
||||
public float Speed { get; private set; }
|
||||
|
||||
public (float clutchTorqueOnEngine, float effectiveEngineInertia) Update(float engineRpm, float engineInertia, float dt)
|
||||
{
|
||||
if (_clutchTimer > 0f)
|
||||
{
|
||||
_clutchTimer -= dt;
|
||||
if (_clutchTimer < 0f) _clutchTimer = 0f;
|
||||
}
|
||||
|
||||
float target = TargetEngagement;
|
||||
float smoothing = 1f - MathF.Exp(-dt / Math.Max(EngagementSmoothTime, 0.001f));
|
||||
_currentEngagement += (target - _currentEngagement) * smoothing;
|
||||
if (MathF.Abs(_currentEngagement - target) < 0.001f)
|
||||
_currentEngagement = target;
|
||||
|
||||
float engagement = _currentEngagement;
|
||||
|
||||
float totalGear = 1f;
|
||||
if (CurrentGear > 0)
|
||||
totalGear = GearRatios[CurrentGear - 1] * FinalDriveRatio * PrimaryReduction;
|
||||
|
||||
float engineRadPerSec = engineRpm * 2f * MathF.PI / 60f;
|
||||
|
||||
float v = MathF.Max(Speed, 0f);
|
||||
float drag = 0.5f * AirDensity * DragCoefficient * FrontalArea * v * v;
|
||||
float rolling = RollingFrictionCoeff * Mass * Gravity;
|
||||
float resistanceForce = drag + rolling;
|
||||
|
||||
float clutchTorque = 0f;
|
||||
float effectiveInertia = engineInertia;
|
||||
|
||||
if (engagement > 0f && CurrentGear > 0)
|
||||
{
|
||||
float vehicleReflectedRadPerSec = (Speed / WheelRadius) * totalGear;
|
||||
float slip = engineRadPerSec - vehicleReflectedRadPerSec;
|
||||
|
||||
// Stall prevention: reduce max torque when engine RPM is near idle
|
||||
float torqueLimit = BaseMaxTorque * engagement;
|
||||
if (engineRpm < IdleRpm + StallPreventionRamp)
|
||||
{
|
||||
float factor = Math.Clamp((engineRpm - IdleRpm) / StallPreventionRamp, 0f, 1f);
|
||||
torqueLimit *= factor;
|
||||
}
|
||||
|
||||
float stiffnessTorque = ClutchStiffness * engagement * slip;
|
||||
clutchTorque = Math.Clamp(stiffnessTorque, -torqueLimit, torqueLimit);
|
||||
|
||||
// Lock if slip negligible and engagement high
|
||||
if (engagement >= 0.99f && MathF.Abs(slip) < 1.0f)
|
||||
{
|
||||
float vehicleInertia = Mass * WheelRadius * WheelRadius;
|
||||
float reflectedVehicleInertia = vehicleInertia / (totalGear * totalGear);
|
||||
effectiveInertia = engineInertia + reflectedVehicleInertia;
|
||||
|
||||
Speed = engineRadPerSec * WheelRadius / totalGear;
|
||||
float loadTorque = resistanceForce * WheelRadius / totalGear;
|
||||
return (loadTorque, effectiveInertia);
|
||||
}
|
||||
}
|
||||
|
||||
float driveTorqueAtWheel = clutchTorque * totalGear;
|
||||
float driveForce = driveTorqueAtWheel / WheelRadius;
|
||||
float netForce = driveForce - resistanceForce;
|
||||
float acceleration = netForce / Mass;
|
||||
Speed += acceleration * dt;
|
||||
if (Speed < 0f) Speed = 0f;
|
||||
|
||||
return (clutchTorque, engineInertia);
|
||||
}
|
||||
|
||||
public void ShiftUp()
|
||||
{
|
||||
if (CurrentGear < GearRatios.Length)
|
||||
{
|
||||
CurrentGear++;
|
||||
AutoDisengageClutch();
|
||||
}
|
||||
}
|
||||
|
||||
public void ShiftDown()
|
||||
{
|
||||
if (CurrentGear > 1)
|
||||
{
|
||||
CurrentGear--;
|
||||
AutoDisengageClutch();
|
||||
}
|
||||
}
|
||||
|
||||
public void SetNeutral()
|
||||
{
|
||||
CurrentGear = 0;
|
||||
_clutchTimer = 0f;
|
||||
}
|
||||
|
||||
public void SetFirstGear()
|
||||
{
|
||||
if (CurrentGear == 0)
|
||||
{
|
||||
CurrentGear = 1;
|
||||
AutoDisengageClutch();
|
||||
}
|
||||
}
|
||||
|
||||
private void AutoDisengageClutch()
|
||||
{
|
||||
_clutchTimer = ClutchDisengageTime;
|
||||
}
|
||||
|
||||
public float SpeedKmh => Speed * 3.6f;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user