18
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-12-01 07:07:05 +01:00
Files
maszyna/physics/components/electrics.cpp
T
Hirek 242474dd11 refactor(physics): the lights, the load and the event flags are private to the vehicle
- The lights switched on at each end (iLights) are LitLights(), changed
  through SetLitLights(): the cab's switches, the AI's light patterns and the
  scenery's toggles of the end signals all go through it.
- The exchange of the load, which TDynamicObject ran by setting the status, the
  amount and the mass itself, goes through UnloadStep(), LoadStep(),
  FinishLoadExchange() and AcknowledgeLoadExchange(), with the same arithmetic;
  the change of the kind of the load is taken once (TakeLoadTypeChange()).
- The events the physics reports for the sounds to follow up are raised and
  cleared by name (RaiseEventFlag(), ClearEventFlag(), ClearSoundFlags()).

No change in behaviour: the golden traces recorded on dfb43c4f match bit for bit.
2026-11-29 12:33:13 +01:00

1238 lines
40 KiB
C++

/*
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
*/
// the power supply: the batteries, the main switch, the pantographs, the converter, heating, lights, the genset
#include "stdafx.h"
#include "physics/vehicle.h"
#include "vehicle/DynObj.h"
#include "physics/oerlikonest.h"
#include "utilities/Globals.h"
#include "utilities/Logs.h"
#include "utilities/Timer.h"
#include "utilities/parser.h"
#include "simulation/simulation.h"
#include "vehicle/fieldshunting.h"
#include <algorithm>
#include <charconv>
#include <cmath>
#include <format>
#include <functional>
#include <limits>
#include <utility>
#include <vector>
#include "physics/components/internal.h"
#include "physics/components/drive.h"
// KURS90 - sprężarka pantografów; Ra 2014-07: teraz jest to zbiornik rozrządu, chociaż to jeszcze nie tak
void physics::Vehicle::UpdatePantVolume(double dt)
{
if (pantographAir.Update(PantographAirSupplyNow(), dt))
{
PantPressureSwitchTrip();
}
}
// what the air of the pantographs needs to know in the step
physics::PantographAirSupply physics::Vehicle::PantographAirSupplyNow() const
{
PantographAirSupply supply;
supply.anyPantographActive = pantographs[VehicleEnd::front].is_active || pantographs[VehicleEnd::rear].is_active;
supply.lowVoltage = lowVoltage.IsAvailable();
// tylko jeśli pantografujący
supply.collectors = EnginePowerSource.SourceType == TPowerSource::CurrentCollector && EnginePowerSource.CollectorParameters.CollectorsNo > 0;
supply.multipleUnit = TrainType == train_type::emu;
supply.mainReservoirPressure = mainPipe.Pressure();
supply.controlReservoirPressure = brakes.controlReservoirPressure;
supply.maxPressure = EnginePowerSource.CollectorParameters.MaxPress;
supply.minPressure = EnginePowerSource.CollectorParameters.MinPress;
return supply;
}
// the pantographs' pressure switch: low, it opens the line breaker (or locks the converter of a unit) once;
// primed again over 4.6 bar, where the pantographs' compressor stops at 4.8
void physics::Vehicle::PantPressureSwitchCheck()
{
if (pantographAir.UpdatePressureSwitch(PantographAirSupplyNow()))
{
PantPressureSwitchTrip();
}
}
// the pantographs' pressure switch tripped by the low pressure (pantographAir spent the switch, and locked a unit): the line
// breaker opened, unless the voltage comes from elsewhere, or the converter of a unit switched off
void physics::Vehicle::PantPressureSwitchTrip()
{
// opuszczenie pantografów przy niskim ciśnieniu
if (TrainType != train_type::emu)
{
// pressure switch safety measure -- open the line breaker, unless there's alternate source of traction voltage
// (the genset of a dual-mode vehicle, when the selector is on it, doesn't need the pantographs)
if (GetTrainsetHighVoltage() < EnginePowerSource.CollectorParameters.MinV && false == GensetSelected())
{
// TODO: check whether line breaker should be open EMU-wide
MainSwitch(false, TrainType == train_type::emu ? range_t::unit : range_t::local);
}
}
else
{
// specialized variant for EMU -- pwr system disables converter and heating,
// and prevents their activation until pressure switch is set again
// TODO: separate 'heating allowed' from actual heating flag, so we can disable it here without messing up heating toggle
ConverterSwitch(false, range_t::unit);
}
}
void physics::Vehicle::UpdateBatteryVoltage(double dt)
{ // przeliczenie obciążenia baterii
using enum TEngineType;
if (lowVoltage.BatteryVoltage() > 0 && EngineType != DieselEngine && EngineType != WheelsDriven && lowVoltage.config.nominalBatteryVoltage > 0)
{
// HACK: allow to draw power also from adjacent converter, applicable for EMUs
// TODO: expand power cables system to include low voltage power transfers
// HACK: emulate low voltage generator powered directly by the diesel engine
auto const converteractive{lowVoltage.Is110vAvailable() || (EngineType == DieselElectric && true == lineBreaker.IsClosed()) || (EngineType == DieselEngine && true == lineBreaker.IsClosed())};
if (lowVoltage.DrainBattery(BatteryDrain(dt, converteractive)) && MainSwitch(false) && EngineType != DieselEngine && EngineType != WheelsDriven)
eventFlag = true; // wywalanie szybkiego z powodu zbyt niskiego napiecia
}
else
{
// TODO: check and implement proper way to handle this for diesel engines
lowVoltage.KeepBatteryCharged();
}
};
// the drop of the battery's voltage in dt, by what draws from it, or its rise by the converter charging it
double physics::Vehicle::BatteryDrain(double dt, bool const converteractive) const
{
if (lowVoltage.config.nominalBatteryVoltage / lowVoltage.BatteryVoltage() < 1.22 && lowVoltage.IsBatteryOn())
{ // 110V
return BatteryDrainCharged(dt, converteractive);
}
if (lowVoltage.config.nominalBatteryVoltage / lowVoltage.BatteryVoltage() >= 1.22 && lowVoltage.IsBatteryOn())
{ // 90V
return BatteryDrainLow(dt, converteractive);
}
if (!lowVoltage.IsBatteryOn())
{
return BatteryDrainSwitchedOff(dt);
}
return 0.0;
}
// the drain of a battery at its voltage, the converter charging it
double physics::Vehicle::BatteryDrainCharged(double dt, bool const converteractive) const
{
double sn1;
double sn2;
double sn3;
double sn4;
double sn5;
if (!converteractive)
sn1 = dt * 2.0; // szybki spadek do ok 90V
else
sn1 = 0;
if (converteractive)
sn2 = -(dt * 2.0); // szybki wzrost do 110V
else
sn2 = 0;
if (lineBreaker.IsClosed())
sn3 = dt * 0.05;
else
sn3 = 0;
if (litLights[0] & 63) // 64=blachy, nie ciągną prądu //rozpisać na poszczególne żarówki...
sn4 = dt * 0.003;
else
sn4 = 0;
if (litLights[1] & 63) // 64=blachy, nie ciągną prądu
sn5 = dt * 0.001;
else
sn5 = 0;
return sn1 + sn2 + sn3 + sn4 + sn5;
}
// the drain of a battery run down to 90 V, the converter charging it
double physics::Vehicle::BatteryDrainLow(double dt, bool const converteractive) const
{
double sn1;
double sn2;
double sn3;
double sn4;
double sn5;
if (pantographAir.IsCompressorRunning())
sn1 = dt * 0.0046;
else
sn1 = 0;
if (converteractive)
sn2 = -(dt * 50); // szybki wzrost do 110V
else
sn2 = 0;
if (lineBreaker.IsClosed())
sn3 = dt * 0.001;
else
sn3 = 0;
if (litLights[0] & 63) // 64=blachy, nie ciągną prądu
sn4 = dt * 0.0030;
else
sn4 = 0;
if (litLights[1] & 63) // 64=blachy, nie ciągną prądu
sn5 = dt * 0.0010;
else
sn5 = 0;
return sn1 + sn2 + sn3 + sn4 + sn5;
}
// the drain of a battery switched off, very slow
double physics::Vehicle::BatteryDrainSwitchedOff(double dt) const
{
double sn1;
double sn2;
double sn3;
double sn4;
double sn5;
if (lowVoltage.config.nominalBatteryVoltage / lowVoltage.BatteryVoltage() < 1.22)
sn1 = dt * 50;
else
sn1 = 0;
sn2 = dt * 0.000001;
sn3 = dt * 0.000001;
sn4 = dt * 0.000001;
sn5 = dt * 0.000001; // bardzo powolny spadek przy wyłączonych bateriach
return sn1 + sn2 + sn3 + sn4 + sn5;
}
void physics::Vehicle::MainsCheck(double const Deltatime)
{
// if( MainsInitTime == 0.0 ) { return; }
// TBD, TODO: move voltage calculation to separate method and use also in power coupler state calculation?
auto localvoltage{0.0};
switch (EnginePowerSource.SourceType)
{
case TPowerSource::CurrentCollector:
{
localvoltage = std::max(localvoltage, pantographCircuit.SupplyVoltage());
break;
}
case TPowerSource::Accumulator:
{
localvoltage = std::max(localvoltage, lowVoltage.Voltage24v());
break;
}
default:
{
break;
}
}
if (GensetSelected())
{
// the traction selector of a dual-mode vehicle on the genset isolates the pantographs
localvoltage = Genset.voltage;
}
// a line breaker closed ahead of the pantographs gets ready on the low voltage circuits
auto const maincircuitpowersupply{std::abs(localvoltage) > 0.1 || GetTrainsetHighVoltage() > 0.1 || (lineBreaker.config.pantographsRequireIt && (lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable()))};
// optional automatic circuit start, once the circuit is initialised
if (lineBreaker.UpdateInitialisation(maincircuitpowersupply, Deltatime) && lineBreaker.config.start != start_t::manual && false == (lineBreaker.IsClosed() || diesel.startupRequested))
{
MainSwitch(true);
}
// an emergency brake application made under power opens the line breaker, where the vehicle has such an interlock
if (lineBreaker.IsClosed() && EmergencyBrakeHoldsMainOff())
{
MainSwitch(false, TrainType == train_type::emu ? range_t::unit : range_t::local);
}
}
void physics::Vehicle::LowVoltagePowerCheck(double const /*Deltatime*/)
{
auto const lowvoltagepower{lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable()};
if (EngineType == TEngineType::ElectricSeriesMotor)
{
protection.UpdateGround(lowvoltagepower);
}
}
void physics::Vehicle::PowerCouplersCheck(double const /*Deltatime*/, Coupling const kind)
{
if (kind != Coupling::highVoltage && kind != Coupling::power110v && kind != Coupling::power24v)
{
// only power couplings carry voltage
return;
}
auto const localvoltage{LocalPowerVoltage(kind)};
auto const abslocalvoltage{std::abs(localvoltage)};
auto const localpowersource{(abslocalvoltage > 1.0)};
// przekazywanie napiec
PowerCouplersVoltage(kind, abslocalvoltage, localpowersource);
// przekazywanie pradow
PowerCouplersCurrent(kind, localpowersource);
}
// the current the vehicle draws from the circuit of the power coupling given
double *physics::Vehicle::PowerCircuitCurrent(Coupling const kind)
{
switch (kind)
{
case Coupling::highVoltage:
return &TotalCurrent;
case Coupling::power110v:
return &PowerCircuits[1].second;
case Coupling::power24v:
return &PowerCircuits[0].second;
default:
return nullptr;
}
}
// the voltage of the vehicle's own source for the coupling given; notes the low voltage circuits' too
double physics::Vehicle::LocalPowerVoltage(Coupling const kind)
{
auto localvoltage{0.0};
// local power sources
// the results could be kept in the PowerCircuit fields
switch (kind)
{
case Coupling::highVoltage:
{
// heating power sources
if (trainHeating.IsOn())
{
switch (HeatingPowerSource.SourceType)
{
case TPowerSource::Generator:
{
localvoltage = HeatingPowerSource.EngineGenerator.voltage - TotalCurrent * 0.02;
break;
}
case TPowerSource::CurrentCollector:
{
localvoltage = pantographCircuit.SupplyVoltage();
break;
}
case TPowerSource::Main:
{
// HACK: main circuit can be fed through couplers, so we explicitly check pantograph supply here
// (or the genset's, where the traction selector of a dual-mode vehicle is on it)
localvoltage = MainCircuitPowered() ? TractionSourceVoltage() : 0.0;
break;
}
default:
{
break;
}
}
}
// high voltage power sources: the pantographs, or the genset of a dual-mode vehicle, by its traction selector
if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector)
{
localvoltage = std::max(localvoltage, TractionSourceVoltage());
}
break;
}
case Coupling::power110v:
{
if (converter.IsRunning())
{
localvoltage = lowVoltage.config.nominalBatteryVoltage;
}
// TBD, TODO: reduce by current draw?
PowerCircuits[1].first = localvoltage;
break;
}
case Coupling::power24v:
{
if (lowVoltage.IsBatteryOn())
{
localvoltage = lowVoltage.BatteryVoltage();
}
// TBD, TODO: reduce by current draw?
PowerCircuits[0].first = localvoltage;
break;
}
default:
{
break;
}
}
return localvoltage;
}
// the voltage passed through the vehicle to the coupler at its other end, from the coupled vehicle or its own source
void physics::Vehicle::PowerCouplersVoltage(Coupling const kind, double const abslocalvoltage, bool const localpowersource)
{
if (Couplers[VehicleEnd::front].power(kind) == nullptr)
{
// not a power coupling, there's no voltage to pass
return;
}
for (auto const side : VehicleEnds)
{
auto const &thiscoupler{Couplers[side]};
// NOTE: in the loop we actually update the state of the coupler on the opposite end of the vehicle
auto &oppositecoupler{Couplers[Opposite(side)]};
bool oppositecouplingispresent;
bool localpowerexportisenabled;
switch (kind)
{
case Coupling::highVoltage:
{
auto const oppositehighvoltagecoupling{oppositecoupler.CouplingFlag.HasAny(Coupling::highVoltage)};
auto const oppositeheatingcoupling{oppositecoupler.CouplingFlag.HasAny(Coupling::heating)};
oppositecouplingispresent = oppositehighvoltagecoupling || oppositeheatingcoupling;
localpowerexportisenabled = oppositehighvoltagecoupling || (oppositeheatingcoupling && localpowersource && trainHeating.IsOn());
break;
}
case Coupling::power110v:
{
oppositecouplingispresent = oppositecoupler.CouplingFlag.HasAll(oppositecoupler.PowerCoupling) && oppositecoupler.PowerFlag.HasAny(Coupling::power110v);
localpowerexportisenabled = oppositecouplingispresent;
break;
}
case Coupling::power24v:
{
oppositecouplingispresent = oppositecoupler.CouplingFlag.HasAll(oppositecoupler.PowerCoupling) && oppositecoupler.PowerFlag.HasAny(Coupling::power24v);
localpowerexportisenabled = oppositecouplingispresent;
break;
}
default:
{
break;
}
}
auto const *coupling = thiscoupler.power(kind);
auto *oppositecoupling = oppositecoupler.power(kind);
// start with base voltage
oppositecoupling->voltage = abslocalvoltage;
oppositecoupling->is_live = false;
oppositecoupling->is_local = localpowersource; // indicate power source
// draw from external source
if (thiscoupler.Connected != nullptr)
{
auto const &connectedcoupler{thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr]};
auto const *connectedcoupling = connectedcoupler.power(kind);
auto const connectedvoltage{(connectedcoupling->is_live ? connectedcoupling->voltage : 0.0)};
oppositecoupling->voltage = std::max(oppositecoupling->voltage, connectedvoltage - coupling->current * 0.02);
oppositecoupling->is_live = connectedvoltage > 0.1 && oppositecouplingispresent;
}
// draw from local source
if (localpowersource)
{
oppositecoupling->voltage = std::max(oppositecoupling->voltage, abslocalvoltage - coupling->current * 0.02);
oppositecoupling->is_live |= abslocalvoltage > 0.1 && localpowerexportisenabled;
}
}
}
// the current drawn through the couplers, shared by their voltages, or added to the vehicle's own
void physics::Vehicle::PowerCouplersCurrent(Coupling const kind, bool const localpowersource)
{
auto const *frontcoupling{Couplers[VehicleEnd::front].power(kind)};
auto const *rearcoupling{Couplers[VehicleEnd::rear].power(kind)};
auto *totalcurrent{PowerCircuitCurrent(kind)};
if (frontcoupling == nullptr || rearcoupling == nullptr || totalcurrent == nullptr)
{
// not a power coupling, there's no current to share
return;
}
auto const couplervoltage{static_cast<int>(frontcoupling->voltage + rearcoupling->voltage)};
for (auto &thiscoupler : Couplers)
{
auto *coupling = thiscoupler.power(kind);
coupling->current = 0.0;
if (thiscoupler.Connected == nullptr)
{
continue;
}
auto const &connectedothercoupler{thiscoupler.Connected->Couplers[Opposite(thiscoupler.ConnectedEnd())]};
auto const *connectedothercoupling = connectedothercoupler.power(kind);
auto const extracurrent = kind == Coupling::highVoltage ? std::abs(Itot) * IsVehicleEIMBrakingFactor() : 0.0;
if (false == localpowersource)
{
// bez napiecia...
if (couplervoltage != 0.0)
{
// ...ale jest cos na sprzegach:
coupling->current = (*totalcurrent + extracurrent) * coupling->voltage / couplervoltage; // obciążenie rozkladane stosownie do napiec
if (true == coupling->is_live)
{
coupling->current += connectedothercoupling->current;
}
}
}
else
{
if (true == coupling->is_live)
{
*totalcurrent += connectedothercoupling->current;
}
}
}
}
// sprawdzanie przetwornicy
void physics::Vehicle::ConverterCheck(double const Timestep)
{
ConverterSupply supply;
supply.lineBreakerClosed = lineBreaker.IsClosed();
supply.lowVoltage24v = lowVoltage.Is24vAvailable();
supply.directionActive = DirActive != 0;
supply.pantographPressureLock = pantographAir.IsPressureLockActive();
// HACK: allow carriages to operate converter without (missing) fuse prerequisite
supply.highVoltage = Power > 1.0 ? MainCircuitPowered() : GetTrainsetHighVoltage() > 0.0;
supply.damaged = equipmentFaults.HasAll(EquipmentFault::converter);
converter.Update(supply, Timestep);
}
// heating system status check
void physics::Vehicle::HeatingCheck(double const /*Timestep*/)
{
// update heating devices
// TBD, TODO: move this to a separate method?
if (HeatingPowerSource.SourceType == TPowerSource::Generator)
{
if (HeatingPowerSource.EngineGenerator.engine_revolutions != nullptr && HeatingPowerSource.EngineGenerator.revolutions_max > 0)
{
auto &generator{HeatingPowerSource.EngineGenerator};
// TBD, TODO: engine-generator transmission
generator.revolutions = *generator.engine_revolutions;
auto const absrevolutions{std::abs(generator.revolutions)};
generator.voltage = (false == trainHeating.IsAllowed() ? 0.0 :
// TODO: add support for desired voltage selector
absrevolutions < generator.revolutions_min ?
generator.voltage_min * absrevolutions / generator.revolutions_min :
// absrevolutions > generator.revolutions_max ? generator.voltage_max * absrevolutions / generator.revolutions_max :
std::lerp(generator.voltage_min, generator.voltage_max,
std::clamp((absrevolutions - generator.revolutions_min) / (generator.revolutions_max - generator.revolutions_min), 0.0, 1.0))) *
sign(generator.revolutions);
}
}
// quick check first to avoid unnecessary calls...
if (false == trainHeating.IsAllowed())
{
trainHeating.SetOn(false);
return;
}
// ...detailed check if we're still here
auto const heatingpowerthreshold{0.1};
// start with blank slate
auto voltage{0.0};
// then try specified power source
switch (HeatingPowerSource.SourceType)
{
case TPowerSource::Generator:
{
voltage = HeatingPowerSource.EngineGenerator.voltage;
break;
}
case TPowerSource::CurrentCollector:
{
voltage = pantographCircuit.SupplyVoltage();
break;
}
case TPowerSource::PowerCable:
{
if (HeatingPowerSource.PowerType == TPowerType::ElectricPower)
{
// TBD, TODO: limit input voltage to heating coupling type?
voltage = GetTrainsetHighVoltage();
}
break;
}
case TPowerSource::Main:
{
voltage = MainCircuitPowered() ? TractionSupplyVoltage() : 0.0;
break;
}
default:
{
break;
}
}
trainHeating.SetOn(voltage > heatingpowerthreshold);
if (trainHeating.IsOn())
{
TotalCurrent += 1000 * trainHeating.config.power / voltage; // heater power cost presumably specified in kilowatts
}
}
void physics::Vehicle::PantographsCheck(double const /*Timestep*/)
{
using enum start_t;
{
auto const &valve{pantographAir.valve};
auto const lowvoltagepower{valve.solenoid ? lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable() : true};
auto const autostart{valve.start_type == automatic || valve.start_type == manualwithautofallback};
auto const manualcontrol{valve.start_type == manual || valve.start_type == manualwithautofallback};
pantographAir.valve.is_active = (valve.spring ? lowvoltagepower : true) // spring actuator needs power to maintain non-default state
&& (manualcontrol && lowvoltagepower ? false == valve.is_disabled : true) // needs power to change state
&& (valve.is_active || (autostart ? lowvoltagepower :
!autostart ? lowvoltagepower && valve.is_enabled :
false)); // shouldn't ever get this far but, eh
}
size_t pant_id = 0;
for (auto &pantograph : pantographs)
{
auto &valve{pantograph.valve};
auto const lowvoltagepower{valve.solenoid ? lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable() : true};
auto const autostart{valve.start_type == automatic || valve.start_type == manualwithautofallback};
auto const manualcontrol{valve.start_type == manual || valve.start_type == manualwithautofallback};
valve.is_active = (valve.spring ? lowvoltagepower : true) // spring actuator needs power to maintain non-default state
&& (manualcontrol && lowvoltagepower ? false == valve.is_disabled : true) // needs power to change state, without it just pass through
&& (manualcontrol && lowvoltagepower ? false == pantographCircuit.AllDown() : true) &&
(lineBreaker.IsClosed() || false == lineBreaker.config.pantographsRequireIt) // fed through the closed line breaker, where it comes first
&& (valve.is_active || (manualcontrol && lowvoltagepower && valve.is_enabled) || (autostart && lowvoltagepower)); // shouldn't ever get this far but, eh
auto const pantographexists{EnginePowerSource.SourceType == TPowerSource::CurrentCollector && EnginePowerSource.CollectorParameters.PhysicalLayout & 1 << pant_id};
pantograph.is_active = valve.is_active && pantographAir.valve.is_active && pantographexists;
pant_id++;
}
}
// the genset of a dual-mode vehicle: started on request with the battery on, it cranks for start_time, then runs at
// idle and up to full revolutions with the traction demand; stopped, it coasts down. regulated voltage from idle up
void physics::Vehicle::GensetCheck(double const Deltatime)
{
if (false == Genset.fitted())
{
return;
}
auto &genset{Genset};
auto const wasactive{genset.is_active};
auto const lowvoltagepower{lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable()};
auto const requested{lowvoltagepower && false == genset.is_disabled && (genset.start_type == start_t::automatic ? GensetSelected() : genset.is_enabled)};
if (false == requested)
{
genset.is_active = false;
genset.is_cranking = false;
genset.timer = 0.0;
}
else if (false == genset.is_active)
{
genset.is_cranking = true;
genset.timer += Deltatime;
if (genset.timer >= genset.start_time)
{
genset.is_cranking = false;
genset.is_active = true;
}
}
// revolutions: the start brings them up to idle in start_time; running they follow the traction demand, stopped
// they coast down to 0, both with the time constant spinup_time
if (genset.is_cranking)
{
genset.revolutions = std::max(genset.revolutions, genset.revolutions_idle * std::min(1.0, genset.timer / std::max(genset.start_time, 0.01)));
}
else if (genset.is_active && false == wasactive)
{
genset.revolutions = std::max(genset.revolutions, genset.revolutions_idle);
}
else
{
auto const demand{GensetSelected() && lineBreaker.IsClosed() ? std::clamp(inductionMotor.forceShare, 0.0, 1.0) : 0.0};
auto const target{genset.is_active ? genset.revolutions_idle + (genset.revolutions_max - genset.revolutions_idle) * demand : 0.0};
genset.revolutions += (target - genset.revolutions) * std::min(1.0, Deltatime / genset.spinup_time);
if (genset.revolutions < 0.001)
{
genset.revolutions = 0.0;
}
}
// no excitation while cranking; running or coasting down, regulated from idle up, proportional below it
genset.voltage = genset.is_cranking ? 0.0 : genset.voltage_nominal * std::clamp(genset.revolutions / genset.revolutions_idle, 0.0, 1.0);
if (genset.is_active != wasactive)
{
WriteLog("Genset of " + Name + (genset.is_active ? ": running" : ": stopped"));
}
}
void physics::Vehicle::LightsCheck(double const /*Timestep*/)
{
auto &light{CompartmentLights};
light.is_active =
// TODO: bind properly power source when ld is in place
(lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable()) // power source
&& false == light.is_disabled && (true == light.is_active || (light.start_type == start_t::manual ? light.is_enabled : true));
light.intensity = (light.is_active ? 1.0f : 0.0f)
// TODO: bind properly power source when ld is in place
* (lowVoltage.Is110vAvailable() ? 1.0f :
lowVoltage.Is24vAvailable() ? 0.5f :
0.0f) *
light.dimming;
}
// *************************************************************************************************
// Q: 20160710
// włączenie / wyłączenie baterii
// *************************************************************************************************
bool physics::Vehicle::BatterySwitch(bool State, range_t const Notify)
{
using enum range_t;
if (PulleeMode && State)
{
// the battery of a vehicle prepared for hauling stays off
return false;
}
auto const initialstate{lowVoltage.IsBatteryOn()};
// Ra: ukrotnienie załączania baterii jest jakąś fikcją...
lowVoltage.SwitchBattery(State);
// switching batteries does not require activation
if (Notify != local)
{
SendCtrlToNext(VehicleCommand::batterySwitch, State ? 1 : 0, 1, Notify == unit ? Coupling::control | Coupling::permanent : Coupling::control);
SendCtrlToNext(VehicleCommand::batterySwitch, State ? 1 : 0, -1, Notify == unit ? Coupling::control | Coupling::permanent : Coupling::control);
}
return lowVoltage.IsBatteryOn() != initialstate;
}
bool physics::Vehicle::CompartmentLightsSwitch(bool State, range_t const Notify)
{
if (CompartmentLights.start_type == start_t::automatic)
{
// automatic lights ignore 'manual' state commands
return false;
}
bool const initialstate{CompartmentLights.is_enabled};
CompartmentLights.is_enabled = State;
if (Notify != range_t::local)
{
SendCtrlToNext(VehicleCommand::compartmentLightsSwitch, CompartmentLights.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control);
}
return CompartmentLights.is_enabled != initialstate;
}
// water pump state toggle
bool physics::Vehicle::CompartmentLightsSwitchOff(bool State, range_t const Notify)
{
if (CompartmentLights.start_type == start_t::automatic)
{
// automatic lights ignore 'manual' state commands
return false;
}
bool const initialstate{CompartmentLights.is_disabled};
CompartmentLights.is_disabled = State;
if (Notify != range_t::local)
{
SendCtrlToNext(VehicleCommand::compartmentLightsSwitchOff, CompartmentLights.is_disabled ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control);
}
return CompartmentLights.is_disabled != initialstate;
}
// *************************************************************************************************
// Q: 20160713
// włączenie / wyłączenie obwodu głownego
// *************************************************************************************************
bool physics::Vehicle::MainSwitch(bool const State, range_t const Notify)
{
bool const initialstate{lineBreaker.IsClosed() || diesel.startupRequested};
MainSwitch_(State);
if (Notify != range_t::local)
{
// pass the command to other vehicles
// TBD: pass the requested state, or the actual state?
SendCtrlToNext(VehicleCommand::mainSwitch, State ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control);
}
return (lineBreaker.IsClosed() || diesel.startupRequested) != initialstate;
}
void physics::Vehicle::MainSwitch_(bool const State)
{
if (lineBreaker.IsClosed() == State || MainCtrlPosNo == 0)
{
// nothing to do
return;
}
bool const initialstate{lineBreaker.IsClosed()};
if (false == State || true == MainSwitchCheck())
{
if (true == State)
{
// switch on
if (EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric)
{
// launch diesel engine startup procedure
diesel.startupRequested = true;
}
else
{
// additional check, as vehicles without pantographs won't fail relay checks earlier
lineBreaker.Close();
}
}
else
{
lineBreaker.Open();
// potentially knock out the pumps if their switch doesn't force them on
WaterPump.is_active &= WaterPump.is_enabled;
FuelPump.is_active &= FuelPump.is_enabled;
}
if (lineBreaker.IsClosed() != initialstate)
{
LastSwitchingTime = 0;
Timer::subsystem.switching.note(Timer::switching_counter::mains, this, &TypeName, &Name);
}
}
}
bool physics::Vehicle::MainSwitchCheck() const
{
using enum TEngineType;
// prevent the switch from working if there's no power
// TODO: consider whether it makes sense for diesel engines and such
bool powerisavailable{Drive().MainsPowerAvailable(*this)};
if (GensetSelected())
{
// on the genset of a dual-mode vehicle the line breaker closes only on a running one, whatever the pantographs give
powerisavailable = Genset.is_active && Genset.voltage >= TractionSupplyMinVoltage();
}
return powerisavailable && (scndCtrlPos == 0 || EngineType == ElectricInductionMotor) && lineBreaker.IsInitialised() &&
(converter.IsOverloaded() == false || converter.config.overloadRelayOffWithLineBreaker) && true == protection.GroundHolds() && (true == protection.UndervoltageHolds() || lineBreaker.config.pantographsRequireIt) && true == protection.OvervoltageHolds() &&
LastSwitchingTime > CtrlDelay &&
(HasCamshaft ? IsMainCtrlActualNoPowerPos() :
lineBreaker.config.closesOnlyAtNoPower ? IsMainCtrlNoPowerPos() :
true) &&
false == DamageFlag.HasAll(VehicleDamage::derailed) && false == equipmentFaults.HasAll(EquipmentFault::differentialRelay) && false == EmergencyBrakeHoldsMainOff();
}
// *************************************************************************************************
// Q: 20160713
// włączenie / wyłączenie przetwornicy
// *************************************************************************************************
bool physics::Vehicle::ConverterSwitch(bool State, range_t const Notify)
{
auto const initialstate{converter.IsAllowed()};
converter.Switch(State);
if (Notify != range_t::local)
{
SendCtrlToNext(VehicleCommand::converterSwitch, State ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control);
}
return converter.IsAllowed() != initialstate;
}
bool physics::Vehicle::HeatingSwitch(bool const State, range_t const Notify)
{
bool const initialstate{trainHeating.IsAllowed()};
HeatingSwitch_(State);
if (Notify != range_t::local)
{
// pass the command to other vehicles
// TBD: pass the requested state, or the actual state?
SendCtrlToNext(VehicleCommand::heatingSwitch, State ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control);
}
return trainHeating.IsAllowed() != initialstate;
}
void physics::Vehicle::HeatingSwitch_(bool const State)
{
// TBD, TODO: activation dependencies?
trainHeating.Allow(State);
}
// the start request of the genset of a dual-mode vehicle; one which starts on its own ignores it, but passes it on to
// the cars behind, which may start theirs on request
bool physics::Vehicle::GensetSwitch(bool const State, range_t const Notify)
{
auto const initialstate{Genset.is_enabled};
if (Genset.start_type != start_t::automatic)
{
Genset.is_enabled = State;
}
if (Notify != range_t::local)
{
SendCtrlToNext(VehicleCommand::gensetSwitch, State ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control);
}
return Genset.is_enabled != initialstate;
}
// the voltage of the vehicle's own source the traction selector picks: the catenary through the pantographs, or the
// genset of a dual-mode vehicle
double physics::Vehicle::TractionSourceVoltage() const
{
return GensetSelected() ? Genset.voltage : pantographCircuit.SupplyVoltage();
}
// the voltage the traction circuit gets: from the vehicle's own source, or through the train's high voltage line
double physics::Vehicle::TractionSupplyVoltage() const
{
return std::max(GetTrainsetHighVoltage(), TractionSourceVoltage());
}
// below it the undervoltage trip opens the line breaker
double physics::Vehicle::TractionSupplyMinVoltage() const
{
return GensetSelected() ? 0.5 * Genset.voltage_nominal : EnginePowerSource.CollectorParameters.MinV;
}
// the power the traction may take [kW, at the wheels]: the genset's share at its present revolutions on the genset,
// no limit otherwise
double physics::Vehicle::GensetTractionPowerLimit() const
{
return GensetSelected() ? Genset.available_power() * Genset.traction_share : std::numeric_limits<double>::max();
}
// the current the vehicle draws through its pantographs [A], if they touch the wire: the traction's (none while
// braking on the resistors) and the heating's. on the genset the genset feeds the traction circuit, so only a heating
// fed straight from the pantographs is left
double physics::Vehicle::CatenaryCurrent() const
{
if (GensetSelected())
{
return HeatingPowerSource.SourceType == TPowerSource::CurrentCollector ? TotalCurrent : 0.0;
}
return (brakes.electrodynamic.on && ResistorsFlag ? 0 : std::abs(Itot) * IsVehicleEIMBrakingFactor()) + TotalCurrent;
}
// returns voltage of defined main engine power source
double physics::Vehicle::EnginePowerSourceVoltage() const
{
return EnginePowerSource.SourceType == TPowerSource::CurrentCollector ? TractionSupplyVoltage() :
EnginePowerSource.SourceType == TPowerSource::Accumulator ? lowVoltage.Voltage24v() :
0.0;
}
// whether the main circuit feeds what runs on it: the converter, a compressor, the heating, the motor and resistor
// blowers, the traction motors
bool physics::Vehicle::MainCircuitPowered() const
{
if (false == lineBreaker.IsClosed())
{
return false;
}
if (false == lineBreaker.config.pantographsRequireIt || EnginePowerSource.SourceType != TPowerSource::CurrentCollector)
{
// the closed line breaker says it all: the undervoltage trip opens it without traction voltage, and an engine
// which runs is its own supply
return true;
}
// closed ahead of the pantographs the line breaker holds without the voltage, which the undervoltage trip isn't
// there to vouch for
return EnginePowerSourceVoltage() >= TractionSupplyMinVoltage();
}
bool physics::Vehicle::OperatePantographsValve(operation_t const State, range_t const Notify)
{
if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector && EnginePowerSource.CollectorParameters.CollectorsNo > 0)
{
auto &valve{pantographAir.valve};
switch (State)
{
using enum operation_t;
case none:
{
valve.is_enabled = false;
valve.is_disabled = false;
break;
}
case enable:
{
valve.is_enabled = true;
valve.is_disabled = false;
break;
}
case disable:
{
valve.is_enabled = false;
valve.is_disabled = true;
break;
}
case enable_on:
{
valve.is_enabled = true;
break;
}
case enable_off:
{
valve.is_enabled = false;
break;
}
case disable_on:
{
valve.is_disabled = true;
break;
}
case disable_off:
{
valve.is_disabled = false;
break;
}
}
}
if (Notify != range_t::local)
{
SendCtrlToNext(VehicleCommand::pantographsValve, static_cast<double>(State), CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control);
}
return true;
}
bool physics::Vehicle::OperatePantographValve(VehicleEnd const End, operation_t const State, range_t const Notify)
{
if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector && EnginePowerSource.CollectorParameters.CollectorsNo > 0)
{
auto &valve{pantographs[End].valve};
switch (State)
{
using enum operation_t;
case none:
{
valve.is_enabled = false;
valve.is_disabled = false;
break;
}
case enable:
{
valve.is_enabled = true;
valve.is_disabled = false;
break;
}
case disable:
{
valve.is_enabled = false;
valve.is_disabled = true;
break;
}
case enable_on:
{
valve.is_enabled = true;
break;
}
case enable_off:
{
valve.is_enabled = false;
break;
}
case disable_on:
{
valve.is_disabled = true;
break;
}
case disable_off:
{
valve.is_disabled = false;
break;
}
}
}
if (Notify != range_t::local)
{
SendCtrlToNext(VehicleCommand::pantographValve,
// HACK: pack the state, pantograph index and sender cab into 8-bit value
// with high bit storing front/rear pantograph, and 7th bit storing sender cab
static_cast<double>(0x80 * (End == VehicleEnd::front ? 0 : 1) + 0x40 * (CabActive != -1 ? 1 : 0) + static_cast<int>(State)), CabActive,
Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control);
}
return true;
}
bool physics::Vehicle::DropAllPantographs(bool const State, range_t const Notify)
{
auto const initialstate{pantographCircuit.AllDown()};
pantographCircuit.SetAllDown(State);
if (Notify != range_t::local)
{
SendCtrlToNext(VehicleCommand::pantographsAllDown, State ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control);
}
return State != initialstate;
}
// *************************************************************************************************
// Q: 20160709
// Funkcja zwracajaca napiecie dla calego skladu, przydatna dla EZT
// *************************************************************************************************
double physics::Vehicle::GetTrainsetVoltage(CouplingSet const couplings) const
{ // ABu: funkcja zwracajaca napiecie dla calego skladu, przydatna dla EZT
// TBD, TODO: call once per vehicle update, return cached results?
ByEnd<double> voltages{0.0, 0.0};
for (auto const end : VehicleEnds)
{
if (Couplers[end].Connected == nullptr)
{
continue;
}
auto const &thiscoupler{Couplers[end]};
if (auto const fullcoupling{thiscoupler.CouplingFlag | (thiscoupler.CouplingFlag.HasAll(thiscoupler.PowerCoupling) ? thiscoupler.PowerFlag : CouplingSet{})}; false == fullcoupling.HasAny(couplings))
{
continue;
}
auto const *connectedpowercoupling = couplings.HasAny(Coupling::highVoltage | Coupling::heating) ? &thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr].power_high :
couplings.HasAny(Coupling::power110v) ? &thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr].power_110v :
couplings.HasAny(Coupling::power24v) ? &thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr].power_24v :
nullptr;
if (connectedpowercoupling != nullptr && connectedpowercoupling->is_live)
{
voltages[end] = connectedpowercoupling->voltage;
}
}
return std::max(voltages[VehicleEnd::front], voltages[VehicleEnd::rear]);
}
double physics::Vehicle::GetTrainsetHighVoltage() const
{
return std::max(GetTrainsetVoltage(Coupling::highVoltage), trainHeating.IsAllowed() ? GetTrainsetVoltage(Coupling::heating) : 0.0);
}
int physics::Vehicle::clampDimmerPosition(int const Position) const
{
if (dimPositions.empty())
{
return 0;
}
return std::clamp(Position, 0, static_cast<int>(dimPositions.size()) - 1);
}
physics::Vehicle::dimPosition physics::Vehicle::currentDimPosition() const
{
if (modernDimmerPosition < 0 || modernDimmerPosition >= static_cast<int>(dimPositions.size()))
{
return {};
}
return dimPositions[modernDimmerPosition];
}
bool physics::Vehicle::stepDimmerPosition(int const Step)
{
if (dimPositions.empty())
{
return false;
}
auto const last{static_cast<int>(dimPositions.size()) - 1};
auto const current{clampDimmerPosition(modernDimmerPosition)};
auto next{current + Step};
if (next < 0 || next > last)
{
if (false == modernDimmerCanCycle)
{
next = current;
}
else
{
next = (next < 0 ? last : 0);
}
}
if (next == modernDimmerPosition)
{
return false;
}
modernDimmerPosition = next;
return true;
}
std::optional<lights_preset_cablight> physics::Vehicle::LightsPresetCabLight(int const Position) const
{
if (Position < 1 || Position > static_cast<int>(LightsCabLight.size()))
{
return std::nullopt;
}
auto const flags{LightsCabLight[Position - 1]};
if (flags < 0)
{
return std::nullopt;
}
return lights_preset_cablight{(flags & lights_preset_cablight::light_on) != 0, (flags & lights_preset_cablight::light_dimmed) != 0};
}