diff --git a/CMakeLists.txt b/CMakeLists.txt index faa6ef86d..57ace8499 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -582,6 +582,8 @@ set(CORE_SOURCES "vehicle/brakereleaser.cpp" "vehicle/handover.cpp" "vehicle/crew.cpp" +"vehicle/uphillstart.cpp" +"vehicle/brakecharge.cpp" "vehicle/horn.cpp" "vehicle/cameraviews.cpp" "vehicle/linebreaker.cpp" diff --git a/application/driverhints.cpp b/application/driverhints.cpp index 2c3fbd66b..cd1967aa2 100644 --- a/application/driverhints.cpp +++ b/application/driverhints.cpp @@ -762,6 +762,14 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) return mvPantographUnit->PantPress >= (is_emu() ? (mvPantographUnit->PantPressLockActive ? 4.6 : 2.6) : 4.2); } ); break; } + case driver_hint::waitbrakecharge: { + // NOTE: this action doesn't have AI component: the ai waits through Ready and DecBrake() + hint( + Action, + [this](float const /*Parameter*/) { + return IsConsistCharged; } ); + break; + } case driver_hint::waitloadexchange: { // NOTE: this action doesn't have AI component hint( diff --git a/application/driverhints_def.h b/application/driverhints_def.h index 6f5c86474..2e0556968 100644 --- a/application/driverhints_def.h +++ b/application/driverhints_def.h @@ -59,6 +59,7 @@ DRIVER_HINT_DEF(directionother, STRN("Switch reverser to opposite direction")) DRIVER_HINT_DEF(directionnone, STRN("Set reverser to neutral")) DRIVER_HINT_DEF(waitpressuretoolow, STRN("Wait for main reservoir to fill")) DRIVER_HINT_DEF(waitpantographpressuretoolow, STRN("Wait for sufficient air pressure in pantograph subsystem")) +DRIVER_HINT_DEF(waitbrakecharge, STRN("Wait for the train brakes to charge")) DRIVER_HINT_DEF(sandingon, STRN("Switch on sanding")) DRIVER_HINT_DEF(sandingoff, STRN("Switch off sanding")) DRIVER_HINT_DEF(consistdoorlockson, STRN("Switch on door locks")) diff --git a/ci_shadervalidator/main.cpp b/ci_shadervalidator/main.cpp index bd7db0523..bdc1a9ef4 100644 --- a/ci_shadervalidator/main.cpp +++ b/ci_shadervalidator/main.cpp @@ -113,6 +113,7 @@ bool check_shader_allopts(std::string filename) Global.gfx_shadergamma = true; // the default of the simulator, which compiles the alpha to coverage branches of the shaders Global.iMultisampling = 2; + Global.gfx_headlights_beamwidth = 2.f; if (!check_shader(filename)) suc = false; @@ -124,6 +125,7 @@ bool check_shader_allopts(std::string filename) Global.gfx_extraeffects = false; Global.gfx_shadergamma = false; Global.iMultisampling = 0; + Global.gfx_headlights_beamwidth = 1.f; if (!check_shader(filename)) suc = false; diff --git a/ci_shadervalidator/utilities/Globals.h b/ci_shadervalidator/utilities/Globals.h index e8f548dc3..943ff0adc 100644 --- a/ci_shadervalidator/utilities/Globals.h +++ b/ci_shadervalidator/utilities/Globals.h @@ -9,6 +9,7 @@ struct _global bool gfx_shadergamma; bool gfx_usegles; int iMultisampling; + float gfx_headlights_beamwidth; }; extern _global Global; diff --git a/environment/skydome.cpp b/environment/skydome.cpp index 654b3a345..2a12695d9 100644 --- a/environment/skydome.cpp +++ b/environment/skydome.cpp @@ -5,6 +5,27 @@ #include "simulation/simulationenvironment.h" #include "utilities/Globals.h" +namespace { + +// XYZ to Adobe RGB, as the sky was converted up to 26.05. the legacy renderer still gets its sky this way: +// it draws the colours of the dome as they are, with no tonemapping of its own +glm::vec3 +xyz_to_adobe_rgb( glm::vec3 const &XYZ ) { + + // M^-1 for Adobe RGB from http://www.brucelindbloom.com/Eqn_RGB_XYZ_Matrix.html + std::array const mi{ + glm::vec3{ 2.041369f, -0.969266f, 0.0134474f }, + glm::vec3{ -0.5649464f, 1.8760108f, -0.1183897f }, + glm::vec3{ -0.3446944f, 0.041556f, 1.0154096f } }; + + return glm::vec3{ + XYZ.x * mi[ 0 ].x + XYZ.y * mi[ 1 ].x + XYZ.z * mi[ 2 ].x, + XYZ.x * mi[ 0 ].y + XYZ.y * mi[ 1 ].y + XYZ.z * mi[ 2 ].y, + XYZ.x * mi[ 0 ].z + XYZ.y * mi[ 1 ].z + XYZ.z * mi[ 2 ].z }; +} + +} // namespace + // sky gradient based on "A practical analytic model for daylight" // by A. J. Preetham Peter Shirley Brian Smits (University of Utah) @@ -185,6 +206,11 @@ void CSkyDome::RebuildColors() { float twilightfactor = std::clamp( -simulation::Environment.sun().getAngle(), 0.0f, 18.0f ) / 18.0f; auto gammacorrection = glm::mix( glm::vec3( 1.0f ), glm::vec3( 0.45f ), twilightfactor ); + // the legacy renderer has no tonemapping and no srgb framebuffer, so its sky stays as 26.05 made it: + // display-encoded by day (gamma 0.45), with the brightness knee and the plain gradient, and no horizon band. + // the averages taken from these colours give it the ambient light and the fog of 26.05 too + bool const legacy { Global.LegacyRenderer }; + auto const legacygammacorrection = glm::mix( glm::vec3( 0.45f ), glm::vec3( 1.0f ), twilightfactor ); // get zenith luminance auto const chi = static_cast(( 4.0f / 9.0f - m_turbidity / 120.0f ) * ( M_PI - 2.0f * m_thetasun )); @@ -253,7 +279,7 @@ void CSkyDome::RebuildColors() { float const Z = (1.0f - x - y) / y * Y; colorconverter = glm::vec3( X, Y, Z ); - color = colors::XYZtoRGB( colorconverter ); + color = legacy ? xyz_to_adobe_rgb( colorconverter ) : colors::XYZtoRGB( colorconverter ); colorconverter = colors::RGBtoHSV(color); if ( m_linearexpcontrol ) { @@ -264,7 +290,12 @@ void CSkyDome::RebuildColors() { colorconverter.z = 1.0f - std::exp( -m_expfactor * colorconverter.z ); } - colorconverter.z = std::pow( std::max( colorconverter.z, 0.0f ), gammacorrection.x ); + if( false == legacy ) { + colorconverter.z = std::pow( std::max( colorconverter.z, 0.0f ), gammacorrection.x ); + } + else if( colorconverter.z > 0.85f ) { + colorconverter.z = 0.85f + ( colorconverter.z - 0.85f ) * 0.35f; + } colorconverter.y = std::clamp( colorconverter.y * Global.m_skysaturationcorrection, 0.0f, 1.0f ); // desaturate sky colour, based on overcast level @@ -281,7 +312,7 @@ void CSkyDome::RebuildColors() { // this height-based factor is reduced the farther the sun is up in the sky float const shiftfactor = std::clamp( std::lerp(heightbasedphase, sunbasedphase, sunbasedphase), 0.0f, 1.0f ); // h = 210 makes for 'typical' sky tone - glm::vec3 const skytonecolor = colors::HSVtoRGB( glm::vec3( 210.0f, 0.5f, colorconverter.z ) ); + glm::vec3 const skytonecolor = colors::HSVtoRGB( glm::vec3( 210.0f, legacy ? colorconverter.y : 0.5f, colorconverter.z ) ); color = colors::HSVtoRGB( colorconverter ); color = glm::mix( color, skytonecolor, shiftfactor * Global.m_skyhuecorrection ); @@ -296,14 +327,21 @@ void CSkyDome::RebuildColors() { color.x = 0.20f * color.z; color.y = 0.65f * color.z; } - // simple gradient, darkening towards the top - color *= std::clamp( 1.0f - vertex.y * 0.75f, 0.0f, 1.f ); + if( legacy ) { + // simple gradient, darkening towards the top, then the gamma correction + color *= std::clamp( 1.0f - vertex.y, 0.f, 1.f ); + color = glm::pow( glm::max( color, glm::vec3( 0.f ) ), legacygammacorrection ); + } + else { + // simple gradient, darkening towards the top + color *= std::clamp( 1.0f - vertex.y * 0.75f, 0.0f, 1.f ); - float const horizonboost = 1.5f + m_overcast; - float const horizonbandwidth = 0.2f; // boost tapers to 0 by ~11.5 degrees elevation - float const horizonband = std::clamp( 1.0f - vertex.y / horizonbandwidth, 0.0f, 1.0f ); + float const horizonboost = 1.5f + m_overcast; + float const horizonbandwidth = 0.2f; // boost tapers to 0 by ~11.5 degrees elevation + float const horizonband = std::clamp( 1.0f - vertex.y / horizonbandwidth, 0.0f, 1.0f ); - color *= std::lerp( 1.0, horizonboost, horizonband ); + color *= std::lerp( 1.0, horizonboost, horizonband ); + } //color *= ( 0.25f - vertex.y ); m_colours[ i ] = color; diff --git a/gl/glsl_common.cpp b/gl/glsl_common.cpp index e621fdc6b..9c3cfcb1f 100644 --- a/gl/glsl_common.cpp +++ b/gl/glsl_common.cpp @@ -1,6 +1,23 @@ #include "stdafx.h" #include "glsl_common.h" +#include +#include + +namespace +{ +// a float the way glsl reads it, whatever the locale of the program +std::string glsl_float(float const Value) +{ + std::ostringstream text; + text.imbue(std::locale::classic()); + text.setf(std::ios::fixed); + text.precision(3); + text << Value; + return text.str(); +} +} // namespace + std::string gl::glsl_common; void gl::glsl_common_setup() @@ -12,6 +29,7 @@ void gl::glsl_common_setup() "#define POSTFX_ENABLED " + std::to_string((int)!Global.gfx_skippipeline) + "\n" + "#define EXTRAEFFECTS_ENABLED " + std::to_string((int)Global.gfx_extraeffects) + "\n" + "#define ALPHA_TO_COVERAGE_ENABLED " + std::to_string((int)(Global.iMultisampling > 0)) + "\n" + + "#define HEADLIGHT_BEAM_WIDTH " + glsl_float(Global.gfx_headlights_beamwidth) + "\n" + "#define MAX_LIGHTS " + std::to_string(MAX_LIGHTS) + "U\n" + "#define MAX_CASCADES " + std::to_string(MAX_CASCADES) + "U\n" + "#define MAX_PARAMS " + std::to_string(MAX_PARAMS) + "U\n" + diff --git a/rendering/opengl33renderer.cpp b/rendering/opengl33renderer.cpp index 3a3008a44..5215a7b9f 100644 --- a/rendering/opengl33renderer.cpp +++ b/rendering/opengl33renderer.cpp @@ -988,6 +988,31 @@ void opengl33_renderer::Render_pass(viewport_config &vp, rendermode const Mode) auto const *vehicle = Global.pCamera.m_owner; glm::mat4 mv = OpenGLMatrices.data(GL_MODELVIEW); future = glm::translate(mv, -glm::vec3(vehicle->get_future_movement())) * glm::inverse(mv); + m_freecameraposition.reset(); + } + else if (vp.main) + { + // the free camera (freefly, debug camera) blurs the world with its own movement, as a vehicle does with its: + // without it the ground racing under a low camera strobes in rings at the distances its texture repeats. + // the movement of the frame before stands for the one to come; a jump (a camera preset) is no movement + auto const position{Global.pCamera.Pos}; + if (m_freecameraposition) + { + auto movement{glm::vec3(position - *m_freecameraposition)}; + auto const length{glm::length(movement)}; + if (length < 50.f) + { + // the blur takes the scene where the camera will be: a fast camera (shift, ctrl) moves past the ground + // at the bottom of the screen within a frame, it ends up behind it there and its motion turns over + // into a bright band. half a metre a frame still blurs metres with the shutter of the motion blur + auto const maxmovement{0.5f}; + if (length > maxmovement) + movement *= maxmovement / length; + glm::mat4 mv = OpenGLMatrices.data(GL_MODELVIEW); + future = glm::translate(mv, -movement) * glm::inverse(mv); + } + } + m_freecameraposition = position; } Update_Lights( simulation::Lights ); diff --git a/rendering/opengl33renderer.h b/rendering/opengl33renderer.h index 4322cc2db..3e97683ae 100644 --- a/rendering/opengl33renderer.h +++ b/rendering/opengl33renderer.h @@ -469,6 +469,8 @@ class opengl33_renderer : public gfx_renderer { GLuint64 m_gllasttime = 0; double m_precipitationrotation; + // where the camera with no vehicle of its own was at the frame before, for the motion blur of its movement + std::optional m_freecameraposition; glm::mat4 perspective_projection_raw(float fovy, float aspect, float znear, float zfar); glm::mat4 perspective_projection(const viewport_proj_config &c, float n, float f, glm::mat4 &frustum); diff --git a/shaders/light_common.glsl b/shaders/light_common.glsl index 6261a090d..ddc7c39d3 100644 --- a/shaders/light_common.glsl +++ b/shaders/light_common.glsl @@ -33,7 +33,7 @@ in vec4 UserData; // lit and shaded faces of the same surface). // --------------------------------------------------------------------- const float AMBIENT_SCALE = 0.65; -const float SUN_DIFFUSE_SCALE = 1.5; +const float SUN_DIFFUSE_SCALE = 2.5; // 26.05; at 1.5 the moon left the night black around the headlights const float SUN_NDOTL_SHARPNESS = 1.25; float length2(vec3 v) @@ -242,7 +242,13 @@ vec2 calc_headlights(light_s light, vec3 fragnormal) float distance = length(light.pos - f_pos.xyz); float atten = 1.0f / (1.0f + light.linear * distance + light.quadratic * (distance * distance)); atten *= mix(1.0, 0.0, clamp((coords.z - 0.998) * 500.0, 0.0, 1.0)); - vec3 lights = textureProj(headlightmap, headlightpos).rgb * light.headlight_weights.rgb; + // gfx.headlights.beamwidth spreads the beam sideways around its middle (0.5 of the projected x), so the + // ground beside the track gets the light of the ballast; the brightness along the track stays as it was + vec4 beampos = headlightpos; +#ifdef HEADLIGHT_BEAM_WIDTH + beampos.x = 0.5 * beampos.w + (beampos.x - 0.5 * beampos.w) / HEADLIGHT_BEAM_WIDTH; +#endif + vec3 lights = textureProj(headlightmap, beampos).rgb * light.headlight_weights.rgb; float lightintensity = max(max(lights.r, lights.g), lights.b); return part * atten * lightintensity; } @@ -279,7 +285,9 @@ vec3 EnvBRDFApprox(vec3 F0, float roughness, float NoV) // param[1].x its intensity (HSV value unless a material overrides it). vec3 material_diffuse() { - vec3 diffusecolor = pow(max(param[0].rgb, vec3(0.0)), vec3(2.2)); + // the colour as it is, as 26.05 scaled the light by it; linearised (^2.2) it took a quarter off the default + // 0.8 of every scenery shape and more off darker submodels, and the night went black + vec3 diffusecolor = max(param[0].rgb, vec3(0.0)); float value = max(param[0].r, max(param[0].g, param[0].b)); return (value > 0.0 ? diffusecolor * (param[1].x / value) : vec3(0.0)); } @@ -288,6 +296,8 @@ vec3 material_diffuse() // do magic here vec3 apply_lights(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, float reflectivity, float specularity, float shadowtone) { + // the sun highlight is tinted by the texture alone, as 26.05 drew it, not by the diffuse colour too + vec3 highlight_tint = texturecolor; // Diffuse colour is applied once, to the albedo; the light terms below are not scaled by it again texturecolor *= material_diffuse(); float weathered = (param[3].w > 0.0 ? clamp(param[3].w * UserData.x, 0.0, 1.0) : 0.0); @@ -313,6 +323,10 @@ vec3 apply_lights(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, float refl vec3 view_dir = normalize(-f_pos.xyz); float NdotV = max(dot(fragnormal, view_dir), 0.0); vec3 F0 = mix(vec3(0.04), texturecolor, metalic); + // A metal gives up its diffuse term only as far as its reflection mask lets the environment take its place. + // Assets made before the metal/rough combine mark metal in the specgloss but keep a low mask, and without + // this their metal parts went almost black; a metal with the full mask is drawn as before. + float metal_diffuse_loss = metalic * clamp(reflectivity, 0.0, 1.0); vec3 fresnel = F0 + (1.0 - F0) * pow(1.0 - NdotV, 5.0); const float MAX_REFLECTION_LOD = 8.0; @@ -333,9 +347,9 @@ vec3 apply_lights(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, float refl texturecolor = mix(texturecolor, texturecolorfullv, envyuv.r * reflectivity * env_spec_w); if (lights_count == 0U) - // Metals carry no diffuse term; env reflection is gated by the env BRDF + // Metals carry no diffuse term where they reflect; env reflection is gated by the env BRDF // (F0-tinted, roughness-attenuated) so matte surfaces barely reflect. - return fragcolor * texturecolor * (1.0 - metalic) + return fragcolor * texturecolor * (1.0 - metal_diffuse_loss) + emissioncolor * texturecolor + envcolor * env_spec * reflectivity; @@ -375,16 +389,19 @@ vec3 apply_lights(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, float refl vec3 env_reflection = envcolor * env_spec * reflectivity * (1.0 - shadow1 * 0.5); // --- Physically-based metal/rough combine (Substance 3D Painter parity) --- - // Dielectrics: keep the full diffuse albedo; the direct sun highlight stays - // light-coloured because dielectric F0 is achromatic (~0.04) and - // must NOT be tinted by the base colour. - // Metals: drop the diffuse term entirely and tint the direct highlight - // with the albedo (metal F0 == base colour). + // Dielectrics: keep the full diffuse albedo; the direct sun highlight is tinted + // by the albedo, as 26.05 drew it. The specular strength of the + // assets (param_specular, the specgloss R) was tuned with that + // multiply; an untinted highlight on dark glossy plastic of an old + // asset turned into white glints along edges and speckles on cab + // desks. + // Metals: drop the diffuse term where the reflection mask is full (see + // metal_diffuse_loss) and tint the direct highlight with the + // albedo (metal F0 == base colour). // The highlight *strength* (specularamount) is deliberately left untouched so - // existing material tuning is preserved — only the colour/energy split that - // was previously inverted gets corrected. - vec3 diffuse_albedo = texturecolor * (1.0 - metalic); - vec3 spec_tint = mix(vec3(1.0), texturecolor, metalic); + // existing material tuning is preserved. + vec3 diffuse_albedo = texturecolor * (1.0 - metal_diffuse_loss); + vec3 spec_tint = highlight_tint; vec3 result = fragcolor * diffuse_albedo // sun + ambient + headlight diffuse + specularcolor * spec_tint // direct sun highlight diff --git a/shaders/mat_colored.frag b/shaders/mat_colored.frag index 46de50f09..59ee3e8f8 100644 --- a/shaders/mat_colored.frag +++ b/shaders/mat_colored.frag @@ -24,8 +24,10 @@ layout(location = 1) out vec4 out_motion; void main() { - // no texture: the diffuse colour alone makes the albedo, apply_lights() applies it to the white base - vec4 tex_color = vec4(1.0, 1.0, 1.0, param[0].a); + // no texture: the diffuse colour, linearised, stands in for the texture, and apply_lights() scales it by the + // colour once more, as 26.05 did (c^2.2 * c); on a white base a dark grey of an untextured car came out + // tens of times lighter than in 26.05: tyres, bumpers and glass grey instead of near black + vec4 tex_color = vec4(pow(max(param[0].rgb, vec3(0.0)), vec3(2.2)), param[0].a); // if (tex_color.a < opacity) // discard; @@ -33,7 +35,7 @@ void main() vec3 fragcolor = ambient; vec3 fragnormal = normalize(f_normal); float reflectivity = param[1].z; - float specularity = dot(pow(param[0].rgb, vec3(2.2)), vec3(0.5)); + float specularity = dot(tex_color.rgb, vec3(0.5)); glossiness = abs(param[1].w); fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone); diff --git a/shaders/mat_sunlessnormalmap_specgloss.frag b/shaders/mat_sunlessnormalmap_specgloss.frag index 4e2abe1d9..eb1f9b916 100644 --- a/shaders/mat_sunlessnormalmap_specgloss.frag +++ b/shaders/mat_sunlessnormalmap_specgloss.frag @@ -37,6 +37,7 @@ uniform sampler2D specgloss; vec3 apply_lights_sunless(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, float reflectivity, float specularity, float shadowtone) { // diffuse colour applied once, to the albedo (see material_diffuse() in light_common.glsl) + vec3 highlight_tint = texturecolor; texturecolor *= material_diffuse(); // Cab interior: dim ambient less than the exterior path - ambient // is the dominant indoor illumination, but it was still too bright. @@ -47,6 +48,9 @@ vec3 apply_lights_sunless(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, fl vec3 view_dir = normalize(-f_pos.xyz); float NdotV = max(dot(fragnormal, view_dir), 0.0); vec3 F0 = mix(vec3(0.04), texturecolor, metalic); + // A metal gives up its diffuse term only as far as its reflection mask lets the environment take its place + // (the same as apply_lights in light_common.glsl). + float metal_diffuse_loss = metalic * clamp(reflectivity, 0.0, 1.0); vec3 fresnel = F0 + (1.0 - F0) * pow(1.0 - NdotV, 5.0); const float MAX_REFLECTION_LOD = 8.0; @@ -64,7 +68,7 @@ vec3 apply_lights_sunless(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, fl texturecolor = mix(texturecolor, texturecolorfullv, envyuv.r * reflectivity * env_spec_w); if (lights_count == 0U) - return fragcolor * texturecolor * (1.0 - metalic) + return fragcolor * texturecolor * (1.0 - metal_diffuse_loss) + emissioncolor * texturecolor + envcolor * env_spec * reflectivity; @@ -95,11 +99,11 @@ vec3 apply_lights_sunless(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, fl // Env reflection gated by env BRDF (roughness-attenuated, F0-tinted). vec3 env_reflection = envcolor * env_spec * reflectivity; - // Physically-based metal/rough combine (matches apply_lights / Substance): - // dielectric -> light-coloured highlight + full diffuse; metal -> albedo-tinted - // highlight, no diffuse term. Highlight strength left unchanged. - vec3 diffuse_albedo = texturecolor * (1.0 - metalic); - vec3 spec_tint = mix(vec3(1.0), texturecolor, metalic); + // Metal/rough combine, the same as apply_lights: the direct highlight is tinted by + // the albedo (as 26.05 drew it), a metal drops its diffuse term only where its + // reflection mask is full. Highlight strength left unchanged. + vec3 diffuse_albedo = texturecolor * (1.0 - metal_diffuse_loss); + vec3 spec_tint = highlight_tint; vec3 result = fragcolor * diffuse_albedo + specularcolor * spec_tint diff --git a/shaders/postfx_motionblur.frag b/shaders/postfx_motionblur.frag index 146179ac9..d2b23fd03 100644 --- a/shaders/postfx_motionblur.frag +++ b/shaders/postfx_motionblur.frag @@ -32,6 +32,10 @@ void main() vec2 offset = velocity * (float(i) / float(nSamples - 1) - 0.5); vec2 coord = f_coords + offset; + // a sample off the picture would read its edge row again and again: a fast movement towards the bottom + // of the screen (the ground racing under a low free camera) smeared it into a bright band there + if (any(lessThan(coord, 0.5 * texelSize)) || any(greaterThan(coord, vec2(1.0) - 0.5 * texelSize))) + continue; float depth = texture(depth_tex, coord).x; if (abs(depth - ori_depth) < depth_diff) diff --git a/shaders/tonemapping.glsl b/shaders/tonemapping.glsl index 863fe0fe1..701f9d5fd 100644 --- a/shaders/tonemapping.glsl +++ b/shaders/tonemapping.glsl @@ -139,14 +139,15 @@ vec3 ApplyAgX(vec3 linearColorRec709) vec4 tonemap(vec4 x) { - // Use AgX by default. Reinhard and ACES above are kept for reference. + // ACES, as 26.05 drew it. AgX and Reinhard above are kept for reference: AgX with its look crushed the dark + // end, so the night and everything in shadow went black (a night scene lost half its brightness). // Last-line-of-defense sanitize so NaN/Inf/negative HDR values do not // escape into log2()/pow() and produce black flashes or invalid output. vec3 hdr = x.rgb; hdr = mix(hdr, vec3(0.0), vec3(any(isnan(hdr)) || any(isinf(hdr)))); hdr = max(hdr, vec3(0.0)); - return FBOUT(vec4(ApplyAgX(hdr), x.a)); - //return FBOUT(vec4(ACESFilm(hdr), x.a)); + return FBOUT(vec4(ACESFilm(hdr), x.a)); + //return FBOUT(vec4(ApplyAgX(hdr), x.a)); //return FBOUT(vec4(reinhard(x.rgb), x.a)); } diff --git a/simulation/simulationenvironment.cpp b/simulation/simulationenvironment.cpp index 4e8c0e5f7..57c1074a7 100644 --- a/simulation/simulationenvironment.cpp +++ b/simulation/simulationenvironment.cpp @@ -190,7 +190,9 @@ world_environment::update() { // update the fog. setting it to match the average colour of the sky dome is cheap // but quite effective way to make the distant items blend with background better - Global.FogColor = m_skydome.GetAverageHorizonColor() * keylightcolor * + // the legacy renderer keeps the fog of 26.05, lit by the key light at its diffuse level + glm::vec3 const foglightcolor { Global.LegacyRenderer ? keylightcolor * diffuselevel : keylightcolor }; + Global.FogColor = m_skydome.GetAverageHorizonColor() * foglightcolor * std::clamp((float)Global.fLuminance, 0.f, 1.f); diff --git a/simulation/simulationtest.cpp b/simulation/simulationtest.cpp index 169e0883c..72b4b7e79 100644 --- a/simulation/simulationtest.cpp +++ b/simulation/simulationtest.cpp @@ -62,6 +62,10 @@ void apply_test_mode_settings() Global.local_start_vehicle = "ghostview"; Global.GfxRenderer = "null"; Global.NvRenderer = false; + // the flags of the gfxrenderer line read from the settings go with it: the legacy one picks the colours of the sky, + // and with them the light level the lamps and the AI go by, so a test run would depend on the renderer of the ini + Global.LegacyRenderer = false; + Global.BasicRenderer = false; Global.bSoundEnabled = false; Global.python_enabled = false; Global.bInactivePause = false; diff --git a/staticFiles/python/local/abstractscreenrenderer.py b/staticFiles/python/local/abstractscreenrenderer.py index 3ebf20813..59341c045 100644 --- a/staticFiles/python/local/abstractscreenrenderer.py +++ b/staticFiles/python/local/abstractscreenrenderer.py @@ -1,6 +1,73 @@ from PIL import Image, ImageDraw, ImageFont from math import ceil, floor, cos, sin, radians +import builtins import os +import sys +import time + +# Linux tells the case of the letters in a file name apart, Windows doesn't, and the data is made on Windows: a screen asks for +# "WS_on.png" where the disk has "ws_on.png", or names a folder in another case. The simulator opens such files of its own through +# FileOnDisk(); the files a screen opens itself (images, fonts, text) are found here the same way. The name given when it's on the +# disk, otherwise the one differing from it only in case, of the file or of its folders. On Windows nothing changes. +_case_sensitive = not sys.platform.startswith('win') +_cased_listings = {} # folder -> (when listed, {name in lower case: name on the disk}) + +def _cased_name(folder, name): + """the name in the folder differing from the one given only in case, as on the disk; None when there's none""" + listed = _cased_listings.get(folder) + # a name missing gets the folder listed again, at most once a second, as FileCased() does + if listed is None or (name.lower() not in listed[1] and time.monotonic() - listed[0] >= 1.0): + names = {} + try: + for entry in os.listdir(folder or '.'): + names.setdefault(entry.lower(), entry) + except OSError: + pass + listed = (time.monotonic(), names) + _cased_listings[folder] = listed + return listed[1].get(name.lower()) + +def file_on_disk(path): + """the file to open: as it's named on the disk, the path given when there's none (and on Windows, which finds it itself)""" + if not _case_sensitive or not isinstance(path, str) or os.path.exists(path): + return path + text = path.replace('\\', '/') + parts = [part for part in text.split('/') if part] + cased = '/' if text.startswith('/') else '' + for index, part in enumerate(parts): + last = index == len(parts) - 1 + found = part + if part not in ('.', '..') and not os.path.exists(cased + part): + found = _cased_name(cased, part) + if found is None: + if not last: + return path + # a file not there yet goes into its folder as named on the disk: one written for the first time. The folder + # gets listed anew next time, the file being there by then + _cased_listings.pop(cased, None) + return cased + part + cased += found if last else found + '/' + return cased + +def _open_files_on_disk(): + # Image.open() opens the file through builtins.open(); the fonts are opened by FreeType, from the name. What the wrappers + # call is held here, not looked up in __main__, which the screens share and could name the same + on_disk = file_on_disk + open_given = builtins.open + truetype_given = ImageFont.truetype + + def open_on_disk(file, *args, **kwargs): + return open_given(on_disk(file), *args, **kwargs) + + def truetype_on_disk(font=None, *args, **kwargs): + return truetype_given(on_disk(font), *args, **kwargs) + + open_on_disk.file_on_disk = True + builtins.open = open_on_disk + ImageFont.truetype = truetype_on_disk + +if _case_sensitive and not getattr(builtins.open, 'file_on_disk', False): + _open_files_on_disk() # Pillow 10 removed ImageFont.getsize(), ImageDraw.textsize() and Image.ANTIALIAS, which the screen scripts use; for # Python 3.14 only a newer Pillow is available, so they are put back, on top of getbbox() / textbbox() and LANCZOS @@ -30,7 +97,7 @@ class abstractscreenrenderer(): def openimage(self, name): exts = [ ".png", ".tga", ".dds" ] for e in exts: - path = name + e + path = file_on_disk(name + e) if os.path.isfile(path): if e == ".dds": return Image.open(path).transpose(Image.FLIP_TOP_BOTTOM) diff --git a/tests/unit/test_brake_charge.cpp b/tests/unit/test_brake_charge.cpp new file mode 100644 index 000000000..238d0bef0 --- /dev/null +++ b/tests/unit/test_brake_charge.cpp @@ -0,0 +1,169 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/brakecharge.h" + +// a standing train starts only with its brake pipe and auxiliary reservoirs charged (TController, the consist check) + +using brake_charge::charged; +using brake_charge::state; + +TEST_CASE("brake charge: a train charged to within the margin may start") { + state s; + CHECK(charged(s, 5.0, 5.0, 0.0)); + s = {}; + CHECK(charged(s, 5.0 - brake_charge::margin, 5.0, 0.0)); + s = {}; + // the last wagon of a long train, for good below the working pressure from what leaks along the pipe + CHECK(charged(s, 4.62, 5.0, 0.0)); +} + +TEST_CASE("brake charge: a train prepared from cold waits while its pipe fills") { + state s; + // the pipe of the last wagon empty, then filling by 0.1 bar every 5 s + auto level{0.0}; + auto time{0.0}; + while (level < 5.0 - brake_charge::margin - 0.05) { + CHECK_FALSE(charged(s, level, 5.0, time)); + CHECK_FALSE(s.stalled); + level += 0.1; + time += 5.0; + } + CHECK(charged(s, 5.0 - brake_charge::margin, 5.0, time)); + CHECK(s.going); +} + +TEST_CASE("brake charge: a charge that stops rising lets the train go after the stall time") { + state s; + // a hose not connected: the last wagon stays at 3.2 bar + CHECK_FALSE(charged(s, 3.2, 5.0, 100.0)); + CHECK_FALSE(charged(s, 3.21, 5.0, 130.0)); // less than the gain that counts + CHECK_FALSE(charged(s, 3.21, 5.0, 100.0 + brake_charge::stall_time - 0.1)); + CHECK(charged(s, 3.21, 5.0, 100.0 + brake_charge::stall_time)); + CHECK(s.stalled); + // and stays let go + CHECK(charged(s, 3.2, 5.0, 300.0)); +} + +TEST_CASE("brake charge: a train let go stays let go while its charge rises again as it starts") { + // the train went on a stalled charge; starting, the brakes release and the pipe refills behind them + state s; + REQUIRE_FALSE(charged(s, 4.3, 5.0, 0.0)); + REQUIRE(charged(s, 4.3, 5.0, brake_charge::stall_time)); + CHECK(charged(s, 4.35, 5.0, brake_charge::stall_time + 1.0)); + CHECK(charged(s, 4.4, 5.0, brake_charge::stall_time + 2.0)); + SUBCASE("until the train is to stand again: the next start is checked anew") { + s.going = false; + CHECK_FALSE(charged(s, 4.42, 5.0, brake_charge::stall_time + 3.0)); + CHECK(charged(s, 4.6, 5.0, brake_charge::stall_time + 4.0)); + } +} + +TEST_CASE("brake charge: a train with nothing to charge with yet isn't let go for a stall") { + // prepared from cold: the pipe empty, the engine not started, no air in the main reservoir + state s; + // a look every 5 s for ten times the stall time + auto const looks{static_cast(10.0 * brake_charge::stall_time / 5.0)}; + for (auto i{0}; i < looks; ++i) { + CHECK_FALSE(charged(s, 0.0, 5.0, 5.0 * i, false)); + } + CHECK_FALSE(s.stalled); + CHECK_FALSE(s.going); + // the engine runs, the pipe fills + auto const start{10.0 * brake_charge::stall_time}; + CHECK_FALSE(charged(s, 0.0, 5.0, start, true)); + // the stall time counts from when there was air to charge with + CHECK_FALSE(charged(s, 0.0, 5.0, start + brake_charge::stall_time - 10.0, true)); + CHECK_FALSE(charged(s, 2.0, 5.0, start + brake_charge::stall_time + 10.0, true)); + CHECK(charged(s, 4.6, 5.0, start + brake_charge::stall_time + 60.0, true)); +} + +TEST_CASE("brake charge: a slow but steady charge isn't taken for a stall") { + state s; + auto time{0.0}; + auto level{2.0}; + // 0.03 bar every 50 s: above the gain within the stall time + for (auto i{0}; i < 20; ++i) { + CHECK_FALSE(charged(s, level, 5.0, time)); + level += 0.03; + time += 50.0; + } + CHECK_FALSE(s.stalled); +} + +TEST_CASE("brake charge: a lower working pressure (the reductor turned down) lowers the charge asked for") { + state s; + CHECK(charged(s, 4.35, 4.8, 0.0)); + s = {}; + CHECK_FALSE(charged(s, 4.25, 4.8, 0.0)); +} + +TEST_CASE("brake charge: the locomotive brake holds the train only with the margin over the grade force") { + using brake_charge::locomotive_brake_holds; + // the 752 with about 720 t: 17 kN on -2.4 per mille, 30 kN on -4.3, against about 100 kN of its brake + CHECK(locomotive_brake_holds(100000.0, 17000.0)); + CHECK(locomotive_brake_holds(100000.0, -30000.0)); + CHECK(locomotive_brake_holds(110001.0, 100000.0)); + CHECK_FALSE(locomotive_brake_holds(100000.0, 100000.0)); + CHECK_FALSE(locomotive_brake_holds(0.0, 1000.0)); + CHECK(locomotive_brake_holds(0.0, 0.0)); +} + +TEST_CASE("brake charge: the locomotive brake holds with no more than the wheels pass on to the rails") { + using brake_charge::locomotive_brake_force; + // an ST43 of 116 t: 1031 kN at the brake blocks, 0.25 of its weight on the rails + CHECK(locomotive_brake_force(1031000.0, 116000.0 * 9.81) == doctest::Approx(284490.0)); + // a weak brake stays what it is + CHECK(locomotive_brake_force(50000.0, 116000.0 * 9.81) == doctest::Approx(50000.0)); + CHECK(locomotive_brake_force(0.0, 116000.0 * 9.81) == doctest::Approx(0.0)); + CHECK(locomotive_brake_force(-1.0, 116000.0 * 9.81) == doctest::Approx(0.0)); +} + +TEST_CASE("brake charge: standing not charged, the release of the locomotive brake waits") { + using brake_charge::release_waits; + // the train brake already off: what is left on is the locomotive brake, which holds the train while it charges + CHECK(release_waits(false, true, false)); +} + +TEST_CASE("brake charge: the release doesn't wait once the train is charged, or once it moves") { + using brake_charge::release_waits; + CHECK_FALSE(release_waits(true, true, false)); + // in motion a release is braking control, not a start + CHECK_FALSE(release_waits(false, false, false)); + CHECK_FALSE(release_waits(true, false, false)); +} + +TEST_CASE("brake charge: the train brake may come off while the train charges") { + using brake_charge::release_waits; + // released, the train brake fills the pipe, which is what charges the train + CHECK_FALSE(release_waits(false, true, true)); +} + +TEST_CASE("brake charge: with the train brake applied the train charges to the head of the pipe, not to an empty one") { + using brake_charge::reference; + // released: the working pressure + CHECK(reference(4.7, 5.0, false) == doctest::Approx(5.0)); + // the first service position: what the head of the pipe has + CHECK(reference(4.65, 5.0, true) == doctest::Approx(4.65)); + // a pipe emptied, or just being filled: no lower than a full service application leaves, with the margin a train + // is charged within. an SM42 with 32 wagons at 0.02 bar counted as charged the moment its brake was applied + CHECK(reference(0.02, 5.0, true) == doctest::Approx(4.0)); + state s; + CHECK_FALSE(brake_charge::charged(s, 0.02, reference(0.02, 5.0, true), 0.0)); + // an overcharged pipe doesn't raise it + CHECK(reference(5.4, 5.0, true) == doctest::Approx(5.0)); +} + +TEST_CASE("brake charge: the light application that holds a charging train stays on when the order to go comes") { + using brake_charge::holds_application; + CHECK(holds_application(true, false, true, 1.0)); + CHECK(holds_application(true, false, true, 0.75)); + // charged, or moving: the start releases it + CHECK_FALSE(holds_application(true, true, true, 1.0)); + CHECK_FALSE(holds_application(true, false, false, 1.0)); + // a train the locomotive brake holds has no such application + CHECK_FALSE(holds_application(false, false, true, 1.0)); + // a stronger application comes off down to the first position; a released handle has nothing to hold + CHECK_FALSE(holds_application(true, false, true, 2.0)); + CHECK_FALSE(holds_application(true, false, true, 0.0)); +} diff --git a/tests/unit/test_brake_releaser.cpp b/tests/unit/test_brake_releaser.cpp index 0e32552b3..ce2c9fb20 100644 --- a/tests/unit/test_brake_releaser.cpp +++ b/tests/unit/test_brake_releaser.cpp @@ -112,3 +112,20 @@ TEST_CASE("brake releaser: an overcharged brake pipe turns the releaser off, in uncoupling.pipe_pressure = 5.3; CHECK_FALSE(brake_releaser::decide(uncoupling).actuate); } + +TEST_CASE("brake releaser: a train charging its brakes standing gets an empty pipe filled up before the order to go") { + // a train placed cold, its pipe below the lock of the driver's brake valve, waits for its brakes to charge + // before the first start (#444): the pipe is unlocked as it stands, not only once the driver wants to go + auto state{standing_braked(-0.2)}; + state.pipe_pressure = 1.5; + state.charging_standing = true; + auto const wanted{brake_releaser::decide(state)}; + CHECK(wanted.actuate); + CHECK(wanted.fill_pipe); + + // once the pipe is above the lock the locomotive stays braked: venting it is a rule for the start only + state.pipe_pressure = 3.5; + auto const charging{brake_releaser::decide(state)}; + CHECK_FALSE(charging.actuate); + CHECK_FALSE(charging.fill_pipe); +} diff --git a/tests/unit/test_uphill_start.cpp b/tests/unit/test_uphill_start.cpp new file mode 100644 index 000000000..d450af68b --- /dev/null +++ b/tests/unit/test_uphill_start.cpp @@ -0,0 +1,103 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/uphillstart.h" + +// starting uphill, the train brake is applied further, a step at a time, until the brake of the unpowered vehicles +// holds the train without the locomotive brake (eu07/maszyna#396). the numbers are those of an ST43 with 37 empty +// wagons on 12.5 per mille: 1040 t, 128.6 kN of grade force, the wagons on G with about 22 s to apply + +using uphill_start::brake_top_up; +using uphill_start::top_up; +using uphill_start::top_up_action; + +namespace { + +double const grade{128600.0}; // [N] +double const application{22.0}; // [s] + +// the train standing with the brake handle at Position, held there long enough for the cylinders to fill, while +// each step adds Gain of brake force (as a multiple of the grade force) to the Start it had. runs the top-up until it +// lets the locomotive brake off, and returns the handle position it stopped at and the number of steps +struct outcome { + double position; + int steps; +}; +outcome run_top_up(double Start, double Gain, double Position = 1.25) { + top_up state; + auto force{Start * grade}; + auto steps{0}; + for (auto guard{0}; guard < 100; ++guard) { + auto const action{brake_top_up(state, force, grade, Position, application, application)}; + if (action == top_up_action::none) { + break; + } + REQUIRE(action == top_up_action::step); + Position += 0.25; + force += Gain * grade; + ++steps; + } + return {Position, steps}; +} + +} // namespace + +TEST_CASE("uphill start: a brake that holds the train isn't applied further") { + top_up state; + CHECK(brake_top_up(state, 1.1 * grade, grade, 1.25, application, application) == top_up_action::none); + CHECK(state.last_force < 0.0); +} + +TEST_CASE("uphill start: each step waits the full application time of the brake") { + top_up state; + CHECK(brake_top_up(state, 0.9 * grade, grade, 1.25, 0.5 * application, application) == top_up_action::wait); + CHECK(brake_top_up(state, 0.9 * grade, grade, 1.25, application, application) == top_up_action::step); + // the handle has just moved + CHECK(brake_top_up(state, 0.95 * grade, grade, 1.5, 0.0, application) == top_up_action::wait); + CHECK(brake_top_up(state, 0.95 * grade, grade, 1.5, application - 0.1, application) == top_up_action::wait); +} + +TEST_CASE("uphill start: a light application is topped up until the brake holds the train") { + // before Nowy Zagorz on linia_107_objazdy: 0.64 bar in the wagons, 128 kN against 129 kN + auto const result{run_top_up(0.995, 0.15)}; + CHECK(result.steps == 1); + CHECK(result.position == doctest::Approx(1.5)); +} + +TEST_CASE("uphill start: a brake that doesn't get stronger ends the top-up after one more step") { + // all the wagon brakes cut out: no step adds anything + auto const result{run_top_up(0.0, 0.0)}; + CHECK(result.steps == 1); + CHECK(result.position < uphill_start::top_up_position); +} + +TEST_CASE("uphill start: a brake that gets stronger by too little ends the top-up") { + // a step adds 1% of the grade force, below the 2% that counts + auto const result{run_top_up(0.3, 0.01)}; + CHECK(result.steps == 1); + SUBCASE("and one that gets stronger by enough goes on") { + auto const going{run_top_up(0.3, 0.05)}; + CHECK(going.steps > 1); + } +} + +TEST_CASE("uphill start: the top-up goes no further than full service") { + // every step adds enough to go on, but never enough to hold the train + auto const result{run_top_up(0.0, 0.03)}; + CHECK(result.position == doctest::Approx(uphill_start::top_up_position)); + CHECK(result.steps == 11); + top_up state; + CHECK(brake_top_up(state, 0.0, grade, uphill_start::top_up_position, application, application) == top_up_action::none); +} + +TEST_CASE("uphill start: once ended, the top-up stays ended for the start") { + top_up state; + REQUIRE(brake_top_up(state, 0.2 * grade, grade, 1.25, application, application) == top_up_action::step); + REQUIRE(brake_top_up(state, 0.2 * grade, grade, 1.5, application, application) == top_up_action::none); + CHECK(state.done); + // the brake gets stronger later all the same: the start has gone on without the top-up + CHECK(brake_top_up(state, 0.5 * grade, grade, 1.5, application, application) == top_up_action::none); + // a new start begins with a new top-up + state = {}; + CHECK(brake_top_up(state, 0.5 * grade, grade, 1.5, application, application) == top_up_action::step); +} diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index 3ac6b8f99..9a313dc61 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -1848,6 +1848,12 @@ global_settings::ConfigParse_gfx( cParser &Parser, std::string_view const Token Parser >> gfx_shadow_rank_cutoff; gfx_shadow_rank_cutoff = std::clamp(gfx_shadow_rank_cutoff, 1, 3); } + else if (Token == "gfx.headlights.beamwidth") + { + Parser.getTokens(1); + Parser >> gfx_headlights_beamwidth; + gfx_headlights_beamwidth = std::clamp(gfx_headlights_beamwidth, 1.f, 4.f); + } else { tokenparsed = false; @@ -2137,6 +2143,7 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "gfx.shadergamma", gfx_shadergamma ); export_as_text( Output, "gfx.shadow.angle.min", gfx_shadow_angle_min ); export_as_text( Output, "gfx.shadow.rank.cutoff", gfx_shadow_rank_cutoff ); + export_as_text( Output, "gfx.headlights.beamwidth", gfx_headlights_beamwidth ); export_as_text( Output, "python.enabled", python_enabled ); export_as_text( Output, "python.threadedupload", python_threadedupload ); export_as_text( Output, "python.uploadmain", python_uploadmain ); diff --git a/utilities/Globals.h b/utilities/Globals.h index a5c0bad67..07c04cb14 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -398,6 +398,9 @@ struct global_settings { float gfx_distance_factor_max { 3.f }; float gfx_shadow_angle_min { -0.2f }; int gfx_shadow_rank_cutoff { 3 }; + // how many times wider sideways the headlight beam is spread than its texture: at 1.7 the ground beside the track gets + // most of the light of the ballast; 1 draws the narrow beam of 26.05 + float gfx_headlights_beamwidth { 1.7f }; float ui_fontsize = 13.0f; float ui_scale = 1.0f; diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp index a8477a061..84abd1b97 100644 --- a/vehicle/Driver.cpp +++ b/vehicle/Driver.cpp @@ -3344,9 +3344,13 @@ bool TController::PrepareEngine() } } // set up train brake - if( mvOccupied->fBrakeCtrlPos != mvOccupied->Handle->GetPos( bh_RP ) ) { - if ( !mvOccupied->Handle->Time - || mvOccupied->Handle->GetCP() < mvOccupied->HighPipePress - 0.05 ); + if( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) { + // standing: the locomotive brake first, then the pipe is filled + secure_standing_train(); + } + else if( ( mvOccupied->fBrakeCtrlPos != mvOccupied->Handle->GetPos( bh_RP ) ) + && ( ( false == mvOccupied->Handle->Time ) + || ( mvOccupied->Handle->GetCP() < mvOccupied->HighPipePress - 0.05 ) ) ) { cue_action( driver_hint::trainbrakerelease ); } // sync spring brake state across consist @@ -3799,7 +3803,7 @@ bool TController::DecBrake() { // a position short of the first one brakes no weaker than that deltaAcc = -AccDesired * BrakeAccFactor() - ( fBrake_a0[ 0 ] + 4 * std::max( 0.0, BrakeCtrlPosition - pos_diff ) * fBrake_a1[ 0 ] ); } - if( bUphillStart ) { + if( bUphillStart && ( false == bUphillRelease ) ) { // starting uphill the train brake holds the train until the power does break; } @@ -3808,6 +3812,13 @@ bool TController::DecBrake() { // any release now raises the pipe, and a long train releases more than the handle is moved back, too late // to apply again before the train stands: keep the brake as it is, and the locomotive brake with it break; + } + if( brake_charge::holds_application( + bBrakeChargeHold, IsConsistCharged, mvOccupied->Vel < EU07_AI_NOMOVEMENT, BrakeCtrlPosition ) ) { + // the order to go came while the train still charges: released now, the wagons let go as their + // reservoirs fill and the train stands on a locomotive brake that doesn't hold it. the locomotive + // brake stays on with it + break; } if (deltaAcc < 0 && /*GBH mvOccupied->BrakeCtrlPosR*/ BrakeCtrlPosition > 0) { OK = /*mvOccupied->*/ BrakeLevelAdd(-0.25); @@ -3817,10 +3828,16 @@ bool TController::DecBrake() { if (BrakeCtrlPosition < 0.74) /*mvOccupied->*/ BrakeLevelSet(gbh_RP); } - if( !OK ) { + // standing, the locomotive brake holds the train until its brakes are charged: off before, a train + // released on a gradient rolls with no air to brake with. nor through DecBrakeEIM(), which takes it off + // as well (the locomotive brake of a vehicle without the integrated handle) + auto const holdlocomotive { + ( false == IsConsistCharged ) + && ( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) }; + if( ( !OK ) && ( false == holdlocomotive ) ) { OK = mvOccupied->DecLocalBrakeLevel(2); } - if( !OK ) { + if( ( !OK ) && ( false == holdlocomotive ) ) { OK = DecBrakeEIM(); } /* @@ -6614,24 +6631,41 @@ TController::determine_consist_state() { ConsistShade = 0.0; auto *p { pVehicles[ end::front ] }; // pojazd na czole składu double dy; // składowa styczna grawitacji, w przedziale <0,1> + // starting uphill the power is applied against the train brake on purpose, until the power holds the train and + // then while the brake releases + auto const heldforstart { bUphillStart }; + auto released { true }; // the brakes are off, the hold of an uphill start not counted + auto mostapplied { 0.0 }; // the most applied brake, the hold of an uphill start not counted + auto momentum { 0.0 }; + auto chargelevel { std::numeric_limits::max() }; // the lowest pipe or auxiliary reservoir pressure of a working brake while (p) { // sprawdzenie odhamowania wszystkich połączonych pojazdów auto *vehicle { p->MoverParameters }; auto const bp { std::max( 0.0, vehicle->BrakePress - ( vehicle->SpeedCtrlUnit.Parking ? vehicle->MaxBrakePress[ 0 ] * vehicle->StopBrakeDecc : 0.0 ) ) }; - // starting uphill the power is applied against the train brake on purpose, until the power holds the train - auto const heldforstart { bUphillStart }; - if (Ready) { + momentum += vehicle->TotalMass * vehicle->V * ( p->DirectionGet() == iDirection ? 1 : -1 ); + mostapplied = std::max( bp, mostapplied ); + if( ( vehicle->BrakeSystem != TBrakeSystem::Individual ) + && ( vehicle->MaxBrakePress[ 3 ] > 0.0 ) + && ( false == TestFlag( vehicle->Hamulec->GetBrakeStatus(), b_dmg ) ) ) { // a brake cut out doesn't count + chargelevel = std::min( { chargelevel, vehicle->PipePress, vehicle->Hamulec->GetBRP() } ); + } + auto const wasready { Ready }; + if( released || Ready ) { // bo jak coś nie odhamowane, to dalej nie ma co sprawdzać - if( auto const isbraking { TestFlagAny( vehicle->Hamulec->GetBrakeStatus(), b_hld | b_on ) }; - vehicle->Vel < 1.0 ? + auto const isbraking { TestFlagAny( vehicle->Hamulec->GetBrakeStatus(), b_hld | b_on ) }; + if( vehicle->Vel < 1.0 ? isbraking || bp > 0.4 : // ensure the brakes are sufficiently released when starting to move // once in motion a brake down to 0.4 bar counts as released (UIC), even if its distributor // is still in the lap position while the brake pipe recharges ( isbraking && bp > 0.4 ) || vehicle->Fb > 10000.0 ) { // 10 kN - // ready all the same only at a standstill with the power going on against the brake on purpose; - // in motion a braking force left anywhere in the train (a hand brake) stops it as before - Ready = heldforstart && ( vehicle->Vel < 1.0 ); + released = false; + // ready all the same with the power going on against the brake on purpose: at a standstill, and once + // the power holds the train, while the brake releases; otherwise in motion a braking force left + // anywhere in the train (a hand brake) stops it as before + Ready = Ready && heldforstart && ( bUphillRelease || ( vehicle->Vel < 1.0 ) ); } + } + if( wasready ) { // Ra: odluźnianie przeładowanych lokomotyw, ciągniętych na zimno - prowizorka... if( bp >= 0.4 && (AIControllFlag || Global.AITrainman && mvOccupied->Vel < EU07_AI_NOMOVEMENT && !is_emu() && !is_dmu()) && BrakeCtrlPosition == gbh_RP // jest pozycja jazdy && false == TestFlag(vehicle->Hamulec->GetBrakeStatus(), b_dmg) // brake isn't broken @@ -6648,7 +6682,8 @@ TController::determine_consist_state() { vehicle->BrakeReleaser(0); } } - fReady = std::max( heldforstart ? 0.0 : bp, fReady ); // szukanie najbardziej zahamowanego + // the brake held for the start counts again once it is being released + fReady = std::max( ( heldforstart && ( false == bUphillRelease ) ) ? 0.0 : bp, fReady ); // szukanie najbardziej zahamowanego if( ( dy = p->VectorFront().y ) != 0.0 ) { // istotne tylko dla pojazdów na pochyleniu // ciężar razy składowa styczna grawitacji @@ -6744,6 +6779,73 @@ TController::determine_consist_state() { && fReady < 0.8 ) { // delikatniejszy warunek, obejmuje wszystkie wagony Ready = true; //żeby uznać za odhamowany } + // the same test without the hold of an uphill start + IsConsistReleased = released || ( fAccGravity < -0.05 && mostapplied < 0.8 ); + // the frame of the vehicle the AI drives from, as for fAccGravity and AbsAccS + fConsistVelocity = 3.6 * momentum / std::max( 1.0, fMass ) * ( iDirection >= 0 ? 1 : -1 ); + // standing, the train starts only with its brakes charged: released alone, a train prepared from cold has no air to + // brake with while its auxiliary reservoirs fill. with the train brake applied (held for an uphill start, a light + // application while charging) they charge to what the head of the pipe has. + // only the start the charge is in question for: the first after the train was prepared standing, or one with the + // pipe near empty (after an emergency application, brake_charge::empty_level). after an ordinary stop the + // reservoirs refill as the brake releases, and waiting for the last tenths of a bar there only delays the train and + // those behind it. + // and only the pneumatic brake: multiple units with the electro-pneumatic one start as before + if( mvOccupied->Vel > 1.0 ) { + // the start is made. a shunting engine coupling wagons moves at a walking pace: a higher speed would leave its + // every start the first, waiting for each cut of wagons placed cold to charge + bBrakeChargeStart = false; + bBrakeChargeHold = false; + bHasRun = true; + } + auto const chargeable { + ( BrakeSystem == TBrakeSystem::Pneumatic ) + && ( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) + && ( chargelevel < std::numeric_limits::max() ) }; + if( chargeable && ( chargelevel < brake_charge::empty_level ) ) { + bBrakeChargeStart = true; + } + if( chargeable && bBrakeChargeStart ) { + if( ( VelDesired <= 0.0 ) || ( AccDesired <= EU07_AI_NOACCELERATION ) ) { + // to stand: the next start is checked anew + BrakeCharge.going = false; + } + auto const trainbrakeapplied { + AIControllFlag ? + BrakeCtrlPosition > 0.0 : + // a human driver's handle, which BrakeCtrlPosition doesn't follow + mvOccupied->fBrakeCtrlPos > mvOccupied->Handle->GetPos( bh_RP ) + 0.2 }; + auto const reference { + brake_charge::reference( mvOccupied->PipePress, std::min( mvOccupied->Handle->GetRP(), 5.0 ), trainbrakeapplied ) }; + // air to charge with: the engine prepared, the main reservoir above what the pipe charges to, and the driver's + // brake valve feeding the pipe at the head of the train. a train still being prepared from cold can't charge, + // nor one whose pipe is locked (unlocked by control_releaser()): it waits without that counting as a stall, held + // by its brakes as it can't release them either + auto const supplied { + iEngineActive + && ( std::max( mvControlling->Compressor, mvOccupied->Compressor ) > reference ) + && ( mvOccupied->PipePress >= reference - brake_charge::margin ) }; + auto const wasstalled { BrakeCharge.stalled }; + IsConsistCharged = brake_charge::charged( BrakeCharge, chargelevel, reference, ElapsedTime, supplied ); + if( BrakeCharge.stalled && ( false == wasstalled ) ) { + WriteLog( + "AI: " + mvOccupied->Name + " stopped charging its brakes at " + to_string( chargelevel, 2 ) + + " bar of " + to_string( reference, 2 ) + ", starting all the same" ); + } + if( false == IsConsistCharged ) { + // a human driver is told to wait as the ai does, the locomotive brake applied + cue_action( driver_hint::waitbrakecharge ); + } + } + else { + IsConsistCharged = true; + BrakeCharge = {}; + } + if( AIControllFlag + && ( false == IsConsistCharged ) + && ( false == heldforstart ) ) { + Ready = false; + } auto const departblocked { AIControllFlag && mvOccupied->Vel < EU07_AI_NOMOVEMENT @@ -8830,6 +8932,12 @@ void TController::control_tractive_force() { if( AccDesired > EU07_AI_NOACCELERATION // don't add power if not asked for actual speed-up && (AbsAccS < AccDesired /*- std::min( 0.05, 0.01 * iDriverFailCount )*/ || mvOccupied->SpeedCtrlUnit.IsActive && velocity < mvOccupied->SpeedCtrlUnit.FullPowerVelocity) && false == TestFlag(iDrivigFlags, movePress) && + // starting uphill against the releasing brake, the power that holds the train is enough: the brake coming off + // speeds the train up, more power only drags the brake and slips the wheels. nor is a notch past that taken + // back: the power got there in one notch from below, and the notch below doesn't hold the train + ( false == bUphillRelease || fUphillTractiveForce < uphill_start::holding_force * fUphillHoldingForce ) && + // nor while the train brake is still being applied further to hold the train + false == bUphillBrakeTopUp && velocity < (VelDesired == 1.0 ? // work around for trains getting stuck on tracks with speed limit = 1 VelDesired : VelDesired - fVelMinus) && @@ -8886,15 +8994,20 @@ void TController::control_uphill_start() { && ( false == is_emu() ) && ( false == is_dmu() ) // a multiple unit has no locomotive to hold a train behind it && ( fAccGravity < EU07_AI_UPHILLGRAVITY ) }; false == uphill ) { - bUphillStart = false; + end_uphill_start(); return; } if( false == bUphillStart ) { if( ( std::abs( velocity ) < EU07_AI_NOMOVEMENT ) + // the whole train at a stand, not only its head stopped for a moment while the train rolls back + && ( fConsistVelocity > -0.5 ) && ( AccDesired > EU07_AI_NOACCELERATION ) && ( VelDesired > 0.0 ) - && ( BrakeCtrlPosition > 0.0 ) ) { // only with the train brake still applied to hold the train + && ( BrakeCtrlPosition > 0.0 ) // only with the train brake still applied to hold the train + && ( IsConsistCharged ) ) { // and charged to what the pipe has, or the brake that holds the train has no air bUphillStart = true; + bUphillRelease = false; + UphillTopUp = {}; fUphillStartTime = ElapsedTime; } else { @@ -8903,31 +9016,135 @@ void TController::control_uphill_start() { } if( AccDesired <= EU07_AI_NOACCELERATION ) { // no longer to start: the standing rules take over - bUphillStart = false; + end_uphill_start(); return; } - if( velocity < -0.5 ) { - // rolling back all the same: the rules for a train slipping back take over and apply the brakes - bUphillStart = false; + if( fConsistVelocity < -0.5 ) { + // the train rolls back all the same: the rules for a train slipping back take over and apply the brakes. + // the train as a whole, not its head: with the locomotive brake off, the locomotive and the first vehicles + // run back into the slack of a long train still held by its brake + end_uphill_start(); return; } - if( ( mvOccupied->LocalBrake != TLocalBrake::ManualBrake ) - && ( mvOccupied->LocalBrakePosA > 0.0 ) ) { - cue_action( driver_hint::independentbrakerelease ); - } - auto tractiveforce { 0.0 }; + fUphillTractiveForce = 0.0; for( auto const *vehicle { pVehicles[ end::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { - // Ft is signed in the vehicle's own frame - tractiveforce += std::max( 0.0, vehicle->MoverParameters->Ft * ( vehicle->DirectionGet() == iDirection ? 1 : -1 ) ); + // Ft is signed in the vehicle's own frame, and turned into the direction of travel as AbsAccS is + fUphillTractiveForce += std::max( 0.0, vehicle->MoverParameters->Ft * ( vehicle->DirectionGet() == iDirection ? 1 : -1 ) * ( iDirection >= 0 ? 1 : -1 ) ); } - auto const holdingforce { fMass * -fAccGravity }; - if( ( velocity > 1.0 ) - || ( tractiveforce > 1.1 * holdingforce ) - // a locomotive that can't hold the train on its own power gets the brake off in the end all the same - || ( ElapsedTime - fUphillStartTime > 45.0 ) ) { - // the power holds the train: the train brake can be released - bUphillStart = false; + fUphillHoldingForce = fMass * -fAccGravity; + bUphillBrakeTopUp = false; + if( false == bUphillRelease ) { + bUphillBrakeTopUp = uphill_brake_top_up(); + if( bUphillBrakeTopUp ) { + return; + } + if( ( mvOccupied->LocalBrake != TLocalBrake::ManualBrake ) + && ( mvOccupied->LocalBrakePosA > 0.0 ) ) { + cue_action( driver_hint::independentbrakerelease ); + } + if( ( velocity > 1.0 ) + || ( fUphillTractiveForce > uphill_start::holding_force * fUphillHoldingForce ) + // a locomotive that can't hold the train on its own power gets the brake off in the end all the same + || ( ElapsedTime - fUphillStartTime > 45.0 ) ) { + // the power holds the train: the train brake can be released + bUphillRelease = true; + fUphillReleaseTime = ElapsedTime; + } + return; } + // the train brake is being released with the power on. the start ends once the brakes are off: ended before, + // the brake still on takes the power off, the train rolls back and has to be braked to a stand again + if( IsConsistReleased + // a brake that doesn't come off (a hand brake) ends it all the same + || ( ElapsedTime - fUphillReleaseTime > EU07_AI_UPHILLRELEASETIME ) ) { + end_uphill_start(); + } +} + +// the locomotive brake comes off only once the brake of the rest of the train holds the train on its own: a train +// stopped on a light application stands on the locomotive brake too, and rolls back as soon as it is off. until then +// the train brake is applied further, a step at a time; true while it is +bool TController::uphill_brake_top_up() { + + auto trainbrakeforce { 0.0 }; + auto haswagons { false }; + for( auto const *vehicle { pVehicles[ end::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { + if( vehicle->MoverParameters->Power < 0.01 ) { + trainbrakeforce += vehicle->MoverParameters->Fb; + haswagons = true; + } + } + if( false == haswagons ) { + return false; + } + auto const action { uphill_start::brake_top_up( + UphillTopUp, trainbrakeforce, fUphillHoldingForce, BrakeCtrlPosition, fBrakeHeldTime, + mvOccupied->BrakeDelay[ mvOccupied->BrakeDelayFlag > bdelay_G ? 1 : 3 ] ) }; + if( action == uphill_start::top_up_action::none ) { + return false; + } + // the time for the power to hold the train starts once the brake does + fUphillStartTime = ElapsedTime; + if( action == uphill_start::top_up_action::step ) { + BrakeLevelAdd( BrakingLevelIncrease ); + } + return true; +} + +void TController::end_uphill_start() { + + bUphillStart = false; + bUphillRelease = false; + bUphillBrakeTopUp = false; +} + +// standing, a train is prepared as a driver does it: the locomotive brake first, then the brake pipe is filled. the pipe +// filled at once releases the distributors while the auxiliary reservoirs are still empty: the train has no brake left, +// and on a gradient rolls away as it releases. where the locomotive brake alone doesn't hold the train, the train brake +// is applied lightly, so the reservoirs charge with the train held. the locomotive brake comes off only once the train +// is charged and to start (DecBrake()) +void TController::secure_standing_train() { + + if( BrakeSystem != TBrakeSystem::Pneumatic ) { + // the electro-pneumatic brake of a multiple unit is released as before: nothing there takes the locomotive + // brake off again when the unit starts + cue_action( driver_hint::trainbrakerelease ); + return; + } + // the first start of a train that hasn't run yet waits for the brakes to charge. one that has run, prepared again + // (a change of direction, an engine started anew), has its reservoirs charged from the run and starts as before + if( false == bHasRun ) { + bBrakeChargeStart = true; + } + if( mvOccupied->LocalBrake != TLocalBrake::ManualBrake ) { + cue_action( driver_hint::independentbrakeapply ); + } + if( false == brake_charge::locomotive_brake_holds( locomotive_brake_force(), fMass * fAccGravity ) ) { + // the first service position: the pipe and the reservoirs charge to a little below the working pressure, the + // distributors keep a light application. a stronger application already there is left as it is, but not + // the emergency one or an empty pipe's, which don't charge + if( AIControllFlag + && ( ( BrakeCtrlPosition < 1.0 ) || ( BrakeCtrlPosition > uphill_start::top_up_position ) ) ) { + BrakeLevelSet( 1.0 ); + } + bBrakeChargeHold = true; + return; + } + bBrakeChargeHold = false; + cue_action( driver_hint::trainbrakerelease ); +} + +// the brake force of the locomotive brake at full application [N]. of the occupied vehicle alone: its handle acts on +// no other, not on a second section or a locomotive in multiple control either, let alone one hauled dead +double TController::locomotive_brake_force() const { + + if( ( mvOccupied->LocalBrake == TLocalBrake::ManualBrake ) + || ( mvOccupied->MaxBrakePress[ 0 ] <= 0.0 ) ) { + return 0.0; + } + return brake_charge::locomotive_brake_force( + mvOccupied->BrakeForceP( mvOccupied->MaxBrakePress[ 0 ], 0.0 ), + mvOccupied->TotalMassxg ); } void TController::increase_tractive_force() { @@ -9001,10 +9218,17 @@ void TController::control_braking_force() { if( TestFlag( iDrivigFlags, movePress ) ) { return; } auto const velocity { DirectionalVel() }; + // a train slipping back uphill is braked, also when it is to go on: released now it only rolls back further. + // its head, or the train as a whole: the locomotive may stop for a moment while the rest of the train runs into it + auto const slippingbackuphill { + ( fAccGravity < -0.05 ) + && ( std::min( velocity, fConsistVelocity ) < -0.1 ) + && ( false == bUphillStart ) }; // jeśli przyspieszamy, to nie hamujemy if( AccDesired > 0.0 && OrderCurrentGet() != Disconnect // przy odłączaniu nie zwalniamy tu hamulca - && false == TestFlag(iDrivigFlags, movePress) ) { + && false == TestFlag(iDrivigFlags, movePress) + && false == slippingbackuphill ) { cue_action(driver_hint::brakingforcesetzero); } @@ -9059,7 +9283,7 @@ void TController::control_braking_force() { else { // a stara wersja w miarę dobrze działa na składy wagonowe if( (accdesiredresultant < fAccGravity - 0.1 && AbsAccS > accdesiredresultant + brake_increase_margin() // regular braking - || fAccGravity < -0.05 && velocity < -0.1 && false == bUphillStart) && // also brake if uphill and slipping back + || slippingbackuphill) && // also brake if uphill and slipping back (fBrakeTime < 0.0 // the size of the brake demand decides whether to skip the reaction time, so the brake-only part // (on a descent a heavy train needs its brake built up at once, the gravity does not help it slow) @@ -9085,7 +9309,14 @@ void TController::control_braking_force() { } if ( (accdesiredresultant < fAccGravity - 0.05 || AccDesired >= EU07_AI_NOACCELERATION) // no braking asked for, yet the train is slowing down more than that - && accdesiredresultant - fBrake_a1[0] * 0.51 - AbsAccS > 0.05 && OrderCurrentGet() != Disconnect && VelDesired > 0.0 ) { + && accdesiredresultant - fBrake_a1[0] * 0.51 - AbsAccS > 0.05 && OrderCurrentGet() != Disconnect && VelDesired > 0.0 + // a human driver standing with the train not charged yet keeps the locomotive brake on, told so by the + // waitbrakecharge hint; the ai is held back in DecBrake() + && ( AIControllFlag + || ( false == brake_charge::release_waits( + IsConsistCharged, + mvOccupied->Vel < EU07_AI_NOMOVEMENT, + mvOccupied->fBrakeCtrlPos > mvOccupied->Handle->GetPos( bh_RP ) + 0.2 ) ) ) ) { // the human driver's handle // jak hamuje, to nie tykaj kranu za często // yB: luzuje hamulec dopiero przy różnicy opóźnień rzędu 0.2 // przy odłączaniu nie zwalniamy tu hamulca @@ -9169,6 +9400,14 @@ void TController::control_releaser() { // stage 3 of uncoupling (UpdateDisconnect), from the direction change until the coupler lets go state.compressing_buffers = state.pressing && ( OrderCurrentGet() & Disconnect ) != 0 && iVehicleCount >= 0 && iDirection == iDirectionOrder; + // a train prepared standing charges its brakes before its first start. a pipe left below the lock of the driver's + // brake valve (a train placed cold, as after an emergency application) is unlocked as the train stands, not only + // once it is to go: else it charges only after the order to go, and starts on what the reservoirs got by then. + // a handle which has to be moved to unlock is left where it holds the train with the train brake + state.charging_standing = + bBrakeChargeStart + && ( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) + && ( ( mvOccupied->HandleUnlock == -3 ) || ( BrakeCtrlPosition <= 0.0 ) ); auto const wanted { brake_releaser::decide( state ) }; auto const actuate { wanted.actuate }; auto isbrakehandleinrightposition { true }; @@ -9198,7 +9437,9 @@ void TController::control_releaser() { void TController::control_main_pipe() { // unlocking main pipe - if( AccDesired > -0.03 + if( ( AccDesired > -0.03 + // standing to charge before the first start, as in control_releaser() + || ( bBrakeChargeStart && ( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) ) ) && true == mvOccupied->LockPipe ) { UniversalBrakeButtons |= TUniversalBrake::ub_UnlockPipe; } @@ -9230,9 +9471,12 @@ void TController::control_main_pipe() { update_brake_charging(); - if( mvOccupied->Compressor < 5.0 - || ( BrakeCtrlPosition < gbh_RP - && ( mvOccupied->EqvtPipePress > (fReady < 0.25 ? 5.1 : 5.2) || is_brake_charging_done() ) ) ) { + if( ( mvOccupied->Compressor < 5.0 + || ( BrakeCtrlPosition < gbh_RP + && ( mvOccupied->EqvtPipePress > (fReady < 0.25 ? 5.1 : 5.2) || is_brake_charging_done() ) ) ) + // the light application a charging train stands on stays, as in DecBrake() + && ( false == brake_charge::holds_application( + bBrakeChargeHold, IsConsistCharged, mvOccupied->Vel < EU07_AI_NOMOVEMENT, BrakeCtrlPosition ) ) ) { cue_action( driver_hint::trainbrakerelease ); } } diff --git a/vehicle/Driver.h b/vehicle/Driver.h index 866c913b6..0eae2caf1 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -19,6 +19,8 @@ http://mozilla.org/MPL/2.0/. #include "world/mtable.h" #include "utilities/translation.h" #include "application/driverhints.h" +#include "vehicle/uphillstart.h" +#include "vehicle/brakecharge.h" #include "vehicle/blackbox.h" #include "vehicle/aipower.h" @@ -28,6 +30,7 @@ auto const EU07_AI_BRAKINGTESTACCELERATION = -0.06; auto const EU07_AI_NOMOVEMENT = 0.05; // standstill velocity threshold auto const EU07_AI_MOVEMENT = 1.0; // deliberate movement velocity threshold auto const EU07_AI_UPHILLGRAVITY = -0.025; // [m/s2] about 2.5 per mille up: the gradient that rolls a standing train back +auto const EU07_AI_UPHILLRELEASETIME = 60.0; // [s] the longest an uphill start keeps the power on while the train brake releases auto const EU07_AI_SPEEDLIMITEXTENDSBEYONDSCANRANGE = 10000.0; auto const EU07_AI_SANDEDSTARTVELOCITY = 15.0; // [km/h] a start that slipped keeps the sand on up to this speed @@ -340,6 +343,10 @@ private: bool uphill_stop_hold() const; bool uphill_brake_committed( double const Velocity ) const; void control_uphill_start(); + void end_uphill_start(); + bool uphill_brake_top_up(); + void secure_standing_train(); + double locomotive_brake_force() const; std::pair train_proximity_margins( bool const Passengerstop ) const; void update_timers( double const dt ); @@ -447,6 +454,21 @@ private: bool bSandedStart = false; // the wheels slipped while starting: sand while under power until the train is under way double fSandedStartDecreaseTime = -1.0; // when the power was last taken down a step for a slip while starting double fUphillStartTime = 0.0; // when the uphill start began + bool bUphillRelease = false; // starting uphill, the power holds the train and the train brake is being released + bool bUphillBrakeTopUp = false; // starting uphill, the train brake is applied further before the locomotive brake comes off + uphill_start::top_up UphillTopUp; // starting uphill, what has been done to apply the train brake further + double fUphillReleaseTime = 0.0; // when the release began + double fUphillTractiveForce = 0.0; // the tractive force of the consist while starting uphill [N] + double fUphillHoldingForce = 0.0; // the grade force on the consist while starting uphill [N] + bool IsConsistReleased = true; // the brakes of the consist are off, the hold of an uphill start not counted + bool IsConsistCharged = true; // standing, the brake pipe and the auxiliary reservoirs are charged to start (or stopped charging) + brake_charge::state BrakeCharge; // standing, how the charge of the brakes rose + // the next start waits for the brakes to charge: the first after the train was prepared standing, or one with the + // pipe near empty. cleared once the train runs + bool bBrakeChargeStart = false; + bool bHasRun = false; // the train has moved (above 1 km/h) since it was placed + bool bBrakeChargeHold = false; // charging, the train stands on a light application of the train brake as well + double fConsistVelocity = 0.0; // the mass-weighted speed of the consist, positive in the direction of travel [km/h] double fAccDesiredGravity = 0.0; // część AccDesired odjęta na spadku jako kompensacja pochylenia; AbsAccS zawiera ją już sam double VelforDriver = -1.0; // prędkość, używana przy zmianie kierunku (ograniczenie przy nieznajmości szlaku?) double VelSignal = 0.0; // ograniczenie prędkości z kompilacji znaków i sygnałów // normalnie na początku ma stać, no chyba że jedzie diff --git a/vehicle/brakecharge.cpp b/vehicle/brakecharge.cpp new file mode 100644 index 000000000..18668987d --- /dev/null +++ b/vehicle/brakecharge.cpp @@ -0,0 +1,65 @@ +/* +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/. +*/ + +#include "stdafx.h" +#include "vehicle/brakecharge.h" + +namespace brake_charge { + +bool charged(state &State, double const Level, double const Reference, double const Time, bool const Supplied) { + + if (State.going) { + return true; + } + if (Level >= Reference - margin) { + State = {}; + State.going = true; + return true; + } + if ((State.best < 0.0) || (Level > State.best + stall_gain) || (false == Supplied)) { + // still charging, or nothing to charge with yet: the time for a stall counts from when there is + State.best = Level; + State.best_time = Time; + State.stalled = false; + return false; + } + State.stalled = (Time - State.best_time >= stall_time); + State.going = State.stalled; + return State.stalled; +} + +double locomotive_brake_force(double const Blockforce, double const Weight) { + + return std::max(0.0, std::min(Blockforce, Weight * adhesion)); +} + +bool locomotive_brake_holds(double const Locomotivebrakeforce, double const Gradeforce) { + + return Locomotivebrakeforce >= holding_force * std::abs(Gradeforce); +} + +double reference(double const Headpipe, double const Working, bool const Trainbrakeapplied) { + + if (false == Trainbrakeapplied) { + return Working; + } + return std::clamp(Headpipe, Working - service_drop + margin, Working); +} + +bool holds_application(bool const Hold, bool const Charged, bool const Standing, double const Position) { + + return Hold && (false == Charged) && Standing && (Position > 0.0) && (Position <= 1.0); +} + +bool release_waits(bool const Charged, bool const Standing, bool const Trainbrakeapplied) { + + return (false == Charged) && Standing && (false == Trainbrakeapplied); +} + +} // namespace brake_charge diff --git a/vehicle/brakecharge.h b/vehicle/brakecharge.h new file mode 100644 index 000000000..f283dade9 --- /dev/null +++ b/vehicle/brakecharge.h @@ -0,0 +1,76 @@ +/* +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/. +*/ + +#pragma once + +// a standing train starts only with its brakes charged, as a driver checks before setting off: the brake pipe and the +// auxiliary reservoir of every vehicle with a working brake close to the working pressure. released alone isn't enough: +// a train prepared from cold is released at once, its pipe still filling, and has no air to brake with +// (TController::PrepareEngine(), TController::determine_consist_state()) +namespace brake_charge { + +// [bar] below the working pressure the pipe and the reservoir count as charged: 4.5 of 5.0. the last wagon of a long +// train stays at about 4.6-4.7 for good, from what leaks along the pipe +auto const margin{0.5}; +// below this the pipe counts as near empty (after an emergency application): the next start waits for the charge +// whatever came before. well below what a service application leaves: the AI stops at a station with the handle past +// the full service position, the pipe at 3.0-3.5 bar, and wagons coupled from cold come with about 3 bar. waiting there +// only delays the train, and the scenery sets the routes of the others later (calkowo_v2_osoba_jar_poranek, l053_poranek) +auto const empty_level{2.5}; // [bar] +// a charge that rises by less than this in stall_time has stopped (a leak, a hose not connected, a pipe cock shut): the +// train goes all the same, rather than stand for good +auto const stall_gain{0.02}; // [bar] +auto const stall_time{60.0}; // [s] +// standing, the locomotive brake alone has to give this multiple of the grade force to hold the train while it charges +auto const holding_force{1.1}; +// the share of a locomotive's weight its brake can hold the train with at most: what the wheels pass on to the rails, +// taken low (a wet rail). the force of the brake blocks alone is several times that +auto const adhesion{0.25}; +// [bar] how far below the working pressure the pipe is at a full service application: with the train brake applied the +// train charges to what the head of the pipe has, but a pipe below this (emptied, or just being filled) is no charge +auto const service_drop{1.5}; + +struct state { + double best{-1.0}; // the highest charge seen while it still rose [bar], -1 before the first look + double best_time{0.0}; // when it was seen [s] + bool stalled{false}; // the charge stopped rising short of charged + // the train was let go: it stays so until the driver clears this, when the train is to stand again. otherwise a + // charge rising again as the train starts (the pipe refilling behind the release) would stop it at a crawl + bool going{false}; +}; + +// Level: the lowest pressure of the brake pipes and auxiliary reservoirs among the vehicles with a working brake [bar]; +// Reference: the pressure they charge to [bar]; Time: now [s]; Supplied: there is air to charge with (the engine +// prepared, the main reservoir above the reference): without it the charge can't rise, and that isn't a stall. +// true once the train may start, and from then on +bool charged(state &State, double Level, double Reference, double Time, bool Supplied = true); + +// what the locomotive brake of a vehicle holds with at full application [N]: the force of its brake blocks (Blockforce), +// but no more than its wheels pass on to the rails, the adhesion share of its Weight [N] +double locomotive_brake_force(double Blockforce, double Weight); + +// whether the locomotive brake, Locomotivebrakeforce at full application [N], holds the standing train against its +// Gradeforce [N] on its own; when it doesn't, the train brake is applied lightly while the train charges +bool locomotive_brake_holds(double Locomotivebrakeforce, double Gradeforce); + +// the pressure the train is to be charged to [bar]: the working pressure with the train brake released; with it applied +// what the head of the pipe has (Headpipe), as the reservoirs get no more, though no less than a full service +// application leaves, or a pipe emptied by an emergency application would count as charged at once +double reference(double Headpipe, double Working, bool Trainbrakeapplied); + +// whether a light application of the train brake (Position, up to the first service position) stays on: the train +// stands on it while it charges (Hold), the locomotive brake not holding it alone +bool holds_application(bool Hold, bool Charged, bool Standing, double Position); + +// whether a release of the brakes waits for the charge: standing, a train not charged yet keeps its locomotive brake +// on. the train brake (Trainbrakeapplied) may come off all the same: released, it fills the pipe, which is what charges +// the train. the hint a human driver gets to release the brakes waits with it (driver_hint::waitbrakecharge instead) +bool release_waits(bool Charged, bool Standing, bool Trainbrakeapplied); + +} // namespace brake_charge diff --git a/vehicle/brakereleaser.cpp b/vehicle/brakereleaser.cpp index 0a51c9a62..e9c189bb2 100644 --- a/vehicle/brakereleaser.cpp +++ b/vehicle/brakereleaser.cpp @@ -43,6 +43,11 @@ decision decide(conditions const &State) { result.fill_pipe = State.pipe_pressure < 3.0; result.actuate = wanted_to_start(State); } + else if (State.charging_standing) { + // a train placed cold charges its brakes standing: only the pipe is filled up, the other rules are for a start + result.fill_pipe = State.pipe_pressure < 3.0; + result.actuate = result.fill_pipe; + } // uncoupling, stage 3: the locomotive has to push the slack of the coupler out whatever its speed table says. // the consist stays held by its own brakes, applied in stage 2, and the push asks for 2 km/h at most. a signal // at stop that the consist stands across after the direction change caps the speed at 0 and so AccDesired diff --git a/vehicle/brakereleaser.h b/vehicle/brakereleaser.h index 62bc2e7c1..e4ba14ad6 100644 --- a/vehicle/brakereleaser.h +++ b/vehicle/brakereleaser.h @@ -24,6 +24,9 @@ struct conditions { bool uphill_start{false}; // starting uphill with the train brake held on purpose bool pressing{false}; // (un)coupling: the driver presses the buffers (movePress) bool compressing_buffers{false}; // uncoupling, stage 3: pushing towards the cut to slacken the coupler + // standing, the train charges its brakes before its first start (bBrakeChargeStart), with the brake handle where + // the pipe can be unlocked: a pipe below the lock is unlocked as the train stands, not only once it is to go + bool charging_standing{false}; }; struct decision { diff --git a/vehicle/uphillstart.cpp b/vehicle/uphillstart.cpp new file mode 100644 index 000000000..dd1895b11 --- /dev/null +++ b/vehicle/uphillstart.cpp @@ -0,0 +1,36 @@ +/* +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/. +*/ + +#include "stdafx.h" +#include "vehicle/uphillstart.h" + +namespace uphill_start { + +top_up_action brake_top_up( + top_up &State, double const Brakeforce, double const Holdingforce, double const Brakeposition, double const Heldtime, + double const Applicationtime) { + + if (State.done || (Brakeforce >= holding_force * Holdingforce) || (Brakeposition >= top_up_position)) { + return top_up_action::none; + } + // each step is given the full application time of the train brake, for the cylinders along the train to fill + if (Heldtime < Applicationtime) { + return top_up_action::wait; + } + if ((State.last_force >= 0.0) && (Brakeforce - State.last_force < top_up_gain * Holdingforce)) { + // the last step added next to nothing: the brake of this train can't hold it (brakes cut out, a load setting + // too low), and the start goes on without + State.done = true; + return top_up_action::none; + } + State.last_force = Brakeforce; + return top_up_action::step; +} + +} // namespace uphill_start diff --git a/vehicle/uphillstart.h b/vehicle/uphillstart.h new file mode 100644 index 000000000..108662cbe --- /dev/null +++ b/vehicle/uphillstart.h @@ -0,0 +1,41 @@ +/* +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/. +*/ + +#pragma once + +// starting uphill (TController::control_uphill_start()), the AI's driver lets the locomotive brake off only once +// the brake of the rest of the train holds the train on its own: a train stopped on a light application stands on +// the locomotive brake too, and rolls back as soon as it is off. until then the train brake is applied further, a +// step at a time +namespace uphill_start { + +auto const holding_force{1.1}; // a force that holds a train uphill, as a multiple of the grade force +auto const top_up_position{4.0}; // full service: the furthest the train brake is applied to hold the train +// a step that adds less brake force than this, as a multiple of the grade force, is the last one +auto const top_up_gain{0.02}; + +// what has been done to apply the train brake further, in one start +struct top_up { + double last_force{-1.0}; // the brake force when the last step was given, -1 before the first [N] + bool done{false}; // a step added next to nothing: no more of them in this start +}; + +enum class top_up_action { + none, // the brake holds the train, or can't be made to: the start goes on + wait, // the cylinders are still filling after the last step + step // apply the train brake one step further +}; + +// Brakeforce: the brake force of the unpowered vehicles [N]; Holdingforce: the grade force on the train [N]; +// Brakeposition: the train brake handle, as BrakeCtrlPosition; Heldtime: how long the handle has been where it +// is [s]; Applicationtime: the time the train brake takes to apply, for the cylinders along the train to fill [s] +top_up_action brake_top_up( + top_up &State, double Brakeforce, double Holdingforce, double Brakeposition, double Heldtime, double Applicationtime); + +} // namespace uphill_start